@cloak.dev/sdk 0.2.6-staging.af2dfc0 → 0.2.6-staging.f92dd96

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -843,7 +843,7 @@ async function relayFetch(url, init, options) {
843
843
  assertAllowedRelayOrigin(url);
844
844
  const extra = sanitizeExtraHeaders(options?.extraHeaders);
845
845
  const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
846
- observeRelayClock(response);
846
+ if (options?.observeClock !== false) observeRelayClock(response);
847
847
  return response;
848
848
  }
849
849
  var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
@@ -3970,6 +3970,27 @@ function isRootAccepted(data, rootHex) {
3970
3970
  const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
3971
3971
  return readRootHistory(data).some((r) => r === want);
3972
3972
  }
3973
+ function treeAccountAcceptsRoot(data, rootHex) {
3974
+ const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
3975
+ if (data.length >= ROOT_OFFSET + 32) {
3976
+ const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
3977
+ if (current === want) return true;
3978
+ }
3979
+ return isRootAccepted(data, want);
3980
+ }
3981
+ function readTreeAccountFrontier(data) {
3982
+ if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
3983
+ const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
3984
+ const next = readBigUInt64LE(buf, 32);
3985
+ if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
3986
+ const subtrees = [];
3987
+ for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
3988
+ const offset = SUBTREES_OFFSET + level * 32;
3989
+ subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
3990
+ }
3991
+ const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
3992
+ return { nextIndex: Number(next), subtrees, root };
3993
+ }
3973
3994
 
3974
3995
  // src/proving/merkle.ts
3975
3996
  import { buildPoseidon } from "circomlibjs";
@@ -4129,6 +4150,89 @@ var MerkleTree = class _MerkleTree {
4129
4150
  async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
4130
4151
  return MerkleTree.create(height, commitments);
4131
4152
  }
4153
+ var MerkleFrontier = class _MerkleFrontier {
4154
+ constructor(levels, zeros, poseidon2, count, left) {
4155
+ this.levels = levels;
4156
+ this.zeros = zeros;
4157
+ this.poseidon = poseidon2;
4158
+ this.count = count;
4159
+ this.left = left;
4160
+ }
4161
+ static async create(state, levels = MERKLE_TREE_HEIGHT2) {
4162
+ const zeros = await getZeroValues();
4163
+ const poseidon2 = await getPoseidon();
4164
+ const left = new Array(levels).fill(null);
4165
+ let count = 0;
4166
+ if (state) {
4167
+ if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
4168
+ throw new Error("MerkleFrontierState.nextIndex out of range");
4169
+ }
4170
+ if (!Array.isArray(state.left) || state.left.length !== levels) {
4171
+ throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
4172
+ }
4173
+ count = state.nextIndex;
4174
+ for (let l = 0; l < levels; l++) {
4175
+ const odd = Math.floor(count / 2 ** l) % 2 === 1;
4176
+ const entry = state.left[l];
4177
+ if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
4178
+ if (odd) {
4179
+ if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
4180
+ left[l] = BigInt("0x" + entry);
4181
+ }
4182
+ }
4183
+ }
4184
+ return new _MerkleFrontier(levels, zeros, poseidon2, count, left);
4185
+ }
4186
+ get nextIndex() {
4187
+ return this.count;
4188
+ }
4189
+ /**
4190
+ * The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
4191
+ * present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
4192
+ * With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
4193
+ */
4194
+ leftAt(level) {
4195
+ if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
4196
+ return this.left[level];
4197
+ }
4198
+ hash(a, b) {
4199
+ return this.poseidon.F.toObject(this.poseidon([a, b]));
4200
+ }
4201
+ /** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
4202
+ append(leaves) {
4203
+ if (leaves.length === 0) return;
4204
+ if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
4205
+ let nodes = leaves;
4206
+ for (let l = 0; l < this.levels && nodes.length > 0; l++) {
4207
+ const before = Math.floor(this.count / 2 ** l);
4208
+ const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
4209
+ const parents = [];
4210
+ for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
4211
+ this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
4212
+ nodes = parents;
4213
+ }
4214
+ this.count += leaves.length;
4215
+ }
4216
+ /** The root of the first `nextIndex` leaves, zero-padded to the right. */
4217
+ root() {
4218
+ let partial = this.zeros[0];
4219
+ for (let l = 0; l < this.levels; l++) {
4220
+ const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
4221
+ if (odd) partial = this.hash(this.left[l], partial);
4222
+ else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
4223
+ }
4224
+ return partial;
4225
+ }
4226
+ toState() {
4227
+ return {
4228
+ nextIndex: this.count,
4229
+ left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
4230
+ };
4231
+ }
4232
+ clone() {
4233
+ return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
4234
+ }
4235
+ };
4132
4236
 
4133
4237
  // src/config/transaction-version.ts
4134
4238
  var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
@@ -4641,38 +4745,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
4641
4745
  const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
4642
4746
  return new Uint8Array(plaintext);
4643
4747
  }
4644
- async function deriveAesKeyAndNonce(nk, commitmentHex) {
4748
+ async function importNkHkdfKey(nk) {
4645
4749
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
4646
4750
  throw new Error("nk must be 32 bytes");
4647
4751
  }
4752
+ return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
4753
+ }
4754
+ async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
4648
4755
  const subtle = getSubtleCrypto2();
4649
- const ikm = await subtle.importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
4650
- const salt = hexToBytes32(commitmentHex);
4651
- const keyBits = await subtle.deriveBits(
4652
- {
4653
- name: "HKDF",
4654
- hash: "SHA-256",
4655
- salt: toArrayBuffer2(salt),
4656
- info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
4657
- },
4658
- ikm,
4659
- 256
4660
- );
4661
- const nonceBits = await subtle.deriveBits(
4662
- {
4663
- name: "HKDF",
4664
- hash: "SHA-256",
4665
- salt: toArrayBuffer2(salt),
4666
- info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
4667
- },
4668
- ikm,
4669
- 96
4670
- );
4756
+ const [keyBits, nonceBits] = await Promise.all([
4757
+ subtle.deriveBits(
4758
+ {
4759
+ name: "HKDF",
4760
+ hash: "SHA-256",
4761
+ salt: toArrayBuffer2(salt),
4762
+ info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
4763
+ },
4764
+ ikm,
4765
+ 256
4766
+ ),
4767
+ subtle.deriveBits(
4768
+ {
4769
+ name: "HKDF",
4770
+ hash: "SHA-256",
4771
+ salt: toArrayBuffer2(salt),
4772
+ info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
4773
+ },
4774
+ ikm,
4775
+ 96
4776
+ )
4777
+ ]);
4671
4778
  return {
4672
4779
  key: new Uint8Array(keyBits),
4673
4780
  nonce: new Uint8Array(nonceBits)
4674
4781
  };
4675
4782
  }
4783
+ async function deriveAesKeyAndNonce(nk, commitmentHex) {
4784
+ const ikm = await importNkHkdfKey(nk);
4785
+ return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
4786
+ }
4787
+ function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
4788
+ if (version === NOTE_VERSION_V4) {
4789
+ if (plaintext.length !== PLAINTEXT_LEN_V4) {
4790
+ throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
4791
+ }
4792
+ return {
4793
+ timestamp: readU64LE(plaintext, 0),
4794
+ commitment: commitmentHex.toLowerCase(),
4795
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
4796
+ outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
4797
+ outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
4798
+ isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
4799
+ };
4800
+ }
4801
+ if (version === NOTE_VERSION_V3) {
4802
+ if (plaintext.length !== PLAINTEXT_LEN_V3) {
4803
+ throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
4804
+ }
4805
+ return {
4806
+ timestamp: readU64LE(plaintext, 0),
4807
+ commitment: commitmentHex.toLowerCase(),
4808
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
4809
+ };
4810
+ }
4811
+ if (plaintext.length !== PLAINTEXT_LEN_V2) {
4812
+ throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
4813
+ }
4814
+ return {
4815
+ timestamp: readU64LE(plaintext, 0),
4816
+ commitment: commitmentHex.toLowerCase()
4817
+ };
4818
+ }
4676
4819
  async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
4677
4820
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
4678
4821
  throw new Error("nk must be 32 bytes");
@@ -4736,36 +4879,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
4736
4879
  try {
4737
4880
  const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
4738
4881
  const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
4739
- if (version === NOTE_VERSION_V4) {
4740
- if (plaintext.length !== PLAINTEXT_LEN_V4) {
4741
- throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
4742
- }
4743
- return {
4744
- timestamp: readU64LE(plaintext, 0),
4745
- commitment: commitment.toLowerCase(),
4746
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
4747
- outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
4748
- outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
4749
- isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
4750
- };
4751
- }
4752
- if (version === NOTE_VERSION_V3) {
4753
- if (plaintext.length !== PLAINTEXT_LEN_V3) {
4754
- throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
4755
- }
4756
- return {
4757
- timestamp: readU64LE(plaintext, 0),
4758
- commitment: commitment.toLowerCase(),
4759
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
4760
- };
4761
- }
4762
- if (plaintext.length !== PLAINTEXT_LEN_V2) {
4763
- throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
4764
- }
4765
- return {
4766
- timestamp: readU64LE(plaintext, 0),
4767
- commitment: commitment.toLowerCase()
4768
- };
4882
+ return decodeChainNotePlaintext(version, plaintext, commitment);
4769
4883
  } catch (error) {
4770
4884
  lastError = error;
4771
4885
  }
@@ -4774,6 +4888,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
4774
4888
  `Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
4775
4889
  );
4776
4890
  }
4891
+ async function createCompactChainNoteDecryptor(nk) {
4892
+ const ikm = await importNkHkdfKey(nk);
4893
+ return async (noteBytes, commitment) => {
4894
+ if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
4895
+ if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
4896
+ const version = noteBytes[0];
4897
+ if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
4898
+ return null;
4899
+ }
4900
+ try {
4901
+ const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
4902
+ const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
4903
+ let hex = "";
4904
+ for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
4905
+ return decodeChainNotePlaintext(version, plaintext, hex);
4906
+ } catch {
4907
+ return null;
4908
+ }
4909
+ };
4910
+ }
4777
4911
  function chainNoteToBase64(noteBytes) {
4778
4912
  return Buffer.from(noteBytes).toString("base64");
4779
4913
  }
@@ -4870,6 +5004,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
4870
5004
  return null;
4871
5005
  }
4872
5006
  }
5007
+ var X25519_PKCS8_PREFIX = Uint8Array.from([
5008
+ 48,
5009
+ 46,
5010
+ 2,
5011
+ 1,
5012
+ 0,
5013
+ 48,
5014
+ 5,
5015
+ 6,
5016
+ 3,
5017
+ 43,
5018
+ 101,
5019
+ 110,
5020
+ 4,
5021
+ 34,
5022
+ 4,
5023
+ 32
5024
+ ]);
5025
+ var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
5026
+ function decodeOpened(plaintext) {
5027
+ if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
5028
+ return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
5029
+ }
5030
+ async function createRecipientDeliveryOpener(viewingSecretKey) {
5031
+ if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
5032
+ throw new Error("viewingSecretKey must be 32 bytes");
5033
+ }
5034
+ const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
5035
+ const subtle = globalThis.crypto?.subtle;
5036
+ const hsalsa = nacl4.lowlevel?.crypto_core_hsalsa20;
5037
+ if (!subtle || typeof hsalsa !== "function") return slow;
5038
+ let privateKey;
5039
+ const sharedKey = async (ephemeralPk) => {
5040
+ const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
5041
+ const shared = new Uint8Array(
5042
+ await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
5043
+ );
5044
+ const key = new Uint8Array(32);
5045
+ hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
5046
+ return key;
5047
+ };
5048
+ try {
5049
+ const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
5050
+ pkcs8.set(X25519_PKCS8_PREFIX);
5051
+ pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
5052
+ privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
5053
+ const probe = nacl4.box.keyPair().publicKey;
5054
+ const fast = await sharedKey(probe);
5055
+ const reference = nacl4.box.before(probe, viewingSecretKey);
5056
+ if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
5057
+ } catch {
5058
+ return slow;
5059
+ }
5060
+ return async (envelope) => {
5061
+ if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
5062
+ const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
5063
+ const nonce = envelope.subarray(
5064
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
5065
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
5066
+ );
5067
+ const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
5068
+ let key;
5069
+ try {
5070
+ key = await sharedKey(ephemeralPk);
5071
+ } catch {
5072
+ return openRecipientDeliveryNote(envelope, viewingSecretKey);
5073
+ }
5074
+ try {
5075
+ return decodeOpened(nacl4.secretbox.open(ciphertext, nonce, key));
5076
+ } catch {
5077
+ return null;
5078
+ }
5079
+ };
5080
+ }
4873
5081
  function recipientDeliveryNoteToBase64(envelope) {
4874
5082
  return Buffer.from(envelope).toString("base64");
4875
5083
  }
@@ -11613,6 +11821,1563 @@ function formatComplianceCsv(report) {
11613
11821
  return header + rows;
11614
11822
  }
11615
11823
 
11824
+ // src/relay/note-index-format.ts
11825
+ import { sha256 as sha2565 } from "@noble/hashes/sha2";
11826
+ var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
11827
+ var NOTE_INDEX_FORMAT_VERSION = 1;
11828
+ var NOTE_INDEX_PAGE_SIZE = 1024;
11829
+ var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
11830
+ var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
11831
+ var NOTE_INDEX_HEADER_LEN = 68;
11832
+ var NOTE_INDEX_KIND_TX = 1;
11833
+ var NOTE_INDEX_KIND_DELIVERY = 2;
11834
+ var NOTE_INDEX_KIND_SWAP_REFUND = 3;
11835
+ var NOTE_SOURCE_NONE = 0;
11836
+ var NOTE_SOURCE_CARRIER = 2;
11837
+ var ITEM_HEADER_LEN = 3;
11838
+ var TX_FIXED_LEN = 263;
11839
+ var DELIVERY_BODY_LEN = 256;
11840
+ var SWAP_REFUND_BODY_LEN = 184;
11841
+ var MAX_UNKNOWN_BODY_LEN = 1024;
11842
+ var DELIVERY_ENVELOPE_LEN = 112;
11843
+ var SIGNATURE_LEN = 64;
11844
+ var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
11845
+ [25, 2],
11846
+ [57, 3],
11847
+ [98, 4]
11848
+ ]);
11849
+ var COMPLETE_FLAG = 1;
11850
+ var U64_MAX2 = (1n << 64n) - 1n;
11851
+ var U32_MAX = 4294967295;
11852
+ var MAX_LEAF_INDEX = (1n << 32n) - 1n;
11853
+ var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
11854
+ var NoteIndexFormatError = class extends Error {
11855
+ constructor(message) {
11856
+ super(`Note index format error: ${message}`);
11857
+ this.name = "NoteIndexFormatError";
11858
+ }
11859
+ };
11860
+ function isAllZero2(bytes) {
11861
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
11862
+ return true;
11863
+ }
11864
+ function bytesEqual(a, b) {
11865
+ if (a.length !== b.length) return false;
11866
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
11867
+ return true;
11868
+ }
11869
+ function checkLeafPair(commitment, leaf, label) {
11870
+ if (isAllZero2(commitment)) {
11871
+ if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
11872
+ return;
11873
+ }
11874
+ if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
11875
+ }
11876
+ var Reader = class {
11877
+ constructor(bytes, start, end) {
11878
+ this.bytes = bytes;
11879
+ this.end = end;
11880
+ this.offset = start;
11881
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11882
+ }
11883
+ take(len) {
11884
+ if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
11885
+ const at = this.offset;
11886
+ this.offset += len;
11887
+ return at;
11888
+ }
11889
+ u8() {
11890
+ return this.bytes[this.take(1)];
11891
+ }
11892
+ u32() {
11893
+ return this.view.getUint32(this.take(4), true);
11894
+ }
11895
+ u64() {
11896
+ return this.view.getBigUint64(this.take(8), true);
11897
+ }
11898
+ i64() {
11899
+ return this.view.getBigInt64(this.take(8), true);
11900
+ }
11901
+ raw(len) {
11902
+ const at = this.take(len);
11903
+ return this.bytes.slice(at, at + len);
11904
+ }
11905
+ get position() {
11906
+ return this.offset;
11907
+ }
11908
+ };
11909
+ function parseTx(r, bodyLen) {
11910
+ const mint = r.raw(32);
11911
+ const slot = r.u64();
11912
+ const blockPos = r.u32();
11913
+ const ixTag = r.u8();
11914
+ if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
11915
+ const publicAmount = r.i64();
11916
+ const nullifier0 = r.raw(32);
11917
+ const nullifier1 = r.raw(32);
11918
+ const comm0 = r.raw(32);
11919
+ const leaf0 = r.u64();
11920
+ const comm1 = r.raw(32);
11921
+ const leaf1 = r.u64();
11922
+ const noteSource = r.u8();
11923
+ if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
11924
+ const noteLen = r.u8();
11925
+ if (noteSource === NOTE_SOURCE_NONE) {
11926
+ if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
11927
+ } else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
11928
+ throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
11929
+ }
11930
+ if (bodyLen !== TX_FIXED_LEN + noteLen) {
11931
+ throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
11932
+ }
11933
+ const note = r.raw(noteLen);
11934
+ if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
11935
+ throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
11936
+ }
11937
+ const signature = r.raw(SIGNATURE_LEN);
11938
+ checkLeafPair(comm0, leaf0, "TX comm0");
11939
+ checkLeafPair(comm1, leaf1, "TX comm1");
11940
+ return {
11941
+ kind: 1,
11942
+ mint,
11943
+ slot,
11944
+ blockPos,
11945
+ ixTag,
11946
+ publicAmount,
11947
+ nullifier0,
11948
+ nullifier1,
11949
+ comm0,
11950
+ leaf0,
11951
+ comm1,
11952
+ leaf1,
11953
+ noteSource,
11954
+ note,
11955
+ signature
11956
+ };
11957
+ }
11958
+ function parseDelivery(r) {
11959
+ const mint = r.raw(32);
11960
+ const slot = r.u64();
11961
+ const commitment = r.raw(32);
11962
+ const leaf = r.u64();
11963
+ const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
11964
+ const signature = r.raw(SIGNATURE_LEN);
11965
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
11966
+ checkLeafPair(commitment, leaf, "DELIVERY");
11967
+ return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
11968
+ }
11969
+ function parseSwapRefund(r) {
11970
+ const mint = r.raw(32);
11971
+ if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
11972
+ const slot = r.u64();
11973
+ const commitment = r.raw(32);
11974
+ const leaf = r.u64();
11975
+ const amountAfterFee = r.u64();
11976
+ const nullifier0 = r.raw(32);
11977
+ const signature = r.raw(SIGNATURE_LEN);
11978
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
11979
+ checkLeafPair(commitment, leaf, "SWAP_REFUND");
11980
+ return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
11981
+ }
11982
+ function parseNoteIndexPage(bytes, expect) {
11983
+ if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
11984
+ if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
11985
+ throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
11986
+ }
11987
+ if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
11988
+ for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
11989
+ if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
11990
+ }
11991
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11992
+ const version = bytes[4];
11993
+ if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
11994
+ const flags = bytes[5];
11995
+ if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
11996
+ if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
11997
+ const epoch = view.getBigUint64(8, true);
11998
+ const page = view.getBigUint64(16, true);
11999
+ const firstSeq = view.getBigUint64(24, true);
12000
+ const count = view.getUint32(32, true);
12001
+ const prevChain = bytes.slice(36, 68);
12002
+ const complete = (flags & COMPLETE_FLAG) !== 0;
12003
+ if (expect) {
12004
+ if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
12005
+ if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
12006
+ }
12007
+ if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12008
+ if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
12009
+ if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
12010
+ throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
12011
+ }
12012
+ const items = [];
12013
+ const rawItems = [];
12014
+ let skippedUnknown = 0;
12015
+ let offset = NOTE_INDEX_HEADER_LEN;
12016
+ for (let i = 0; i < count; i++) {
12017
+ if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
12018
+ const kind = bytes[offset];
12019
+ const bodyLen = view.getUint16(offset + 1, true);
12020
+ const bodyStart = offset + ITEM_HEADER_LEN;
12021
+ const bodyEnd = bodyStart + bodyLen;
12022
+ if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12023
+ const r = new Reader(bytes, bodyStart, bodyEnd);
12024
+ let item;
12025
+ switch (kind) {
12026
+ case NOTE_INDEX_KIND_TX:
12027
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12028
+ item = parseTx(r, bodyLen);
12029
+ break;
12030
+ case NOTE_INDEX_KIND_DELIVERY:
12031
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12032
+ item = parseDelivery(r);
12033
+ break;
12034
+ case NOTE_INDEX_KIND_SWAP_REFUND:
12035
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12036
+ item = parseSwapRefund(r);
12037
+ break;
12038
+ default:
12039
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12040
+ skippedUnknown++;
12041
+ offset = bodyEnd;
12042
+ continue;
12043
+ }
12044
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12045
+ items.push(item);
12046
+ rawItems.push(bytes.slice(offset, bodyEnd));
12047
+ offset = bodyEnd;
12048
+ }
12049
+ if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12050
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown };
12051
+ }
12052
+ function parseNoteIndexItem(raw) {
12053
+ if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
12054
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
12055
+ const kind = raw[0];
12056
+ const bodyLen = view.getUint16(1, true);
12057
+ if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
12058
+ const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
12059
+ let item;
12060
+ if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
12061
+ else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
12062
+ else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
12063
+ else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
12064
+ if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
12065
+ return item;
12066
+ }
12067
+ function computeNoteIndexChain(prevChain, pageBytes) {
12068
+ if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
12069
+ if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12070
+ const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
12071
+ const input = new Uint8Array(32 + items.length);
12072
+ input.set(prevChain);
12073
+ input.set(items, 32);
12074
+ return sha2565(input);
12075
+ }
12076
+ var Writer = class {
12077
+ constructor() {
12078
+ this.chunks = [];
12079
+ this.length = 0;
12080
+ }
12081
+ push(bytes) {
12082
+ this.chunks.push(bytes);
12083
+ this.length += bytes.length;
12084
+ }
12085
+ u8(v) {
12086
+ if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
12087
+ this.push(Uint8Array.of(v));
12088
+ }
12089
+ u16(v) {
12090
+ if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
12091
+ const b = new Uint8Array(2);
12092
+ new DataView(b.buffer).setUint16(0, v, true);
12093
+ this.push(b);
12094
+ }
12095
+ u32(v) {
12096
+ if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
12097
+ const b = new Uint8Array(4);
12098
+ new DataView(b.buffer).setUint32(0, v, true);
12099
+ this.push(b);
12100
+ }
12101
+ u64(v) {
12102
+ if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
12103
+ const b = new Uint8Array(8);
12104
+ new DataView(b.buffer).setBigUint64(0, v, true);
12105
+ this.push(b);
12106
+ }
12107
+ i64(v) {
12108
+ if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
12109
+ const b = new Uint8Array(8);
12110
+ new DataView(b.buffer).setBigInt64(0, v, true);
12111
+ this.push(b);
12112
+ }
12113
+ fixed(bytes, len, label) {
12114
+ if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
12115
+ this.push(bytes);
12116
+ }
12117
+ finish() {
12118
+ const out = new Uint8Array(this.length);
12119
+ let off = 0;
12120
+ for (const c of this.chunks) {
12121
+ out.set(c, off);
12122
+ off += c.length;
12123
+ }
12124
+ return out;
12125
+ }
12126
+ };
12127
+ function encodeItemBody(item) {
12128
+ const w = new Writer();
12129
+ switch (item.kind) {
12130
+ case NOTE_INDEX_KIND_TX: {
12131
+ w.fixed(item.mint, 32, "mint");
12132
+ w.u64(item.slot);
12133
+ w.u32(item.blockPos);
12134
+ w.u8(item.ixTag);
12135
+ w.i64(item.publicAmount);
12136
+ w.fixed(item.nullifier0, 32, "nullifier0");
12137
+ w.fixed(item.nullifier1, 32, "nullifier1");
12138
+ w.fixed(item.comm0, 32, "comm0");
12139
+ w.u64(item.leaf0);
12140
+ w.fixed(item.comm1, 32, "comm1");
12141
+ w.u64(item.leaf1);
12142
+ w.u8(item.noteSource);
12143
+ const noteLen = item.note.length;
12144
+ if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
12145
+ throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
12146
+ }
12147
+ w.u8(noteLen);
12148
+ w.push(item.note);
12149
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12150
+ break;
12151
+ }
12152
+ case NOTE_INDEX_KIND_DELIVERY:
12153
+ w.fixed(item.mint, 32, "mint");
12154
+ w.u64(item.slot);
12155
+ w.fixed(item.commitment, 32, "commitment");
12156
+ w.u64(item.leaf);
12157
+ w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
12158
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12159
+ break;
12160
+ case NOTE_INDEX_KIND_SWAP_REFUND:
12161
+ w.fixed(item.mint, 32, "mint");
12162
+ w.u64(item.slot);
12163
+ w.fixed(item.commitment, 32, "commitment");
12164
+ w.u64(item.leaf);
12165
+ w.u64(item.amountAfterFee);
12166
+ w.fixed(item.nullifier0, 32, "nullifier0");
12167
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
12168
+ break;
12169
+ default:
12170
+ throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
12171
+ }
12172
+ return w.finish();
12173
+ }
12174
+ function encodeNoteIndexItem(item) {
12175
+ const body = encodeItemBody(item);
12176
+ const w = new Writer();
12177
+ w.u8(item.kind);
12178
+ w.u16(body.length);
12179
+ w.push(body);
12180
+ return w.finish();
12181
+ }
12182
+ function encodeNoteIndexPage(params) {
12183
+ const items = params.items ?? [];
12184
+ if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12185
+ const w = new Writer();
12186
+ w.push(NOTE_INDEX_MAGIC);
12187
+ w.u8(NOTE_INDEX_FORMAT_VERSION);
12188
+ w.u8(params.complete ? COMPLETE_FLAG : 0);
12189
+ w.u16(0);
12190
+ w.u64(BigInt(params.epoch));
12191
+ w.u64(BigInt(params.page));
12192
+ w.u64(BigInt(params.firstSeq));
12193
+ w.u32(items.length);
12194
+ w.fixed(params.prevChain, 32, "prevChain");
12195
+ for (const item of items) w.push(encodeNoteIndexItem(item));
12196
+ return w.finish();
12197
+ }
12198
+
12199
+ // src/relay/note-index-client.ts
12200
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
12201
+ var DEFAULT_MAX_RETRIES2 = 3;
12202
+ var RETRY_BASE_DELAY_MS = 500;
12203
+ var U64_MAX3 = (1n << 64n) - 1n;
12204
+ function joinPath(relayUrl, path) {
12205
+ const url = new URL(relayUrl);
12206
+ url.pathname = url.pathname.replace(/\/$/, "") + path;
12207
+ return url;
12208
+ }
12209
+ function abortError() {
12210
+ const error = new Error("Note index request aborted");
12211
+ error.name = "AbortError";
12212
+ return error;
12213
+ }
12214
+ function sleep4(ms, signal) {
12215
+ return new Promise((resolve, reject) => {
12216
+ if (signal?.aborted) return reject(abortError());
12217
+ const timer = setTimeout(() => {
12218
+ signal?.removeEventListener("abort", onAbort);
12219
+ resolve();
12220
+ }, ms);
12221
+ const onAbort = () => {
12222
+ clearTimeout(timer);
12223
+ reject(abortError());
12224
+ };
12225
+ signal?.addEventListener("abort", onAbort, { once: true });
12226
+ });
12227
+ }
12228
+ var RetryableStatusError = class extends Error {
12229
+ };
12230
+ var HttpStatusError = class extends Error {
12231
+ constructor(status, message) {
12232
+ super(message);
12233
+ this.status = status;
12234
+ this.name = "HttpStatusError";
12235
+ }
12236
+ };
12237
+ async function requestWithRetry(url, options, read) {
12238
+ assertAllowedRelayOrigin(url);
12239
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
12240
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
12241
+ let lastError;
12242
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
12243
+ if (options.signal?.aborted) throw abortError();
12244
+ const controller = new AbortController();
12245
+ const onAbort = () => controller.abort();
12246
+ options.signal?.addEventListener("abort", onAbort, { once: true });
12247
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
12248
+ try {
12249
+ const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
12250
+ if (response.status === 429 || response.status >= 500) {
12251
+ throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
12252
+ }
12253
+ return await read(response, controller.signal);
12254
+ } catch (error) {
12255
+ if (options.signal?.aborted) throw abortError();
12256
+ const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
12257
+ if (!retryable || attempt >= maxRetries) throw error;
12258
+ lastError = error;
12259
+ await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
12260
+ } finally {
12261
+ clearTimeout(timer);
12262
+ options.signal?.removeEventListener("abort", onAbort);
12263
+ }
12264
+ }
12265
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
12266
+ }
12267
+ async function readBoundedBody(response, maxBytes) {
12268
+ const declaredHeader = response.headers?.get?.("content-length") ?? null;
12269
+ const declared = declaredHeader === null ? NaN : Number(declaredHeader);
12270
+ if (Number.isFinite(declared) && declared > maxBytes) {
12271
+ throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
12272
+ }
12273
+ const reader = response.body?.getReader?.();
12274
+ if (!reader) {
12275
+ const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
12276
+ if (!Number.isSafeInteger(declared) || declared < 0) {
12277
+ throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
12278
+ }
12279
+ if (encoding !== "" && encoding !== "identity") {
12280
+ throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
12281
+ }
12282
+ const buffer = new Uint8Array(await response.arrayBuffer());
12283
+ if (buffer.length > maxBytes || buffer.length !== declared) {
12284
+ throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
12285
+ }
12286
+ return buffer;
12287
+ }
12288
+ const chunks = [];
12289
+ let total = 0;
12290
+ for (; ; ) {
12291
+ const { done, value } = await reader.read();
12292
+ if (done) break;
12293
+ total += value.length;
12294
+ if (total > maxBytes) {
12295
+ await reader.cancel().catch(() => void 0);
12296
+ throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
12297
+ }
12298
+ chunks.push(value);
12299
+ }
12300
+ const out = new Uint8Array(total);
12301
+ let off = 0;
12302
+ for (const c of chunks) {
12303
+ out.set(c, off);
12304
+ off += c.length;
12305
+ }
12306
+ return out;
12307
+ }
12308
+ function isNonNegativeSafeInteger(value) {
12309
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
12310
+ }
12311
+ async function fetchNoteIndexHead(relayUrl, options = {}) {
12312
+ const url = joinPath(relayUrl, "/note-index/v1/head").toString();
12313
+ const raw = await requestWithRetry(url, options, async (response) => {
12314
+ if (!response.ok) {
12315
+ throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
12316
+ }
12317
+ const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
12318
+ try {
12319
+ return JSON.parse(text);
12320
+ } catch {
12321
+ throw new NoteIndexFormatError("head is not JSON");
12322
+ }
12323
+ });
12324
+ if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
12325
+ if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
12326
+ throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
12327
+ }
12328
+ if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
12329
+ throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
12330
+ }
12331
+ if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
12332
+ throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
12333
+ }
12334
+ if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
12335
+ throw new NoteIndexFormatError(
12336
+ `complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
12337
+ );
12338
+ }
12339
+ if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
12340
+ throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
12341
+ }
12342
+ if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
12343
+ throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
12344
+ }
12345
+ return {
12346
+ format: 1,
12347
+ epoch: BigInt(raw.epoch),
12348
+ pageSize: NOTE_INDEX_PAGE_SIZE,
12349
+ watermark: raw.watermark,
12350
+ completePages: raw.complete_pages,
12351
+ chainTip: raw.chain_tip.toLowerCase()
12352
+ };
12353
+ }
12354
+ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
12355
+ if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
12356
+ if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
12357
+ const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
12358
+ return requestWithRetry(url, options, async (response) => {
12359
+ if (!response.ok) {
12360
+ throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
12361
+ }
12362
+ return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
12363
+ });
12364
+ }
12365
+
12366
+ // src/scanning/note-index.ts
12367
+ import _bs584 from "bs58";
12368
+ import { sha256 as sha2566 } from "@noble/hashes/sha2";
12369
+ var bs584 = _bs584.default || _bs584;
12370
+ var CURSOR_VERSION = 2;
12371
+ var DEFAULT_CONCURRENCY = 6;
12372
+ var MAX_CONCURRENCY = 32;
12373
+ var ITEM_BATCH = 64;
12374
+ var CURSOR_PAGE_ALIGN = 8;
12375
+ var MAX_PERSISTED_PENDING_LEAVES = 4096;
12376
+ var MAX_CARRIED_PENDING = 256;
12377
+ var MAX_REJECTED_IDS = 1024;
12378
+ var LEAF_WINDOW = 512;
12379
+ var MAX_OVERRIDES = 256;
12380
+ var MAX_CURSOR_OWN_ITEMS = 65536;
12381
+ var MAX_CURSOR_KEYS = 131072;
12382
+ var MAX_CURSOR_POOLS = 256;
12383
+ var MAX_CURSOR_PAGE = 2 ** 32;
12384
+ var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
12385
+ var ZERO_CHAIN = "00".repeat(32);
12386
+ var U64_MAX4 = (1n << 64n) - 1n;
12387
+ var NoteIndexHeadBehindError = class extends Error {
12388
+ constructor(cursorWatermark, headWatermark) {
12389
+ super(
12390
+ `note index head is behind this cursor (watermark ${headWatermark} < ${cursorWatermark} seen before in this epoch): a stale cache or a rollback; retry later with the same cursor`
12391
+ );
12392
+ this.cursorWatermark = cursorWatermark;
12393
+ this.headWatermark = headWatermark;
12394
+ this.retryable = true;
12395
+ this.name = "NoteIndexHeadBehindError";
12396
+ }
12397
+ };
12398
+ var FullPassSignal = class {
12399
+ constructor(reason) {
12400
+ this.reason = reason;
12401
+ }
12402
+ };
12403
+ function abortError2() {
12404
+ const error = new Error("recoverNotesFromIndex aborted");
12405
+ error.name = "AbortError";
12406
+ return error;
12407
+ }
12408
+ function bytesToBigint2(bytes) {
12409
+ let v = 0n;
12410
+ for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
12411
+ return v;
12412
+ }
12413
+ function toHex2(bytes) {
12414
+ let s = "";
12415
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
12416
+ return s;
12417
+ }
12418
+ function fromHex(hex) {
12419
+ return Uint8Array.from(Buffer.from(hex, "hex"));
12420
+ }
12421
+ function hex32(v) {
12422
+ return v.toString(16).padStart(64, "0");
12423
+ }
12424
+ function isAllZero3(bytes) {
12425
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
12426
+ return true;
12427
+ }
12428
+ function floorAlign(page) {
12429
+ return page - page % CURSOR_PAGE_ALIGN;
12430
+ }
12431
+ function verifiedKey(mint, leaf, commitment) {
12432
+ return `${mint}:${leaf}:${hex32(commitment)}`;
12433
+ }
12434
+ function itemIdentity(raw) {
12435
+ return toHex2(sha2566(raw).subarray(0, 16));
12436
+ }
12437
+ var LeafBuffer = class {
12438
+ constructor() {
12439
+ this.bytes = new Uint8Array(32 * 1024);
12440
+ this.view = new DataView(this.bytes.buffer);
12441
+ this.count = 0;
12442
+ }
12443
+ get length() {
12444
+ return this.count;
12445
+ }
12446
+ push(values) {
12447
+ const need = (this.count + values.length) * 32;
12448
+ if (need > this.bytes.length) {
12449
+ let size = this.bytes.length;
12450
+ while (size < need) size *= 2;
12451
+ const next = new Uint8Array(size);
12452
+ next.set(this.bytes.subarray(0, this.count * 32));
12453
+ this.bytes = next;
12454
+ this.view = new DataView(next.buffer);
12455
+ }
12456
+ for (const v of values) {
12457
+ const o = this.count * 32;
12458
+ this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
12459
+ this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
12460
+ this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
12461
+ this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
12462
+ this.count++;
12463
+ }
12464
+ }
12465
+ get(i) {
12466
+ if (i < 0 || i >= this.count) return void 0;
12467
+ const o = i * 32;
12468
+ return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
12469
+ }
12470
+ };
12471
+ async function trialItem(item, trial) {
12472
+ if (item.kind === 1) {
12473
+ if (item.note.length === 0) return null;
12474
+ let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
12475
+ if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
12476
+ return note ? { note } : null;
12477
+ }
12478
+ if (item.kind === 2) {
12479
+ const delivery = await trial.open(item.envelope);
12480
+ return delivery ? { delivery } : null;
12481
+ }
12482
+ if (item.amountAfterFee === 0n) return null;
12483
+ const refund = await matchSwapRefundLeaf({
12484
+ viewingKeyNk: trial.nk,
12485
+ inputNullifier: item.nullifier0,
12486
+ amountAfterFee: item.amountAfterFee,
12487
+ commitment: item.commitment,
12488
+ ownerUtxoKeypair: trial.owner
12489
+ });
12490
+ return refund ? { refund } : null;
12491
+ }
12492
+ function txOutputs(item) {
12493
+ const out = [toHex2(item.comm0)];
12494
+ if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
12495
+ return out;
12496
+ }
12497
+ function leafOfTxOutput(item, commitment) {
12498
+ if (!isAllZero3(item.comm0) && commitment === bytesToBigint2(item.comm0)) return Number(item.leaf0);
12499
+ if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
12500
+ return null;
12501
+ }
12502
+ async function matchOwnItems(own, trial, onReject) {
12503
+ const { nk, owner } = trial;
12504
+ const candidates = [];
12505
+ const claimed = /* @__PURE__ */ new Set();
12506
+ const byNullifier = /* @__PURE__ */ new Map();
12507
+ const legacyKeys = /* @__PURE__ */ new Map();
12508
+ const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
12509
+ const spendsOf = /* @__PURE__ */ new Map();
12510
+ const byOutKey = /* @__PURE__ */ new Map();
12511
+ const index = (map, key, o) => {
12512
+ const list = map.get(key);
12513
+ if (list) list.push(o);
12514
+ else map.set(key, [o]);
12515
+ };
12516
+ for (const o of ownTxs) {
12517
+ for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
12518
+ if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
12519
+ }
12520
+ const queue = [];
12521
+ const queued = /* @__PURE__ */ new Set();
12522
+ const enqueue = (o) => {
12523
+ if (queued.has(o)) return;
12524
+ queued.add(o);
12525
+ queue.push(o);
12526
+ };
12527
+ const add = async (c) => {
12528
+ const nullifier = hex32(
12529
+ await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
12530
+ );
12531
+ const full = { ...c, nullifier };
12532
+ candidates.push(full);
12533
+ if (!byNullifier.has(nullifier)) {
12534
+ byNullifier.set(nullifier, full);
12535
+ for (const o of spendsOf.get(nullifier) ?? []) enqueue(o);
12536
+ }
12537
+ if (full.atRisk && !legacyKeys.has(full.keypair.publicKey)) {
12538
+ legacyKeys.set(full.keypair.publicKey, full.keypair);
12539
+ for (const o of byOutKey.get(full.keypair.publicKey) ?? []) enqueue(o);
12540
+ }
12541
+ };
12542
+ const base = (o) => ({ signature: o.item.signature, page: o.page, seq: o.seq });
12543
+ const tryDeposit = async (o, item, amount) => {
12544
+ const note = o.note;
12545
+ const mint = addressFromBytes(item.mint);
12546
+ const deposit = await matchDepositNote({
12547
+ viewingKeyNk: nk,
12548
+ noteSalt: note.noteSalt,
12549
+ amount,
12550
+ mintAddress: mint,
12551
+ outputCommitments: txOutputs(item),
12552
+ ownerUtxoKeypair: owner
12553
+ });
12554
+ const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
12555
+ if (!deposit || leaf === null) return false;
12556
+ await add({
12557
+ kind: "deposit",
12558
+ atRisk: deposit.legacyExposed,
12559
+ amount: deposit.amount,
12560
+ blinding: deposit.blinding,
12561
+ keypair: deposit.legacyExposed ? deposit.keypair : owner,
12562
+ mint,
12563
+ commitment: deposit.commitment,
12564
+ leaf,
12565
+ ...base(o)
12566
+ });
12567
+ return true;
12568
+ };
12569
+ const tryChange0 = async (o, item, keypair, atRisk) => {
12570
+ const note = o.note;
12571
+ const mint = addressFromBytes(item.mint);
12572
+ const change = await matchChangeNote({
12573
+ viewingKeyNk: nk,
12574
+ noteSalt: note.noteSalt,
12575
+ amount: note.outAmount0,
12576
+ keypair,
12577
+ mintAddress: mint,
12578
+ outputIndex: 0,
12579
+ outputCommitments: [toHex2(item.comm0)],
12580
+ ownerUtxoPublicKey: owner.publicKey
12581
+ });
12582
+ if (!change) return false;
12583
+ await add({
12584
+ kind: "change",
12585
+ atRisk,
12586
+ amount: change.amount,
12587
+ blinding: change.blinding,
12588
+ keypair,
12589
+ mint,
12590
+ commitment: change.commitment,
12591
+ leaf: Number(item.leaf0),
12592
+ ...base(o)
12593
+ });
12594
+ return true;
12595
+ };
12596
+ for (const o of own) {
12597
+ const item = o.item;
12598
+ if (item.kind === 1 && o.note?.noteSalt !== void 0) {
12599
+ const note = o.note;
12600
+ if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
12601
+ if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
12602
+ }
12603
+ if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
12604
+ if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
12605
+ }
12606
+ } else if (item.kind === 2 && o.delivery) {
12607
+ const mint = addressFromBytes(item.mint);
12608
+ if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
12609
+ onReject(o);
12610
+ continue;
12611
+ }
12612
+ const commitment = await computeCommitment({
12613
+ amount: o.delivery.amount,
12614
+ keypair: { privateKey: 0n, publicKey: owner.publicKey },
12615
+ blinding: o.delivery.blinding,
12616
+ mintAddress: mint
12617
+ });
12618
+ if (commitment !== bytesToBigint2(item.commitment)) {
12619
+ onReject(o);
12620
+ continue;
12621
+ }
12622
+ await add({
12623
+ kind: "received",
12624
+ atRisk: false,
12625
+ amount: o.delivery.amount,
12626
+ blinding: o.delivery.blinding,
12627
+ keypair: owner,
12628
+ mint,
12629
+ commitment,
12630
+ leaf: Number(item.leaf),
12631
+ ...base(o)
12632
+ });
12633
+ } else if (item.kind === 3 && o.refund) {
12634
+ await add({
12635
+ kind: "swap_refund",
12636
+ atRisk: o.refund.legacyExposed,
12637
+ amount: o.refund.amount,
12638
+ blinding: o.refund.blinding,
12639
+ keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
12640
+ mint: NATIVE_SOL_MINT,
12641
+ commitment: o.refund.commitment,
12642
+ leaf: Number(item.leaf),
12643
+ ...base(o)
12644
+ });
12645
+ }
12646
+ }
12647
+ const processTx = async (o) => {
12648
+ const item = o.item;
12649
+ const note = o.note;
12650
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
12651
+ const legacy = legacyKeys.get(note.outPubkey0);
12652
+ if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
12653
+ }
12654
+ const mint = addressFromBytes(item.mint);
12655
+ const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
12656
+ if (inputs.length === 0) return;
12657
+ const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
12658
+ if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
12659
+ const out1 = sumIn + item.publicAmount - note.outAmount0;
12660
+ if (out1 > 0n) {
12661
+ const blinding = deriveChangeNoteBlinding(nk, note.noteSalt, 1);
12662
+ const owners = [{ keypair: owner, atRisk: false }];
12663
+ const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
12664
+ if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
12665
+ for (const { keypair, atRisk } of owners) {
12666
+ const commitment = await computeCommitment({ amount: out1, keypair, blinding, mintAddress: mint });
12667
+ if (commitment !== bytesToBigint2(item.comm1)) continue;
12668
+ claimed.add(`${o.seq}:1`);
12669
+ await add({ kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1), ...base(o) });
12670
+ break;
12671
+ }
12672
+ }
12673
+ }
12674
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
12675
+ if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
12676
+ }
12677
+ };
12678
+ for (const o of ownTxs) enqueue(o);
12679
+ for (let i = 0; i < queue.length; i++) {
12680
+ const o = queue[i];
12681
+ queued.delete(o);
12682
+ await processTx(o);
12683
+ }
12684
+ return candidates;
12685
+ }
12686
+ async function replayStream(start, pages, overrides, chain, targetPage) {
12687
+ const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
12688
+ const startN = frontier.nextIndex;
12689
+ const pending = new Map(start.pending);
12690
+ const flushed = new LeafBuffer();
12691
+ const corrections = /* @__PURE__ */ new Map();
12692
+ let conflicts = 0;
12693
+ let verifiedPrefix = 0;
12694
+ let mismatch = false;
12695
+ const checks = [];
12696
+ const setBits = [];
12697
+ if (chain && chain.nextIndex > 0) {
12698
+ const last = chain.nextIndex - 1;
12699
+ for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
12700
+ for (const l of setBits) {
12701
+ const at = Math.floor(last / 2 ** l) * 2 ** l;
12702
+ if (at >= startN) checks.push({ at, level: l });
12703
+ }
12704
+ if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
12705
+ checks.sort((a, b) => a.at - b.at);
12706
+ }
12707
+ let nextCheck = 0;
12708
+ const runChecks = () => {
12709
+ while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
12710
+ const { at, level } = checks[nextCheck++];
12711
+ const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
12712
+ if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
12713
+ else mismatch = true;
12714
+ }
12715
+ };
12716
+ const append = (values) => {
12717
+ let i = 0;
12718
+ while (i < values.length) {
12719
+ const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
12720
+ const take = Math.min(values.length - i, room);
12721
+ if (take > 0) {
12722
+ const part = values.slice(i, i + take);
12723
+ frontier.append(part);
12724
+ flushed.push(part);
12725
+ i += take;
12726
+ }
12727
+ runChecks();
12728
+ }
12729
+ };
12730
+ const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
12731
+ const flush = () => {
12732
+ const batch = [];
12733
+ let next = frontier.nextIndex;
12734
+ while (pending.has(next)) {
12735
+ batch.push(pending.get(next));
12736
+ pending.delete(next);
12737
+ next++;
12738
+ }
12739
+ if (batch.length > 0) append(batch);
12740
+ };
12741
+ let snapshot = null;
12742
+ let taken = false;
12743
+ const takeSnapshot = () => {
12744
+ taken = true;
12745
+ if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
12746
+ snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
12747
+ };
12748
+ runChecks();
12749
+ flush();
12750
+ for (const { page, entries } of pages) {
12751
+ if (!taken && page >= targetPage) takeSnapshot();
12752
+ for (const e of entries) {
12753
+ if (e.leaf < startN) continue;
12754
+ const prior = valueAt(e.leaf);
12755
+ if (prior !== void 0) {
12756
+ if (prior !== e.commitment) {
12757
+ conflicts++;
12758
+ corrections.set(e.leaf, e.commitment);
12759
+ }
12760
+ continue;
12761
+ }
12762
+ pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
12763
+ }
12764
+ flush();
12765
+ }
12766
+ if (!taken) takeSnapshot();
12767
+ if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
12768
+ verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
12769
+ }
12770
+ return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
12771
+ }
12772
+ var HEX64 = /^[0-9a-f]{64}$/;
12773
+ var HEX32 = /^[0-9a-f]{32}$/;
12774
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
12775
+ var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
12776
+ function isRecord(v) {
12777
+ return typeof v === "object" && v !== null && !Array.isArray(v);
12778
+ }
12779
+ function isIntIn(v, min, max) {
12780
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
12781
+ }
12782
+ function isBoundedArray(v, max) {
12783
+ return Array.isArray(v) && v.length <= max;
12784
+ }
12785
+ function emptyStartTree() {
12786
+ return {
12787
+ frontier: null,
12788
+ nextIndex: 0,
12789
+ pending: /* @__PURE__ */ new Map(),
12790
+ window: [],
12791
+ windowStart: 0,
12792
+ verified: 0,
12793
+ overrides: /* @__PURE__ */ new Map(),
12794
+ mismatch: false,
12795
+ hiBefore: -1
12796
+ };
12797
+ }
12798
+ async function parseCursor(cursor, poolMints) {
12799
+ try {
12800
+ if (!isRecord(cursor)) return "not an object";
12801
+ if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
12802
+ const c = cursor;
12803
+ if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
12804
+ if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
12805
+ if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
12806
+ if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
12807
+ if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
12808
+ if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
12809
+ const trees = /* @__PURE__ */ new Map();
12810
+ for (const mint of poolMints) {
12811
+ const t = c.trees[mint];
12812
+ if (!isRecord(t)) return "a listed pool is missing from the cursor";
12813
+ const tree = t;
12814
+ if (!isRecord(tree.frontier)) return "bad frontier";
12815
+ let frontier;
12816
+ try {
12817
+ frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
12818
+ } catch {
12819
+ return "bad frontier";
12820
+ }
12821
+ const nextIndex = frontier.nextIndex;
12822
+ if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
12823
+ const pending = /* @__PURE__ */ new Map();
12824
+ let hiBefore = nextIndex - 1;
12825
+ for (const entry of tree.pending) {
12826
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
12827
+ const [leaf, value] = entry;
12828
+ if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
12829
+ return "bad pending leaves";
12830
+ }
12831
+ pending.set(leaf, BigInt("0x" + value));
12832
+ hiBefore = Math.max(hiBefore, leaf);
12833
+ }
12834
+ if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
12835
+ const windowLen = tree.window.length / 64;
12836
+ if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
12837
+ const window2 = [];
12838
+ for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
12839
+ if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
12840
+ if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
12841
+ const overrides = /* @__PURE__ */ new Map();
12842
+ for (const entry of tree.overrides) {
12843
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
12844
+ const [leaf, value] = entry;
12845
+ if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
12846
+ overrides.set(leaf, BigInt("0x" + value));
12847
+ }
12848
+ if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
12849
+ trees.set(mint, {
12850
+ frontier: frontier.toState(),
12851
+ nextIndex,
12852
+ pending,
12853
+ window: window2,
12854
+ windowStart: nextIndex - windowLen,
12855
+ verified: tree.verified,
12856
+ overrides,
12857
+ mismatch: tree.mismatch,
12858
+ hiBefore
12859
+ });
12860
+ }
12861
+ const own = c.own;
12862
+ if (!isRecord(own)) return "bad own state";
12863
+ if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
12864
+ const items = [];
12865
+ const seqs = /* @__PURE__ */ new Set();
12866
+ for (const entry of own.items) {
12867
+ if (!isRecord(entry)) return "bad own items";
12868
+ const { seq, item } = entry;
12869
+ if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
12870
+ if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
12871
+ seqs.add(seq);
12872
+ const raw = fromHex(item);
12873
+ items.push({ seq, raw, item: parseNoteIndexItem(raw) });
12874
+ }
12875
+ if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
12876
+ return "bad verified notes";
12877
+ }
12878
+ if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
12879
+ if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
12880
+ const pendingLeaves = /* @__PURE__ */ new Map();
12881
+ for (const entry of own.pendingLeaves) {
12882
+ if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
12883
+ const [mint, leaf, value] = entry;
12884
+ if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
12885
+ return "bad pending notes";
12886
+ }
12887
+ pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
12888
+ }
12889
+ if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
12890
+ return "bad rejected set";
12891
+ }
12892
+ return {
12893
+ raw: c,
12894
+ trees,
12895
+ items,
12896
+ verified: new Set(own.verified),
12897
+ spent: new Set(own.spent),
12898
+ pendingLeaves,
12899
+ rejected: own.rejected
12900
+ };
12901
+ } catch {
12902
+ return "unreadable state";
12903
+ }
12904
+ }
12905
+ async function recoverNotesFromIndex(params) {
12906
+ const startedAt = Date.now();
12907
+ const { relayUrl, connection, viewingKeyNk, programId } = params;
12908
+ assertAllowedRelayOrigin(relayUrl);
12909
+ assertAllowedRpcConnection(connection);
12910
+ if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
12911
+ const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
12912
+ if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
12913
+ const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
12914
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
12915
+ throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
12916
+ }
12917
+ if (params.signal?.aborted) throw abortError2();
12918
+ const stats = {
12919
+ pages: 0,
12920
+ items: 0,
12921
+ bytes: 0,
12922
+ rpcCalls: 0,
12923
+ ms: 0,
12924
+ dropped: 0,
12925
+ decrypted: 0,
12926
+ candidates: 0,
12927
+ spent: 0,
12928
+ conflicts: 0,
12929
+ pendingDropped: 0
12930
+ };
12931
+ const rpc = new Proxy(connection, {
12932
+ get(target, prop, receiver) {
12933
+ const value = Reflect.get(target, prop, receiver);
12934
+ if (typeof value !== "function") return value;
12935
+ return (...args) => {
12936
+ const pending = value.apply(target, args);
12937
+ if (pending && typeof pending.send === "function") {
12938
+ const send = pending.send.bind(pending);
12939
+ return {
12940
+ ...pending,
12941
+ send: (...sendArgs) => {
12942
+ stats.rpcCalls++;
12943
+ return send(...sendArgs);
12944
+ }
12945
+ };
12946
+ }
12947
+ return pending;
12948
+ };
12949
+ }
12950
+ });
12951
+ const trial = {
12952
+ nk: viewingKeyNk,
12953
+ owner,
12954
+ decrypt: await createCompactChainNoteDecryptor(viewingKeyNk),
12955
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(viewingKeyNk).privateKey)
12956
+ };
12957
+ const poolMints = Array.from(new Set(params.poolMints));
12958
+ const warnings = [];
12959
+ const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
12960
+ let cursor;
12961
+ if (params.cursor !== void 0) {
12962
+ const checked = await parseCursor(params.cursor, poolMints);
12963
+ if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
12964
+ else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
12965
+ else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
12966
+ throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
12967
+ } else cursor = checked;
12968
+ }
12969
+ const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
12970
+ let treeRead;
12971
+ const readTrees = () => treeRead ?? (treeRead = (async () => {
12972
+ const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
12973
+ return poolMints.map((_, i) => {
12974
+ const account = accounts[i];
12975
+ const parsed = account ? readTreeAccountFrontier(account.data) : null;
12976
+ return account && parsed ? { ...parsed, data: account.data } : null;
12977
+ });
12978
+ })());
12979
+ const ctx = { params, head, trial, stats, poolMints, warnings, readTrees };
12980
+ let outcome = await runOnce(ctx, cursor);
12981
+ if (outcome instanceof FullPassSignal) {
12982
+ warnings.push(`${outcome.reason}; re-syncing from page 0`);
12983
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
12984
+ outcome = await runOnce(ctx, void 0);
12985
+ if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
12986
+ }
12987
+ stats.ms = Date.now() - startedAt;
12988
+ return { ...outcome, stats, warnings };
12989
+ }
12990
+ async function runOnce(ctx, cursor) {
12991
+ const { params, head, trial, stats, poolMints } = ctx;
12992
+ const { relayUrl, onProgress } = params;
12993
+ const owner = trial.owner;
12994
+ const poolSet = new Set(poolMints);
12995
+ const startPage = cursor?.raw.page ?? 0;
12996
+ const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
12997
+ const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
12998
+ const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
12999
+ const targetPage = Math.max(startPage, floorAlign(head.completePages));
13000
+ const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
13001
+ const rejectedIds = new Set(cursor?.rejected ?? []);
13002
+ const controller = new AbortController();
13003
+ const onCallerAbort = () => controller.abort();
13004
+ params.signal?.addEventListener("abort", onCallerAbort, { once: true });
13005
+ const signal = controller.signal;
13006
+ try {
13007
+ const pageData = /* @__PURE__ */ new Map();
13008
+ const ownItems = [];
13009
+ const nullifiers = /* @__PURE__ */ new Set();
13010
+ let fullPassReason = null;
13011
+ const lateReference = (mint, leaf, value, seq) => {
13012
+ if (!cursor || seq < fullPassSeq) return null;
13013
+ const t = startTrees.get(mint);
13014
+ if (leaf < t.nextIndex) {
13015
+ if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
13016
+ if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
13017
+ return null;
13018
+ }
13019
+ const held = t.pending.get(leaf);
13020
+ if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
13021
+ if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
13022
+ return null;
13023
+ };
13024
+ const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
13025
+ const waiting = /* @__PURE__ */ new Map();
13026
+ let chainNext = startPage;
13027
+ let chainError = null;
13028
+ let wakers = [];
13029
+ const wakeAll = () => {
13030
+ const w = wakers;
13031
+ wakers = [];
13032
+ for (const f of w) f();
13033
+ };
13034
+ signal.addEventListener("abort", wakeAll);
13035
+ const advanceChain = () => {
13036
+ while (!chainError && waiting.has(chainNext)) {
13037
+ const w = waiting.get(chainNext);
13038
+ waiting.delete(chainNext);
13039
+ const expected = chainAt.get(chainNext);
13040
+ if (w.prevChain !== expected) {
13041
+ chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
13042
+ controller.abort();
13043
+ return;
13044
+ }
13045
+ if (!w.complete) break;
13046
+ chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
13047
+ chainNext++;
13048
+ }
13049
+ wakeAll();
13050
+ };
13051
+ const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
13052
+ const lookahead = 2 * workerCount + 2;
13053
+ let nextToFetch = startPage;
13054
+ let pagesDone = 0;
13055
+ const worker = async () => {
13056
+ for (; ; ) {
13057
+ if (signal.aborted) throw abortError2();
13058
+ const pageNo = nextToFetch++;
13059
+ if (pageNo >= pagesTotal) return;
13060
+ while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
13061
+ if (signal.aborted) throw abortError2();
13062
+ const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13063
+ stats.bytes += bytes.length;
13064
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
13065
+ if (pageNo < head.completePages && !page2.complete) {
13066
+ throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13067
+ }
13068
+ stats.pages++;
13069
+ waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13070
+ advanceChain();
13071
+ const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
13072
+ const late = (reason) => {
13073
+ if (reason && !fullPassReason) {
13074
+ fullPassReason = reason;
13075
+ controller.abort();
13076
+ }
13077
+ };
13078
+ const addLeaf = (mintBytes, commitment, leaf, seq) => {
13079
+ if (isAllZero3(commitment)) return;
13080
+ const mint = addressFromBytes(mintBytes);
13081
+ if (!poolSet.has(mint)) return;
13082
+ const entry = { leaf: Number(leaf), commitment: bytesToBigint2(commitment) };
13083
+ late(lateReference(mint, entry.leaf, entry.commitment, seq));
13084
+ const list = data.leaves.get(mint);
13085
+ if (list) list.push(entry);
13086
+ else data.leaves.set(mint, [entry]);
13087
+ };
13088
+ page2.items.forEach((item, i) => {
13089
+ const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
13090
+ if (item.kind === 1) {
13091
+ addLeaf(item.mint, item.comm0, item.leaf0, seq);
13092
+ addLeaf(item.mint, item.comm1, item.leaf1, seq);
13093
+ if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
13094
+ if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
13095
+ } else if (item.kind === 3) {
13096
+ addLeaf(item.mint, item.commitment, item.leaf, seq);
13097
+ } else {
13098
+ const mint = addressFromBytes(item.mint);
13099
+ if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
13100
+ }
13101
+ });
13102
+ if (signal.aborted) throw abortError2();
13103
+ for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
13104
+ if (signal.aborted) throw abortError2();
13105
+ const batch = page2.items.slice(i, i + ITEM_BATCH);
13106
+ const opened = await Promise.all(batch.map((item) => trialItem(item, trial)));
13107
+ opened.forEach((o, k) => {
13108
+ if (!o) return;
13109
+ stats.decrypted++;
13110
+ const raw = page2.rawItems[i + k];
13111
+ const id = itemIdentity(raw);
13112
+ if (rejectedIds.has(id)) {
13113
+ stats.dropped++;
13114
+ return;
13115
+ }
13116
+ ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o });
13117
+ });
13118
+ stats.items += batch.length;
13119
+ }
13120
+ pageData.set(pageNo, data);
13121
+ pagesDone++;
13122
+ onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
13123
+ }
13124
+ };
13125
+ const workers = Array.from(
13126
+ { length: workerCount },
13127
+ () => worker().catch((error) => {
13128
+ controller.abort();
13129
+ throw error;
13130
+ })
13131
+ );
13132
+ const settled = await Promise.allSettled(workers);
13133
+ signal.removeEventListener("abort", wakeAll);
13134
+ if (params.signal?.aborted) throw abortError2();
13135
+ const lateReason = fullPassReason;
13136
+ if (lateReason) return new FullPassSignal(lateReason);
13137
+ const chainFailure = chainError;
13138
+ if (chainFailure) {
13139
+ if (chainFailure instanceof FullPassSignal) return chainFailure;
13140
+ throw chainFailure;
13141
+ }
13142
+ const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
13143
+ if (failure) throw failure.reason;
13144
+ if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
13145
+ if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
13146
+ throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
13147
+ }
13148
+ for (const entry of cursor?.items ?? []) {
13149
+ const o = await trialItem(entry.item, trial);
13150
+ if (!o) continue;
13151
+ const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
13152
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o });
13153
+ if (entry.item.kind === 1) {
13154
+ if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
13155
+ if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
13156
+ }
13157
+ }
13158
+ const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
13159
+ ownItems.sort((a, b) => a.seq - b.seq);
13160
+ const rejectedNow = /* @__PURE__ */ new Set();
13161
+ const allCandidates = await matchOwnItems(ownItems, trial, (o) => {
13162
+ stats.dropped++;
13163
+ rejectedNow.add(o.id);
13164
+ });
13165
+ stats.candidates = allCandidates.length;
13166
+ const cutoff = params.legacyCutoffLeaf ?? {};
13167
+ const candidates = allCandidates.filter((c) => {
13168
+ const limit = cutoff[c.mint];
13169
+ if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
13170
+ stats.dropped++;
13171
+ return false;
13172
+ }
13173
+ return true;
13174
+ });
13175
+ const chainTrees = await ctx.readTrees();
13176
+ const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
13177
+ const replays = /* @__PURE__ */ new Map();
13178
+ for (let i = 0; i < poolMints.length; i++) {
13179
+ const mint = poolMints[i];
13180
+ const start = startTrees.get(mint);
13181
+ const chainTree = chainTrees[i] ?? null;
13182
+ const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
13183
+ let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
13184
+ let overrides = start.overrides;
13185
+ stats.conflicts += r.conflicts;
13186
+ if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
13187
+ const merged = new Map([...start.overrides, ...r.corrections]);
13188
+ const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
13189
+ if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
13190
+ r = alternative;
13191
+ overrides = merged;
13192
+ }
13193
+ }
13194
+ if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
13195
+ replays.set(mint, { r, overrides });
13196
+ }
13197
+ const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
13198
+ const streamValue = (mint, leaf) => {
13199
+ const v = replays.get(mint)?.r.valueAt(leaf);
13200
+ if (v !== void 0) return v;
13201
+ const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
13202
+ if (carried !== void 0) return carried;
13203
+ const t = startTrees.get(mint);
13204
+ if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
13205
+ return void 0;
13206
+ };
13207
+ const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
13208
+ const verified = [];
13209
+ const pendingByKey = /* @__PURE__ */ new Map();
13210
+ const rejectedCandidates = /* @__PURE__ */ new Set();
13211
+ const outcomeOf = /* @__PURE__ */ new Map();
13212
+ const tally = (c, what) => {
13213
+ const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
13214
+ t.total++;
13215
+ if (what === "kept") t.kept = true;
13216
+ if (what === "rejected") t.rejected++;
13217
+ outcomeOf.set(c.seq, t);
13218
+ };
13219
+ const pend = (c, rank) => {
13220
+ const key = verifiedKey(c.mint, c.leaf, c.commitment);
13221
+ const prior = pendingByKey.get(key);
13222
+ if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
13223
+ };
13224
+ for (const c of candidates) {
13225
+ if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
13226
+ verified.push(c);
13227
+ continue;
13228
+ }
13229
+ if (!poolSet.has(c.mint)) {
13230
+ pend(c, 3);
13231
+ continue;
13232
+ }
13233
+ const value = streamValue(c.mint, c.leaf);
13234
+ if (value === void 0) {
13235
+ if (c.leaf < startTrees.get(c.mint).nextIndex) {
13236
+ stats.dropped++;
13237
+ tally(c, "other");
13238
+ } else pend(c, 1);
13239
+ } else if (c.leaf >= verifiedUpTo(c.mint)) {
13240
+ pend(c, value === c.commitment ? 0 : 2);
13241
+ } else if (value === c.commitment) {
13242
+ verified.push(c);
13243
+ } else {
13244
+ stats.dropped++;
13245
+ rejectedCandidates.add(c);
13246
+ tally(c, "rejected");
13247
+ }
13248
+ }
13249
+ verified.sort((a, b) => a.seq - b.seq);
13250
+ const byLeaf = /* @__PURE__ */ new Map();
13251
+ for (const c of verified) {
13252
+ const key = `${c.mint}:${c.leaf}`;
13253
+ if (byLeaf.has(key)) {
13254
+ stats.dropped++;
13255
+ tally(c, "other");
13256
+ continue;
13257
+ }
13258
+ byLeaf.set(key, c);
13259
+ }
13260
+ const notes = [];
13261
+ const atRisk = [];
13262
+ const spentOut = new Set(knownSpent);
13263
+ const verifiedOut = new Set(knownVerified);
13264
+ const keyChecked = /* @__PURE__ */ new Map();
13265
+ for (const c of byLeaf.values()) {
13266
+ const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
13267
+ keyChecked.set(c.keypair.privateKey, pubOk);
13268
+ if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
13269
+ stats.dropped++;
13270
+ tally(c, "rejected");
13271
+ continue;
13272
+ }
13273
+ tally(c, "kept");
13274
+ verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
13275
+ const utxo = {
13276
+ amount: c.amount,
13277
+ keypair: c.atRisk ? { ...c.keypair } : owner,
13278
+ blinding: c.blinding,
13279
+ mintAddress: c.mint,
13280
+ index: c.leaf,
13281
+ commitment: c.commitment
13282
+ };
13283
+ if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
13284
+ stats.spent++;
13285
+ spentOut.add(c.nullifier);
13286
+ continue;
13287
+ }
13288
+ const note = {
13289
+ kind: c.kind,
13290
+ utxo,
13291
+ signature: bs584.encode(c.signature),
13292
+ legacyExposed: c.atRisk
13293
+ };
13294
+ (c.atRisk ? atRisk : notes).push(note);
13295
+ }
13296
+ const sortNotes = (list) => list.sort((a, b) => a.utxo.mintAddress === b.utxo.mintAddress ? a.utxo.index - b.utxo.index : a.utxo.mintAddress < b.utxo.mintAddress ? -1 : 1);
13297
+ sortNotes(notes);
13298
+ sortNotes(atRisk);
13299
+ const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
13300
+ const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
13301
+ const overflow = pendingList.length - carriedPending.length;
13302
+ if (overflow > 0) {
13303
+ stats.pendingDropped += overflow;
13304
+ ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
13305
+ }
13306
+ for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
13307
+ for (const c of carriedPending) tally(c, "kept");
13308
+ for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
13309
+ let page = targetPage;
13310
+ for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
13311
+ const trees = {};
13312
+ const treeEnd = /* @__PURE__ */ new Map();
13313
+ for (const mint of poolMints) {
13314
+ const start = startTrees.get(mint);
13315
+ const { r, overrides } = replays.get(mint);
13316
+ const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
13317
+ const n = snap.nextIndex;
13318
+ const window2 = [];
13319
+ for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
13320
+ const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
13321
+ if (v === void 0) break;
13322
+ window2.push(hex32(v));
13323
+ }
13324
+ window2.reverse();
13325
+ trees[mint] = {
13326
+ frontier: snap.frontier,
13327
+ pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
13328
+ window: window2.join(""),
13329
+ verified: Math.min(verifiedUpTo(mint), n),
13330
+ overrides: Array.from(overrides.entries()).filter(([leaf]) => leaf >= n && !snap.pending.has(leaf)).sort((a, b) => a[0] - b[0]).slice(0, MAX_OVERRIDES).map(([leaf, v]) => [leaf, hex32(v)]),
13331
+ mismatch: r.mismatch
13332
+ };
13333
+ treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
13334
+ }
13335
+ const pendingLeaves = [];
13336
+ const pendingLeafSeen = /* @__PURE__ */ new Set();
13337
+ for (const c of carriedPending) {
13338
+ const end = treeEnd.get(c.mint);
13339
+ if (!end || c.leaf >= end.nextIndex) continue;
13340
+ const value = streamValue(c.mint, c.leaf);
13341
+ const key = `${c.mint}:${c.leaf}`;
13342
+ if (value === void 0 || pendingLeafSeen.has(key)) continue;
13343
+ pendingLeafSeen.add(key);
13344
+ pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
13345
+ }
13346
+ const keptItems = [];
13347
+ const keptIds = /* @__PURE__ */ new Set();
13348
+ for (const o of ownItems) {
13349
+ const t = outcomeOf.get(o.seq);
13350
+ if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
13351
+ rejectedNow.add(o.id);
13352
+ continue;
13353
+ }
13354
+ if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
13355
+ keptIds.add(o.id);
13356
+ keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
13357
+ }
13358
+ const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
13359
+ const nextCursor = {
13360
+ v: CURSOR_VERSION,
13361
+ epoch: head.epoch.toString(10),
13362
+ page,
13363
+ chain: chainAt.get(page) ?? startChain,
13364
+ watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
13365
+ fullPassSeq: cursor ? fullPassSeq : head.watermark,
13366
+ trees,
13367
+ own: {
13368
+ items: keptItems,
13369
+ verified: Array.from(verifiedOut),
13370
+ spent: Array.from(spentOut),
13371
+ pendingLeaves,
13372
+ rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
13373
+ }
13374
+ };
13375
+ return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
13376
+ } finally {
13377
+ params.signal?.removeEventListener("abort", onCallerAbort);
13378
+ }
13379
+ }
13380
+
11616
13381
  // src/wallet/utxo-wallet.ts
11617
13382
  var UtxoWallet = class _UtxoWallet {
11618
13383
  constructor(viewingKey) {
@@ -11967,7 +13732,7 @@ async function loadWeb3() {
11967
13732
 
11968
13733
  // src/bridge/rail-verify.ts
11969
13734
  import nacl6 from "tweetnacl";
11970
- import { sha256 as sha2565 } from "@noble/hashes/sha256";
13735
+ import { sha256 as sha2567 } from "@noble/hashes/sha256";
11971
13736
  var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
11972
13737
  var b58 = /* @__PURE__ */ (() => {
11973
13738
  const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -12073,7 +13838,7 @@ function canonicalPayloadString(resp) {
12073
13838
  function verifyQuoteSignature(resp) {
12074
13839
  if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
12075
13840
  const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
12076
- const digest = sha2565(new TextEncoder().encode(stable(payload)));
13841
+ const digest = sha2567(new TextEncoder().encode(stable(payload)));
12077
13842
  const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
12078
13843
  const sig = resp.signature.replace(/^ed25519:/, "");
12079
13844
  try {
@@ -12823,13 +14588,13 @@ var DoNotRetry = class extends Error {
12823
14588
  };
12824
14589
  async function withShieldRetries(attempt, hooks = {}) {
12825
14590
  const attempts = hooks.attempts ?? 3;
12826
- const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
14591
+ const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
12827
14592
  let last = "";
12828
14593
  for (let n = 1; n <= attempts; n++) {
12829
14594
  if (n > 1) {
12830
14595
  const delay = retryDelayMs(n);
12831
14596
  hooks.onRetry?.(n, delay, last);
12832
- await sleep4(delay);
14597
+ await sleep5(delay);
12833
14598
  }
12834
14599
  try {
12835
14600
  return await attempt(n);
@@ -12877,6 +14642,10 @@ export {
12877
14642
  MemoryStorageAdapter,
12878
14643
  MerkleTree,
12879
14644
  NATIVE_SOL_MINT,
14645
+ NOTE_INDEX_NO_LEAF,
14646
+ NOTE_INDEX_PAGE_SIZE,
14647
+ NoteIndexFormatError,
14648
+ NoteIndexHeadBehindError,
12880
14649
  ONECLICK_PUBKEY_B58,
12881
14650
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
12882
14651
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -12953,6 +14722,7 @@ export {
12953
14722
  computeChainNoteHash,
12954
14723
  computeExtDataHash,
12955
14724
  computeMerkleRoot,
14725
+ computeNoteIndexChain,
12956
14726
  computeProofForLatestDeposit,
12957
14727
  computeProofFromChain,
12958
14728
  computeSignature,
@@ -13001,6 +14771,8 @@ export {
13001
14771
  discoverSwapRefunds,
13002
14772
  downloadNote,
13003
14773
  encodeDeliveryCarrierMemo,
14774
+ encodeNoteIndexItem,
14775
+ encodeNoteIndexPage,
13004
14776
  encodeNoteSimple,
13005
14777
  encodeRecipientDeliveryNote,
13006
14778
  encryptCompactChainNote,
@@ -13016,6 +14788,8 @@ export {
13016
14788
  fetchCommitments,
13017
14789
  fetchLatestBlockhash,
13018
14790
  fetchLookupTables,
14791
+ fetchNoteIndexHead,
14792
+ fetchNoteIndexPage,
13019
14793
  fetchRiskQuoteInstruction,
13020
14794
  fetchRiskQuoteIx,
13021
14795
  fetchSignaturesForAddress,
@@ -13088,6 +14862,8 @@ export {
13088
14862
  parseDeliveryCarrierMemo,
13089
14863
  parseError,
13090
14864
  parseNote2 as parseNote,
14865
+ parseNoteIndexItem,
14866
+ parseNoteIndexPage,
13091
14867
  parseRelayErrorResponse,
13092
14868
  parseRelayErrorSignature,
13093
14869
  parseTransactionError,
@@ -13109,6 +14885,7 @@ export {
13109
14885
  readMerkleTreeState,
13110
14886
  readRent,
13111
14887
  recipientDeliveryNoteToBase64,
14888
+ recoverNotesFromIndex,
13112
14889
  registerViewingKey,
13113
14890
  relayRequestDigestHex,
13114
14891
  removePendingDeposit,