@cloak.dev/sdk 0.2.6-staging.f92dd96 → 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/CHANGELOG.md CHANGED
@@ -91,6 +91,10 @@ it. These notes are still found by `matchDepositNote`, `matchSwapRefundLeaf`, `m
91
91
  * The paymaster client judges the relay-issued voucher expiry on the relay clock.
92
92
  * With no sample (a relay that predates the header, or no relay reachable) every stamp falls back to
93
93
  `Date.now()`, the 0.2.5 behaviour.
94
+ * A relay clock more than 24 hours from the machine's is ignored (the bound was a year). The clock
95
+ dates the proof-bound chain-note timestamp, which stays on chain and shows in history and
96
+ compliance reports, so a relay must not be able to move it by months. A machine more than 24
97
+ hours off falls back to its own clock, and the relay's auth window decides.
94
98
 
95
99
  ### Note Index v1 (restore without walking the chain)
96
100
 
@@ -103,8 +107,8 @@ of every confirmed Cloak transaction that the relay indexes once, server side. A
103
107
  #### Added
104
108
 
105
109
  * `recoverNotesFromIndex({ relayUrl, connection, programId, poolMints, viewingKeyNk,
106
- ownerUtxoKeypair, cursor?, legacyCutoffLeaf?, concurrency?, onProgress?, signal? })` returns
107
- `{ notes, atRisk, pending, cursor, stats }`. It downloads every page (the only request
110
+ ownerUtxoKeypair, cursor?, legacyViewingKeyNks?, legacyCutoffLeaf?, concurrency?, onProgress?,
111
+ signal? })` returns `{ notes, atRisk, pending, cursor, stats, warnings }`. It downloads every page (the only request
108
112
  parameters are the epoch and the page number, so the relay learns nothing about which notes are
109
113
  the wallet's), opens each item locally, rebuilds the tree of every listed pool from the index's
110
114
  own leaf stream and checks it against the chain, and computes spent status from the index's
@@ -114,6 +118,16 @@ of every confirmed Cloak transaction that the relay indexes once, server side. A
114
118
  leaf in a root-verified tree. Notes owned by the wallet keypair go to `notes`; legacy notes whose
115
119
  owner key is derivable from `nk` go to `atRisk` with `legacyExposed: true`, never into `notes`.
116
120
  Candidates that cannot be verified yet are counted in `pending` and carried in the cursor.
121
+ `pending` depends on what the wallet owns: gate polls on the public head (epoch, watermark), never
122
+ on `pending`, or the download pattern tells the relay which client owns an item it tampered with.
123
+ * `legacyViewingKeyNks` (at most 8): other viewing keys older clients of the wallet encrypted chain
124
+ notes under (older mobile builds used SHA-512 of the public wallet address, or the embedded
125
+ wallet's nsk). Each item is tried under the canonical `nk` first, then under each legacy key, in
126
+ the same download: no extra request, still one `getMultipleAccounts`. Everything found only
127
+ through a legacy key is returned in `atRisk` whatever its owner key, a legacy key never opens a
128
+ delivered note, and nothing it opens can enter `notes`. A migration (a canonical-`nk` spend of a
129
+ legacy note) marks the legacy note spent and returns its change, which is found by conservation
130
+ over the legacy input.
117
131
  * The cursor (format v2) is JSON with no key material; persist it for incremental syncs. An epoch
118
132
  change, a broken hash chain or an invalid cursor re-syncs from page 0; a head behind the cursor
119
133
  throws the retryable `NoteIndexHeadBehindError`.
@@ -127,10 +141,26 @@ of every confirmed Cloak transaction that the relay indexes once, server side. A
127
141
  * The relay is untrusted. It can hide items but cannot inject, alter or forge a note. A hidden
128
142
  nullifier can make a spent note look unspent, so restored notes must be spent through
129
143
  `transact`, `partialWithdraw`, `fullWithdraw` or `swapUtxo`, which run `preflightNullifiers`
130
- before proving. `buildTransactInstruction` and `submitTransactToRelay` document that they do not.
144
+ before proving. `submitTransactToRelay` documents that it does not (as does the internal
145
+ `buildTransactInstruction`, which is not exported).
131
146
  * Note Index reads never set the relay clock. Complete pages are immutable and cacheable for a
132
147
  year, so a cached response replays a stale `x-cloak-server-time`; learning from it would date
133
148
  later signed requests in the past.
149
+ * One malformed, crafted or undecryptable entry never aborts a restore or a sync (QA2 F9). A legacy
150
+ viewing key may be public, so anyone could deposit to the owner key derived from it and spend
151
+ that deposit with a chain note under the same key carrying a salt of 0 (or over 96 bits); the
152
+ output-1 conservation path threw on it and every restore passing that key failed, for good.
153
+ Such an entry is now skipped and counted in `stats.skipped` (with a generic warning), and so is
154
+ anything else a matcher throws for one item, and a known-kind item whose body fails its format
155
+ checks while its framing in the page is intact (`parseNoteIndexPage(bytes, expect,
156
+ { skipMalformedItems: true })`, which also reports `skippedMalformed` and each item's
157
+ `itemPositions`). Page-level faults (header, framing, hash chain, head) still fail the run.
158
+ * What a restored note is checked against, precisely: it opens under AES-GCM keyed by HKDF(nk,
159
+ the item's own `comm0`), its commitment recomputes from the opened values, and it sits at its
160
+ leaf in a chain-authenticated tree. The proof-bound `chainNoteHash` is NOT re-checked: an index
161
+ item does not carry it (nor the `extDataHash` its preimage needs), and fetching it would cost RPC
162
+ per transaction. It would add nothing: a chain note written for one transaction never opens
163
+ when the relay pairs it with another, so a mispairing can hide notes but never yield a wrong one.
134
164
 
135
165
  ### Fixed
136
166
 
package/README.md CHANGED
@@ -540,6 +540,10 @@ scan.deliveredNotes; // notes sent to this wallet (amount + blinding; the
540
540
  scan.transactions; // history rows for compliance reporting
541
541
  ```
542
542
 
543
+ `scanTransactions` walks the chain with paid RPC calls per wallet. To restore a wallet or pick up
544
+ received notes, prefer [the Note Index](#restore-from-the-note-index-no-chain-walk), which costs one
545
+ RPC request; keep `scanTransactions` for compliance history.
546
+
543
547
  `scanRecipientDeliveryNotes` does the delivery sweep alone, returning `{ notes, rpcCalls }`
544
548
  instead of a full scan result. Deposit recovery applies to deposits built with
545
549
  `createRecoverableDepositUtxo` (the default in the examples); a deposit built with
@@ -563,7 +567,7 @@ a base58 `mint` (set only when the scan was given `ownerUtxoPublicKey`) and no k
563
567
  keypair is yours.
564
568
 
565
569
  ```ts
566
- import { address } from "@cloak.dev/sdk";
570
+ import { address, fetchCommitments, NATIVE_SOL_MINT, type Utxo } from "@cloak.dev/sdk";
567
571
 
568
572
  const entries = await fetchCommitments(relayUrl, { mint: NATIVE_SOL_MINT });
569
573
  const indexOf = (commitment: bigint) =>
@@ -602,6 +606,98 @@ the `Utxo` from one as shown under [Timed-out swaps](#timed-out-swaps).
602
606
 
603
607
  `toComplianceReport(scan)` and `formatComplianceCsv(report)` turn a scan into a report.
604
608
 
609
+ ## Restore from the Note Index (no chain walk)
610
+
611
+ `scanTransactions` walks the program's signature history and fetches every transaction over RPC:
612
+ thousands of paid calls per wallet. From 0.2.6 the relay also serves a **Note Index**: one bulk,
613
+ unauthenticated, cacheable feed of every confirmed Cloak transaction (encrypted notes, leaves,
614
+ nullifiers), the same bytes for everyone. `recoverNotesFromIndex` downloads all of it, opens each
615
+ item locally under the wallet's keys, rebuilds every listed pool's tree from the index's own leaf
616
+ stream, and checks those trees with exactly **one** RPC request (`getMultipleAccounts` of the pool
617
+ tree accounts). Spent status comes from the nullifiers in the index, so no nullifier of the wallet
618
+ reaches the relay or the RPC, and the only request parameters are the epoch and a page number.
619
+
620
+ It needs a relay that serves `GET /note-index/v1/head` (the 0.2.6 relay with the index enabled); an
621
+ older relay answers 404. Use it for restore after a reinstall, for received private sends, and for
622
+ change made on another device.
623
+
624
+ ```ts
625
+ import {
626
+ address,
627
+ CLOAK_PROGRAM_ID,
628
+ fetchNoteIndexHead,
629
+ NATIVE_SOL_MINT,
630
+ recoverNotesFromIndex,
631
+ type NoteIndexCursor,
632
+ } from "@cloak.dev/sdk";
633
+
634
+ const USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
635
+ const USDT = address("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");
636
+ let savedCursor: NoteIndexCursor | undefined = loadCursor(); // your own private storage
637
+
638
+ const result = await recoverNotesFromIndex({
639
+ relayUrl, // must be on this build's relay allowlist
640
+ connection, // used for ONE getMultipleAccounts
641
+ programId: CLOAK_PROGRAM_ID,
642
+ poolMints: [NATIVE_SOL_MINT, USDC, USDT], // every pool the app uses, not only the ones with notes
643
+ viewingKeyNk: nk,
644
+ ownerUtxoKeypair: owner, // with its real private key
645
+ cursor: savedCursor, // omit for a full sync from page 0
646
+ onProgress: ({ pagesDone, pagesTotal }) => console.log(`${pagesDone}/${pagesTotal}`),
647
+ });
648
+
649
+ result.notes; // verified, unspent, owned by `owner`: ready to spend (leaf index included)
650
+ result.atRisk; // verified, unspent, but spendable or readable by nk holders (legacyExposed: true): migrate
651
+ result.pending; // candidates not verifiable yet; they travel inside the cursor
652
+ result.cursor; // persist it and pass it back next time
653
+ result.stats; // pages, items, bytes, rpcCalls (1), ms, ...
654
+ result.warnings; // non-fatal events, e.g. a re-sync from page 0
655
+ ```
656
+
657
+ **What you can trust.** A note is returned only when it opens under the wallet's keys, its
658
+ commitment recomputes from the opened values and the wallet's owner key, and it sits at its leaf in
659
+ a tree the chain authenticates. A dishonest relay can hide items; it cannot inject, alter or
660
+ re-point a note. A hidden nullifier can make a spent note look unspent, so spend restored notes
661
+ through `transact`, `transfer`, `partialWithdraw`, `fullWithdraw` or `swapUtxo`, which run
662
+ `preflightNullifiers` before proving.
663
+ One malformed or crafted entry (anyone can write a note under a public legacy viewing key) is
664
+ skipped and counted in `stats.skipped`, never fatal; only a broken page, hash chain or head fails
665
+ the run.
666
+
667
+ **The cursor.** JSON, no key material, but it records which index items are the wallet's: store it
668
+ as privately as the notes, one per wallet and relay origin, and never hand one wallet's cursor to
669
+ another wallet or another owner key. Write it only after the notes it covers are stored. An epoch
670
+ change, a broken hash chain or an invalid cursor re-syncs from page 0 by itself.
671
+
672
+ **Polling.** Fetch the head (tiny and cacheable) and run a recovery only when it moved:
673
+
674
+ ```ts
675
+ const head = await fetchNoteIndexHead(relayUrl);
676
+ const moved = !savedCursor || savedCursor.epoch !== head.epoch.toString(10) || savedCursor.watermark !== head.watermark;
677
+ if (moved) {
678
+ /* recoverNotesFromIndex({ ..., cursor: savedCursor }) */
679
+ }
680
+ ```
681
+
682
+ Decide on the head alone. `pending` depends on what the wallet owns (a relay can make it non-zero
683
+ for the owner of one item), so a poll that re-downloads while `pending > 0` tells the relay which
684
+ client owns that item. Pending candidates are retried on the next run the head triggers.
685
+
686
+ **Errors.** `NoteIndexHeadBehindError` is retryable: a cached head from another CDN edge trails the
687
+ cursor; keep the cursor and try again later. `NoteIndexFormatError` means the relay served data that
688
+ did not verify; keep the cursor and report it. A 404 on the head means the relay does not serve the
689
+ index.
690
+
691
+ **Notes from older clients.** Notes whose owner key an SDK before 0.2.6 derived from nk come back in
692
+ `atRisk`. If an older version of your app encrypted chain notes under a different viewing key, pass
693
+ those keys as `legacyViewingKeyNks` (at most 8): they are tried in the same download at no extra
694
+ request, and everything found only through one of them is returned in `atRisk`, never in `notes`.
695
+ A legacy key never opens a delivered note. `legacyCutoffLeaf` (per mint) ignores legacy-shaped notes
696
+ at or after a leaf, for example the first leaf after your app stopped writing them.
697
+
698
+ From a browser the relay answers only the origins its CORS policy allows; servers and native apps
699
+ are not affected.
700
+
605
701
  ## Nullifiers and spent checks
606
702
 
607
703
  The nullifier export is `computeUtxoNullifier(utxo)`, the circuit's scheme:
@@ -696,9 +792,11 @@ relay endpoint and the localhost-RPC check.
696
792
 
697
793
  - SDK 0.2.6 pairs with the mainnet program at `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`
698
794
  (deployed 2026-08-24) and the 0.2.0 circuit bundle — the program and circuit bundle are unchanged
699
- since 0.2.0; only the SDK package version has moved. All flows in this README were exercised on
700
- mainnet on 2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to
701
- USDC and USDT; viewing-key discovery followed by a spend; keypair-only deposit recovery.
795
+ since 0.2.0; only the SDK package version has moved. The 0.2.5 flows were exercised on mainnet on
796
+ 2026-08-25: deposit, private send and withdraw on SOL, USDC and USDT; swaps SOL to USDC and USDT;
797
+ viewing-key discovery followed by a spend; keypair-only deposit recovery. The 0.2.6 API (the
798
+ required `ownerUtxoKeypair`, the relay clock and the Note Index restore) was exercised end to end
799
+ against a local mainnet fork with the 0.2.6 relay, not yet on mainnet.
702
800
  - 0.2.2 adds the opt-in `TransactOptions.relaySupplementalAlt` (see [SPL pools](#spl-pools-usdc-usdt)):
703
801
  off by default, and existing behavior is unchanged when it is left unset.
704
802
  - 0.2.5 moves the SDK from `@solana/web3.js` to `@solana/kit`. The program, the circuit bundle,
package/dist/index.cjs CHANGED
@@ -1562,7 +1562,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
1562
1562
 
1563
1563
  // src/config/relay.ts
1564
1564
  var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
1565
- var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
1565
+ var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
1566
1566
  var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
1567
1567
  var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
1568
1568
  var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
@@ -1642,7 +1642,7 @@ var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
1642
1642
  // src/relay/clock.ts
1643
1643
  var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
1644
1644
  var MAX_CLOCK_DIVERGENCE_MS = 2e3;
1645
- var MAX_PLAUSIBLE_OFFSET_MS = 365 * 24 * 60 * 60 * 1e3;
1645
+ var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
1646
1646
  var sample = null;
1647
1647
  function monotonicNowMs() {
1648
1648
  const perf = globalThis.performance;
@@ -12875,7 +12875,7 @@ function parseSwapRefund(r) {
12875
12875
  checkLeafPair(commitment, leaf, "SWAP_REFUND");
12876
12876
  return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
12877
12877
  }
12878
- function parseNoteIndexPage(bytes, expect) {
12878
+ function parseNoteIndexPage(bytes, expect, options = {}) {
12879
12879
  if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
12880
12880
  if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
12881
12881
  throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
@@ -12907,7 +12907,9 @@ function parseNoteIndexPage(bytes, expect) {
12907
12907
  }
12908
12908
  const items = [];
12909
12909
  const rawItems = [];
12910
+ const itemPositions = [];
12910
12911
  let skippedUnknown = 0;
12912
+ let skippedMalformed = 0;
12911
12913
  let offset = NOTE_INDEX_HEADER_LEN;
12912
12914
  for (let i = 0; i < count; i++) {
12913
12915
  if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
@@ -12916,34 +12918,45 @@ function parseNoteIndexPage(bytes, expect) {
12916
12918
  const bodyStart = offset + ITEM_HEADER_LEN;
12917
12919
  const bodyEnd = bodyStart + bodyLen;
12918
12920
  if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
12919
- const r = new Reader(bytes, bodyStart, bodyEnd);
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
+ }
12920
12927
  let item;
12921
- switch (kind) {
12922
- case NOTE_INDEX_KIND_TX:
12923
- if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
12924
- item = parseTx(r, bodyLen);
12925
- break;
12926
- case NOTE_INDEX_KIND_DELIVERY:
12927
- if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
12928
- item = parseDelivery(r);
12929
- break;
12930
- case NOTE_INDEX_KIND_SWAP_REFUND:
12931
- if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
12932
- item = parseSwapRefund(r);
12933
- break;
12934
- default:
12935
- if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
12936
- skippedUnknown++;
12937
- offset = bodyEnd;
12938
- continue;
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;
12939
12935
  }
12940
- if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
12941
12936
  items.push(item);
12942
12937
  rawItems.push(bytes.slice(offset, bodyEnd));
12938
+ itemPositions.push(i);
12943
12939
  offset = bodyEnd;
12944
12940
  }
12945
12941
  if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
12946
- return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown };
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;
12947
12960
  }
12948
12961
  function parseNoteIndexItem(raw) {
12949
12962
  if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
@@ -13276,6 +13289,7 @@ var MAX_REJECTED_IDS = 1024;
13276
13289
  var LEAF_WINDOW = 512;
13277
13290
  var MAX_OVERRIDES = 256;
13278
13291
  var MAX_CURSOR_OWN_ITEMS = 65536;
13292
+ var MAX_LEGACY_VIEWING_KEYS = 8;
13279
13293
  var MAX_CURSOR_KEYS = 131072;
13280
13294
  var MAX_CURSOR_POOLS = 256;
13281
13295
  var MAX_CURSOR_PAGE = 2 ** 32;
@@ -13366,7 +13380,23 @@ var LeafBuffer = class {
13366
13380
  return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
13367
13381
  }
13368
13382
  };
13369
- async function trialItem(item, trial) {
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) {
13370
13400
  if (item.kind === 1) {
13371
13401
  if (item.note.length === 0) return null;
13372
13402
  let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
@@ -13397,8 +13427,14 @@ function leafOfTxOutput(item, commitment) {
13397
13427
  if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
13398
13428
  return null;
13399
13429
  }
13400
- async function matchOwnItems(own, trial, onReject) {
13401
- const { nk, owner } = trial;
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) {
13402
13438
  const candidates = [];
13403
13439
  const claimed = /* @__PURE__ */ new Set();
13404
13440
  const byNullifier = /* @__PURE__ */ new Map();
@@ -13422,27 +13458,26 @@ async function matchOwnItems(own, trial, onReject) {
13422
13458
  queued.add(o);
13423
13459
  queue.push(o);
13424
13460
  };
13425
- const add = async (c) => {
13461
+ const add = async (o, c) => {
13426
13462
  const nullifier = hex32(
13427
13463
  await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
13428
13464
  );
13429
- const full = { ...c, nullifier };
13465
+ const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
13430
13466
  candidates.push(full);
13431
13467
  if (!byNullifier.has(nullifier)) {
13432
13468
  byNullifier.set(nullifier, full);
13433
- for (const o of spendsOf.get(nullifier) ?? []) enqueue(o);
13469
+ for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
13434
13470
  }
13435
- if (full.atRisk && !legacyKeys.has(full.keypair.publicKey)) {
13436
- legacyKeys.set(full.keypair.publicKey, full.keypair);
13437
- for (const o of byOutKey.get(full.keypair.publicKey) ?? []) enqueue(o);
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);
13438
13474
  }
13439
13475
  };
13440
- const base = (o) => ({ signature: o.item.signature, page: o.page, seq: o.seq });
13441
13476
  const tryDeposit = async (o, item, amount) => {
13442
13477
  const note = o.note;
13443
13478
  const mint = addressFromBytes(item.mint);
13444
13479
  const deposit = await matchDepositNote({
13445
- viewingKeyNk: nk,
13480
+ viewingKeyNk: o.trial.nk,
13446
13481
  noteSalt: note.noteSalt,
13447
13482
  amount,
13448
13483
  mintAddress: mint,
@@ -13451,7 +13486,7 @@ async function matchOwnItems(own, trial, onReject) {
13451
13486
  });
13452
13487
  const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
13453
13488
  if (!deposit || leaf === null) return false;
13454
- await add({
13489
+ await add(o, {
13455
13490
  kind: "deposit",
13456
13491
  atRisk: deposit.legacyExposed,
13457
13492
  amount: deposit.amount,
@@ -13459,8 +13494,7 @@ async function matchOwnItems(own, trial, onReject) {
13459
13494
  keypair: deposit.legacyExposed ? deposit.keypair : owner,
13460
13495
  mint,
13461
13496
  commitment: deposit.commitment,
13462
- leaf,
13463
- ...base(o)
13497
+ leaf
13464
13498
  });
13465
13499
  return true;
13466
13500
  };
@@ -13468,7 +13502,7 @@ async function matchOwnItems(own, trial, onReject) {
13468
13502
  const note = o.note;
13469
13503
  const mint = addressFromBytes(item.mint);
13470
13504
  const change = await matchChangeNote({
13471
- viewingKeyNk: nk,
13505
+ viewingKeyNk: o.trial.nk,
13472
13506
  noteSalt: note.noteSalt,
13473
13507
  amount: note.outAmount0,
13474
13508
  keypair,
@@ -13478,7 +13512,7 @@ async function matchOwnItems(own, trial, onReject) {
13478
13512
  ownerUtxoPublicKey: owner.publicKey
13479
13513
  });
13480
13514
  if (!change) return false;
13481
- await add({
13515
+ await add(o, {
13482
13516
  kind: "change",
13483
13517
  atRisk,
13484
13518
  amount: change.amount,
@@ -13486,12 +13520,11 @@ async function matchOwnItems(own, trial, onReject) {
13486
13520
  keypair,
13487
13521
  mint,
13488
13522
  commitment: change.commitment,
13489
- leaf: Number(item.leaf0),
13490
- ...base(o)
13523
+ leaf: Number(item.leaf0)
13491
13524
  });
13492
13525
  return true;
13493
13526
  };
13494
- for (const o of own) {
13527
+ const direct = async (o) => {
13495
13528
  const item = o.item;
13496
13529
  if (item.kind === 1 && o.note?.noteSalt !== void 0) {
13497
13530
  const note = o.note;
@@ -13505,7 +13538,7 @@ async function matchOwnItems(own, trial, onReject) {
13505
13538
  const mint = addressFromBytes(item.mint);
13506
13539
  if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
13507
13540
  onReject(o);
13508
- continue;
13541
+ return;
13509
13542
  }
13510
13543
  const commitment = await computeCommitment2({
13511
13544
  amount: o.delivery.amount,
@@ -13515,9 +13548,9 @@ async function matchOwnItems(own, trial, onReject) {
13515
13548
  });
13516
13549
  if (commitment !== bytesToBigint3(item.commitment)) {
13517
13550
  onReject(o);
13518
- continue;
13551
+ return;
13519
13552
  }
13520
- await add({
13553
+ await add(o, {
13521
13554
  kind: "received",
13522
13555
  atRisk: false,
13523
13556
  amount: o.delivery.amount,
@@ -13525,11 +13558,10 @@ async function matchOwnItems(own, trial, onReject) {
13525
13558
  keypair: owner,
13526
13559
  mint,
13527
13560
  commitment,
13528
- leaf: Number(item.leaf),
13529
- ...base(o)
13561
+ leaf: Number(item.leaf)
13530
13562
  });
13531
13563
  } else if (item.kind === 3 && o.refund) {
13532
- await add({
13564
+ await add(o, {
13533
13565
  kind: "swap_refund",
13534
13566
  atRisk: o.refund.legacyExposed,
13535
13567
  amount: o.refund.amount,
@@ -13537,10 +13569,16 @@ async function matchOwnItems(own, trial, onReject) {
13537
13569
  keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
13538
13570
  mint: NATIVE_SOL_MINT,
13539
13571
  commitment: o.refund.commitment,
13540
- leaf: Number(item.leaf),
13541
- ...base(o)
13572
+ leaf: Number(item.leaf)
13542
13573
  });
13543
13574
  }
13575
+ };
13576
+ for (const o of own) {
13577
+ try {
13578
+ await direct(o);
13579
+ } catch {
13580
+ onSkip(o);
13581
+ }
13544
13582
  }
13545
13583
  const processTx = async (o) => {
13546
13584
  const item = o.item;
@@ -13555,8 +13593,9 @@ async function matchOwnItems(own, trial, onReject) {
13555
13593
  const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
13556
13594
  if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
13557
13595
  const out1 = sumIn + item.publicAmount - note.outAmount0;
13558
- if (out1 > 0n) {
13559
- const blinding = deriveChangeNoteBlinding(nk, note.noteSalt, 1);
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) {
13560
13599
  const owners = [{ keypair: owner, atRisk: false }];
13561
13600
  const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
13562
13601
  if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
@@ -13564,7 +13603,7 @@ async function matchOwnItems(own, trial, onReject) {
13564
13603
  const commitment = await computeCommitment2({ amount: out1, keypair, blinding, mintAddress: mint });
13565
13604
  if (commitment !== bytesToBigint3(item.comm1)) continue;
13566
13605
  claimed.add(`${o.seq}:1`);
13567
- await add({ kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1), ...base(o) });
13606
+ await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
13568
13607
  break;
13569
13608
  }
13570
13609
  }
@@ -13577,7 +13616,11 @@ async function matchOwnItems(own, trial, onReject) {
13577
13616
  for (let i = 0; i < queue.length; i++) {
13578
13617
  const o = queue[i];
13579
13618
  queued.delete(o);
13580
- await processTx(o);
13619
+ try {
13620
+ await processTx(o);
13621
+ } catch {
13622
+ onSkip(o);
13623
+ }
13581
13624
  }
13582
13625
  return candidates;
13583
13626
  }
@@ -13824,7 +13867,8 @@ async function recoverNotesFromIndex(params) {
13824
13867
  candidates: 0,
13825
13868
  spent: 0,
13826
13869
  conflicts: 0,
13827
- pendingDropped: 0
13870
+ pendingDropped: 0,
13871
+ skipped: 0
13828
13872
  };
13829
13873
  const rpc = new Proxy(connection, {
13830
13874
  get(target, prop, receiver) {
@@ -13846,12 +13890,25 @@ async function recoverNotesFromIndex(params) {
13846
13890
  };
13847
13891
  }
13848
13892
  });
13849
- const trial = {
13850
- nk: viewingKeyNk,
13893
+ const makeTrial = async (nk, legacy) => ({
13894
+ nk,
13895
+ legacy,
13851
13896
  owner,
13852
- decrypt: await createCompactChainNoteDecryptor(viewingKeyNk),
13853
- open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(viewingKeyNk).privateKey)
13854
- };
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
+ }
13855
13912
  const poolMints = Array.from(new Set(params.poolMints));
13856
13913
  const warnings = [];
13857
13914
  const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
@@ -13874,21 +13931,21 @@ async function recoverNotesFromIndex(params) {
13874
13931
  return account && parsed ? { ...parsed, data: account.data } : null;
13875
13932
  });
13876
13933
  })());
13877
- const ctx = { params, head, trial, stats, poolMints, warnings, readTrees };
13934
+ const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
13878
13935
  let outcome = await runOnce(ctx, cursor);
13879
13936
  if (outcome instanceof FullPassSignal) {
13880
13937
  warnings.push(`${outcome.reason}; re-syncing from page 0`);
13881
- Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0 });
13938
+ Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
13882
13939
  outcome = await runOnce(ctx, void 0);
13883
13940
  if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
13884
13941
  }
13942
+ if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
13885
13943
  stats.ms = Date.now() - startedAt;
13886
13944
  return { ...outcome, stats, warnings };
13887
13945
  }
13888
13946
  async function runOnce(ctx, cursor) {
13889
- const { params, head, trial, stats, poolMints } = ctx;
13947
+ const { params, head, trials, owner, stats, poolMints } = ctx;
13890
13948
  const { relayUrl, onProgress } = params;
13891
- const owner = trial.owner;
13892
13949
  const poolSet = new Set(poolMints);
13893
13950
  const startPage = cursor?.raw.page ?? 0;
13894
13951
  const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
@@ -13959,11 +14016,13 @@ async function runOnce(ctx, cursor) {
13959
14016
  if (signal.aborted) throw abortError2();
13960
14017
  const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
13961
14018
  stats.bytes += bytes.length;
13962
- const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo });
14019
+ const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
13963
14020
  if (pageNo < head.completePages && !page2.complete) {
13964
14021
  throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
13965
14022
  }
13966
14023
  stats.pages++;
14024
+ stats.skipped += page2.skippedMalformed;
14025
+ const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
13967
14026
  waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
13968
14027
  advanceChain();
13969
14028
  const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
@@ -13984,7 +14043,7 @@ async function runOnce(ctx, cursor) {
13984
14043
  else data.leaves.set(mint, [entry]);
13985
14044
  };
13986
14045
  page2.items.forEach((item, i) => {
13987
- const seq = pageNo * NOTE_INDEX_PAGE_SIZE + i;
14046
+ const seq = seqOf(i);
13988
14047
  if (item.kind === 1) {
13989
14048
  addLeaf(item.mint, item.comm0, item.leaf0, seq);
13990
14049
  addLeaf(item.mint, item.comm1, item.leaf1, seq);
@@ -14001,7 +14060,7 @@ async function runOnce(ctx, cursor) {
14001
14060
  for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
14002
14061
  if (signal.aborted) throw abortError2();
14003
14062
  const batch = page2.items.slice(i, i + ITEM_BATCH);
14004
- const opened = await Promise.all(batch.map((item) => trialItem(item, trial)));
14063
+ const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
14005
14064
  opened.forEach((o, k) => {
14006
14065
  if (!o) return;
14007
14066
  stats.decrypted++;
@@ -14011,7 +14070,7 @@ async function runOnce(ctx, cursor) {
14011
14070
  stats.dropped++;
14012
14071
  return;
14013
14072
  }
14014
- ownItems.push({ page: pageNo, seq: pageNo * NOTE_INDEX_PAGE_SIZE + i + k, raw, id, item: batch[k], fromCursor: false, ...o });
14073
+ ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
14015
14074
  });
14016
14075
  stats.items += batch.length;
14017
14076
  }
@@ -14044,10 +14103,10 @@ async function runOnce(ctx, cursor) {
14044
14103
  throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
14045
14104
  }
14046
14105
  for (const entry of cursor?.items ?? []) {
14047
- const o = await trialItem(entry.item, trial);
14106
+ const o = await trialItemIsolated(entry.item, trials, stats);
14048
14107
  if (!o) continue;
14049
14108
  const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
14050
- ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o });
14109
+ ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
14051
14110
  if (entry.item.kind === 1) {
14052
14111
  if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
14053
14112
  if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
@@ -14056,10 +14115,20 @@ async function runOnce(ctx, cursor) {
14056
14115
  const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
14057
14116
  ownItems.sort((a, b) => a.seq - b.seq);
14058
14117
  const rejectedNow = /* @__PURE__ */ new Set();
14059
- const allCandidates = await matchOwnItems(ownItems, trial, (o) => {
14060
- stats.dropped++;
14061
- rejectedNow.add(o.id);
14062
- });
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
+ );
14063
14132
  stats.candidates = allCandidates.length;
14064
14133
  const cutoff = params.legacyCutoffLeaf ?? {};
14065
14134
  const candidates = allCandidates.filter((c) => {