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

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.cjs CHANGED
@@ -606,6 +606,10 @@ __export(index_exports, {
606
606
  MemoryStorageAdapter: () => MemoryStorageAdapter,
607
607
  MerkleTree: () => MerkleTree,
608
608
  NATIVE_SOL_MINT: () => NATIVE_SOL_MINT,
609
+ NOTE_INDEX_NO_LEAF: () => NOTE_INDEX_NO_LEAF,
610
+ NOTE_INDEX_PAGE_SIZE: () => NOTE_INDEX_PAGE_SIZE,
611
+ NoteIndexFormatError: () => NoteIndexFormatError,
612
+ NoteIndexHeadBehindError: () => NoteIndexHeadBehindError,
609
613
  ONECLICK_PUBKEY_B58: () => ONECLICK_PUBKEY_B58,
610
614
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN: () => RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
611
615
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN: () => RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -682,6 +686,7 @@ __export(index_exports, {
682
686
  computeChainNoteHash: () => computeChainNoteHash,
683
687
  computeExtDataHash: () => computeExtDataHash,
684
688
  computeMerkleRoot: () => computeMerkleRoot,
689
+ computeNoteIndexChain: () => computeNoteIndexChain,
685
690
  computeProofForLatestDeposit: () => computeProofForLatestDeposit,
686
691
  computeProofFromChain: () => computeProofFromChain,
687
692
  computeSignature: () => computeSignature,
@@ -730,6 +735,8 @@ __export(index_exports, {
730
735
  discoverSwapRefunds: () => discoverSwapRefunds,
731
736
  downloadNote: () => downloadNote,
732
737
  encodeDeliveryCarrierMemo: () => encodeDeliveryCarrierMemo,
738
+ encodeNoteIndexItem: () => encodeNoteIndexItem,
739
+ encodeNoteIndexPage: () => encodeNoteIndexPage,
733
740
  encodeNoteSimple: () => encodeNoteSimple,
734
741
  encodeRecipientDeliveryNote: () => encodeRecipientDeliveryNote,
735
742
  encryptCompactChainNote: () => encryptCompactChainNote,
@@ -745,6 +752,8 @@ __export(index_exports, {
745
752
  fetchCommitments: () => fetchCommitments,
746
753
  fetchLatestBlockhash: () => fetchLatestBlockhash,
747
754
  fetchLookupTables: () => fetchLookupTables,
755
+ fetchNoteIndexHead: () => fetchNoteIndexHead,
756
+ fetchNoteIndexPage: () => fetchNoteIndexPage,
748
757
  fetchRiskQuoteInstruction: () => fetchRiskQuoteInstruction,
749
758
  fetchRiskQuoteIx: () => fetchRiskQuoteIx,
750
759
  fetchSignaturesForAddress: () => fetchSignaturesForAddress,
@@ -817,6 +826,8 @@ __export(index_exports, {
817
826
  parseDeliveryCarrierMemo: () => parseDeliveryCarrierMemo,
818
827
  parseError: () => parseError,
819
828
  parseNote: () => parseNote2,
829
+ parseNoteIndexItem: () => parseNoteIndexItem,
830
+ parseNoteIndexPage: () => parseNoteIndexPage,
820
831
  parseRelayErrorResponse: () => parseRelayErrorResponse,
821
832
  parseRelayErrorSignature: () => parseRelayErrorSignature,
822
833
  parseTransactionError: () => parseTransactionError,
@@ -838,6 +849,7 @@ __export(index_exports, {
838
849
  readMerkleTreeState: () => readMerkleTreeState,
839
850
  readRent: () => readRent,
840
851
  recipientDeliveryNoteToBase64: () => recipientDeliveryNoteToBase64,
852
+ recoverNotesFromIndex: () => recoverNotesFromIndex,
841
853
  registerViewingKey: () => registerViewingKey,
842
854
  relayRequestDigestHex: () => relayRequestDigestHex,
843
855
  removePendingDeposit: () => removePendingDeposit,
@@ -1550,7 +1562,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
1550
1562
 
1551
1563
  // src/config/relay.ts
1552
1564
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
1553
- var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
1565
+ var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
1554
1566
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
1555
1567
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
1556
1568
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -1630,7 +1642,7 @@ var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
1630
1642
  // src/relay/clock.ts
1631
1643
  var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
1632
1644
  var MAX_CLOCK_DIVERGENCE_MS = 2e3;
1633
- var MAX_PLAUSIBLE_OFFSET_MS = 365 * 24 * 60 * 60 * 1e3;
1645
+ var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
1634
1646
  var sample = null;
1635
1647
  function monotonicNowMs() {
1636
1648
  const perf = globalThis.performance;
@@ -1717,7 +1729,7 @@ async function relayFetch(url, init, options) {
1717
1729
  assertAllowedRelayOrigin(url);
1718
1730
  const extra = sanitizeExtraHeaders(options?.extraHeaders);
1719
1731
  const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
1720
- observeRelayClock(response);
1732
+ if (options?.observeClock !== false) observeRelayClock(response);
1721
1733
  return response;
1722
1734
  }
1723
1735
  var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
@@ -4843,6 +4855,27 @@ function isRootAccepted(data, rootHex) {
4843
4855
  const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
4844
4856
  return readRootHistory(data).some((r) => r === want);
4845
4857
  }
4858
+ function treeAccountAcceptsRoot(data, rootHex) {
4859
+ const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
4860
+ if (data.length >= ROOT_OFFSET + 32) {
4861
+ const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
4862
+ if (current === want) return true;
4863
+ }
4864
+ return isRootAccepted(data, want);
4865
+ }
4866
+ function readTreeAccountFrontier(data) {
4867
+ if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
4868
+ const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
4869
+ const next = readBigUInt64LE(buf, 32);
4870
+ if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
4871
+ const subtrees = [];
4872
+ for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
4873
+ const offset = SUBTREES_OFFSET + level * 32;
4874
+ subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
4875
+ }
4876
+ const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
4877
+ return { nextIndex: Number(next), subtrees, root };
4878
+ }
4846
4879
 
4847
4880
  // src/proving/merkle.ts
4848
4881
  var import_circomlibjs3 = require("circomlibjs");
@@ -5002,6 +5035,89 @@ var MerkleTree = class _MerkleTree {
5002
5035
  async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
5003
5036
  return MerkleTree.create(height, commitments);
5004
5037
  }
5038
+ var MerkleFrontier = class _MerkleFrontier {
5039
+ constructor(levels, zeros, poseidon3, count, left) {
5040
+ this.levels = levels;
5041
+ this.zeros = zeros;
5042
+ this.poseidon = poseidon3;
5043
+ this.count = count;
5044
+ this.left = left;
5045
+ }
5046
+ static async create(state, levels = MERKLE_TREE_HEIGHT2) {
5047
+ const zeros = await getZeroValues();
5048
+ const poseidon3 = await getPoseidon3();
5049
+ const left = new Array(levels).fill(null);
5050
+ let count = 0;
5051
+ if (state) {
5052
+ if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
5053
+ throw new Error("MerkleFrontierState.nextIndex out of range");
5054
+ }
5055
+ if (!Array.isArray(state.left) || state.left.length !== levels) {
5056
+ throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
5057
+ }
5058
+ count = state.nextIndex;
5059
+ for (let l = 0; l < levels; l++) {
5060
+ const odd = Math.floor(count / 2 ** l) % 2 === 1;
5061
+ const entry = state.left[l];
5062
+ if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
5063
+ if (odd) {
5064
+ if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
5065
+ left[l] = BigInt("0x" + entry);
5066
+ }
5067
+ }
5068
+ }
5069
+ return new _MerkleFrontier(levels, zeros, poseidon3, count, left);
5070
+ }
5071
+ get nextIndex() {
5072
+ return this.count;
5073
+ }
5074
+ /**
5075
+ * The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
5076
+ * present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
5077
+ * With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
5078
+ */
5079
+ leftAt(level) {
5080
+ if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
5081
+ return this.left[level];
5082
+ }
5083
+ hash(a, b) {
5084
+ return this.poseidon.F.toObject(this.poseidon([a, b]));
5085
+ }
5086
+ /** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
5087
+ append(leaves) {
5088
+ if (leaves.length === 0) return;
5089
+ if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
5090
+ let nodes = leaves;
5091
+ for (let l = 0; l < this.levels && nodes.length > 0; l++) {
5092
+ const before = Math.floor(this.count / 2 ** l);
5093
+ const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
5094
+ const parents = [];
5095
+ for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
5096
+ this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
5097
+ nodes = parents;
5098
+ }
5099
+ this.count += leaves.length;
5100
+ }
5101
+ /** The root of the first `nextIndex` leaves, zero-padded to the right. */
5102
+ root() {
5103
+ let partial = this.zeros[0];
5104
+ for (let l = 0; l < this.levels; l++) {
5105
+ const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
5106
+ if (odd) partial = this.hash(this.left[l], partial);
5107
+ else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
5108
+ }
5109
+ return partial;
5110
+ }
5111
+ toState() {
5112
+ return {
5113
+ nextIndex: this.count,
5114
+ left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
5115
+ };
5116
+ }
5117
+ clone() {
5118
+ return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
5119
+ }
5120
+ };
5005
5121
 
5006
5122
  // src/relay/client.ts
5007
5123
  init_address();
@@ -5506,38 +5622,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
5506
5622
  const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
5507
5623
  return new Uint8Array(plaintext);
5508
5624
  }
5509
- async function deriveAesKeyAndNonce(nk, commitmentHex) {
5625
+ async function importNkHkdfKey(nk) {
5510
5626
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
5511
5627
  throw new Error("nk must be 32 bytes");
5512
5628
  }
5629
+ return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
5630
+ }
5631
+ async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
5513
5632
  const subtle = getSubtleCrypto2();
5514
- const ikm = await subtle.importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
5515
- const salt = hexToBytes32(commitmentHex);
5516
- const keyBits = await subtle.deriveBits(
5517
- {
5518
- name: "HKDF",
5519
- hash: "SHA-256",
5520
- salt: toArrayBuffer2(salt),
5521
- info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
5522
- },
5523
- ikm,
5524
- 256
5525
- );
5526
- const nonceBits = await subtle.deriveBits(
5527
- {
5528
- name: "HKDF",
5529
- hash: "SHA-256",
5530
- salt: toArrayBuffer2(salt),
5531
- info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
5532
- },
5533
- ikm,
5534
- 96
5535
- );
5633
+ const [keyBits, nonceBits] = await Promise.all([
5634
+ subtle.deriveBits(
5635
+ {
5636
+ name: "HKDF",
5637
+ hash: "SHA-256",
5638
+ salt: toArrayBuffer2(salt),
5639
+ info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
5640
+ },
5641
+ ikm,
5642
+ 256
5643
+ ),
5644
+ subtle.deriveBits(
5645
+ {
5646
+ name: "HKDF",
5647
+ hash: "SHA-256",
5648
+ salt: toArrayBuffer2(salt),
5649
+ info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
5650
+ },
5651
+ ikm,
5652
+ 96
5653
+ )
5654
+ ]);
5536
5655
  return {
5537
5656
  key: new Uint8Array(keyBits),
5538
5657
  nonce: new Uint8Array(nonceBits)
5539
5658
  };
5540
5659
  }
5660
+ async function deriveAesKeyAndNonce(nk, commitmentHex) {
5661
+ const ikm = await importNkHkdfKey(nk);
5662
+ return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
5663
+ }
5664
+ function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
5665
+ if (version === NOTE_VERSION_V4) {
5666
+ if (plaintext.length !== PLAINTEXT_LEN_V4) {
5667
+ throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
5668
+ }
5669
+ return {
5670
+ timestamp: readU64LE(plaintext, 0),
5671
+ commitment: commitmentHex.toLowerCase(),
5672
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
5673
+ outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
5674
+ outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
5675
+ isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
5676
+ };
5677
+ }
5678
+ if (version === NOTE_VERSION_V3) {
5679
+ if (plaintext.length !== PLAINTEXT_LEN_V3) {
5680
+ throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
5681
+ }
5682
+ return {
5683
+ timestamp: readU64LE(plaintext, 0),
5684
+ commitment: commitmentHex.toLowerCase(),
5685
+ noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
5686
+ };
5687
+ }
5688
+ if (plaintext.length !== PLAINTEXT_LEN_V2) {
5689
+ throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
5690
+ }
5691
+ return {
5692
+ timestamp: readU64LE(plaintext, 0),
5693
+ commitment: commitmentHex.toLowerCase()
5694
+ };
5695
+ }
5541
5696
  async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
5542
5697
  if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
5543
5698
  throw new Error("nk must be 32 bytes");
@@ -5601,36 +5756,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
5601
5756
  try {
5602
5757
  const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
5603
5758
  const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
5604
- if (version === NOTE_VERSION_V4) {
5605
- if (plaintext.length !== PLAINTEXT_LEN_V4) {
5606
- throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
5607
- }
5608
- return {
5609
- timestamp: readU64LE(plaintext, 0),
5610
- commitment: commitment.toLowerCase(),
5611
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
5612
- outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
5613
- outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
5614
- isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
5615
- };
5616
- }
5617
- if (version === NOTE_VERSION_V3) {
5618
- if (plaintext.length !== PLAINTEXT_LEN_V3) {
5619
- throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
5620
- }
5621
- return {
5622
- timestamp: readU64LE(plaintext, 0),
5623
- commitment: commitment.toLowerCase(),
5624
- noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
5625
- };
5626
- }
5627
- if (plaintext.length !== PLAINTEXT_LEN_V2) {
5628
- throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
5629
- }
5630
- return {
5631
- timestamp: readU64LE(plaintext, 0),
5632
- commitment: commitment.toLowerCase()
5633
- };
5759
+ return decodeChainNotePlaintext(version, plaintext, commitment);
5634
5760
  } catch (error) {
5635
5761
  lastError = error;
5636
5762
  }
@@ -5639,6 +5765,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
5639
5765
  `Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
5640
5766
  );
5641
5767
  }
5768
+ async function createCompactChainNoteDecryptor(nk) {
5769
+ const ikm = await importNkHkdfKey(nk);
5770
+ return async (noteBytes, commitment) => {
5771
+ if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
5772
+ if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
5773
+ const version = noteBytes[0];
5774
+ if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
5775
+ return null;
5776
+ }
5777
+ try {
5778
+ const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
5779
+ const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
5780
+ let hex = "";
5781
+ for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
5782
+ return decodeChainNotePlaintext(version, plaintext, hex);
5783
+ } catch {
5784
+ return null;
5785
+ }
5786
+ };
5787
+ }
5642
5788
  function chainNoteToBase64(noteBytes) {
5643
5789
  return Buffer.from(noteBytes).toString("base64");
5644
5790
  }
@@ -5735,6 +5881,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
5735
5881
  return null;
5736
5882
  }
5737
5883
  }
5884
+ var X25519_PKCS8_PREFIX = Uint8Array.from([
5885
+ 48,
5886
+ 46,
5887
+ 2,
5888
+ 1,
5889
+ 0,
5890
+ 48,
5891
+ 5,
5892
+ 6,
5893
+ 3,
5894
+ 43,
5895
+ 101,
5896
+ 110,
5897
+ 4,
5898
+ 34,
5899
+ 4,
5900
+ 32
5901
+ ]);
5902
+ var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
5903
+ function decodeOpened(plaintext) {
5904
+ if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
5905
+ return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
5906
+ }
5907
+ async function createRecipientDeliveryOpener(viewingSecretKey) {
5908
+ if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
5909
+ throw new Error("viewingSecretKey must be 32 bytes");
5910
+ }
5911
+ const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
5912
+ const subtle = globalThis.crypto?.subtle;
5913
+ const hsalsa = import_tweetnacl4.default.lowlevel?.crypto_core_hsalsa20;
5914
+ if (!subtle || typeof hsalsa !== "function") return slow;
5915
+ let privateKey;
5916
+ const sharedKey = async (ephemeralPk) => {
5917
+ const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
5918
+ const shared = new Uint8Array(
5919
+ await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
5920
+ );
5921
+ const key = new Uint8Array(32);
5922
+ hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
5923
+ return key;
5924
+ };
5925
+ try {
5926
+ const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
5927
+ pkcs8.set(X25519_PKCS8_PREFIX);
5928
+ pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
5929
+ privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
5930
+ const probe = import_tweetnacl4.default.box.keyPair().publicKey;
5931
+ const fast = await sharedKey(probe);
5932
+ const reference = import_tweetnacl4.default.box.before(probe, viewingSecretKey);
5933
+ if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
5934
+ } catch {
5935
+ return slow;
5936
+ }
5937
+ return async (envelope) => {
5938
+ if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
5939
+ const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
5940
+ const nonce = envelope.subarray(
5941
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
5942
+ RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
5943
+ );
5944
+ const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
5945
+ let key;
5946
+ try {
5947
+ key = await sharedKey(ephemeralPk);
5948
+ } catch {
5949
+ return openRecipientDeliveryNote(envelope, viewingSecretKey);
5950
+ }
5951
+ try {
5952
+ return decodeOpened(import_tweetnacl4.default.secretbox.open(ciphertext, nonce, key));
5953
+ } catch {
5954
+ return null;
5955
+ }
5956
+ };
5957
+ }
5738
5958
  function recipientDeliveryNoteToBase64(envelope) {
5739
5959
  return Buffer.from(envelope).toString("base64");
5740
5960
  }
@@ -12495,6 +12715,1636 @@ function formatComplianceCsv(report) {
12495
12715
  return header + rows;
12496
12716
  }
12497
12717
 
12718
+ // src/relay/note-index-format.ts
12719
+ var import_sha25 = require("@noble/hashes/sha2");
12720
+ init_address();
12721
+ init_utxo();
12722
+ var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
12723
+ var NOTE_INDEX_FORMAT_VERSION = 1;
12724
+ var NOTE_INDEX_PAGE_SIZE = 1024;
12725
+ var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
12726
+ var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
12727
+ var NOTE_INDEX_HEADER_LEN = 68;
12728
+ var NOTE_INDEX_KIND_TX = 1;
12729
+ var NOTE_INDEX_KIND_DELIVERY = 2;
12730
+ var NOTE_INDEX_KIND_SWAP_REFUND = 3;
12731
+ var NOTE_SOURCE_NONE = 0;
12732
+ var NOTE_SOURCE_CARRIER = 2;
12733
+ var ITEM_HEADER_LEN = 3;
12734
+ var TX_FIXED_LEN = 263;
12735
+ var DELIVERY_BODY_LEN = 256;
12736
+ var SWAP_REFUND_BODY_LEN = 184;
12737
+ var MAX_UNKNOWN_BODY_LEN = 1024;
12738
+ var DELIVERY_ENVELOPE_LEN = 112;
12739
+ var SIGNATURE_LEN = 64;
12740
+ var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
12741
+ [25, 2],
12742
+ [57, 3],
12743
+ [98, 4]
12744
+ ]);
12745
+ var COMPLETE_FLAG = 1;
12746
+ var U64_MAX2 = (1n << 64n) - 1n;
12747
+ var U32_MAX = 4294967295;
12748
+ var MAX_LEAF_INDEX = (1n << 32n) - 1n;
12749
+ var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
12750
+ var NoteIndexFormatError = class extends Error {
12751
+ constructor(message) {
12752
+ super(`Note index format error: ${message}`);
12753
+ this.name = "NoteIndexFormatError";
12754
+ }
12755
+ };
12756
+ function isAllZero2(bytes) {
12757
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
12758
+ return true;
12759
+ }
12760
+ function bytesEqual(a, b) {
12761
+ if (a.length !== b.length) return false;
12762
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
12763
+ return true;
12764
+ }
12765
+ function checkLeafPair(commitment, leaf, label) {
12766
+ if (isAllZero2(commitment)) {
12767
+ if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
12768
+ return;
12769
+ }
12770
+ if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
12771
+ }
12772
+ var Reader = class {
12773
+ constructor(bytes, start, end) {
12774
+ this.bytes = bytes;
12775
+ this.end = end;
12776
+ this.offset = start;
12777
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12778
+ }
12779
+ take(len) {
12780
+ if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
12781
+ const at = this.offset;
12782
+ this.offset += len;
12783
+ return at;
12784
+ }
12785
+ u8() {
12786
+ return this.bytes[this.take(1)];
12787
+ }
12788
+ u32() {
12789
+ return this.view.getUint32(this.take(4), true);
12790
+ }
12791
+ u64() {
12792
+ return this.view.getBigUint64(this.take(8), true);
12793
+ }
12794
+ i64() {
12795
+ return this.view.getBigInt64(this.take(8), true);
12796
+ }
12797
+ raw(len) {
12798
+ const at = this.take(len);
12799
+ return this.bytes.slice(at, at + len);
12800
+ }
12801
+ get position() {
12802
+ return this.offset;
12803
+ }
12804
+ };
12805
+ function parseTx(r, bodyLen) {
12806
+ const mint = r.raw(32);
12807
+ const slot = r.u64();
12808
+ const blockPos = r.u32();
12809
+ const ixTag = r.u8();
12810
+ if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
12811
+ const publicAmount = r.i64();
12812
+ const nullifier0 = r.raw(32);
12813
+ const nullifier1 = r.raw(32);
12814
+ const comm0 = r.raw(32);
12815
+ const leaf0 = r.u64();
12816
+ const comm1 = r.raw(32);
12817
+ const leaf1 = r.u64();
12818
+ const noteSource = r.u8();
12819
+ if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
12820
+ const noteLen = r.u8();
12821
+ if (noteSource === NOTE_SOURCE_NONE) {
12822
+ if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
12823
+ } else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
12824
+ throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
12825
+ }
12826
+ if (bodyLen !== TX_FIXED_LEN + noteLen) {
12827
+ throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
12828
+ }
12829
+ const note = r.raw(noteLen);
12830
+ if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
12831
+ throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
12832
+ }
12833
+ const signature = r.raw(SIGNATURE_LEN);
12834
+ checkLeafPair(comm0, leaf0, "TX comm0");
12835
+ checkLeafPair(comm1, leaf1, "TX comm1");
12836
+ return {
12837
+ kind: 1,
12838
+ mint,
12839
+ slot,
12840
+ blockPos,
12841
+ ixTag,
12842
+ publicAmount,
12843
+ nullifier0,
12844
+ nullifier1,
12845
+ comm0,
12846
+ leaf0,
12847
+ comm1,
12848
+ leaf1,
12849
+ noteSource,
12850
+ note,
12851
+ signature
12852
+ };
12853
+ }
12854
+ function parseDelivery(r) {
12855
+ const mint = r.raw(32);
12856
+ const slot = r.u64();
12857
+ const commitment = r.raw(32);
12858
+ const leaf = r.u64();
12859
+ const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
12860
+ const signature = r.raw(SIGNATURE_LEN);
12861
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
12862
+ checkLeafPair(commitment, leaf, "DELIVERY");
12863
+ return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
12864
+ }
12865
+ function parseSwapRefund(r) {
12866
+ const mint = r.raw(32);
12867
+ if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
12868
+ const slot = r.u64();
12869
+ const commitment = r.raw(32);
12870
+ const leaf = r.u64();
12871
+ const amountAfterFee = r.u64();
12872
+ const nullifier0 = r.raw(32);
12873
+ const signature = r.raw(SIGNATURE_LEN);
12874
+ if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
12875
+ checkLeafPair(commitment, leaf, "SWAP_REFUND");
12876
+ return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
12877
+ }
12878
+ function parseNoteIndexPage(bytes, expect, options = {}) {
12879
+ if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
12880
+ if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
12881
+ throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
12882
+ }
12883
+ if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12884
+ for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
12885
+ if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
12886
+ }
12887
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12888
+ const version = bytes[4];
12889
+ if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
12890
+ const flags = bytes[5];
12891
+ if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
12892
+ if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
12893
+ const epoch = view.getBigUint64(8, true);
12894
+ const page = view.getBigUint64(16, true);
12895
+ const firstSeq = view.getBigUint64(24, true);
12896
+ const count = view.getUint32(32, true);
12897
+ const prevChain = bytes.slice(36, 68);
12898
+ const complete = (flags & COMPLETE_FLAG) !== 0;
12899
+ if (expect) {
12900
+ if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
12901
+ if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
12902
+ }
12903
+ if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
12904
+ if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
12905
+ if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
12906
+ throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
12907
+ }
12908
+ const items = [];
12909
+ const rawItems = [];
12910
+ const itemPositions = [];
12911
+ let skippedUnknown = 0;
12912
+ let skippedMalformed = 0;
12913
+ let offset = NOTE_INDEX_HEADER_LEN;
12914
+ for (let i = 0; i < count; i++) {
12915
+ if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
12916
+ const kind = bytes[offset];
12917
+ const bodyLen = view.getUint16(offset + 1, true);
12918
+ const bodyStart = offset + ITEM_HEADER_LEN;
12919
+ const bodyEnd = bodyStart + bodyLen;
12920
+ if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12921
+ if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
12922
+ if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12923
+ skippedUnknown++;
12924
+ offset = bodyEnd;
12925
+ continue;
12926
+ }
12927
+ let item;
12928
+ try {
12929
+ item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
12930
+ } catch (error) {
12931
+ if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
12932
+ skippedMalformed++;
12933
+ offset = bodyEnd;
12934
+ continue;
12935
+ }
12936
+ items.push(item);
12937
+ rawItems.push(bytes.slice(offset, bodyEnd));
12938
+ itemPositions.push(i);
12939
+ offset = bodyEnd;
12940
+ }
12941
+ if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12942
+ return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
12943
+ }
12944
+ function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
12945
+ const bodyLen = bodyEnd - bodyStart;
12946
+ const r = new Reader(bytes, bodyStart, bodyEnd);
12947
+ let item;
12948
+ if (kind === NOTE_INDEX_KIND_TX) {
12949
+ if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12950
+ item = parseTx(r, bodyLen);
12951
+ } else if (kind === NOTE_INDEX_KIND_DELIVERY) {
12952
+ if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12953
+ item = parseDelivery(r);
12954
+ } else {
12955
+ if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12956
+ item = parseSwapRefund(r);
12957
+ }
12958
+ if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12959
+ return item;
12960
+ }
12961
+ function parseNoteIndexItem(raw) {
12962
+ if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
12963
+ const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
12964
+ const kind = raw[0];
12965
+ const bodyLen = view.getUint16(1, true);
12966
+ if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
12967
+ const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
12968
+ let item;
12969
+ if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
12970
+ else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
12971
+ else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
12972
+ else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
12973
+ if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
12974
+ return item;
12975
+ }
12976
+ function computeNoteIndexChain(prevChain, pageBytes) {
12977
+ if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
12978
+ if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
12979
+ const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
12980
+ const input = new Uint8Array(32 + items.length);
12981
+ input.set(prevChain);
12982
+ input.set(items, 32);
12983
+ return (0, import_sha25.sha256)(input);
12984
+ }
12985
+ var Writer = class {
12986
+ constructor() {
12987
+ this.chunks = [];
12988
+ this.length = 0;
12989
+ }
12990
+ push(bytes) {
12991
+ this.chunks.push(bytes);
12992
+ this.length += bytes.length;
12993
+ }
12994
+ u8(v) {
12995
+ if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
12996
+ this.push(Uint8Array.of(v));
12997
+ }
12998
+ u16(v) {
12999
+ if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
13000
+ const b = new Uint8Array(2);
13001
+ new DataView(b.buffer).setUint16(0, v, true);
13002
+ this.push(b);
13003
+ }
13004
+ u32(v) {
13005
+ if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
13006
+ const b = new Uint8Array(4);
13007
+ new DataView(b.buffer).setUint32(0, v, true);
13008
+ this.push(b);
13009
+ }
13010
+ u64(v) {
13011
+ if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
13012
+ const b = new Uint8Array(8);
13013
+ new DataView(b.buffer).setBigUint64(0, v, true);
13014
+ this.push(b);
13015
+ }
13016
+ i64(v) {
13017
+ if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
13018
+ const b = new Uint8Array(8);
13019
+ new DataView(b.buffer).setBigInt64(0, v, true);
13020
+ this.push(b);
13021
+ }
13022
+ fixed(bytes, len, label) {
13023
+ if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
13024
+ this.push(bytes);
13025
+ }
13026
+ finish() {
13027
+ const out = new Uint8Array(this.length);
13028
+ let off = 0;
13029
+ for (const c of this.chunks) {
13030
+ out.set(c, off);
13031
+ off += c.length;
13032
+ }
13033
+ return out;
13034
+ }
13035
+ };
13036
+ function encodeItemBody(item) {
13037
+ const w = new Writer();
13038
+ switch (item.kind) {
13039
+ case NOTE_INDEX_KIND_TX: {
13040
+ w.fixed(item.mint, 32, "mint");
13041
+ w.u64(item.slot);
13042
+ w.u32(item.blockPos);
13043
+ w.u8(item.ixTag);
13044
+ w.i64(item.publicAmount);
13045
+ w.fixed(item.nullifier0, 32, "nullifier0");
13046
+ w.fixed(item.nullifier1, 32, "nullifier1");
13047
+ w.fixed(item.comm0, 32, "comm0");
13048
+ w.u64(item.leaf0);
13049
+ w.fixed(item.comm1, 32, "comm1");
13050
+ w.u64(item.leaf1);
13051
+ w.u8(item.noteSource);
13052
+ const noteLen = item.note.length;
13053
+ if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
13054
+ throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
13055
+ }
13056
+ w.u8(noteLen);
13057
+ w.push(item.note);
13058
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13059
+ break;
13060
+ }
13061
+ case NOTE_INDEX_KIND_DELIVERY:
13062
+ w.fixed(item.mint, 32, "mint");
13063
+ w.u64(item.slot);
13064
+ w.fixed(item.commitment, 32, "commitment");
13065
+ w.u64(item.leaf);
13066
+ w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
13067
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13068
+ break;
13069
+ case NOTE_INDEX_KIND_SWAP_REFUND:
13070
+ w.fixed(item.mint, 32, "mint");
13071
+ w.u64(item.slot);
13072
+ w.fixed(item.commitment, 32, "commitment");
13073
+ w.u64(item.leaf);
13074
+ w.u64(item.amountAfterFee);
13075
+ w.fixed(item.nullifier0, 32, "nullifier0");
13076
+ w.fixed(item.signature, SIGNATURE_LEN, "signature");
13077
+ break;
13078
+ default:
13079
+ throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
13080
+ }
13081
+ return w.finish();
13082
+ }
13083
+ function encodeNoteIndexItem(item) {
13084
+ const body = encodeItemBody(item);
13085
+ const w = new Writer();
13086
+ w.u8(item.kind);
13087
+ w.u16(body.length);
13088
+ w.push(body);
13089
+ return w.finish();
13090
+ }
13091
+ function encodeNoteIndexPage(params) {
13092
+ const items = params.items ?? [];
13093
+ if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
13094
+ const w = new Writer();
13095
+ w.push(NOTE_INDEX_MAGIC);
13096
+ w.u8(NOTE_INDEX_FORMAT_VERSION);
13097
+ w.u8(params.complete ? COMPLETE_FLAG : 0);
13098
+ w.u16(0);
13099
+ w.u64(BigInt(params.epoch));
13100
+ w.u64(BigInt(params.page));
13101
+ w.u64(BigInt(params.firstSeq));
13102
+ w.u32(items.length);
13103
+ w.fixed(params.prevChain, 32, "prevChain");
13104
+ for (const item of items) w.push(encodeNoteIndexItem(item));
13105
+ return w.finish();
13106
+ }
13107
+
13108
+ // src/relay/note-index-client.ts
13109
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
13110
+ var DEFAULT_MAX_RETRIES2 = 3;
13111
+ var RETRY_BASE_DELAY_MS = 500;
13112
+ var U64_MAX3 = (1n << 64n) - 1n;
13113
+ function joinPath(relayUrl, path) {
13114
+ const url = new URL(relayUrl);
13115
+ url.pathname = url.pathname.replace(/\/$/, "") + path;
13116
+ return url;
13117
+ }
13118
+ function abortError() {
13119
+ const error = new Error("Note index request aborted");
13120
+ error.name = "AbortError";
13121
+ return error;
13122
+ }
13123
+ function sleep4(ms, signal) {
13124
+ return new Promise((resolve, reject) => {
13125
+ if (signal?.aborted) return reject(abortError());
13126
+ const timer = setTimeout(() => {
13127
+ signal?.removeEventListener("abort", onAbort);
13128
+ resolve();
13129
+ }, ms);
13130
+ const onAbort = () => {
13131
+ clearTimeout(timer);
13132
+ reject(abortError());
13133
+ };
13134
+ signal?.addEventListener("abort", onAbort, { once: true });
13135
+ });
13136
+ }
13137
+ var RetryableStatusError = class extends Error {
13138
+ };
13139
+ var HttpStatusError = class extends Error {
13140
+ constructor(status, message) {
13141
+ super(message);
13142
+ this.status = status;
13143
+ this.name = "HttpStatusError";
13144
+ }
13145
+ };
13146
+ async function requestWithRetry(url, options, read) {
13147
+ assertAllowedRelayOrigin(url);
13148
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
13149
+ const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
13150
+ let lastError;
13151
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
13152
+ if (options.signal?.aborted) throw abortError();
13153
+ const controller = new AbortController();
13154
+ const onAbort = () => controller.abort();
13155
+ options.signal?.addEventListener("abort", onAbort, { once: true });
13156
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
13157
+ try {
13158
+ const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
13159
+ if (response.status === 429 || response.status >= 500) {
13160
+ throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
13161
+ }
13162
+ return await read(response, controller.signal);
13163
+ } catch (error) {
13164
+ if (options.signal?.aborted) throw abortError();
13165
+ const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
13166
+ if (!retryable || attempt >= maxRetries) throw error;
13167
+ lastError = error;
13168
+ await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
13169
+ } finally {
13170
+ clearTimeout(timer);
13171
+ options.signal?.removeEventListener("abort", onAbort);
13172
+ }
13173
+ }
13174
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
13175
+ }
13176
+ async function readBoundedBody(response, maxBytes) {
13177
+ const declaredHeader = response.headers?.get?.("content-length") ?? null;
13178
+ const declared = declaredHeader === null ? NaN : Number(declaredHeader);
13179
+ if (Number.isFinite(declared) && declared > maxBytes) {
13180
+ throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
13181
+ }
13182
+ const reader = response.body?.getReader?.();
13183
+ if (!reader) {
13184
+ const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
13185
+ if (!Number.isSafeInteger(declared) || declared < 0) {
13186
+ throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
13187
+ }
13188
+ if (encoding !== "" && encoding !== "identity") {
13189
+ throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
13190
+ }
13191
+ const buffer = new Uint8Array(await response.arrayBuffer());
13192
+ if (buffer.length > maxBytes || buffer.length !== declared) {
13193
+ throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
13194
+ }
13195
+ return buffer;
13196
+ }
13197
+ const chunks = [];
13198
+ let total = 0;
13199
+ for (; ; ) {
13200
+ const { done, value } = await reader.read();
13201
+ if (done) break;
13202
+ total += value.length;
13203
+ if (total > maxBytes) {
13204
+ await reader.cancel().catch(() => void 0);
13205
+ throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
13206
+ }
13207
+ chunks.push(value);
13208
+ }
13209
+ const out = new Uint8Array(total);
13210
+ let off = 0;
13211
+ for (const c of chunks) {
13212
+ out.set(c, off);
13213
+ off += c.length;
13214
+ }
13215
+ return out;
13216
+ }
13217
+ function isNonNegativeSafeInteger(value) {
13218
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
13219
+ }
13220
+ async function fetchNoteIndexHead(relayUrl, options = {}) {
13221
+ const url = joinPath(relayUrl, "/note-index/v1/head").toString();
13222
+ const raw = await requestWithRetry(url, options, async (response) => {
13223
+ if (!response.ok) {
13224
+ throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
13225
+ }
13226
+ const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
13227
+ try {
13228
+ return JSON.parse(text);
13229
+ } catch {
13230
+ throw new NoteIndexFormatError("head is not JSON");
13231
+ }
13232
+ });
13233
+ if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
13234
+ if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
13235
+ throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
13236
+ }
13237
+ if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
13238
+ throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
13239
+ }
13240
+ if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
13241
+ throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
13242
+ }
13243
+ if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
13244
+ throw new NoteIndexFormatError(
13245
+ `complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
13246
+ );
13247
+ }
13248
+ if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
13249
+ throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
13250
+ }
13251
+ if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
13252
+ throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
13253
+ }
13254
+ return {
13255
+ format: 1,
13256
+ epoch: BigInt(raw.epoch),
13257
+ pageSize: NOTE_INDEX_PAGE_SIZE,
13258
+ watermark: raw.watermark,
13259
+ completePages: raw.complete_pages,
13260
+ chainTip: raw.chain_tip.toLowerCase()
13261
+ };
13262
+ }
13263
+ async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
13264
+ if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
13265
+ if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
13266
+ const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
13267
+ return requestWithRetry(url, options, async (response) => {
13268
+ if (!response.ok) {
13269
+ throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
13270
+ }
13271
+ return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
13272
+ });
13273
+ }
13274
+
13275
+ // src/scanning/note-index.ts
13276
+ var import_bs584 = __toESM(require("bs58"), 1);
13277
+ var import_sha26 = require("@noble/hashes/sha2");
13278
+ init_address();
13279
+ init_utxo();
13280
+ var bs584 = import_bs584.default.default || import_bs584.default;
13281
+ var CURSOR_VERSION = 2;
13282
+ var DEFAULT_CONCURRENCY = 6;
13283
+ var MAX_CONCURRENCY = 32;
13284
+ var ITEM_BATCH = 64;
13285
+ var CURSOR_PAGE_ALIGN = 8;
13286
+ var MAX_PERSISTED_PENDING_LEAVES = 4096;
13287
+ var MAX_CARRIED_PENDING = 256;
13288
+ var MAX_REJECTED_IDS = 1024;
13289
+ var LEAF_WINDOW = 512;
13290
+ var MAX_OVERRIDES = 256;
13291
+ var MAX_CURSOR_OWN_ITEMS = 65536;
13292
+ var MAX_LEGACY_VIEWING_KEYS = 8;
13293
+ var MAX_CURSOR_KEYS = 131072;
13294
+ var MAX_CURSOR_POOLS = 256;
13295
+ var MAX_CURSOR_PAGE = 2 ** 32;
13296
+ var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
13297
+ var ZERO_CHAIN = "00".repeat(32);
13298
+ var U64_MAX4 = (1n << 64n) - 1n;
13299
+ var NoteIndexHeadBehindError = class extends Error {
13300
+ constructor(cursorWatermark, headWatermark) {
13301
+ super(
13302
+ `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`
13303
+ );
13304
+ this.cursorWatermark = cursorWatermark;
13305
+ this.headWatermark = headWatermark;
13306
+ this.retryable = true;
13307
+ this.name = "NoteIndexHeadBehindError";
13308
+ }
13309
+ };
13310
+ var FullPassSignal = class {
13311
+ constructor(reason) {
13312
+ this.reason = reason;
13313
+ }
13314
+ };
13315
+ function abortError2() {
13316
+ const error = new Error("recoverNotesFromIndex aborted");
13317
+ error.name = "AbortError";
13318
+ return error;
13319
+ }
13320
+ function bytesToBigint3(bytes) {
13321
+ let v = 0n;
13322
+ for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
13323
+ return v;
13324
+ }
13325
+ function toHex2(bytes) {
13326
+ let s = "";
13327
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
13328
+ return s;
13329
+ }
13330
+ function fromHex(hex) {
13331
+ return Uint8Array.from(Buffer.from(hex, "hex"));
13332
+ }
13333
+ function hex32(v) {
13334
+ return v.toString(16).padStart(64, "0");
13335
+ }
13336
+ function isAllZero3(bytes) {
13337
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
13338
+ return true;
13339
+ }
13340
+ function floorAlign(page) {
13341
+ return page - page % CURSOR_PAGE_ALIGN;
13342
+ }
13343
+ function verifiedKey(mint, leaf, commitment) {
13344
+ return `${mint}:${leaf}:${hex32(commitment)}`;
13345
+ }
13346
+ function itemIdentity(raw) {
13347
+ return toHex2((0, import_sha26.sha256)(raw).subarray(0, 16));
13348
+ }
13349
+ var LeafBuffer = class {
13350
+ constructor() {
13351
+ this.bytes = new Uint8Array(32 * 1024);
13352
+ this.view = new DataView(this.bytes.buffer);
13353
+ this.count = 0;
13354
+ }
13355
+ get length() {
13356
+ return this.count;
13357
+ }
13358
+ push(values) {
13359
+ const need = (this.count + values.length) * 32;
13360
+ if (need > this.bytes.length) {
13361
+ let size = this.bytes.length;
13362
+ while (size < need) size *= 2;
13363
+ const next = new Uint8Array(size);
13364
+ next.set(this.bytes.subarray(0, this.count * 32));
13365
+ this.bytes = next;
13366
+ this.view = new DataView(next.buffer);
13367
+ }
13368
+ for (const v of values) {
13369
+ const o = this.count * 32;
13370
+ this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
13371
+ this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
13372
+ this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
13373
+ this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
13374
+ this.count++;
13375
+ }
13376
+ }
13377
+ get(i) {
13378
+ if (i < 0 || i >= this.count) return void 0;
13379
+ const o = i * 32;
13380
+ return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
13381
+ }
13382
+ };
13383
+ async function trialItem(item, trials) {
13384
+ for (const trial of trials) {
13385
+ if (trial.legacy && item.kind === 2) continue;
13386
+ const opened = await trialItemWith(item, trial);
13387
+ if (opened) return { ...opened, trial };
13388
+ }
13389
+ return null;
13390
+ }
13391
+ async function trialItemIsolated(item, trials, stats) {
13392
+ try {
13393
+ return await trialItem(item, trials);
13394
+ } catch {
13395
+ stats.skipped++;
13396
+ return null;
13397
+ }
13398
+ }
13399
+ async function trialItemWith(item, trial) {
13400
+ if (item.kind === 1) {
13401
+ if (item.note.length === 0) return null;
13402
+ let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
13403
+ if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
13404
+ return note ? { note } : null;
13405
+ }
13406
+ if (item.kind === 2) {
13407
+ const delivery = await trial.open(item.envelope);
13408
+ return delivery ? { delivery } : null;
13409
+ }
13410
+ if (item.amountAfterFee === 0n) return null;
13411
+ const refund = await matchSwapRefundLeaf({
13412
+ viewingKeyNk: trial.nk,
13413
+ inputNullifier: item.nullifier0,
13414
+ amountAfterFee: item.amountAfterFee,
13415
+ commitment: item.commitment,
13416
+ ownerUtxoKeypair: trial.owner
13417
+ });
13418
+ return refund ? { refund } : null;
13419
+ }
13420
+ function txOutputs(item) {
13421
+ const out = [toHex2(item.comm0)];
13422
+ if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
13423
+ return out;
13424
+ }
13425
+ function leafOfTxOutput(item, commitment) {
13426
+ if (!isAllZero3(item.comm0) && commitment === bytesToBigint3(item.comm0)) return Number(item.leaf0);
13427
+ if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
13428
+ return null;
13429
+ }
13430
+ function changeBlindingOrNull(nk, noteSalt, outputIndex) {
13431
+ try {
13432
+ return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
13433
+ } catch {
13434
+ return null;
13435
+ }
13436
+ }
13437
+ async function matchOwnItems(own, owner, onReject, onSkip) {
13438
+ const candidates = [];
13439
+ const claimed = /* @__PURE__ */ new Set();
13440
+ const byNullifier = /* @__PURE__ */ new Map();
13441
+ const legacyKeys = /* @__PURE__ */ new Map();
13442
+ const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
13443
+ const spendsOf = /* @__PURE__ */ new Map();
13444
+ const byOutKey = /* @__PURE__ */ new Map();
13445
+ const index = (map, key, o) => {
13446
+ const list = map.get(key);
13447
+ if (list) list.push(o);
13448
+ else map.set(key, [o]);
13449
+ };
13450
+ for (const o of ownTxs) {
13451
+ for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
13452
+ if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
13453
+ }
13454
+ const queue = [];
13455
+ const queued = /* @__PURE__ */ new Set();
13456
+ const enqueue = (o) => {
13457
+ if (queued.has(o)) return;
13458
+ queued.add(o);
13459
+ queue.push(o);
13460
+ };
13461
+ const add = async (o, c) => {
13462
+ const nullifier = hex32(
13463
+ await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
13464
+ );
13465
+ const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
13466
+ candidates.push(full);
13467
+ if (!byNullifier.has(nullifier)) {
13468
+ byNullifier.set(nullifier, full);
13469
+ for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
13470
+ }
13471
+ if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
13472
+ legacyKeys.set(c.keypair.publicKey, c.keypair);
13473
+ for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
13474
+ }
13475
+ };
13476
+ const tryDeposit = async (o, item, amount) => {
13477
+ const note = o.note;
13478
+ const mint = addressFromBytes(item.mint);
13479
+ const deposit = await matchDepositNote({
13480
+ viewingKeyNk: o.trial.nk,
13481
+ noteSalt: note.noteSalt,
13482
+ amount,
13483
+ mintAddress: mint,
13484
+ outputCommitments: txOutputs(item),
13485
+ ownerUtxoKeypair: owner
13486
+ });
13487
+ const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
13488
+ if (!deposit || leaf === null) return false;
13489
+ await add(o, {
13490
+ kind: "deposit",
13491
+ atRisk: deposit.legacyExposed,
13492
+ amount: deposit.amount,
13493
+ blinding: deposit.blinding,
13494
+ keypair: deposit.legacyExposed ? deposit.keypair : owner,
13495
+ mint,
13496
+ commitment: deposit.commitment,
13497
+ leaf
13498
+ });
13499
+ return true;
13500
+ };
13501
+ const tryChange0 = async (o, item, keypair, atRisk) => {
13502
+ const note = o.note;
13503
+ const mint = addressFromBytes(item.mint);
13504
+ const change = await matchChangeNote({
13505
+ viewingKeyNk: o.trial.nk,
13506
+ noteSalt: note.noteSalt,
13507
+ amount: note.outAmount0,
13508
+ keypair,
13509
+ mintAddress: mint,
13510
+ outputIndex: 0,
13511
+ outputCommitments: [toHex2(item.comm0)],
13512
+ ownerUtxoPublicKey: owner.publicKey
13513
+ });
13514
+ if (!change) return false;
13515
+ await add(o, {
13516
+ kind: "change",
13517
+ atRisk,
13518
+ amount: change.amount,
13519
+ blinding: change.blinding,
13520
+ keypair,
13521
+ mint,
13522
+ commitment: change.commitment,
13523
+ leaf: Number(item.leaf0)
13524
+ });
13525
+ return true;
13526
+ };
13527
+ const direct = async (o) => {
13528
+ const item = o.item;
13529
+ if (item.kind === 1 && o.note?.noteSalt !== void 0) {
13530
+ const note = o.note;
13531
+ if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
13532
+ if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
13533
+ }
13534
+ if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
13535
+ if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
13536
+ }
13537
+ } else if (item.kind === 2 && o.delivery) {
13538
+ const mint = addressFromBytes(item.mint);
13539
+ if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
13540
+ onReject(o);
13541
+ return;
13542
+ }
13543
+ const commitment = await computeCommitment2({
13544
+ amount: o.delivery.amount,
13545
+ keypair: { privateKey: 0n, publicKey: owner.publicKey },
13546
+ blinding: o.delivery.blinding,
13547
+ mintAddress: mint
13548
+ });
13549
+ if (commitment !== bytesToBigint3(item.commitment)) {
13550
+ onReject(o);
13551
+ return;
13552
+ }
13553
+ await add(o, {
13554
+ kind: "received",
13555
+ atRisk: false,
13556
+ amount: o.delivery.amount,
13557
+ blinding: o.delivery.blinding,
13558
+ keypair: owner,
13559
+ mint,
13560
+ commitment,
13561
+ leaf: Number(item.leaf)
13562
+ });
13563
+ } else if (item.kind === 3 && o.refund) {
13564
+ await add(o, {
13565
+ kind: "swap_refund",
13566
+ atRisk: o.refund.legacyExposed,
13567
+ amount: o.refund.amount,
13568
+ blinding: o.refund.blinding,
13569
+ keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
13570
+ mint: NATIVE_SOL_MINT,
13571
+ commitment: o.refund.commitment,
13572
+ leaf: Number(item.leaf)
13573
+ });
13574
+ }
13575
+ };
13576
+ for (const o of own) {
13577
+ try {
13578
+ await direct(o);
13579
+ } catch {
13580
+ onSkip(o);
13581
+ }
13582
+ }
13583
+ const processTx = async (o) => {
13584
+ const item = o.item;
13585
+ const note = o.note;
13586
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
13587
+ const legacy = legacyKeys.get(note.outPubkey0);
13588
+ if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
13589
+ }
13590
+ const mint = addressFromBytes(item.mint);
13591
+ const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
13592
+ if (inputs.length === 0) return;
13593
+ const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
13594
+ if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
13595
+ const out1 = sumIn + item.publicAmount - note.outAmount0;
13596
+ const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
13597
+ if (out1 > 0n && blinding === null) onSkip(o);
13598
+ else if (blinding !== null) {
13599
+ const owners = [{ keypair: owner, atRisk: false }];
13600
+ const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
13601
+ if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
13602
+ for (const { keypair, atRisk } of owners) {
13603
+ const commitment = await computeCommitment2({ amount: out1, keypair, blinding, mintAddress: mint });
13604
+ if (commitment !== bytesToBigint3(item.comm1)) continue;
13605
+ claimed.add(`${o.seq}:1`);
13606
+ await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
13607
+ break;
13608
+ }
13609
+ }
13610
+ }
13611
+ if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
13612
+ if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
13613
+ }
13614
+ };
13615
+ for (const o of ownTxs) enqueue(o);
13616
+ for (let i = 0; i < queue.length; i++) {
13617
+ const o = queue[i];
13618
+ queued.delete(o);
13619
+ try {
13620
+ await processTx(o);
13621
+ } catch {
13622
+ onSkip(o);
13623
+ }
13624
+ }
13625
+ return candidates;
13626
+ }
13627
+ async function replayStream(start, pages, overrides, chain, targetPage) {
13628
+ const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
13629
+ const startN = frontier.nextIndex;
13630
+ const pending = new Map(start.pending);
13631
+ const flushed = new LeafBuffer();
13632
+ const corrections = /* @__PURE__ */ new Map();
13633
+ let conflicts = 0;
13634
+ let verifiedPrefix = 0;
13635
+ let mismatch = false;
13636
+ const checks = [];
13637
+ const setBits = [];
13638
+ if (chain && chain.nextIndex > 0) {
13639
+ const last = chain.nextIndex - 1;
13640
+ for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
13641
+ for (const l of setBits) {
13642
+ const at = Math.floor(last / 2 ** l) * 2 ** l;
13643
+ if (at >= startN) checks.push({ at, level: l });
13644
+ }
13645
+ if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
13646
+ checks.sort((a, b) => a.at - b.at);
13647
+ }
13648
+ let nextCheck = 0;
13649
+ const runChecks = () => {
13650
+ while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
13651
+ const { at, level } = checks[nextCheck++];
13652
+ const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
13653
+ if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
13654
+ else mismatch = true;
13655
+ }
13656
+ };
13657
+ const append = (values) => {
13658
+ let i = 0;
13659
+ while (i < values.length) {
13660
+ const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
13661
+ const take = Math.min(values.length - i, room);
13662
+ if (take > 0) {
13663
+ const part = values.slice(i, i + take);
13664
+ frontier.append(part);
13665
+ flushed.push(part);
13666
+ i += take;
13667
+ }
13668
+ runChecks();
13669
+ }
13670
+ };
13671
+ const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
13672
+ const flush = () => {
13673
+ const batch = [];
13674
+ let next = frontier.nextIndex;
13675
+ while (pending.has(next)) {
13676
+ batch.push(pending.get(next));
13677
+ pending.delete(next);
13678
+ next++;
13679
+ }
13680
+ if (batch.length > 0) append(batch);
13681
+ };
13682
+ let snapshot = null;
13683
+ let taken = false;
13684
+ const takeSnapshot = () => {
13685
+ taken = true;
13686
+ if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
13687
+ snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
13688
+ };
13689
+ runChecks();
13690
+ flush();
13691
+ for (const { page, entries } of pages) {
13692
+ if (!taken && page >= targetPage) takeSnapshot();
13693
+ for (const e of entries) {
13694
+ if (e.leaf < startN) continue;
13695
+ const prior = valueAt(e.leaf);
13696
+ if (prior !== void 0) {
13697
+ if (prior !== e.commitment) {
13698
+ conflicts++;
13699
+ corrections.set(e.leaf, e.commitment);
13700
+ }
13701
+ continue;
13702
+ }
13703
+ pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
13704
+ }
13705
+ flush();
13706
+ }
13707
+ if (!taken) takeSnapshot();
13708
+ if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
13709
+ verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
13710
+ }
13711
+ return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
13712
+ }
13713
+ var HEX64 = /^[0-9a-f]{64}$/;
13714
+ var HEX32 = /^[0-9a-f]{32}$/;
13715
+ var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
13716
+ var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
13717
+ function isRecord(v) {
13718
+ return typeof v === "object" && v !== null && !Array.isArray(v);
13719
+ }
13720
+ function isIntIn(v, min, max) {
13721
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
13722
+ }
13723
+ function isBoundedArray(v, max) {
13724
+ return Array.isArray(v) && v.length <= max;
13725
+ }
13726
+ function emptyStartTree() {
13727
+ return {
13728
+ frontier: null,
13729
+ nextIndex: 0,
13730
+ pending: /* @__PURE__ */ new Map(),
13731
+ window: [],
13732
+ windowStart: 0,
13733
+ verified: 0,
13734
+ overrides: /* @__PURE__ */ new Map(),
13735
+ mismatch: false,
13736
+ hiBefore: -1
13737
+ };
13738
+ }
13739
+ async function parseCursor(cursor, poolMints) {
13740
+ try {
13741
+ if (!isRecord(cursor)) return "not an object";
13742
+ if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
13743
+ const c = cursor;
13744
+ if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
13745
+ if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
13746
+ if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
13747
+ if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
13748
+ if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
13749
+ if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
13750
+ const trees = /* @__PURE__ */ new Map();
13751
+ for (const mint of poolMints) {
13752
+ const t = c.trees[mint];
13753
+ if (!isRecord(t)) return "a listed pool is missing from the cursor";
13754
+ const tree = t;
13755
+ if (!isRecord(tree.frontier)) return "bad frontier";
13756
+ let frontier;
13757
+ try {
13758
+ frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
13759
+ } catch {
13760
+ return "bad frontier";
13761
+ }
13762
+ const nextIndex = frontier.nextIndex;
13763
+ if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
13764
+ const pending = /* @__PURE__ */ new Map();
13765
+ let hiBefore = nextIndex - 1;
13766
+ for (const entry of tree.pending) {
13767
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
13768
+ const [leaf, value] = entry;
13769
+ if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
13770
+ return "bad pending leaves";
13771
+ }
13772
+ pending.set(leaf, BigInt("0x" + value));
13773
+ hiBefore = Math.max(hiBefore, leaf);
13774
+ }
13775
+ if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
13776
+ const windowLen = tree.window.length / 64;
13777
+ if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
13778
+ const window2 = [];
13779
+ for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
13780
+ if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
13781
+ if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
13782
+ const overrides = /* @__PURE__ */ new Map();
13783
+ for (const entry of tree.overrides) {
13784
+ if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
13785
+ const [leaf, value] = entry;
13786
+ if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
13787
+ overrides.set(leaf, BigInt("0x" + value));
13788
+ }
13789
+ if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
13790
+ trees.set(mint, {
13791
+ frontier: frontier.toState(),
13792
+ nextIndex,
13793
+ pending,
13794
+ window: window2,
13795
+ windowStart: nextIndex - windowLen,
13796
+ verified: tree.verified,
13797
+ overrides,
13798
+ mismatch: tree.mismatch,
13799
+ hiBefore
13800
+ });
13801
+ }
13802
+ const own = c.own;
13803
+ if (!isRecord(own)) return "bad own state";
13804
+ if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
13805
+ const items = [];
13806
+ const seqs = /* @__PURE__ */ new Set();
13807
+ for (const entry of own.items) {
13808
+ if (!isRecord(entry)) return "bad own items";
13809
+ const { seq, item } = entry;
13810
+ if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
13811
+ if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
13812
+ seqs.add(seq);
13813
+ const raw = fromHex(item);
13814
+ items.push({ seq, raw, item: parseNoteIndexItem(raw) });
13815
+ }
13816
+ if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
13817
+ return "bad verified notes";
13818
+ }
13819
+ if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
13820
+ if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
13821
+ const pendingLeaves = /* @__PURE__ */ new Map();
13822
+ for (const entry of own.pendingLeaves) {
13823
+ if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
13824
+ const [mint, leaf, value] = entry;
13825
+ if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
13826
+ return "bad pending notes";
13827
+ }
13828
+ pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
13829
+ }
13830
+ if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
13831
+ return "bad rejected set";
13832
+ }
13833
+ return {
13834
+ raw: c,
13835
+ trees,
13836
+ items,
13837
+ verified: new Set(own.verified),
13838
+ spent: new Set(own.spent),
13839
+ pendingLeaves,
13840
+ rejected: own.rejected
13841
+ };
13842
+ } catch {
13843
+ return "unreadable state";
13844
+ }
13845
+ }
13846
+ async function recoverNotesFromIndex(params) {
13847
+ const startedAt = Date.now();
13848
+ const { relayUrl, connection, viewingKeyNk, programId } = params;
13849
+ assertAllowedRelayOrigin(relayUrl);
13850
+ assertAllowedRpcConnection(connection);
13851
+ if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
13852
+ const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
13853
+ if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
13854
+ const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
13855
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
13856
+ throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
13857
+ }
13858
+ if (params.signal?.aborted) throw abortError2();
13859
+ const stats = {
13860
+ pages: 0,
13861
+ items: 0,
13862
+ bytes: 0,
13863
+ rpcCalls: 0,
13864
+ ms: 0,
13865
+ dropped: 0,
13866
+ decrypted: 0,
13867
+ candidates: 0,
13868
+ spent: 0,
13869
+ conflicts: 0,
13870
+ pendingDropped: 0,
13871
+ skipped: 0
13872
+ };
13873
+ const rpc = new Proxy(connection, {
13874
+ get(target, prop, receiver) {
13875
+ const value = Reflect.get(target, prop, receiver);
13876
+ if (typeof value !== "function") return value;
13877
+ return (...args) => {
13878
+ const pending = value.apply(target, args);
13879
+ if (pending && typeof pending.send === "function") {
13880
+ const send = pending.send.bind(pending);
13881
+ return {
13882
+ ...pending,
13883
+ send: (...sendArgs) => {
13884
+ stats.rpcCalls++;
13885
+ return send(...sendArgs);
13886
+ }
13887
+ };
13888
+ }
13889
+ return pending;
13890
+ };
13891
+ }
13892
+ });
13893
+ const makeTrial = async (nk, legacy) => ({
13894
+ nk,
13895
+ legacy,
13896
+ owner,
13897
+ decrypt: await createCompactChainNoteDecryptor(nk),
13898
+ open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
13899
+ });
13900
+ const trials = [await makeTrial(viewingKeyNk, false)];
13901
+ const legacyNks = params.legacyViewingKeyNks ?? [];
13902
+ if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
13903
+ if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
13904
+ const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
13905
+ for (const nk of legacyNks) {
13906
+ if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
13907
+ const key = toHex2(nk);
13908
+ if (seenNks.has(key)) continue;
13909
+ seenNks.add(key);
13910
+ trials.push(await makeTrial(Uint8Array.from(nk), true));
13911
+ }
13912
+ const poolMints = Array.from(new Set(params.poolMints));
13913
+ const warnings = [];
13914
+ const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
13915
+ let cursor;
13916
+ if (params.cursor !== void 0) {
13917
+ const checked = await parseCursor(params.cursor, poolMints);
13918
+ if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
13919
+ else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
13920
+ else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
13921
+ throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
13922
+ } else cursor = checked;
13923
+ }
13924
+ const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
13925
+ let treeRead;
13926
+ const readTrees = () => treeRead ?? (treeRead = (async () => {
13927
+ const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
13928
+ return poolMints.map((_, i) => {
13929
+ const account = accounts[i];
13930
+ const parsed = account ? readTreeAccountFrontier(account.data) : null;
13931
+ return account && parsed ? { ...parsed, data: account.data } : null;
13932
+ });
13933
+ })());
13934
+ const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
13935
+ let outcome = await runOnce(ctx, cursor);
13936
+ if (outcome instanceof FullPassSignal) {
13937
+ warnings.push(`${outcome.reason}; re-syncing from page 0`);
13938
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
13939
+ outcome = await runOnce(ctx, void 0);
13940
+ if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13941
+ }
13942
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
13943
+ stats.ms = Date.now() - startedAt;
13944
+ return { ...outcome, stats, warnings };
13945
+ }
13946
+ async function runOnce(ctx, cursor) {
13947
+ const { params, head, trials, owner, stats, poolMints } = ctx;
13948
+ const { relayUrl, onProgress } = params;
13949
+ const poolSet = new Set(poolMints);
13950
+ const startPage = cursor?.raw.page ?? 0;
13951
+ const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
13952
+ const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
13953
+ const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
13954
+ const targetPage = Math.max(startPage, floorAlign(head.completePages));
13955
+ const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
13956
+ const rejectedIds = new Set(cursor?.rejected ?? []);
13957
+ const controller = new AbortController();
13958
+ const onCallerAbort = () => controller.abort();
13959
+ params.signal?.addEventListener("abort", onCallerAbort, { once: true });
13960
+ const signal = controller.signal;
13961
+ try {
13962
+ const pageData = /* @__PURE__ */ new Map();
13963
+ const ownItems = [];
13964
+ const nullifiers = /* @__PURE__ */ new Set();
13965
+ let fullPassReason = null;
13966
+ const lateReference = (mint, leaf, value, seq) => {
13967
+ if (!cursor || seq < fullPassSeq) return null;
13968
+ const t = startTrees.get(mint);
13969
+ if (leaf < t.nextIndex) {
13970
+ if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
13971
+ if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
13972
+ return null;
13973
+ }
13974
+ const held = t.pending.get(leaf);
13975
+ if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
13976
+ if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
13977
+ return null;
13978
+ };
13979
+ const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
13980
+ const waiting = /* @__PURE__ */ new Map();
13981
+ let chainNext = startPage;
13982
+ let chainError = null;
13983
+ let wakers = [];
13984
+ const wakeAll = () => {
13985
+ const w = wakers;
13986
+ wakers = [];
13987
+ for (const f of w) f();
13988
+ };
13989
+ signal.addEventListener("abort", wakeAll);
13990
+ const advanceChain = () => {
13991
+ while (!chainError && waiting.has(chainNext)) {
13992
+ const w = waiting.get(chainNext);
13993
+ waiting.delete(chainNext);
13994
+ const expected = chainAt.get(chainNext);
13995
+ if (w.prevChain !== expected) {
13996
+ chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
13997
+ controller.abort();
13998
+ return;
13999
+ }
14000
+ if (!w.complete) break;
14001
+ chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
14002
+ chainNext++;
14003
+ }
14004
+ wakeAll();
14005
+ };
14006
+ const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
14007
+ const lookahead = 2 * workerCount + 2;
14008
+ let nextToFetch = startPage;
14009
+ let pagesDone = 0;
14010
+ const worker = async () => {
14011
+ for (; ; ) {
14012
+ if (signal.aborted) throw abortError2();
14013
+ const pageNo = nextToFetch++;
14014
+ if (pageNo >= pagesTotal) return;
14015
+ while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
14016
+ if (signal.aborted) throw abortError2();
14017
+ const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
14018
+ stats.bytes += bytes.length;
14019
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
14020
+ if (pageNo < head.completePages && !page2.complete) {
14021
+ throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
14022
+ }
14023
+ stats.pages++;
14024
+ stats.skipped += page2.skippedMalformed;
14025
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
14026
+ waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
14027
+ advanceChain();
14028
+ const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
14029
+ const late = (reason) => {
14030
+ if (reason && !fullPassReason) {
14031
+ fullPassReason = reason;
14032
+ controller.abort();
14033
+ }
14034
+ };
14035
+ const addLeaf = (mintBytes, commitment, leaf, seq) => {
14036
+ if (isAllZero3(commitment)) return;
14037
+ const mint = addressFromBytes(mintBytes);
14038
+ if (!poolSet.has(mint)) return;
14039
+ const entry = { leaf: Number(leaf), commitment: bytesToBigint3(commitment) };
14040
+ late(lateReference(mint, entry.leaf, entry.commitment, seq));
14041
+ const list = data.leaves.get(mint);
14042
+ if (list) list.push(entry);
14043
+ else data.leaves.set(mint, [entry]);
14044
+ };
14045
+ page2.items.forEach((item, i) => {
14046
+ const seq = seqOf(i);
14047
+ if (item.kind === 1) {
14048
+ addLeaf(item.mint, item.comm0, item.leaf0, seq);
14049
+ addLeaf(item.mint, item.comm1, item.leaf1, seq);
14050
+ if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
14051
+ if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
14052
+ } else if (item.kind === 3) {
14053
+ addLeaf(item.mint, item.commitment, item.leaf, seq);
14054
+ } else {
14055
+ const mint = addressFromBytes(item.mint);
14056
+ if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
14057
+ }
14058
+ });
14059
+ if (signal.aborted) throw abortError2();
14060
+ for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
14061
+ if (signal.aborted) throw abortError2();
14062
+ const batch = page2.items.slice(i, i + ITEM_BATCH);
14063
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
14064
+ opened.forEach((o, k) => {
14065
+ if (!o) return;
14066
+ stats.decrypted++;
14067
+ const raw = page2.rawItems[i + k];
14068
+ const id = itemIdentity(raw);
14069
+ if (rejectedIds.has(id)) {
14070
+ stats.dropped++;
14071
+ return;
14072
+ }
14073
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
14074
+ });
14075
+ stats.items += batch.length;
14076
+ }
14077
+ pageData.set(pageNo, data);
14078
+ pagesDone++;
14079
+ onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
14080
+ }
14081
+ };
14082
+ const workers = Array.from(
14083
+ { length: workerCount },
14084
+ () => worker().catch((error) => {
14085
+ controller.abort();
14086
+ throw error;
14087
+ })
14088
+ );
14089
+ const settled = await Promise.allSettled(workers);
14090
+ signal.removeEventListener("abort", wakeAll);
14091
+ if (params.signal?.aborted) throw abortError2();
14092
+ const lateReason = fullPassReason;
14093
+ if (lateReason) return new FullPassSignal(lateReason);
14094
+ const chainFailure = chainError;
14095
+ if (chainFailure) {
14096
+ if (chainFailure instanceof FullPassSignal) return chainFailure;
14097
+ throw chainFailure;
14098
+ }
14099
+ const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
14100
+ if (failure) throw failure.reason;
14101
+ if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
14102
+ if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
14103
+ throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
14104
+ }
14105
+ for (const entry of cursor?.items ?? []) {
14106
+ const o = await trialItemIsolated(entry.item, trials, stats);
14107
+ if (!o) continue;
14108
+ const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
14109
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
14110
+ if (entry.item.kind === 1) {
14111
+ if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
14112
+ if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
14113
+ }
14114
+ }
14115
+ const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
14116
+ ownItems.sort((a, b) => a.seq - b.seq);
14117
+ const rejectedNow = /* @__PURE__ */ new Set();
14118
+ const skippedNow = /* @__PURE__ */ new Set();
14119
+ const allCandidates = await matchOwnItems(
14120
+ ownItems,
14121
+ owner,
14122
+ (o) => {
14123
+ stats.dropped++;
14124
+ rejectedNow.add(o.id);
14125
+ },
14126
+ (o) => {
14127
+ if (skippedNow.has(o)) return;
14128
+ skippedNow.add(o);
14129
+ stats.skipped++;
14130
+ }
14131
+ );
14132
+ stats.candidates = allCandidates.length;
14133
+ const cutoff = params.legacyCutoffLeaf ?? {};
14134
+ const candidates = allCandidates.filter((c) => {
14135
+ const limit = cutoff[c.mint];
14136
+ if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
14137
+ stats.dropped++;
14138
+ return false;
14139
+ }
14140
+ return true;
14141
+ });
14142
+ const chainTrees = await ctx.readTrees();
14143
+ const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
14144
+ const replays = /* @__PURE__ */ new Map();
14145
+ for (let i = 0; i < poolMints.length; i++) {
14146
+ const mint = poolMints[i];
14147
+ const start = startTrees.get(mint);
14148
+ const chainTree = chainTrees[i] ?? null;
14149
+ const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
14150
+ let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
14151
+ let overrides = start.overrides;
14152
+ stats.conflicts += r.conflicts;
14153
+ if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
14154
+ const merged = new Map([...start.overrides, ...r.corrections]);
14155
+ const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
14156
+ if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
14157
+ r = alternative;
14158
+ overrides = merged;
14159
+ }
14160
+ }
14161
+ if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
14162
+ replays.set(mint, { r, overrides });
14163
+ }
14164
+ const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
14165
+ const streamValue = (mint, leaf) => {
14166
+ const v = replays.get(mint)?.r.valueAt(leaf);
14167
+ if (v !== void 0) return v;
14168
+ const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
14169
+ if (carried !== void 0) return carried;
14170
+ const t = startTrees.get(mint);
14171
+ if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
14172
+ return void 0;
14173
+ };
14174
+ const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
14175
+ const verified = [];
14176
+ const pendingByKey = /* @__PURE__ */ new Map();
14177
+ const rejectedCandidates = /* @__PURE__ */ new Set();
14178
+ const outcomeOf = /* @__PURE__ */ new Map();
14179
+ const tally = (c, what) => {
14180
+ const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
14181
+ t.total++;
14182
+ if (what === "kept") t.kept = true;
14183
+ if (what === "rejected") t.rejected++;
14184
+ outcomeOf.set(c.seq, t);
14185
+ };
14186
+ const pend = (c, rank) => {
14187
+ const key = verifiedKey(c.mint, c.leaf, c.commitment);
14188
+ const prior = pendingByKey.get(key);
14189
+ if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
14190
+ };
14191
+ for (const c of candidates) {
14192
+ if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
14193
+ verified.push(c);
14194
+ continue;
14195
+ }
14196
+ if (!poolSet.has(c.mint)) {
14197
+ pend(c, 3);
14198
+ continue;
14199
+ }
14200
+ const value = streamValue(c.mint, c.leaf);
14201
+ if (value === void 0) {
14202
+ if (c.leaf < startTrees.get(c.mint).nextIndex) {
14203
+ stats.dropped++;
14204
+ tally(c, "other");
14205
+ } else pend(c, 1);
14206
+ } else if (c.leaf >= verifiedUpTo(c.mint)) {
14207
+ pend(c, value === c.commitment ? 0 : 2);
14208
+ } else if (value === c.commitment) {
14209
+ verified.push(c);
14210
+ } else {
14211
+ stats.dropped++;
14212
+ rejectedCandidates.add(c);
14213
+ tally(c, "rejected");
14214
+ }
14215
+ }
14216
+ verified.sort((a, b) => a.seq - b.seq);
14217
+ const byLeaf = /* @__PURE__ */ new Map();
14218
+ for (const c of verified) {
14219
+ const key = `${c.mint}:${c.leaf}`;
14220
+ if (byLeaf.has(key)) {
14221
+ stats.dropped++;
14222
+ tally(c, "other");
14223
+ continue;
14224
+ }
14225
+ byLeaf.set(key, c);
14226
+ }
14227
+ const notes = [];
14228
+ const atRisk = [];
14229
+ const spentOut = new Set(knownSpent);
14230
+ const verifiedOut = new Set(knownVerified);
14231
+ const keyChecked = /* @__PURE__ */ new Map();
14232
+ for (const c of byLeaf.values()) {
14233
+ const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
14234
+ keyChecked.set(c.keypair.privateKey, pubOk);
14235
+ if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
14236
+ stats.dropped++;
14237
+ tally(c, "rejected");
14238
+ continue;
14239
+ }
14240
+ tally(c, "kept");
14241
+ verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
14242
+ const utxo = {
14243
+ amount: c.amount,
14244
+ keypair: c.atRisk ? { ...c.keypair } : owner,
14245
+ blinding: c.blinding,
14246
+ mintAddress: c.mint,
14247
+ index: c.leaf,
14248
+ commitment: c.commitment
14249
+ };
14250
+ if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
14251
+ stats.spent++;
14252
+ spentOut.add(c.nullifier);
14253
+ continue;
14254
+ }
14255
+ const note = {
14256
+ kind: c.kind,
14257
+ utxo,
14258
+ signature: bs584.encode(c.signature),
14259
+ legacyExposed: c.atRisk
14260
+ };
14261
+ (c.atRisk ? atRisk : notes).push(note);
14262
+ }
14263
+ 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);
14264
+ sortNotes(notes);
14265
+ sortNotes(atRisk);
14266
+ const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
14267
+ const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
14268
+ const overflow = pendingList.length - carriedPending.length;
14269
+ if (overflow > 0) {
14270
+ stats.pendingDropped += overflow;
14271
+ ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
14272
+ }
14273
+ for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
14274
+ for (const c of carriedPending) tally(c, "kept");
14275
+ for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
14276
+ let page = targetPage;
14277
+ for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
14278
+ const trees = {};
14279
+ const treeEnd = /* @__PURE__ */ new Map();
14280
+ for (const mint of poolMints) {
14281
+ const start = startTrees.get(mint);
14282
+ const { r, overrides } = replays.get(mint);
14283
+ const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
14284
+ const n = snap.nextIndex;
14285
+ const window2 = [];
14286
+ for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
14287
+ const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
14288
+ if (v === void 0) break;
14289
+ window2.push(hex32(v));
14290
+ }
14291
+ window2.reverse();
14292
+ trees[mint] = {
14293
+ frontier: snap.frontier,
14294
+ pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
14295
+ window: window2.join(""),
14296
+ verified: Math.min(verifiedUpTo(mint), n),
14297
+ 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)]),
14298
+ mismatch: r.mismatch
14299
+ };
14300
+ treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
14301
+ }
14302
+ const pendingLeaves = [];
14303
+ const pendingLeafSeen = /* @__PURE__ */ new Set();
14304
+ for (const c of carriedPending) {
14305
+ const end = treeEnd.get(c.mint);
14306
+ if (!end || c.leaf >= end.nextIndex) continue;
14307
+ const value = streamValue(c.mint, c.leaf);
14308
+ const key = `${c.mint}:${c.leaf}`;
14309
+ if (value === void 0 || pendingLeafSeen.has(key)) continue;
14310
+ pendingLeafSeen.add(key);
14311
+ pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
14312
+ }
14313
+ const keptItems = [];
14314
+ const keptIds = /* @__PURE__ */ new Set();
14315
+ for (const o of ownItems) {
14316
+ const t = outcomeOf.get(o.seq);
14317
+ if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
14318
+ rejectedNow.add(o.id);
14319
+ continue;
14320
+ }
14321
+ if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
14322
+ keptIds.add(o.id);
14323
+ keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
14324
+ }
14325
+ const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
14326
+ const nextCursor = {
14327
+ v: CURSOR_VERSION,
14328
+ epoch: head.epoch.toString(10),
14329
+ page,
14330
+ chain: chainAt.get(page) ?? startChain,
14331
+ watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
14332
+ fullPassSeq: cursor ? fullPassSeq : head.watermark,
14333
+ trees,
14334
+ own: {
14335
+ items: keptItems,
14336
+ verified: Array.from(verifiedOut),
14337
+ spent: Array.from(spentOut),
14338
+ pendingLeaves,
14339
+ rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
14340
+ }
14341
+ };
14342
+ return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
14343
+ } finally {
14344
+ params.signal?.removeEventListener("abort", onCallerAbort);
14345
+ }
14346
+ }
14347
+
12498
14348
  // src/wallet/utxo-wallet.ts
12499
14349
  init_address();
12500
14350
  init_utxo();
@@ -13703,13 +15553,13 @@ var DoNotRetry = class extends Error {
13703
15553
  };
13704
15554
  async function withShieldRetries(attempt, hooks = {}) {
13705
15555
  const attempts = hooks.attempts ?? 3;
13706
- const sleep4 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
15556
+ const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13707
15557
  let last = "";
13708
15558
  for (let n = 1; n <= attempts; n++) {
13709
15559
  if (n > 1) {
13710
15560
  const delay = retryDelayMs(n);
13711
15561
  hooks.onRetry?.(n, delay, last);
13712
- await sleep4(delay);
15562
+ await sleep5(delay);
13713
15563
  }
13714
15564
  try {
13715
15565
  return await attempt(n);
@@ -13758,6 +15608,10 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13758
15608
  MemoryStorageAdapter,
13759
15609
  MerkleTree,
13760
15610
  NATIVE_SOL_MINT,
15611
+ NOTE_INDEX_NO_LEAF,
15612
+ NOTE_INDEX_PAGE_SIZE,
15613
+ NoteIndexFormatError,
15614
+ NoteIndexHeadBehindError,
13761
15615
  ONECLICK_PUBKEY_B58,
13762
15616
  RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
13763
15617
  RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
@@ -13834,6 +15688,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13834
15688
  computeChainNoteHash,
13835
15689
  computeExtDataHash,
13836
15690
  computeMerkleRoot,
15691
+ computeNoteIndexChain,
13837
15692
  computeProofForLatestDeposit,
13838
15693
  computeProofFromChain,
13839
15694
  computeSignature,
@@ -13882,6 +15737,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13882
15737
  discoverSwapRefunds,
13883
15738
  downloadNote,
13884
15739
  encodeDeliveryCarrierMemo,
15740
+ encodeNoteIndexItem,
15741
+ encodeNoteIndexPage,
13885
15742
  encodeNoteSimple,
13886
15743
  encodeRecipientDeliveryNote,
13887
15744
  encryptCompactChainNote,
@@ -13897,6 +15754,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13897
15754
  fetchCommitments,
13898
15755
  fetchLatestBlockhash,
13899
15756
  fetchLookupTables,
15757
+ fetchNoteIndexHead,
15758
+ fetchNoteIndexPage,
13900
15759
  fetchRiskQuoteInstruction,
13901
15760
  fetchRiskQuoteIx,
13902
15761
  fetchSignaturesForAddress,
@@ -13969,6 +15828,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13969
15828
  parseDeliveryCarrierMemo,
13970
15829
  parseError,
13971
15830
  parseNote,
15831
+ parseNoteIndexItem,
15832
+ parseNoteIndexPage,
13972
15833
  parseRelayErrorResponse,
13973
15834
  parseRelayErrorSignature,
13974
15835
  parseTransactionError,
@@ -13990,6 +15851,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
13990
15851
  readMerkleTreeState,
13991
15852
  readRent,
13992
15853
  recipientDeliveryNoteToBase64,
15854
+ recoverNotesFromIndex,
13993
15855
  registerViewingKey,
13994
15856
  relayRequestDigestHex,
13995
15857
  removePendingDeposit,