@audren-xyz/sdk 0.0.0-stage → 1.3.0

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.
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Indexer-free ordinary Solana RPC (`getMultipleAccounts`) 2-pass sync & historical witness
3
+ * reconstruction with privacy-preserving defaults (`privacyMode: 'strict'`):
4
+ *
5
+ * 1. `SubtreeRootPage` fast sync (`126 KB` / 1M notes vs `32.3 MB` of sealed `SubtreePage`s).
6
+ * 2. Default `'strict'` mode fetches full `10,240 B` `MemoPage`s in uniform 100-account batches
7
+ * (never revealing view-tag hits via `dataSlice` -> single-page re-fetch), fetches
8
+ * `SubtreePage`s covering newly synced leaves uniformly on incremental syncs (`<= 25` pages /
9
+ * `<= 25` subtrees), and uses deterministic wallet-keyed decoy selection
10
+ * (`SHA256(viewSk || "audren/v1/decoy" || epochBucket)`) with a fixed uniform batch count
11
+ * independent of hit count on large catch-ups (`> 25` pages) so repeated syncs cannot be
12
+ * intersected.
13
+ * 3. Opt-in `'fast'` mode (for bandwidth-constrained cold recovery over self-hosted/trusted RPCs)
14
+ * uses `MemoPage` SoA `dataSlice` (`[0..3,328]`) on large catch-ups (`> 25` pages), while
15
+ * still fetching full `MemoPage`s directly on small incremental syncs (`<= 25` pages).
16
+ * 4. Optional `birthdaySlot` binary search on `64 B` page headers (`closedSlot < birthdaySlot`).
17
+ * 5. `reconstructWitness()` decoy-pads `SubtreePage` fetches across active lanes up to
18
+ * `min(16, totalSubtrees)` and shuffles them so spending never issues a pinpoint single-page
19
+ * fetch.
20
+ *
21
+ * Pass 1 ingests tree subroots, memos, and frontier leaves across ALL active lanes first so every
22
+ * owned note is present in `store.notes`. Pass 2 ALWAYS executes unconditionally on every sync
23
+ * (even after a transient Pass 1D `SubtreePage` miss — preventing a Pass 1D -> Pass 2 drop oracle),
24
+ * streaming ALL new `NullifierPage`s up to `laneHdr.nfCount` in uniform 100-account batches
25
+ * (zero early-exit when 0 unspent notes exist or after the last unspent note is spent), matching
26
+ * against an `O(owned_unspent_notes)` map and discarding stranger prefixes immediately.
27
+ */
28
+ import type { FullViewingKey } from './keys.ts';
29
+ import { type DecodedGlobalRootHistory, type DecodedLaneHeader, type DecodedPoolState, type RootSnapshotChoice } from './layout.ts';
30
+ import { type CompactWalletStore, type MerklePath4Ary } from './store.ts';
31
+ /** Maximum new `MemoPage`s fetched as an incremental sync (`<= ~256 KB`). */
32
+ export declare const INCREMENTAL_FULL_MEMO_PAGE_THRESHOLD = 25;
33
+ /** Maximum newly synced `SubtreePage`s fetched uniformly on incremental sync in `'strict'` mode. */
34
+ export declare const INCREMENTAL_UNIFORM_SUBTREE_THRESHOLD = 25;
35
+ /** Minimum sealed `SubtreePage` anonymity set size when decoy-padding in `'strict'` mode. */
36
+ export declare const STRICT_DECOY_SEALED_SUBTREE_TARGET = 16;
37
+ /** Maximum publicly-duplicated `canonEpk` sealed `SubtreePage`s resolved per sync call in `'strict'` mode. */
38
+ export declare const MAX_PUBLIC_DUP_SUBTREES = 64;
39
+ /** Sealed-subtree count divisor for deterministic decoy epoch buckets (synced with Rust SDK). */
40
+ export declare const DECOY_EPOCH_BUCKET_SIZE = 64;
41
+ /** Maximum pages fetched per pass in a single `syncCompactStoreWithRpc` call (prevents untrusted-RPC OOM/hang). */
42
+ export declare const MAX_SYNC_PAGES_PER_CALL = 4096;
43
+ /** Maximum total `SubtreeRootPage`s fetched in a single `reconstructWitness` call (`4,096 * 300 = 1.22M` subtrees). */
44
+ export declare const MAX_WITNESS_SR_PAGES = 4096;
45
+ /** Maximum total sealed subtrees scanned by `selectHrwSealedDecoys` (`262,144 * 256 = 67M` notes). */
46
+ export declare const MAX_HRW_SEALED_SUBTREES = 262144;
47
+ export type SyncPrivacyMode = 'strict' | 'fast';
48
+ /**
49
+ * Deterministic Rendezvous (Highest Random Weight) sealed `SubtreePage` decoy selection matching
50
+ * `crates/client/src/scanner.rs::try_select_hrw_sealed_decoys_in_ranges` bit-for-bit:
51
+ *
52
+ * `score = SHA256(viewSk[32] || "audren/v1/decoy" || scope || epochBucket_le8 || laneId || pageSeq_le8)`
53
+ *
54
+ * Supports optional `startSeq` per lane (default `0n`) so Pass 1D catch-up syncs restrict decoys
55
+ * strictly to the RPC-visible scanned window `[startSeq .. sealedCount)`.
56
+ */
57
+ export declare function selectHrwSealedDecoys(params: {
58
+ viewSk: Uint8Array;
59
+ scope: Uint8Array;
60
+ epochBucket: bigint;
61
+ sealedByLane: ReadonlyArray<{
62
+ laneId: number;
63
+ startSeq?: bigint;
64
+ sealedCount: bigint;
65
+ }>;
66
+ alreadySelected: ReadonlySet<string>;
67
+ targetSealed: number;
68
+ }): Array<{
69
+ laneId: number;
70
+ pageSeq: bigint;
71
+ }>;
72
+ /**
73
+ * Hit-independent O(`targetSealed`) deterministic uniform decoy sampler across ALL sealed
74
+ * subtrees `[0 .. fc_l)` on ALL active lanes when `totalSealed > MAX_HRW_SEALED_SUBTREES`.
75
+ *
76
+ * Matches `crates/client/src/scanner.rs::select_large_pool_hrw_sealed_decoys` bit-for-bit.
77
+ */
78
+ export declare function selectLargePoolHrwSealedDecoys(params: {
79
+ viewSk: Uint8Array;
80
+ scope: Uint8Array;
81
+ epochBucket: bigint;
82
+ sealedByLane: ReadonlyArray<{
83
+ laneId: number;
84
+ sealedCount: bigint;
85
+ }>;
86
+ alreadySelected: ReadonlySet<string>;
87
+ targetSealed: number;
88
+ }): Array<{
89
+ laneId: number;
90
+ pageSeq: bigint;
91
+ }>;
92
+ export interface AccountBatchFetchOptions {
93
+ dataSlice?: {
94
+ offset: number;
95
+ length: number;
96
+ };
97
+ }
98
+ export type AccountBatchFetcher = (addresses: readonly string[], options?: AccountBatchFetchOptions) => Promise<(Uint8Array | null)[]>;
99
+ /** Ordinary Solana JSON-RPC `getMultipleAccounts` batch fetcher (chunks by 100 accounts, supports `dataSlice` and timeouts/abort signals). */
100
+ export declare function createSolanaRpcBatchFetcher(rpcUrl: string, commitment?: 'confirmed' | 'finalized', options?: {
101
+ timeoutMs?: number;
102
+ signal?: AbortSignal;
103
+ }): AccountBatchFetcher;
104
+ /**
105
+ * Fetch `PoolState` + all `NUM_LANES` (16) `LaneTreeState` headers atomically in ONE
106
+ * 17-account `getMultipleAccounts` RPC batch (eliminating `InitLane` expansion snapshot skew
107
+ * and saving 1 RPC round-trip on every sync).
108
+ */
109
+ export declare function fetchPoolAndLanes(fetchBatch: AccountBatchFetcher, poolId?: number, programId?: string): Promise<{
110
+ pool: DecodedPoolState;
111
+ lanes: DecodedLaneHeader[];
112
+ }>;
113
+ /**
114
+ * Incrementally sync `CompactWalletStore` across all active lanes via ordinary `getMultipleAccounts`
115
+ * calls using 2-pass sync (`SubtreeRootPage` fast sync + privacy-first `'strict'` full-`MemoPage`
116
+ * batches & deterministic wallet-keyed decoy-padded `SubtreePage` fetches, or explicit opt-in
117
+ * `'fast'` SoA `dataSlice` on `> 25` pages + optional `birthdaySlot` header binary search +
118
+ * unconditional zero-early-exit `NullifierPage` streaming).
119
+ */
120
+ export declare function syncCompactStoreWithRpc(params: {
121
+ store: CompactWalletStore;
122
+ fvk: FullViewingKey;
123
+ fetchBatch: AccountBatchFetcher;
124
+ programId?: string;
125
+ birthdaySlot?: bigint | number;
126
+ latestRootHistory?: DecodedGlobalRootHistory | RootSnapshotChoice;
127
+ privacyMode?: SyncPrivacyMode;
128
+ decoyEpochBucket?: bigint;
129
+ }): Promise<{
130
+ pool: DecodedPoolState;
131
+ lanes: DecodedLaneHeader[];
132
+ discoveredNotes: number;
133
+ incomplete: boolean;
134
+ }>;
135
+ /**
136
+ * Strictly validate a decoded `GlobalRootHistory` before trusting any root or lane count from an
137
+ * untrusted RPC: enforces u32 `poolId`, ring cursor/count and ring-array bounds, `epochInterval`,
138
+ * `stableSlot <= latestSlot`, `stableEpochId === stableSlot / epochInterval`, `NUM_LANES` arrays,
139
+ * `0..=MAX_LEAVES_PER_LANE` counts, `stableLaneCounts[l] <= latestLaneCounts[l]`, non-zero
140
+ * `latest`/`stable` super-roots, ring cursor `superRoot` & `slot` equality, full canonical BN254
141
+ * `Fr` + 4-ary super-root integrity for BOTH `latest` and `stable` snapshots, zero-count
142
+ * `ZERO_HASHES_4ARY[18]` lane roots, and equal-count lane-root equality.
143
+ */
144
+ export declare function validateGlobalRootHistory(history: DecodedGlobalRootHistory, poolId: number): void;
145
+ /**
146
+ * Strictly validate a `RootSnapshotChoice`: runtime shape, ring kind/index bounds, u64 `slot`,
147
+ * non-zero canonical BN254 `Fr` `superRoot` & `laneRoots`, `computeSuperRoot4Ary(laneRoots) === superRoot`,
148
+ * `laneCounts[l]` in `0n..=MAX_LEAVES_PER_LANE`, and `laneCounts[l] === 0n <=> laneRoots[l] === ZERO_HASHES_4ARY[18]`.
149
+ */
150
+ export declare function validateRootSnapshotChoice(snapshot: RootSnapshotChoice): void;
151
+ /**
152
+ * Fetch and strictly validate `GlobalRootHistory` using a `finalized`-first + `confirmed`-fallback
153
+ * strategy:
154
+ * - Reads `finalized` first for maximum reorg-proof proving stability (`ROOT_RING_EPOCH` when
155
+ * covered, else `ROOT_RING_SLOT`).
156
+ * - Seamlessly falls back to `confirmed` when a freshly deposited note in `requiredNotes` is not
157
+ * yet included in the `finalized` root history (enabling instant 0-slot spendability).
158
+ */
159
+ export declare function fetchGlobalRootHistory(params: {
160
+ poolId?: number;
161
+ programId?: string;
162
+ fetchFinalized?: AccountBatchFetcher;
163
+ fetchConfirmed?: AccountBatchFetcher;
164
+ rpcUrl?: string;
165
+ requiredNotes?: ReadonlyArray<{
166
+ laneId: number;
167
+ leafIndex: bigint;
168
+ }>;
169
+ }): Promise<{
170
+ history: DecodedGlobalRootHistory;
171
+ snapshot: RootSnapshotChoice;
172
+ commitment: 'finalized' | 'confirmed';
173
+ }>;
174
+ export interface ReconstructedWitnessResult {
175
+ roots: DecodedGlobalRootHistory | null;
176
+ snapshot: RootSnapshotChoice;
177
+ rootRingKind: number;
178
+ rootRingIdx: number;
179
+ superRoot: bigint;
180
+ snapshotSlot: bigint;
181
+ laneRoots: Uint8Array[];
182
+ laneCounts: bigint[];
183
+ path: MerklePath4Ary;
184
+ }
185
+ /**
186
+ * Stateless witness reconstruction for `(laneId, leafIdx)` against `GlobalRootHistory`
187
+ * (`deriveRootsPdaSync(poolId)`).
188
+ *
189
+ * Supports multi-note snapshot selection (`allInputNotes` or pre-selected `rootSnapshot`) so
190
+ * 2-input `Transact` / `ExecViaEscrow` and multi-instruction batches all prove against the exact
191
+ * same `(rootRingKind, rootRingIdx, superRoot)`.
192
+ *
193
+ * In default `'strict'` mode, eliminates `laneId` and pinpoint-spend correlation:
194
+ * - Requires a 32-byte `viewSk` (preventing fresh-key retry intersection).
195
+ * - Fetches ALL active lanes' `SubtreeRootPage`s uniformly (never capped by `neededSrPages`).
196
+ * - Fetches ALL active lanes' unsealed frontier `SubtreePage`s uniformly (never only `params.laneId`).
197
+ * - Fetches `min(16, totalSealed)` sealed `SubtreePage`s via Rendezvous (HRW) hashing scoped to
198
+ * `("witness" || laneId || targetPageSeq_le8, epochBucket=0)` so spending two different notes
199
+ * in the same epoch uses independent decoy sets while retries of the same note stay identical.
200
+ * - Shuffles the combined batch, fetches in 100-account chunks, and uniformly validates EVERY
201
+ * fetched page (both target AND decoy/non-target lanes) so an adversarial RPC dropping half the
202
+ * batch cannot learn which lane or page is the user's.
203
+ * - Verifies `computeMerkleRoot4Ary(path, targetLeaf) === superRoot` before returning.
204
+ */
205
+ export interface ReconstructedWitnessesBatchResult {
206
+ roots: DecodedGlobalRootHistory | null;
207
+ snapshot: RootSnapshotChoice;
208
+ rootRingKind: number;
209
+ rootRingIdx: number;
210
+ superRoot: bigint;
211
+ snapshotSlot: bigint;
212
+ laneRoots: Uint8Array[];
213
+ laneCounts: bigint[];
214
+ paths: MerklePath4Ary[];
215
+ }
216
+ /**
217
+ * Reconstruct 4-ary Depth-20 Merkle witnesses for one or more notes in a SINGLE uniform,
218
+ * decoy-padded `getMultipleAccounts` batch matching Rust
219
+ * `crates/client/src/scanner.rs::reconstruct_witness_for_notes_with_batch` bit-for-bit.
220
+ *
221
+ * Eliminates multi-note input-count leakage (`1` vs `2` vs `2k`) on RPC fallback by combining
222
+ * all notes into one canonical byte-sorted batch with order-independent HRW decoy scope.
223
+ */
224
+ export declare function reconstructWitnessesForNotes(params: {
225
+ fetchBatch: AccountBatchFetcher;
226
+ poolId: number;
227
+ notes: ReadonlyArray<{
228
+ laneId: number;
229
+ leafIndex: bigint;
230
+ }>;
231
+ allInputNotes?: ReadonlyArray<{
232
+ laneId: number;
233
+ leafIndex: bigint;
234
+ }>;
235
+ rootSnapshot?: RootSnapshotChoice;
236
+ rootHistory?: DecodedGlobalRootHistory;
237
+ programId?: string;
238
+ privacyMode?: SyncPrivacyMode;
239
+ viewSk?: Uint8Array;
240
+ decoyEpochBucket?: bigint;
241
+ }): Promise<ReconstructedWitnessesBatchResult>;
242
+ /**
243
+ * Reconstruct a 4-ary Depth-20 Merkle witness for a single note (thin wrapper around
244
+ * `reconstructWitnessesForNotes`). For multi-note spends, prefer calling
245
+ * `reconstructWitnessesForNotes` directly so all inputs share ONE decoy-padded RPC batch.
246
+ */
247
+ export declare function reconstructWitness(params: {
248
+ fetchBatch: AccountBatchFetcher;
249
+ poolId: number;
250
+ laneId: number;
251
+ leafIdx: bigint;
252
+ allInputNotes?: ReadonlyArray<{
253
+ laneId: number;
254
+ leafIndex: bigint;
255
+ }>;
256
+ rootSnapshot?: RootSnapshotChoice;
257
+ rootHistory?: DecodedGlobalRootHistory;
258
+ programId?: string;
259
+ privacyMode?: SyncPrivacyMode;
260
+ viewSk?: Uint8Array;
261
+ decoyEpochBucket?: bigint;
262
+ }): Promise<ReconstructedWitnessResult>;