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

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,76 @@ 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.
98
+
99
+ ### Note Index v1 (restore without walking the chain)
100
+
101
+ Restore and note discovery read the relay's Note Index: one bulk, unauthenticated, cacheable feed
102
+ of every confirmed Cloak transaction that the relay indexes once, server side. A restore costs one
103
+ `getMultipleAccounts` (the pool tree accounts) instead of a `getSignaturesForAddress` /
104
+ `getTransaction` walk per user. Needs a relay with migration `26_note_index.sql` and
105
+ `NOTE_INDEX_PUBLISH_ENABLED=true`.
106
+
107
+ #### Added
108
+
109
+ * `recoverNotesFromIndex({ relayUrl, connection, programId, poolMints, viewingKeyNk,
110
+ ownerUtxoKeypair, cursor?, legacyViewingKeyNks?, legacyCutoffLeaf?, concurrency?, onProgress?,
111
+ signal? })` returns `{ notes, atRisk, pending, cursor, stats, warnings }`. It downloads every page (the only request
112
+ parameters are the epoch and the page number, so the relay learns nothing about which notes are
113
+ the wallet's), opens each item locally, rebuilds the tree of every listed pool from the index's
114
+ own leaf stream and checks it against the chain, and computes spent status from the index's
115
+ nullifiers. No nullifier of the wallet is sent to the relay or the RPC.
116
+ * A note is returned only when it opens under the wallet's keys, its commitment recomputes with
117
+ `ownerUtxoKeypair.publicKey` (or a legacy key this recovery derived from `nk`), and it sits at its
118
+ leaf in a root-verified tree. Notes owned by the wallet keypair go to `notes`; legacy notes whose
119
+ owner key is derivable from `nk` go to `atRisk` with `legacyExposed: true`, never into `notes`.
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.
131
+ * The cursor (format v2) is JSON with no key material; persist it for incremental syncs. An epoch
132
+ change, a broken hash chain or an invalid cursor re-syncs from page 0; a head behind the cursor
133
+ throws the retryable `NoteIndexHeadBehindError`.
134
+ * `fetchNoteIndexHead`, `fetchNoteIndexPage`, the strict wire format (`parseNoteIndexPage`,
135
+ `parseNoteIndexItem`, `encodeNoteIndexPage`, `encodeNoteIndexItem`, `computeNoteIndexChain`,
136
+ `NoteIndexFormatError`, `NOTE_INDEX_PAGE_SIZE`, `NOTE_INDEX_NO_LEAF`) and their types. The golden
137
+ vector `note-index-golden-v1.hex` is shared with the relay.
138
+
139
+ #### Security notes
140
+
141
+ * The relay is untrusted. It can hide items but cannot inject, alter or forge a note. A hidden
142
+ nullifier can make a spent note look unspent, so restored notes must be spent through
143
+ `transact`, `partialWithdraw`, `fullWithdraw` or `swapUtxo`, which run `preflightNullifiers`
144
+ before proving. `submitTransactToRelay` documents that it does not (as does the internal
145
+ `buildTransactInstruction`, which is not exported).
146
+ * Note Index reads never set the relay clock. Complete pages are immutable and cacheable for a
147
+ year, so a cached response replays a stale `x-cloak-server-time`; learning from it would date
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.
94
164
 
95
165
  ### Fixed
96
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,