@audren-xyz/sdk 0.0.0-stage → 1.3.1
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/LICENSE +202 -0
- package/README.md +102 -2
- package/dist/constants.d.ts +229 -0
- package/dist/constants.js +301 -0
- package/dist/crypto.d.ts +85 -0
- package/dist/crypto.js +520 -0
- package/dist/idl.d.ts +4291 -0
- package/dist/idl.js +5608 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +13 -0
- package/dist/instructions.d.ts +398 -0
- package/dist/instructions.js +1139 -0
- package/dist/keys.d.ts +67 -0
- package/dist/keys.js +194 -0
- package/dist/layout.d.ts +153 -0
- package/dist/layout.js +535 -0
- package/dist/pda.d.ts +65 -0
- package/dist/pda.js +508 -0
- package/dist/poseidon-constants.d.ts +13 -0
- package/dist/poseidon-constants.js +1401 -0
- package/dist/poseidon.d.ts +46 -0
- package/dist/poseidon.js +214 -0
- package/dist/prover-entry.d.ts +1 -0
- package/dist/prover-entry.js +1 -0
- package/dist/prover.d.ts +100 -0
- package/dist/prover.js +507 -0
- package/dist/relayer.d.ts +353 -0
- package/dist/relayer.js +270 -0
- package/dist/scanner.d.ts +262 -0
- package/dist/scanner.js +3119 -0
- package/dist/store.d.ts +186 -0
- package/dist/store.js +1403 -0
- package/dist/swap.d.ts +105 -0
- package/dist/swap.js +156 -0
- package/dist/token2022.d.ts +29 -0
- package/dist/token2022.js +168 -0
- package/dist/tx-v1.d.ts +63 -0
- package/dist/tx-v1.js +249 -0
- package/idl/audren.anchor.json +1750 -0
- package/idl/audren.codama.json +3856 -0
- package/package.json +76 -4
- package/wasm/audren_circuits.wasm +0 -0
- package/wasm/audren_joinsplit.pk +0 -0
package/dist/scanner.js
ADDED
|
@@ -0,0 +1,3119 @@
|
|
|
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 { sha256 } from '@noble/hashes/sha2.js';
|
|
29
|
+
import { AUDREN_PROGRAM_ID, EPOCH_RING_LEN, LANE_DEPTH_4ARY, MAX_ROOT_EPOCH_INTERVAL, MEMO_CT_LEN, MEMO_NOTES_PER_PAGE, MEMO_PAGE_HEADER_LEN, MEMO_PAGE_LEN, MEMO_PAGE_SCAN_SLICE_LEN, MM_OFF_CIPHERTEXTS, NF_PAGE_HEADER_LEN, NF_PER_PAGE, NUM_LANES, ROOT_RING_EPOCH, ROOT_RING_SLOT, SLOT_RING_LEN, SUBROOTS_PER_PAGE, SUBTREE_LEAVES, SUBTREE_LEVELS_4ARY, ZERO_HASHES_4ARY, } from './constants.js';
|
|
30
|
+
import { canonicalizePublicEpk, checkMemoPayloadForScan, checkMemoViewTag, tryDecryptAndVerifyMemoEntry, } from './crypto.js';
|
|
31
|
+
import { MAX_LEAVES_PER_LANE, decodeGlobalRootHistory, decodeLaneHeader, decodeMemoPage, decodeMemoPageHeader, decodeMemoPageScanSlice, decodeNullifierPageHeader, decodePoolState, decodeSubtreePage, decodeSubtreeRootPage, selectRootSnapshotForNotes, } from './layout.js';
|
|
32
|
+
import { base58Decode, deriveLanePdaSync, deriveMemoPdaSync, deriveNfPagePdaSync, derivePoolPdaSync, deriveRootsPdaSync, deriveSubrootPdaSync, deriveSubtreePdaSync, } from './pda.js';
|
|
33
|
+
import { computeSubtree256Root, computeSuperRoot4Ary, frFromBeBytesStrict, frToBeBytes, poseidon4, } from './poseidon.js';
|
|
34
|
+
import { buildHistoricalWitness4Ary, computeMerkleRoot4Ary, extractIntraSubtreeSiblings, } from './store.js';
|
|
35
|
+
const RPC_BATCH_CHUNK = 100;
|
|
36
|
+
const utf8Encoder = new TextEncoder();
|
|
37
|
+
const DECOY_DOMAIN_BYTES = utf8Encoder.encode('audren/v1/decoy');
|
|
38
|
+
const DECOY_LARGE_DOMAIN_BYTES = utf8Encoder.encode('audren/v1/hrw_large_dyadic');
|
|
39
|
+
const LARGE_HRW_HEIGHT = 62;
|
|
40
|
+
const LN2_Q32 = 2977044472n; // round(ln(2) * 2^32)
|
|
41
|
+
const DECOY_SCOPE_SYNC_BYTES = utf8Encoder.encode('sync');
|
|
42
|
+
const DECOY_SCOPE_WITNESS_PREFIX = utf8Encoder.encode('witness');
|
|
43
|
+
/** Maximum new `MemoPage`s fetched as an incremental sync (`<= ~256 KB`). */
|
|
44
|
+
export const INCREMENTAL_FULL_MEMO_PAGE_THRESHOLD = 25;
|
|
45
|
+
/** Maximum newly synced `SubtreePage`s fetched uniformly on incremental sync in `'strict'` mode. */
|
|
46
|
+
export const INCREMENTAL_UNIFORM_SUBTREE_THRESHOLD = 25;
|
|
47
|
+
/** Minimum sealed `SubtreePage` anonymity set size when decoy-padding in `'strict'` mode. */
|
|
48
|
+
export const STRICT_DECOY_SEALED_SUBTREE_TARGET = 16;
|
|
49
|
+
/** Maximum publicly-duplicated `canonEpk` sealed `SubtreePage`s resolved per sync call in `'strict'` mode. */
|
|
50
|
+
export const MAX_PUBLIC_DUP_SUBTREES = 64;
|
|
51
|
+
/** Sealed-subtree count divisor for deterministic decoy epoch buckets (synced with Rust SDK). */
|
|
52
|
+
export const DECOY_EPOCH_BUCKET_SIZE = 64;
|
|
53
|
+
/** Maximum pages fetched per pass in a single `syncCompactStoreWithRpc` call (prevents untrusted-RPC OOM/hang). */
|
|
54
|
+
export const MAX_SYNC_PAGES_PER_CALL = 4_096;
|
|
55
|
+
/** Maximum total `SubtreeRootPage`s fetched in a single `reconstructWitness` call (`4,096 * 300 = 1.22M` subtrees). */
|
|
56
|
+
export const MAX_WITNESS_SR_PAGES = 4_096;
|
|
57
|
+
/** Maximum total sealed subtrees scanned by `selectHrwSealedDecoys` (`262,144 * 256 = 67M` notes). */
|
|
58
|
+
export const MAX_HRW_SEALED_SUBTREES = 262_144;
|
|
59
|
+
function computeLaneRootFromSubrootsAndFrontier(finalizedSubroots, frontierLeaves, frontierRem = 0) {
|
|
60
|
+
let levelNodes = [...finalizedSubroots];
|
|
61
|
+
if (frontierRem > 0) {
|
|
62
|
+
if (!frontierLeaves || frontierLeaves.length < frontierRem) {
|
|
63
|
+
throw new Error('Missing frontier SubtreePage leaves');
|
|
64
|
+
}
|
|
65
|
+
levelNodes.push(computeSubtree256Root(frontierLeaves, frontierRem));
|
|
66
|
+
}
|
|
67
|
+
if (levelNodes.length === 0) {
|
|
68
|
+
return ZERO_HASHES_4ARY[LANE_DEPTH_4ARY];
|
|
69
|
+
}
|
|
70
|
+
for (let h = SUBTREE_LEVELS_4ARY; h < LANE_DEPTH_4ARY; h++) {
|
|
71
|
+
const zeroAtH = ZERO_HASHES_4ARY[h];
|
|
72
|
+
const nextLen = Math.ceil(levelNodes.length / 4);
|
|
73
|
+
const nextLevel = new Array(nextLen);
|
|
74
|
+
for (let g = 0; g < nextLen; g++) {
|
|
75
|
+
const base = g * 4;
|
|
76
|
+
nextLevel[g] = poseidon4(base < levelNodes.length ? levelNodes[base] : zeroAtH, base + 1 < levelNodes.length ? levelNodes[base + 1] : zeroAtH, base + 2 < levelNodes.length ? levelNodes[base + 2] : zeroAtH, base + 3 < levelNodes.length ? levelNodes[base + 3] : zeroAtH);
|
|
77
|
+
}
|
|
78
|
+
levelNodes = nextLevel;
|
|
79
|
+
}
|
|
80
|
+
return levelNodes[0];
|
|
81
|
+
}
|
|
82
|
+
function compareBytes32(a, b) {
|
|
83
|
+
for (let i = 0; i < 32; i++) {
|
|
84
|
+
const diff = a[i] - b[i];
|
|
85
|
+
if (diff !== 0)
|
|
86
|
+
return diff;
|
|
87
|
+
}
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Derive deterministic watermark-bound HRW decoy scope for Pass 1D catch-up syncs matching
|
|
92
|
+
* `crates/client/src/scanner.rs::make_sync_decoy_scope` bit-for-bit:
|
|
93
|
+
* `"sync" || laneCount(1) || sorted(laneId(1) || startLeaf_le8(8))...`.
|
|
94
|
+
*/
|
|
95
|
+
function makeSyncDecoyScope(startLeavesByLane) {
|
|
96
|
+
const byLane = new Map();
|
|
97
|
+
for (const { laneId, startLeaf } of startLeavesByLane) {
|
|
98
|
+
byLane.set(laneId, startLeaf);
|
|
99
|
+
}
|
|
100
|
+
const sorted = [...byLane.entries()].sort((a, b) => a[0] - b[0]);
|
|
101
|
+
const out = new Uint8Array(DECOY_SCOPE_SYNC_BYTES.byteLength + 1 + sorted.length * 9);
|
|
102
|
+
out.set(DECOY_SCOPE_SYNC_BYTES, 0);
|
|
103
|
+
let off = DECOY_SCOPE_SYNC_BYTES.byteLength;
|
|
104
|
+
out[off++] = sorted.length & 0xff;
|
|
105
|
+
const dv = new DataView(out.buffer);
|
|
106
|
+
for (const [laneId, startLeaf] of sorted) {
|
|
107
|
+
out[off++] = laneId & 0xff;
|
|
108
|
+
dv.setBigUint64(off, startLeaf, true);
|
|
109
|
+
off += 8;
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Derive order-independent HRW decoy scope across all input notes' `(laneId, pageSeq)` targets
|
|
115
|
+
* matching `crates/client/src/scanner.rs::make_witness_decoy_scope_for_notes` bit-for-bit.
|
|
116
|
+
*/
|
|
117
|
+
function makeWitnessDecoyScopeForNotes(notes, subSize) {
|
|
118
|
+
const pageMap = new Map();
|
|
119
|
+
for (const n of notes) {
|
|
120
|
+
const pageSeq = n.leafIndex / subSize;
|
|
121
|
+
const key = `${n.laneId}:${pageSeq.toString()}`;
|
|
122
|
+
if (!pageMap.has(key)) {
|
|
123
|
+
pageMap.set(key, { laneId: n.laneId, pageSeq });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const pages = [...pageMap.values()].sort((a, b) => {
|
|
127
|
+
if (a.laneId !== b.laneId)
|
|
128
|
+
return a.laneId - b.laneId;
|
|
129
|
+
return a.pageSeq < b.pageSeq ? -1 : a.pageSeq > b.pageSeq ? 1 : 0;
|
|
130
|
+
});
|
|
131
|
+
if (pages.length === 1) {
|
|
132
|
+
const single = pages[0];
|
|
133
|
+
const out = new Uint8Array(DECOY_SCOPE_WITNESS_PREFIX.byteLength + 1 + 8);
|
|
134
|
+
out.set(DECOY_SCOPE_WITNESS_PREFIX, 0);
|
|
135
|
+
out[DECOY_SCOPE_WITNESS_PREFIX.byteLength] = single.laneId & 0xff;
|
|
136
|
+
new DataView(out.buffer).setBigUint64(DECOY_SCOPE_WITNESS_PREFIX.byteLength + 1, single.pageSeq, true);
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
const count = Math.min(pages.length, 0xffff);
|
|
140
|
+
const out = new Uint8Array(DECOY_SCOPE_WITNESS_PREFIX.byteLength + 2 + pages.length * 9);
|
|
141
|
+
out.set(DECOY_SCOPE_WITNESS_PREFIX, 0);
|
|
142
|
+
let off = DECOY_SCOPE_WITNESS_PREFIX.byteLength;
|
|
143
|
+
const dv = new DataView(out.buffer);
|
|
144
|
+
dv.setUint16(off, count, true);
|
|
145
|
+
off += 2;
|
|
146
|
+
for (const p of pages) {
|
|
147
|
+
out[off++] = p.laneId & 0xff;
|
|
148
|
+
dv.setBigUint64(off, p.pageSeq, true);
|
|
149
|
+
off += 8;
|
|
150
|
+
}
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
function assertU64OrSafeInt(v, label) {
|
|
154
|
+
if (typeof v === 'bigint') {
|
|
155
|
+
if (v < 0n || v > U64_MAX) {
|
|
156
|
+
throw new RangeError(`${label} must be a u64 bigint in 0..=2^64-1, got ${String(v)}`);
|
|
157
|
+
}
|
|
158
|
+
return v;
|
|
159
|
+
}
|
|
160
|
+
if (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0) {
|
|
161
|
+
return BigInt(v);
|
|
162
|
+
}
|
|
163
|
+
throw new RangeError(`${label} must be a non-negative safe integer or u64 bigint, got ${String(v)}`);
|
|
164
|
+
}
|
|
165
|
+
const DEC_UINT_RE = /^\d+$/;
|
|
166
|
+
/**
|
|
167
|
+
* Deterministic Rendezvous (Highest Random Weight) sealed `SubtreePage` decoy selection matching
|
|
168
|
+
* `crates/client/src/scanner.rs::try_select_hrw_sealed_decoys_in_ranges` bit-for-bit:
|
|
169
|
+
*
|
|
170
|
+
* `score = SHA256(viewSk[32] || "audren/v1/decoy" || scope || epochBucket_le8 || laneId || pageSeq_le8)`
|
|
171
|
+
*
|
|
172
|
+
* Supports optional `startSeq` per lane (default `0n`) so Pass 1D catch-up syncs restrict decoys
|
|
173
|
+
* strictly to the RPC-visible scanned window `[startSeq .. sealedCount)`.
|
|
174
|
+
*/
|
|
175
|
+
export function selectHrwSealedDecoys(params) {
|
|
176
|
+
if (!params || typeof params !== 'object') {
|
|
177
|
+
throw new RangeError('selectHrwSealedDecoys params must be an object');
|
|
178
|
+
}
|
|
179
|
+
const { viewSk, scope, epochBucket, sealedByLane, alreadySelected, targetSealed } = params;
|
|
180
|
+
if (!(viewSk instanceof Uint8Array) || viewSk.byteLength !== 32) {
|
|
181
|
+
throw new RangeError(`viewSk must be a 32-byte Uint8Array, got ${viewSk instanceof Uint8Array ? viewSk.byteLength : String(viewSk)}`);
|
|
182
|
+
}
|
|
183
|
+
if (!(scope instanceof Uint8Array)) {
|
|
184
|
+
throw new RangeError(`scope must be a Uint8Array, got ${String(scope)}`);
|
|
185
|
+
}
|
|
186
|
+
if (typeof epochBucket !== 'bigint' || epochBucket < 0n || epochBucket > U64_MAX) {
|
|
187
|
+
throw new RangeError(`epochBucket must be a u64 bigint, got ${String(epochBucket)}`);
|
|
188
|
+
}
|
|
189
|
+
if (!Array.isArray(sealedByLane)) {
|
|
190
|
+
throw new RangeError('sealedByLane must be an array');
|
|
191
|
+
}
|
|
192
|
+
if (!Number.isInteger(targetSealed) || targetSealed < 0) {
|
|
193
|
+
throw new RangeError(`targetSealed must be a non-negative integer, got ${String(targetSealed)}`);
|
|
194
|
+
}
|
|
195
|
+
let totalSealed = 0n;
|
|
196
|
+
let alreadySealedCount = 0;
|
|
197
|
+
const seenLanes = new Set();
|
|
198
|
+
const normalizedRanges = [];
|
|
199
|
+
for (const entry of sealedByLane) {
|
|
200
|
+
if (!entry || typeof entry !== 'object') {
|
|
201
|
+
throw new RangeError('sealedByLane entries must be objects');
|
|
202
|
+
}
|
|
203
|
+
const { laneId, sealedCount } = entry;
|
|
204
|
+
const startSeq = entry.startSeq ?? 0n;
|
|
205
|
+
if (!Number.isInteger(laneId) || laneId < 0 || laneId >= NUM_LANES) {
|
|
206
|
+
throw new RangeError(`sealedByLane laneId must be 0..${NUM_LANES - 1}, got ${String(laneId)}`);
|
|
207
|
+
}
|
|
208
|
+
if (seenLanes.has(laneId)) {
|
|
209
|
+
throw new RangeError(`Duplicate laneId ${laneId} in sealedByLane`);
|
|
210
|
+
}
|
|
211
|
+
seenLanes.add(laneId);
|
|
212
|
+
if (typeof startSeq !== 'bigint' || startSeq < 0n || startSeq > U64_MAX) {
|
|
213
|
+
throw new RangeError(`startSeq must be a non-negative u64 bigint, got ${String(startSeq)}`);
|
|
214
|
+
}
|
|
215
|
+
if (typeof sealedCount !== 'bigint' || sealedCount < 0n || sealedCount > U64_MAX) {
|
|
216
|
+
throw new RangeError(`sealedCount must be a non-negative u64 bigint, got ${String(sealedCount)}`);
|
|
217
|
+
}
|
|
218
|
+
if (startSeq > sealedCount) {
|
|
219
|
+
throw new RangeError(`startSeq (${startSeq}) exceeds sealedCount (${sealedCount})`);
|
|
220
|
+
}
|
|
221
|
+
normalizedRanges.push({ laneId, startSeq, endSeq: sealedCount });
|
|
222
|
+
totalSealed += sealedCount - startSeq;
|
|
223
|
+
if (totalSealed > BigInt(MAX_HRW_SEALED_SUBTREES)) {
|
|
224
|
+
throw new RangeError(`Total sealed subtrees (${totalSealed}) exceeds HRW operational bound (${MAX_HRW_SEALED_SUBTREES})`);
|
|
225
|
+
}
|
|
226
|
+
for (const key of alreadySelected) {
|
|
227
|
+
if (typeof key !== 'string')
|
|
228
|
+
continue;
|
|
229
|
+
const sep = key.indexOf(':');
|
|
230
|
+
if (sep <= 0)
|
|
231
|
+
continue;
|
|
232
|
+
const laneStr = key.slice(0, sep);
|
|
233
|
+
const seqStr = key.slice(sep + 1);
|
|
234
|
+
if (!DEC_UINT_RE.test(laneStr) || !DEC_UINT_RE.test(seqStr))
|
|
235
|
+
continue;
|
|
236
|
+
const kLane = Number(laneStr);
|
|
237
|
+
if (kLane === laneId) {
|
|
238
|
+
const kSeq = BigInt(seqStr);
|
|
239
|
+
if (kSeq >= startSeq && kSeq < sealedCount)
|
|
240
|
+
alreadySealedCount++;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const cappedTarget = Number(totalSealed < BigInt(targetSealed) ? totalSealed : BigInt(targetSealed));
|
|
245
|
+
const need = cappedTarget - alreadySealedCount;
|
|
246
|
+
if (need <= 0)
|
|
247
|
+
return [];
|
|
248
|
+
if (totalSealed <= BigInt(cappedTarget)) {
|
|
249
|
+
const out = [];
|
|
250
|
+
for (const { laneId, startSeq, endSeq } of normalizedRanges) {
|
|
251
|
+
for (let s = startSeq; s < endSeq; s++) {
|
|
252
|
+
if (!alreadySelected.has(`${laneId}:${s.toString()}`)) {
|
|
253
|
+
out.push({ laneId, pageSeq: s });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return out;
|
|
258
|
+
}
|
|
259
|
+
const preimageLen = 32 + DECOY_DOMAIN_BYTES.byteLength + scope.byteLength + 8 + 1 + 8;
|
|
260
|
+
const preimage = new Uint8Array(preimageLen);
|
|
261
|
+
const dv = new DataView(preimage.buffer);
|
|
262
|
+
let off = 0;
|
|
263
|
+
preimage.set(viewSk, off);
|
|
264
|
+
off += 32;
|
|
265
|
+
preimage.set(DECOY_DOMAIN_BYTES, off);
|
|
266
|
+
off += DECOY_DOMAIN_BYTES.byteLength;
|
|
267
|
+
preimage.set(scope, off);
|
|
268
|
+
off += scope.byteLength;
|
|
269
|
+
dv.setBigUint64(off, epochBucket, true);
|
|
270
|
+
off += 8;
|
|
271
|
+
const laneOff = off;
|
|
272
|
+
const seqOff = off + 1;
|
|
273
|
+
// Bounded top-`need` list kept sorted descending by `(score, -laneId, -pageSeq)` so `top[need - 1]`
|
|
274
|
+
// is the current threshold.
|
|
275
|
+
const top = [];
|
|
276
|
+
const beats = (scoreA, laneA, seqA, b) => {
|
|
277
|
+
const cmp = compareBytes32(scoreA, b.score);
|
|
278
|
+
if (cmp !== 0)
|
|
279
|
+
return cmp > 0;
|
|
280
|
+
if (laneA !== b.laneId)
|
|
281
|
+
return laneA < b.laneId;
|
|
282
|
+
return seqA < b.pageSeq;
|
|
283
|
+
};
|
|
284
|
+
for (const { laneId, startSeq, endSeq } of normalizedRanges) {
|
|
285
|
+
preimage[laneOff] = laneId & 0xff;
|
|
286
|
+
for (let s = startSeq; s < endSeq; s++) {
|
|
287
|
+
if (alreadySelected.has(`${laneId}:${s.toString()}`))
|
|
288
|
+
continue;
|
|
289
|
+
dv.setBigUint64(seqOff, s, true);
|
|
290
|
+
const score = sha256(preimage);
|
|
291
|
+
if (top.length === need && !beats(score, laneId, s, top[need - 1])) {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
let insertAt = top.length;
|
|
295
|
+
while (insertAt > 0 && beats(score, laneId, s, top[insertAt - 1])) {
|
|
296
|
+
insertAt--;
|
|
297
|
+
}
|
|
298
|
+
top.splice(insertAt, 0, { score, laneId, pageSeq: s });
|
|
299
|
+
if (top.length > need) {
|
|
300
|
+
top.pop();
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
preimage.fill(0);
|
|
305
|
+
return top.map(({ laneId, pageSeq }) => ({ laneId, pageSeq }));
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Hit-independent O(`targetSealed`) deterministic uniform decoy sampler across ALL sealed
|
|
309
|
+
* subtrees `[0 .. fc_l)` on ALL active lanes when `totalSealed > MAX_HRW_SEALED_SUBTREES`.
|
|
310
|
+
*
|
|
311
|
+
* Matches `crates/client/src/scanner.rs::select_large_pool_hrw_sealed_decoys` bit-for-bit.
|
|
312
|
+
*/
|
|
313
|
+
export function selectLargePoolHrwSealedDecoys(params) {
|
|
314
|
+
if (!params || typeof params !== 'object') {
|
|
315
|
+
throw new RangeError('selectLargePoolHrwSealedDecoys params must be an object');
|
|
316
|
+
}
|
|
317
|
+
const { viewSk, scope, epochBucket, sealedByLane, alreadySelected, targetSealed } = params;
|
|
318
|
+
if (!(viewSk instanceof Uint8Array) || viewSk.byteLength !== 32) {
|
|
319
|
+
throw new RangeError(`viewSk must be a 32-byte Uint8Array, got ${viewSk instanceof Uint8Array ? viewSk.byteLength : String(viewSk)}`);
|
|
320
|
+
}
|
|
321
|
+
if (!(scope instanceof Uint8Array)) {
|
|
322
|
+
throw new RangeError(`scope must be a Uint8Array, got ${String(scope)}`);
|
|
323
|
+
}
|
|
324
|
+
if (typeof epochBucket !== 'bigint' || epochBucket < 0n || epochBucket > U64_MAX) {
|
|
325
|
+
throw new RangeError(`epochBucket must be a u64 bigint, got ${String(epochBucket)}`);
|
|
326
|
+
}
|
|
327
|
+
if (!Array.isArray(sealedByLane)) {
|
|
328
|
+
throw new RangeError('sealedByLane must be an array');
|
|
329
|
+
}
|
|
330
|
+
if (!Number.isInteger(targetSealed) || targetSealed < 0) {
|
|
331
|
+
throw new RangeError(`targetSealed must be a non-negative integer, got ${String(targetSealed)}`);
|
|
332
|
+
}
|
|
333
|
+
const seenLanes = new Set();
|
|
334
|
+
const fcByLane = new Array(NUM_LANES).fill(0n);
|
|
335
|
+
const activeLanes = [];
|
|
336
|
+
let totalSealed = 0n;
|
|
337
|
+
let alreadySealedCount = 0;
|
|
338
|
+
for (const entry of sealedByLane) {
|
|
339
|
+
if (!entry || typeof entry !== 'object') {
|
|
340
|
+
throw new RangeError('sealedByLane entries must be objects');
|
|
341
|
+
}
|
|
342
|
+
const { laneId, sealedCount } = entry;
|
|
343
|
+
if (!Number.isInteger(laneId) || laneId < 0 || laneId >= NUM_LANES) {
|
|
344
|
+
throw new RangeError(`sealedByLane laneId must be 0..${NUM_LANES - 1}, got ${String(laneId)}`);
|
|
345
|
+
}
|
|
346
|
+
if (seenLanes.has(laneId)) {
|
|
347
|
+
throw new RangeError(`Duplicate laneId ${laneId} in sealedByLane`);
|
|
348
|
+
}
|
|
349
|
+
seenLanes.add(laneId);
|
|
350
|
+
if (typeof sealedCount !== 'bigint' || sealedCount < 0n || sealedCount > U64_MAX) {
|
|
351
|
+
throw new RangeError(`sealedCount must be a non-negative u64 bigint, got ${String(sealedCount)}`);
|
|
352
|
+
}
|
|
353
|
+
totalSealed += sealedCount;
|
|
354
|
+
if (totalSealed > U64_MAX) {
|
|
355
|
+
throw new RangeError('sealed subtree count overflow');
|
|
356
|
+
}
|
|
357
|
+
fcByLane[laneId] = sealedCount;
|
|
358
|
+
if (sealedCount > 0n) {
|
|
359
|
+
activeLanes.push({ laneId, sealedCount });
|
|
360
|
+
}
|
|
361
|
+
for (const key of alreadySelected) {
|
|
362
|
+
if (typeof key !== 'string')
|
|
363
|
+
continue;
|
|
364
|
+
const sep = key.indexOf(':');
|
|
365
|
+
if (sep <= 0)
|
|
366
|
+
continue;
|
|
367
|
+
const laneStr = key.slice(0, sep);
|
|
368
|
+
const seqStr = key.slice(sep + 1);
|
|
369
|
+
if (!DEC_UINT_RE.test(laneStr) || !DEC_UINT_RE.test(seqStr))
|
|
370
|
+
continue;
|
|
371
|
+
if (Number(laneStr) === laneId && BigInt(seqStr) < sealedCount) {
|
|
372
|
+
alreadySealedCount++;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
if (totalSealed === 0n || totalSealed > 1n << BigInt(LARGE_HRW_HEIGHT))
|
|
377
|
+
return [];
|
|
378
|
+
activeLanes.sort((a, b) => a.laneId - b.laneId);
|
|
379
|
+
const cappedTarget = Number(totalSealed < BigInt(targetSealed) ? totalSealed : BigInt(targetSealed));
|
|
380
|
+
const need = cappedTarget - alreadySealedCount;
|
|
381
|
+
if (need <= 0)
|
|
382
|
+
return [];
|
|
383
|
+
const exp1Q32 = (raw) => {
|
|
384
|
+
const rNz = raw === 0n ? 1n : raw;
|
|
385
|
+
let k = 0n;
|
|
386
|
+
let m = rNz;
|
|
387
|
+
const msb = 1n << 63n;
|
|
388
|
+
while ((m & msb) === 0n) {
|
|
389
|
+
m <<= 1n;
|
|
390
|
+
k++;
|
|
391
|
+
}
|
|
392
|
+
const gQ32 = ((1n << 64n) - m) >> 32n;
|
|
393
|
+
let term = 1n << 32n;
|
|
394
|
+
let sum = 0n;
|
|
395
|
+
for (let j = 1n; j <= 24n; j++) {
|
|
396
|
+
term = (term * gQ32) >> 32n;
|
|
397
|
+
sum += term / j;
|
|
398
|
+
}
|
|
399
|
+
return k * LN2_Q32 + sum;
|
|
400
|
+
};
|
|
401
|
+
const cmpNode = (a, b) => {
|
|
402
|
+
if (a.s !== b.s)
|
|
403
|
+
return a.s < b.s ? -1 : 1;
|
|
404
|
+
if (a.laneId !== b.laneId)
|
|
405
|
+
return a.laneId - b.laneId;
|
|
406
|
+
if (a.level !== b.level)
|
|
407
|
+
return a.level - b.level;
|
|
408
|
+
return a.nodeIdx < b.nodeIdx ? -1 : a.nodeIdx > b.nodeIdx ? 1 : 0;
|
|
409
|
+
};
|
|
410
|
+
const heap = [];
|
|
411
|
+
const heapPush = (node) => {
|
|
412
|
+
heap.push(node);
|
|
413
|
+
let idx = heap.length - 1;
|
|
414
|
+
while (idx > 0) {
|
|
415
|
+
const parent = (idx - 1) >> 1;
|
|
416
|
+
if (cmpNode(heap[idx], heap[parent]) < 0) {
|
|
417
|
+
const tmp = heap[idx];
|
|
418
|
+
heap[idx] = heap[parent];
|
|
419
|
+
heap[parent] = tmp;
|
|
420
|
+
idx = parent;
|
|
421
|
+
}
|
|
422
|
+
else {
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
const heapPop = () => {
|
|
428
|
+
if (heap.length === 0)
|
|
429
|
+
return undefined;
|
|
430
|
+
const top = heap[0];
|
|
431
|
+
const last = heap.pop();
|
|
432
|
+
if (heap.length > 0) {
|
|
433
|
+
heap[0] = last;
|
|
434
|
+
let idx = 0;
|
|
435
|
+
const len = heap.length;
|
|
436
|
+
while (true) {
|
|
437
|
+
const l = idx * 2 + 1;
|
|
438
|
+
const r = l + 1;
|
|
439
|
+
let best = idx;
|
|
440
|
+
if (l < len && cmpNode(heap[l], heap[best]) < 0)
|
|
441
|
+
best = l;
|
|
442
|
+
if (r < len && cmpNode(heap[r], heap[best]) < 0)
|
|
443
|
+
best = r;
|
|
444
|
+
if (best === idx)
|
|
445
|
+
break;
|
|
446
|
+
const tmp = heap[idx];
|
|
447
|
+
heap[idx] = heap[best];
|
|
448
|
+
heap[best] = tmp;
|
|
449
|
+
idx = best;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return top;
|
|
453
|
+
};
|
|
454
|
+
const preimageLen = DECOY_LARGE_DOMAIN_BYTES.byteLength + 32 + 4 + scope.byteLength + 8 + 1 + 1 + 8;
|
|
455
|
+
const preimage = new Uint8Array(preimageLen);
|
|
456
|
+
const dv = new DataView(preimage.buffer);
|
|
457
|
+
let off = 0;
|
|
458
|
+
preimage.set(DECOY_LARGE_DOMAIN_BYTES, off);
|
|
459
|
+
off += DECOY_LARGE_DOMAIN_BYTES.byteLength;
|
|
460
|
+
preimage.set(viewSk, off);
|
|
461
|
+
off += 32;
|
|
462
|
+
dv.setUint32(off, scope.byteLength, true);
|
|
463
|
+
off += 4;
|
|
464
|
+
preimage.set(scope, off);
|
|
465
|
+
off += scope.byteLength;
|
|
466
|
+
dv.setBigUint64(off, epochBucket, true);
|
|
467
|
+
off += 8;
|
|
468
|
+
const laneOff = off;
|
|
469
|
+
const hashNode = (laneId, level, nodeIdx) => {
|
|
470
|
+
preimage[laneOff] = laneId & 0xff;
|
|
471
|
+
preimage[laneOff + 1] = level & 0xff;
|
|
472
|
+
dv.setBigUint64(laneOff + 2, nodeIdx, true);
|
|
473
|
+
return sha256(preimage);
|
|
474
|
+
};
|
|
475
|
+
const out = [];
|
|
476
|
+
try {
|
|
477
|
+
for (const { laneId } of activeLanes) {
|
|
478
|
+
const digest = hashNode(laneId, LARGE_HRW_HEIGHT + 1, 0n);
|
|
479
|
+
const raw = new DataView(digest.buffer, digest.byteOffset, 8).getBigUint64(0, true);
|
|
480
|
+
heapPush({ s: exp1Q32(raw), laneId, level: LARGE_HRW_HEIGHT, nodeIdx: 0n });
|
|
481
|
+
}
|
|
482
|
+
while (out.length < need) {
|
|
483
|
+
const top = heapPop();
|
|
484
|
+
if (!top)
|
|
485
|
+
break;
|
|
486
|
+
if (top.level === 0) {
|
|
487
|
+
const key = `${top.laneId}:${top.nodeIdx.toString()}`;
|
|
488
|
+
if (!alreadySelected.has(key)) {
|
|
489
|
+
out.push({ laneId: top.laneId, pageSeq: top.nodeIdx });
|
|
490
|
+
}
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
const digest = hashNode(top.laneId, top.level, top.nodeIdx);
|
|
494
|
+
const raw = new DataView(digest.buffer, digest.byteOffset, 8).getBigUint64(0, true);
|
|
495
|
+
const winnerRight = (digest[8] & 1) !== 0;
|
|
496
|
+
const shift = BigInt(LARGE_HRW_HEIGHT + 1 - top.level);
|
|
497
|
+
const sLoser = top.s + (exp1Q32(raw) << shift);
|
|
498
|
+
const childLevel = top.level - 1;
|
|
499
|
+
const leftIdx = top.nodeIdx << 1n;
|
|
500
|
+
const rightIdx = leftIdx | 1n;
|
|
501
|
+
const fc = fcByLane[top.laneId];
|
|
502
|
+
heapPush({
|
|
503
|
+
s: winnerRight ? sLoser : top.s,
|
|
504
|
+
laneId: top.laneId,
|
|
505
|
+
level: childLevel,
|
|
506
|
+
nodeIdx: leftIdx,
|
|
507
|
+
});
|
|
508
|
+
const rightLo = rightIdx << BigInt(childLevel);
|
|
509
|
+
if (rightLo < fc) {
|
|
510
|
+
heapPush({
|
|
511
|
+
s: winnerRight ? top.s : sLoser,
|
|
512
|
+
laneId: top.laneId,
|
|
513
|
+
level: childLevel,
|
|
514
|
+
nodeIdx: rightIdx,
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
finally {
|
|
520
|
+
preimage.fill(0);
|
|
521
|
+
}
|
|
522
|
+
return out;
|
|
523
|
+
}
|
|
524
|
+
function base64ToBytes(b64) {
|
|
525
|
+
const bin = atob(b64);
|
|
526
|
+
const out = new Uint8Array(bin.length);
|
|
527
|
+
for (let i = 0; i < bin.length; i++)
|
|
528
|
+
out[i] = bin.charCodeAt(i);
|
|
529
|
+
return out;
|
|
530
|
+
}
|
|
531
|
+
/** Ordinary Solana JSON-RPC `getMultipleAccounts` batch fetcher (chunks by 100 accounts, supports `dataSlice` and timeouts/abort signals). */
|
|
532
|
+
export function createSolanaRpcBatchFetcher(rpcUrl, commitment = 'confirmed', options) {
|
|
533
|
+
const timeoutMs = options?.timeoutMs ?? 30_000;
|
|
534
|
+
return async (addresses, fetchOptions) => {
|
|
535
|
+
const out = new Array(addresses.length).fill(null);
|
|
536
|
+
const rpcCfg = { encoding: 'base64', commitment };
|
|
537
|
+
if (fetchOptions?.dataSlice) {
|
|
538
|
+
rpcCfg.dataSlice = {
|
|
539
|
+
offset: fetchOptions.dataSlice.offset,
|
|
540
|
+
length: fetchOptions.dataSlice.length,
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
for (let off = 0; off < addresses.length; off += RPC_BATCH_CHUNK) {
|
|
544
|
+
const chunk = addresses.slice(off, off + RPC_BATCH_CHUNK);
|
|
545
|
+
const signal = options?.signal ??
|
|
546
|
+
(typeof AbortSignal !== 'undefined' &&
|
|
547
|
+
typeof AbortSignal.timeout === 'function' &&
|
|
548
|
+
timeoutMs > 0
|
|
549
|
+
? AbortSignal.timeout(timeoutMs)
|
|
550
|
+
: undefined);
|
|
551
|
+
const res = await fetch(rpcUrl, {
|
|
552
|
+
method: 'POST',
|
|
553
|
+
headers: { 'content-type': 'application/json' },
|
|
554
|
+
...(signal ? { signal } : {}),
|
|
555
|
+
body: JSON.stringify({
|
|
556
|
+
jsonrpc: '2.0',
|
|
557
|
+
id: 1,
|
|
558
|
+
method: 'getMultipleAccounts',
|
|
559
|
+
params: [chunk, rpcCfg],
|
|
560
|
+
}),
|
|
561
|
+
});
|
|
562
|
+
if (!res.ok)
|
|
563
|
+
throw new Error(`Solana RPC getMultipleAccounts HTTP ${res.status}`);
|
|
564
|
+
const json = await res.json();
|
|
565
|
+
if (!json || typeof json !== 'object' || Array.isArray(json)) {
|
|
566
|
+
throw new Error('Solana RPC getMultipleAccounts returned invalid JSON-RPC response');
|
|
567
|
+
}
|
|
568
|
+
const rpcResp = json;
|
|
569
|
+
if (rpcResp.error !== undefined && rpcResp.error !== null) {
|
|
570
|
+
const msg = typeof rpcResp.error === 'object' &&
|
|
571
|
+
'message' in rpcResp.error &&
|
|
572
|
+
rpcResp.error.message !== undefined
|
|
573
|
+
? String(rpcResp.error.message)
|
|
574
|
+
: String(rpcResp.error);
|
|
575
|
+
throw new Error(`Solana RPC error: ${msg}`);
|
|
576
|
+
}
|
|
577
|
+
const values = rpcResp.result && typeof rpcResp.result === 'object' ? rpcResp.result.value : undefined;
|
|
578
|
+
if (!Array.isArray(values) || values.length !== chunk.length) {
|
|
579
|
+
throw new Error(`Solana RPC getMultipleAccounts invalid result.value (expected ${chunk.length} entries, got ${Array.isArray(values) ? values.length : String(values)})`);
|
|
580
|
+
}
|
|
581
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
582
|
+
const acc = values[i];
|
|
583
|
+
if (acc === null) {
|
|
584
|
+
out[off + i] = null;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
if (!acc ||
|
|
588
|
+
typeof acc !== 'object' ||
|
|
589
|
+
!Array.isArray(acc.data) ||
|
|
590
|
+
typeof acc.data[0] !== 'string') {
|
|
591
|
+
throw new Error(`Solana RPC getMultipleAccounts invalid account entry at index ${i}`);
|
|
592
|
+
}
|
|
593
|
+
const b64 = acc.data[0];
|
|
594
|
+
out[off + i] = b64 ? base64ToBytes(b64) : null;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return out;
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Fetch `PoolState` + all `NUM_LANES` (16) `LaneTreeState` headers atomically in ONE
|
|
602
|
+
* 17-account `getMultipleAccounts` RPC batch (eliminating `InitLane` expansion snapshot skew
|
|
603
|
+
* and saving 1 RPC round-trip on every sync).
|
|
604
|
+
*/
|
|
605
|
+
export async function fetchPoolAndLanes(fetchBatch, poolId = 0, programId = AUDREN_PROGRAM_ID) {
|
|
606
|
+
const poolPda = derivePoolPdaSync(poolId, programId).address;
|
|
607
|
+
const batchAddrs = [poolPda];
|
|
608
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
609
|
+
batchAddrs.push(deriveLanePdaSync(poolId, l, programId).address);
|
|
610
|
+
}
|
|
611
|
+
const raws = await fetchBatch(batchAddrs);
|
|
612
|
+
if (raws.length !== batchAddrs.length) {
|
|
613
|
+
throw new Error(`Phase 0 batch response length mismatch (expected ${batchAddrs.length}, got ${raws.length})`);
|
|
614
|
+
}
|
|
615
|
+
const poolRaw = raws[0];
|
|
616
|
+
if (!poolRaw)
|
|
617
|
+
throw new Error(`PoolState account missing at ${poolPda}`);
|
|
618
|
+
const pool = decodePoolState(poolRaw);
|
|
619
|
+
if (pool.poolId !== poolId) {
|
|
620
|
+
throw new Error(`PoolState poolId mismatch (expected ${poolId}, got ${pool.poolId})`);
|
|
621
|
+
}
|
|
622
|
+
const lanes = [];
|
|
623
|
+
for (let l = 0; l < pool.activeLanes; l++) {
|
|
624
|
+
const raw = raws[1 + l];
|
|
625
|
+
if (!raw)
|
|
626
|
+
throw new Error(`LaneTreeState #${l} missing`);
|
|
627
|
+
const hdr = decodeLaneHeader(raw);
|
|
628
|
+
if (hdr.laneId !== l) {
|
|
629
|
+
throw new Error(`LaneTreeState #${l} laneId mismatch (got ${hdr.laneId})`);
|
|
630
|
+
}
|
|
631
|
+
if (hdr.poolId !== poolId) {
|
|
632
|
+
throw new Error(`LaneTreeState #${l} poolId mismatch (expected ${poolId}, got ${hdr.poolId})`);
|
|
633
|
+
}
|
|
634
|
+
lanes.push(hdr);
|
|
635
|
+
}
|
|
636
|
+
return { pool, lanes };
|
|
637
|
+
}
|
|
638
|
+
function bytes32Hex(b) {
|
|
639
|
+
let out = '';
|
|
640
|
+
for (let i = 0; i < b.byteLength; i++) {
|
|
641
|
+
out += b[i].toString(16).padStart(2, '0');
|
|
642
|
+
}
|
|
643
|
+
return out;
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Incrementally sync `CompactWalletStore` across all active lanes via ordinary `getMultipleAccounts`
|
|
647
|
+
* calls using 2-pass sync (`SubtreeRootPage` fast sync + privacy-first `'strict'` full-`MemoPage`
|
|
648
|
+
* batches & deterministic wallet-keyed decoy-padded `SubtreePage` fetches, or explicit opt-in
|
|
649
|
+
* `'fast'` SoA `dataSlice` on `> 25` pages + optional `birthdaySlot` header binary search +
|
|
650
|
+
* unconditional zero-early-exit `NullifierPage` streaming).
|
|
651
|
+
*/
|
|
652
|
+
export async function syncCompactStoreWithRpc(params) {
|
|
653
|
+
if (!params || typeof params !== 'object') {
|
|
654
|
+
throw new RangeError('syncCompactStoreWithRpc params must be an object');
|
|
655
|
+
}
|
|
656
|
+
if (!params.store || typeof params.store !== 'object' || !Array.isArray(params.store.lanes)) {
|
|
657
|
+
throw new RangeError('syncCompactStoreWithRpc requires a valid CompactWalletStore');
|
|
658
|
+
}
|
|
659
|
+
if (!params.fvk ||
|
|
660
|
+
typeof params.fvk !== 'object' ||
|
|
661
|
+
!(params.fvk.viewSk instanceof Uint8Array) ||
|
|
662
|
+
params.fvk.viewSk.byteLength !== 32 ||
|
|
663
|
+
!(params.fvk.spendPk instanceof Uint8Array) ||
|
|
664
|
+
params.fvk.spendPk.byteLength !== 32 ||
|
|
665
|
+
!(params.fvk.nk instanceof Uint8Array) ||
|
|
666
|
+
params.fvk.nk.byteLength !== 32) {
|
|
667
|
+
throw new RangeError('syncCompactStoreWithRpc requires fvk with 32-byte Uint8Array viewSk, spendPk, and nk');
|
|
668
|
+
}
|
|
669
|
+
const programId = params.programId ?? AUDREN_PROGRAM_ID;
|
|
670
|
+
const poolId = params.store.poolId;
|
|
671
|
+
const privacyMode = params.privacyMode === undefined ? 'strict' : params.privacyMode;
|
|
672
|
+
if (privacyMode !== 'strict' && privacyMode !== 'fast') {
|
|
673
|
+
throw new RangeError(`Invalid privacyMode: ${String(privacyMode)}`);
|
|
674
|
+
}
|
|
675
|
+
const storeWasGenesis = params.store.lanes.every((ln) => ln.nextMemoLeaf === 0n);
|
|
676
|
+
const storedBirthdaySlot = assertU64OrSafeInt(params.store.birthdaySlot, 'store.birthdaySlot');
|
|
677
|
+
const requestedBirthdaySlot = params.birthdaySlot !== undefined
|
|
678
|
+
? assertU64OrSafeInt(params.birthdaySlot, 'birthdaySlot')
|
|
679
|
+
: storedBirthdaySlot;
|
|
680
|
+
// Once any lane has advanced past genesis, never let a repeated loop parameter raise a lowered
|
|
681
|
+
// persisted birthday floor (prevents multi-round ghost balances after Pass 1B subtree rounding).
|
|
682
|
+
const birthdaySlot = storeWasGenesis || requestedBirthdaySlot <= storedBirthdaySlot
|
|
683
|
+
? requestedBirthdaySlot
|
|
684
|
+
: storedBirthdaySlot;
|
|
685
|
+
if (params.decoyEpochBucket !== undefined &&
|
|
686
|
+
(typeof params.decoyEpochBucket !== 'bigint' ||
|
|
687
|
+
params.decoyEpochBucket < 0n ||
|
|
688
|
+
params.decoyEpochBucket > U64_MAX)) {
|
|
689
|
+
throw new RangeError(`Invalid decoyEpochBucket: ${String(params.decoyEpochBucket)}`);
|
|
690
|
+
}
|
|
691
|
+
if (params.store.lanes.length !== NUM_LANES) {
|
|
692
|
+
throw new Error(`Invalid CompactWalletStore: expected ${NUM_LANES} lanes`);
|
|
693
|
+
}
|
|
694
|
+
if (params.latestRootHistory !== undefined) {
|
|
695
|
+
if (!params.latestRootHistory || typeof params.latestRootHistory !== 'object') {
|
|
696
|
+
throw new RangeError('latestRootHistory must be a GlobalRootHistory or RootSnapshotChoice');
|
|
697
|
+
}
|
|
698
|
+
if ('slotRing' in params.latestRootHistory || 'stableLaneCounts' in params.latestRootHistory) {
|
|
699
|
+
validateGlobalRootHistory(params.latestRootHistory, poolId);
|
|
700
|
+
}
|
|
701
|
+
else {
|
|
702
|
+
validateRootSnapshotChoice(params.latestRootHistory);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
const { pool, lanes } = await fetchPoolAndLanes(params.fetchBatch, poolId, programId);
|
|
706
|
+
const subSize = BigInt(SUBTREE_LEAVES);
|
|
707
|
+
const srSize = BigInt(SUBROOTS_PER_PAGE);
|
|
708
|
+
const memoSize = BigInt(MEMO_NOTES_PER_PAGE);
|
|
709
|
+
const nfSize = BigInt(NF_PER_PAGE);
|
|
710
|
+
const srCursors = [];
|
|
711
|
+
const pass1aNewSubroots = new Map();
|
|
712
|
+
for (const laneHdr of lanes) {
|
|
713
|
+
const l = laneHdr.laneId;
|
|
714
|
+
const laneState = params.store.lanes[l];
|
|
715
|
+
pass1aNewSubroots.set(l, []);
|
|
716
|
+
const finalizedCount = laneHdr.nextLeaf / subSize;
|
|
717
|
+
const existingLen = BigInt(laneState.finalizedSubroots.length);
|
|
718
|
+
if (finalizedCount > existingLen) {
|
|
719
|
+
srCursors.push({
|
|
720
|
+
laneId: l,
|
|
721
|
+
nextSr: existingLen / srSize,
|
|
722
|
+
endSr: (finalizedCount - 1n) / srSize,
|
|
723
|
+
finalizedCount,
|
|
724
|
+
stopped: false,
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
let srPagesFetched = 0;
|
|
729
|
+
let anyPass1aRpcLag = false;
|
|
730
|
+
while (srPagesFetched < MAX_SYNC_PAGES_PER_CALL) {
|
|
731
|
+
const chunk = [];
|
|
732
|
+
for (const cursor of srCursors) {
|
|
733
|
+
while (!cursor.stopped &&
|
|
734
|
+
cursor.nextSr <= cursor.endSr &&
|
|
735
|
+
chunk.length < RPC_BATCH_CHUNK &&
|
|
736
|
+
srPagesFetched + chunk.length < MAX_SYNC_PAGES_PER_CALL) {
|
|
737
|
+
const rp = cursor.nextSr;
|
|
738
|
+
cursor.nextSr = rp + 1n;
|
|
739
|
+
chunk.push({
|
|
740
|
+
cursor,
|
|
741
|
+
rootPageSeq: rp,
|
|
742
|
+
addr: deriveSubrootPdaSync(poolId, cursor.laneId, rp, programId).address,
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
if (chunk.length >= RPC_BATCH_CHUNK ||
|
|
746
|
+
srPagesFetched + chunk.length >= MAX_SYNC_PAGES_PER_CALL) {
|
|
747
|
+
break;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
if (chunk.length === 0)
|
|
751
|
+
break;
|
|
752
|
+
srPagesFetched += chunk.length;
|
|
753
|
+
const raws = await params.fetchBatch(chunk.map((r) => r.addr));
|
|
754
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
755
|
+
const { cursor, rootPageSeq } = chunk[i];
|
|
756
|
+
if (cursor.stopped)
|
|
757
|
+
continue;
|
|
758
|
+
const raw = raws[i];
|
|
759
|
+
const pass1aBuf = pass1aNewSubroots.get(cursor.laneId);
|
|
760
|
+
const curLen = BigInt(params.store.lanes[cursor.laneId].finalizedSubroots.length + pass1aBuf.length);
|
|
761
|
+
const base = rootPageSeq * srSize;
|
|
762
|
+
const expectedOnPage = Number(cursor.finalizedCount - base < srSize ? cursor.finalizedCount - base : srSize);
|
|
763
|
+
if (!raw) {
|
|
764
|
+
cursor.stopped = true;
|
|
765
|
+
anyPass1aRpcLag = true;
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
const dec = decodeSubtreeRootPage(raw);
|
|
769
|
+
if (dec.poolId !== poolId || dec.laneId !== cursor.laneId || dec.rootPageSeq !== rootPageSeq) {
|
|
770
|
+
throw new Error(`SubtreeRootPage header mismatch (expected pool=${poolId}, lane=${cursor.laneId}, seq=${rootPageSeq})`);
|
|
771
|
+
}
|
|
772
|
+
const existingSubroots = params.store.lanes[cursor.laneId].finalizedSubroots;
|
|
773
|
+
for (let k = 0; k < dec.roots.length; k++) {
|
|
774
|
+
frFromBeBytesStrict(dec.roots[k]);
|
|
775
|
+
const subIdxBig = base + BigInt(k);
|
|
776
|
+
if (subIdxBig < BigInt(existingSubroots.length)) {
|
|
777
|
+
if (compareBytes32(existingSubroots[Number(subIdxBig)], dec.roots[k]) !== 0) {
|
|
778
|
+
throw new Error(`SubtreeRootPage subroot mismatch against persisted finalizedSubroots at index ${subIdxBig}`);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
const startInPage = curLen > base ? Number(curLen - base) : 0;
|
|
783
|
+
const avail = Math.min(dec.count, expectedOnPage);
|
|
784
|
+
if (avail < startInPage) {
|
|
785
|
+
cursor.stopped = true;
|
|
786
|
+
anyPass1aRpcLag = true;
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
for (let k = startInPage; k < avail; k++) {
|
|
790
|
+
pass1aBuf.push(new Uint8Array(dec.roots[k]));
|
|
791
|
+
}
|
|
792
|
+
if (dec.count < expectedOnPage) {
|
|
793
|
+
cursor.stopped = true;
|
|
794
|
+
anyPass1aRpcLag = true;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
const lookupVerifiedSubroot = (laneId, subSeq) => {
|
|
799
|
+
const existing = params.store.lanes[laneId].finalizedSubroots;
|
|
800
|
+
const existingLen = BigInt(existing.length);
|
|
801
|
+
if (subSeq < existingLen) {
|
|
802
|
+
return existing[Number(subSeq)];
|
|
803
|
+
}
|
|
804
|
+
const buf = pass1aNewSubroots.get(laneId);
|
|
805
|
+
const off = subSeq - existingLen;
|
|
806
|
+
if (buf && off >= 0n && off < BigInt(buf.length)) {
|
|
807
|
+
return buf[Number(off)];
|
|
808
|
+
}
|
|
809
|
+
return undefined;
|
|
810
|
+
};
|
|
811
|
+
// =========================================================================
|
|
812
|
+
// PASS 1B: Optional `birthdaySlot` binary search on `64 B` `MemoPage` headers
|
|
813
|
+
// (deferred commit so Pass 1D misses preserve zero store mutation).
|
|
814
|
+
// =========================================================================
|
|
815
|
+
const scanStartLeafByLane = new Map();
|
|
816
|
+
const pass1bSkippedLanes = new Set();
|
|
817
|
+
for (const laneHdr of lanes) {
|
|
818
|
+
scanStartLeafByLane.set(laneHdr.laneId, params.store.lanes[laneHdr.laneId].nextMemoLeaf);
|
|
819
|
+
}
|
|
820
|
+
if (birthdaySlot > 0n) {
|
|
821
|
+
const bsStates = [];
|
|
822
|
+
for (const laneHdr of lanes) {
|
|
823
|
+
const l = laneHdr.laneId;
|
|
824
|
+
const laneState = params.store.lanes[l];
|
|
825
|
+
if (laneHdr.nextLeaf > 0n && laneState.nextMemoLeaf === 0n) {
|
|
826
|
+
const targetMemoMax = (laneHdr.nextLeaf - 1n) / memoSize;
|
|
827
|
+
if (targetMemoMax > 2n) {
|
|
828
|
+
bsStates.push({ laneId: l, nextLeaf: laneHdr.nextLeaf, lo: 0n, hi: targetMemoMax + 1n });
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
while (bsStates.some((s) => s.lo < s.hi)) {
|
|
833
|
+
const active = bsStates.filter((s) => s.lo < s.hi);
|
|
834
|
+
const mids = active.map((s) => s.lo + ((s.hi - s.lo) >> 1n));
|
|
835
|
+
const addrs = active.map((s, i) => deriveMemoPdaSync(poolId, s.laneId, mids[i], programId).address);
|
|
836
|
+
const raws = await params.fetchBatch(addrs, {
|
|
837
|
+
dataSlice: { offset: 0, length: MEMO_PAGE_HEADER_LEN },
|
|
838
|
+
});
|
|
839
|
+
for (let i = 0; i < active.length; i++) {
|
|
840
|
+
const st = active[i];
|
|
841
|
+
const mid = mids[i];
|
|
842
|
+
const raw = raws[i];
|
|
843
|
+
if (raw) {
|
|
844
|
+
const hdr = decodeMemoPageHeader(raw);
|
|
845
|
+
if (hdr.poolId !== poolId || hdr.laneId !== st.laneId || hdr.pageSeq !== mid) {
|
|
846
|
+
throw new Error(`MemoPage header mismatch (expected pool=${poolId}, lane=${st.laneId}, seq=${mid})`);
|
|
847
|
+
}
|
|
848
|
+
if (hdr.count === MEMO_NOTES_PER_PAGE && hdr.closedSlot > 0n && hdr.closedSlot < birthdaySlot) {
|
|
849
|
+
st.lo = mid + 1n;
|
|
850
|
+
}
|
|
851
|
+
else {
|
|
852
|
+
st.hi = mid;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
else {
|
|
856
|
+
st.hi = mid;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
for (const st of bsStates) {
|
|
861
|
+
if (st.lo > 0n) {
|
|
862
|
+
const skipTo = st.lo * memoSize;
|
|
863
|
+
scanStartLeafByLane.set(st.laneId, skipTo < st.nextLeaf ? skipTo : st.nextLeaf);
|
|
864
|
+
pass1bSkippedLanes.add(st.laneId);
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
// Compute total new MemoPages and newly synced SubtreePages across all active lanes (post-Pass 1B)
|
|
869
|
+
let totalNewMemoPages = 0n;
|
|
870
|
+
let totalNewSubtrees = 0n;
|
|
871
|
+
for (const laneHdr of lanes) {
|
|
872
|
+
const l = laneHdr.laneId;
|
|
873
|
+
const startLeaf = scanStartLeafByLane.get(l) ?? params.store.lanes[l].nextMemoLeaf;
|
|
874
|
+
if (laneHdr.nextLeaf > 0n && startLeaf < laneHdr.nextLeaf) {
|
|
875
|
+
const startMemo = startLeaf / memoSize;
|
|
876
|
+
const targetMemoMax = (laneHdr.nextLeaf - 1n) / memoSize;
|
|
877
|
+
totalNewMemoPages += targetMemoMax - startMemo + 1n;
|
|
878
|
+
const startSub = startLeaf / subSize;
|
|
879
|
+
const endSub = (laneHdr.nextLeaf - 1n) / subSize;
|
|
880
|
+
totalNewSubtrees += endSub - startSub + 1n;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
const isIncrementalMemoSync = totalNewMemoPages <= BigInt(INCREMENTAL_FULL_MEMO_PAGE_THRESHOLD);
|
|
884
|
+
// In `'strict'` mode we NEVER use `dataSlice` + targeted hit re-fetch for MemoPages.
|
|
885
|
+
// Even in opt-in `'fast'` mode, small incremental syncs (`<= 25` pages) fetch full MemoPages directly.
|
|
886
|
+
const useMemoDataSlice = privacyMode === 'fast' && !isIncrementalMemoSync;
|
|
887
|
+
const fetchNewSubtreesUniformly = privacyMode === 'strict' &&
|
|
888
|
+
isIncrementalMemoSync &&
|
|
889
|
+
totalNewSubtrees <= BigInt(INCREMENTAL_UNIFORM_SUBTREE_THRESHOLD);
|
|
890
|
+
const strictSubtreeAtomic = privacyMode === 'strict' && !fetchNewSubtreesUniformly;
|
|
891
|
+
// Pass 1B subtree-boundary alignment (`'strict'` non-uniform mode): when Pass 1B skips into the
|
|
892
|
+
// middle of a sealed `256`-leaf subtree (`skipTo < finalizedCount * 256`), align `startLeaf`
|
|
893
|
+
// down to the exact `256`-leaf boundary so distinct `MemoPage` skip points inside the same
|
|
894
|
+
// subtree can NEVER share `startSub` while scanning different subsets of leaves.
|
|
895
|
+
const pass1bRoundedDownStartMemo = new Map();
|
|
896
|
+
if (strictSubtreeAtomic) {
|
|
897
|
+
for (const laneHdr of lanes) {
|
|
898
|
+
const l = laneHdr.laneId;
|
|
899
|
+
const finalizedLeaves = (laneHdr.nextLeaf / subSize) * subSize;
|
|
900
|
+
const skipTo = scanStartLeafByLane.get(l);
|
|
901
|
+
if (skipTo !== undefined && skipTo < finalizedLeaves) {
|
|
902
|
+
const aligned = (skipTo / subSize) * subSize;
|
|
903
|
+
if (pass1bSkippedLanes.has(l) && aligned < skipTo) {
|
|
904
|
+
pass1bRoundedDownStartMemo.set(l, aligned / memoSize);
|
|
905
|
+
}
|
|
906
|
+
scanStartLeafByLane.set(l, aligned);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
const hitsByLane = new Map();
|
|
911
|
+
const scannedWatermarkByLane = new Map();
|
|
912
|
+
const inlineFullMemos = new Map();
|
|
913
|
+
const neededFullMemos = new Map();
|
|
914
|
+
const memoCursors = [];
|
|
915
|
+
for (const laneHdr of lanes) {
|
|
916
|
+
const l = laneHdr.laneId;
|
|
917
|
+
const startLeaf = scanStartLeafByLane.get(l) ?? params.store.lanes[l].nextMemoLeaf;
|
|
918
|
+
scannedWatermarkByLane.set(l, startLeaf);
|
|
919
|
+
hitsByLane.set(l, []);
|
|
920
|
+
if (laneHdr.nextLeaf === 0n || startLeaf >= laneHdr.nextLeaf)
|
|
921
|
+
continue;
|
|
922
|
+
const startMemo = startLeaf / memoSize;
|
|
923
|
+
const endMemo = (laneHdr.nextLeaf - 1n) / memoSize;
|
|
924
|
+
memoCursors.push({
|
|
925
|
+
laneId: l,
|
|
926
|
+
nextMemo: startMemo,
|
|
927
|
+
endMemo,
|
|
928
|
+
nextLeaf: laneHdr.nextLeaf,
|
|
929
|
+
stopped: false,
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
const publicEpkSubtrees = new Map();
|
|
933
|
+
const roundedDownCreatedSlots = new Map();
|
|
934
|
+
let memoPagesFetched = 0;
|
|
935
|
+
let anyPass1cRpcDrop = false;
|
|
936
|
+
while (memoPagesFetched < MAX_SYNC_PAGES_PER_CALL) {
|
|
937
|
+
const chunk = [];
|
|
938
|
+
for (const cursor of memoCursors) {
|
|
939
|
+
while (!cursor.stopped &&
|
|
940
|
+
cursor.nextMemo <= cursor.endMemo &&
|
|
941
|
+
chunk.length < RPC_BATCH_CHUNK &&
|
|
942
|
+
memoPagesFetched + chunk.length < MAX_SYNC_PAGES_PER_CALL) {
|
|
943
|
+
const m = cursor.nextMemo;
|
|
944
|
+
cursor.nextMemo = m + 1n;
|
|
945
|
+
chunk.push({
|
|
946
|
+
cursor,
|
|
947
|
+
memoSeq: m,
|
|
948
|
+
addr: deriveMemoPdaSync(poolId, cursor.laneId, m, programId).address,
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
if (chunk.length >= RPC_BATCH_CHUNK ||
|
|
952
|
+
memoPagesFetched + chunk.length >= MAX_SYNC_PAGES_PER_CALL) {
|
|
953
|
+
break;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
if (chunk.length === 0)
|
|
957
|
+
break;
|
|
958
|
+
memoPagesFetched += chunk.length;
|
|
959
|
+
const chunkAddrs = chunk.map((item) => item.addr);
|
|
960
|
+
const raws = useMemoDataSlice
|
|
961
|
+
? await params.fetchBatch(chunkAddrs, {
|
|
962
|
+
dataSlice: { offset: 0, length: MEMO_PAGE_SCAN_SLICE_LEN },
|
|
963
|
+
})
|
|
964
|
+
: await params.fetchBatch(chunkAddrs);
|
|
965
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
966
|
+
const item = chunk[i];
|
|
967
|
+
const cursor = item.cursor;
|
|
968
|
+
if (cursor.stopped)
|
|
969
|
+
continue;
|
|
970
|
+
const raw = raws[i];
|
|
971
|
+
if (!raw) {
|
|
972
|
+
cursor.stopped = true;
|
|
973
|
+
anyPass1cRpcDrop = true;
|
|
974
|
+
continue;
|
|
975
|
+
}
|
|
976
|
+
if (!useMemoDataSlice && (!(raw instanceof Uint8Array) || raw.byteLength !== MEMO_PAGE_LEN)) {
|
|
977
|
+
throw new Error(`Invalid full MemoPage account (len=${raw instanceof Uint8Array ? raw.byteLength : String(raw)})`);
|
|
978
|
+
}
|
|
979
|
+
const scan = decodeMemoPageScanSlice(raw);
|
|
980
|
+
if (scan.poolId !== poolId ||
|
|
981
|
+
scan.laneId !== cursor.laneId ||
|
|
982
|
+
scan.pageSeq !== item.memoSeq) {
|
|
983
|
+
throw new Error(`MemoPage header mismatch (expected pool=${poolId}, lane=${cursor.laneId}, seq=${item.memoSeq})`);
|
|
984
|
+
}
|
|
985
|
+
const wm = scannedWatermarkByLane.get(cursor.laneId);
|
|
986
|
+
const pageBase = item.memoSeq * memoSize;
|
|
987
|
+
const startSlot = wm > pageBase ? Number(wm - pageBase) : 0;
|
|
988
|
+
const maxForSnapshot = Math.min(MEMO_NOTES_PER_PAGE, cursor.nextLeaf > pageBase ? Number(cursor.nextLeaf - pageBase) : 0);
|
|
989
|
+
const limitSlot = Math.min(scan.count, maxForSnapshot);
|
|
990
|
+
if (pass1bRoundedDownStartMemo.get(cursor.laneId) === item.memoSeq && limitSlot >= startSlot) {
|
|
991
|
+
roundedDownCreatedSlots.set(cursor.laneId, scan.createdSlot);
|
|
992
|
+
}
|
|
993
|
+
// Never skip a mid-scan `MemoPage` via `closedSlot < birthdaySlot`: Pass 1B already skips
|
|
994
|
+
// pre-birthday prefixes via binary search, and honoring unauthenticated `closedSlot`
|
|
995
|
+
// mid-stream would let an adversarial RPC toggle single-page visibility while holding
|
|
996
|
+
// `actualEndSub` constant.
|
|
997
|
+
const laneHits = hitsByLane.get(cursor.laneId);
|
|
998
|
+
const laneFc = cursor.nextLeaf / subSize;
|
|
999
|
+
let pageMatched = false;
|
|
1000
|
+
for (let slot = startSlot; slot < limitSlot; slot++) {
|
|
1001
|
+
const vt = scan.viewTags[slot];
|
|
1002
|
+
const epk = scan.ephemeralPks[slot];
|
|
1003
|
+
const leafIdx = pageBase + BigInt(slot);
|
|
1004
|
+
if (strictSubtreeAtomic) {
|
|
1005
|
+
const subSeq = leafIdx / subSize;
|
|
1006
|
+
if (subSeq < laneFc) {
|
|
1007
|
+
const canonEpk = canonicalizePublicEpk(epk);
|
|
1008
|
+
if (canonEpk) {
|
|
1009
|
+
const canonHex = bytes32Hex(canonEpk);
|
|
1010
|
+
const existing = publicEpkSubtrees.get(canonHex);
|
|
1011
|
+
if (!existing) {
|
|
1012
|
+
publicEpkSubtrees.set(canonHex, {
|
|
1013
|
+
multi: false,
|
|
1014
|
+
laneId: cursor.laneId,
|
|
1015
|
+
subSeq,
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
else if (!existing.multi) {
|
|
1019
|
+
if (existing.laneId !== cursor.laneId || existing.subSeq !== subSeq) {
|
|
1020
|
+
const set = new Map();
|
|
1021
|
+
set.set(`${existing.laneId}:${existing.subSeq.toString()}`, {
|
|
1022
|
+
laneId: existing.laneId,
|
|
1023
|
+
subSeq: existing.subSeq,
|
|
1024
|
+
});
|
|
1025
|
+
set.set(`${cursor.laneId}:${subSeq.toString()}`, {
|
|
1026
|
+
laneId: cursor.laneId,
|
|
1027
|
+
subSeq,
|
|
1028
|
+
});
|
|
1029
|
+
publicEpkSubtrees.set(canonHex, { multi: true, set });
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
else {
|
|
1033
|
+
existing.set.set(`${cursor.laneId}:${subSeq.toString()}`, {
|
|
1034
|
+
laneId: cursor.laneId,
|
|
1035
|
+
subSeq,
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
if (checkMemoViewTag(params.fvk.viewSk, vt, epk)) {
|
|
1042
|
+
// When the full `10,240 B` `MemoPage` is already fetched (`'strict'` mode and
|
|
1043
|
+
// incremental `'fast'` mode), verify AEAD / `AUD1DYN1` immediately to reject
|
|
1044
|
+
// `1/65536` false positives and single-copy `(vt, epk, junkCt)` probes.
|
|
1045
|
+
if (scan.hasCiphertexts && raw.byteLength === MEMO_PAGE_LEN) {
|
|
1046
|
+
const ctOff = MM_OFF_CIPHERTEXTS + slot * MEMO_CT_LEN;
|
|
1047
|
+
const ct72 = raw.subarray(ctOff, ctOff + MEMO_CT_LEN);
|
|
1048
|
+
if (!checkMemoPayloadForScan(params.fvk.viewSk, vt, epk, ct72)) {
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
pageMatched = true;
|
|
1053
|
+
laneHits.push({
|
|
1054
|
+
laneId: cursor.laneId,
|
|
1055
|
+
memoSeq: item.memoSeq,
|
|
1056
|
+
slot,
|
|
1057
|
+
leafIdx,
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
if (pageMatched) {
|
|
1062
|
+
const memoKey = `${cursor.laneId}:${item.memoSeq.toString()}`;
|
|
1063
|
+
if (scan.hasCiphertexts && raw.byteLength === MEMO_PAGE_LEN) {
|
|
1064
|
+
inlineFullMemos.set(memoKey, decodeMemoPage(raw));
|
|
1065
|
+
}
|
|
1066
|
+
else if (!neededFullMemos.has(memoKey)) {
|
|
1067
|
+
neededFullMemos.set(memoKey, {
|
|
1068
|
+
laneId: cursor.laneId,
|
|
1069
|
+
memoSeq: item.memoSeq,
|
|
1070
|
+
addr: item.addr,
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
const nextWm = pageBase + BigInt(limitSlot);
|
|
1075
|
+
if (nextWm > wm) {
|
|
1076
|
+
scannedWatermarkByLane.set(cursor.laneId, nextWm);
|
|
1077
|
+
}
|
|
1078
|
+
if (scan.count < maxForSnapshot) {
|
|
1079
|
+
cursor.stopped = true;
|
|
1080
|
+
anyPass1cRpcDrop = true;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
// =========================================================================
|
|
1085
|
+
// PASS 1D: Fetch full `MemoPage`s (fast-mode >25 pages only) & `SubtreePage`s
|
|
1086
|
+
// =========================================================================
|
|
1087
|
+
const fetchedFullMemos = new Map(inlineFullMemos);
|
|
1088
|
+
const fullMemoList = [...neededFullMemos.entries()];
|
|
1089
|
+
for (let off = 0; off < fullMemoList.length; off += RPC_BATCH_CHUNK) {
|
|
1090
|
+
const chunk = fullMemoList.slice(off, off + RPC_BATCH_CHUNK);
|
|
1091
|
+
const raws = await params.fetchBatch(chunk.map(([, req]) => req.addr));
|
|
1092
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
1093
|
+
const [key, req] = chunk[i];
|
|
1094
|
+
const raw = raws[i];
|
|
1095
|
+
if (raw) {
|
|
1096
|
+
const dec = decodeMemoPage(raw);
|
|
1097
|
+
if (dec.poolId !== poolId || dec.laneId !== req.laneId || dec.pageSeq !== req.memoSeq) {
|
|
1098
|
+
throw new Error(`MemoPage header mismatch (expected pool=${poolId}, lane=${req.laneId}, seq=${req.memoSeq})`);
|
|
1099
|
+
}
|
|
1100
|
+
fetchedFullMemos.set(key, dec);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
// Determine `SubtreePage`s needed across all active lanes:
|
|
1105
|
+
// - In `'strict'` incremental sync (`<= 25` MemoPages & `<= 25` newly synced SubtreePages),
|
|
1106
|
+
// fetch all SubtreePages covering newly synced leaves uniformly so hits are never revealed.
|
|
1107
|
+
// - In `'strict'` large catch-up (`> 25` MemoPages or `> 25` SubtreePages) OR whenever an
|
|
1108
|
+
// older unfrozen/hit sealed subtree outside the uniform window is requested, ALWAYS fetch a
|
|
1109
|
+
// fixed uniform batch count of sealed `SubtreePage`s (multiples of 16, minimum 16 even on
|
|
1110
|
+
// 0 hits) using Rendezvous (HRW) decoy selection so repeated syncs and `+1` subtree growth
|
|
1111
|
+
// cannot be intersected and 0-hit vs 1..16-hit syncs are indistinguishable.
|
|
1112
|
+
const neededSubtrees = new Map();
|
|
1113
|
+
// Publicly-known, hit-independent sealed `SubtreePage`s (`uniformNewSubtrees` sealed pages +
|
|
1114
|
+
// `hasScannedSealedFrontier` old frontiers): NEVER counted against the private 16-subtree decoy
|
|
1115
|
+
// budget so neither `M = 1..16` returning frontiers nor `U = 1..25` uniform new subtrees can
|
|
1116
|
+
// cannibalize decoys or create a 0-vs-1-note / 1-of-1 pinpoint oracle.
|
|
1117
|
+
const publicSealedSubtrees = new Map();
|
|
1118
|
+
const addNeededSubtree = (laneId, subSeq) => {
|
|
1119
|
+
const key = `${laneId}:${subSeq.toString()}`;
|
|
1120
|
+
if (neededSubtrees.has(key))
|
|
1121
|
+
return false;
|
|
1122
|
+
const pda = deriveSubtreePdaSync(poolId, laneId, subSeq, programId);
|
|
1123
|
+
neededSubtrees.set(key, {
|
|
1124
|
+
laneId,
|
|
1125
|
+
subSeq,
|
|
1126
|
+
addr: pda.address,
|
|
1127
|
+
addrBytes: pda.addressBytes,
|
|
1128
|
+
});
|
|
1129
|
+
return true;
|
|
1130
|
+
};
|
|
1131
|
+
if (fetchNewSubtreesUniformly) {
|
|
1132
|
+
for (const laneHdr of lanes) {
|
|
1133
|
+
const l = laneHdr.laneId;
|
|
1134
|
+
const finalizedCount = laneHdr.nextLeaf / subSize;
|
|
1135
|
+
const startLeaf = scanStartLeafByLane.get(l) ?? params.store.lanes[l].nextMemoLeaf;
|
|
1136
|
+
if (laneHdr.nextLeaf > 0n && startLeaf < laneHdr.nextLeaf) {
|
|
1137
|
+
const startSub = startLeaf / subSize;
|
|
1138
|
+
const endSub = (laneHdr.nextLeaf - 1n) / subSize;
|
|
1139
|
+
for (let s = startSub; s <= endSub; s++) {
|
|
1140
|
+
addNeededSubtree(l, s);
|
|
1141
|
+
if (s < finalizedCount) {
|
|
1142
|
+
publicSealedSubtrees.set(`${l}:${s.toString()}`, { laneId: l, subSeq: s });
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
let hasHitCorrelatedSealedSubtree = false;
|
|
1149
|
+
const finalizedByLane = new Map();
|
|
1150
|
+
const frontierRemByLane = new Map();
|
|
1151
|
+
const startSubByLane = new Map();
|
|
1152
|
+
const actualEndSubByLane = new Map();
|
|
1153
|
+
const windowedRangesByLane = [];
|
|
1154
|
+
let totalSealedSubtrees = 0n;
|
|
1155
|
+
let windowSealedSubtrees = 0n;
|
|
1156
|
+
// Public, note-independent non-lagging predicate across ALL locally persisted lanes:
|
|
1157
|
+
// blocks O(log N) lagging-`nextLeaf` binary-search & decoy-domain shrink oracles on legacy
|
|
1158
|
+
// `locallyFinalizedUnfrozen` notes.
|
|
1159
|
+
let allLocalLanesNonLagging = true;
|
|
1160
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
1161
|
+
const localLen = BigInt(params.store.lanes[l].finalizedSubroots.length);
|
|
1162
|
+
if (localLen === 0n)
|
|
1163
|
+
continue;
|
|
1164
|
+
const hdr = lanes.find((h) => h.laneId === l);
|
|
1165
|
+
if (!hdr || hdr.nextLeaf / subSize < localLen) {
|
|
1166
|
+
allLocalLanesNonLagging = false;
|
|
1167
|
+
break;
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
for (const laneHdr of lanes) {
|
|
1171
|
+
const l = laneHdr.laneId;
|
|
1172
|
+
const laneState = params.store.lanes[l];
|
|
1173
|
+
const finalizedCount = laneHdr.nextLeaf / subSize;
|
|
1174
|
+
const frontierRem = Number(laneHdr.nextLeaf % subSize);
|
|
1175
|
+
const startLeaf = scanStartLeafByLane.get(l) ?? laneState.nextMemoLeaf;
|
|
1176
|
+
const rawStartSub = startLeaf / subSize;
|
|
1177
|
+
const startSub = rawStartSub < finalizedCount ? rawStartSub : finalizedCount;
|
|
1178
|
+
const scannedLeaf = scannedWatermarkByLane.get(l) ?? startLeaf;
|
|
1179
|
+
let actualEndSub = startSub;
|
|
1180
|
+
if (scannedLeaf > startLeaf) {
|
|
1181
|
+
// Subtree-boundary atomicity (`'strict'` non-uniform mode): only sealed subtrees whose full
|
|
1182
|
+
// 256-leaf range was scanned (`(s + 1) * 256 <= scannedLeaf`) enter Pass 1D. Eliminates
|
|
1183
|
+
// sub-subtree `MemoPage`-drop and `MM_OFF_COUNT` binary-search oracles.
|
|
1184
|
+
const rawEndSub = strictSubtreeAtomic
|
|
1185
|
+
? scannedLeaf / subSize
|
|
1186
|
+
: (scannedLeaf + subSize - 1n) / subSize;
|
|
1187
|
+
const cappedSub = rawEndSub < finalizedCount ? rawEndSub : finalizedCount;
|
|
1188
|
+
actualEndSub = cappedSub > startSub ? cappedSub : startSub;
|
|
1189
|
+
}
|
|
1190
|
+
finalizedByLane.set(l, finalizedCount);
|
|
1191
|
+
frontierRemByLane.set(l, frontierRem);
|
|
1192
|
+
startSubByLane.set(l, startSub);
|
|
1193
|
+
actualEndSubByLane.set(l, actualEndSub);
|
|
1194
|
+
totalSealedSubtrees += finalizedCount;
|
|
1195
|
+
}
|
|
1196
|
+
// Public, key-independent cross-subtree duplicate `canonEpk` resolution (`'strict'` non-uniform
|
|
1197
|
+
// mode): if any Curve25519 `canonEpk` (collapsing all 16 torsion + bit-255 + `u + p` variants)
|
|
1198
|
+
// appears in >= 2 distinct sealed subtrees inside `[startSub .. actualEndSub)`, BOTH 0-note and
|
|
1199
|
+
// N-note wallets identically schedule up to `MAX_PUBLIC_DUP_SUBTREES` (64) such subtrees in
|
|
1200
|
+
// `publicSealedSubtrees` (ascending `(laneId, subSeq)` order) and cap overflowing lanes'
|
|
1201
|
+
// `actualEndSub` & `verifiedWatermark` at the minimum deferred duplicate `subSeq`.
|
|
1202
|
+
const dupEndSubCap = new Map();
|
|
1203
|
+
if (strictSubtreeAtomic) {
|
|
1204
|
+
const publicDupMap = new Map();
|
|
1205
|
+
for (const tracker of publicEpkSubtrees.values()) {
|
|
1206
|
+
if (!tracker.multi)
|
|
1207
|
+
continue;
|
|
1208
|
+
const inWindow = [];
|
|
1209
|
+
for (const [k, v] of tracker.set.entries()) {
|
|
1210
|
+
const sStart = startSubByLane.get(v.laneId) ?? 0n;
|
|
1211
|
+
const sEnd = actualEndSubByLane.get(v.laneId) ?? sStart;
|
|
1212
|
+
if (v.subSeq >= sStart && v.subSeq < sEnd) {
|
|
1213
|
+
inWindow.push({ key: k, laneId: v.laneId, subSeq: v.subSeq });
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
if (inWindow.length >= 2) {
|
|
1217
|
+
for (const item of inWindow) {
|
|
1218
|
+
publicDupMap.set(item.key, { laneId: item.laneId, subSeq: item.subSeq });
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
const sortedPublicDups = [...publicDupMap.values()].sort((a, b) => a.laneId !== b.laneId
|
|
1223
|
+
? a.laneId - b.laneId
|
|
1224
|
+
: a.subSeq < b.subSeq
|
|
1225
|
+
? -1
|
|
1226
|
+
: a.subSeq > b.subSeq
|
|
1227
|
+
? 1
|
|
1228
|
+
: 0);
|
|
1229
|
+
for (let idx = 0; idx < sortedPublicDups.length; idx++) {
|
|
1230
|
+
const { laneId: lid, subSeq: s } = sortedPublicDups[idx];
|
|
1231
|
+
if (idx < MAX_PUBLIC_DUP_SUBTREES) {
|
|
1232
|
+
addNeededSubtree(lid, s);
|
|
1233
|
+
publicSealedSubtrees.set(`${lid}:${s.toString()}`, { laneId: lid, subSeq: s });
|
|
1234
|
+
}
|
|
1235
|
+
else {
|
|
1236
|
+
const cur = dupEndSubCap.get(lid);
|
|
1237
|
+
if (cur === undefined || s < cur) {
|
|
1238
|
+
dupEndSubCap.set(lid, s);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
for (const [lid, capSub] of dupEndSubCap.entries()) {
|
|
1243
|
+
const sStart = startSubByLane.get(lid) ?? 0n;
|
|
1244
|
+
const curEnd = actualEndSubByLane.get(lid) ?? sStart;
|
|
1245
|
+
const minEnd = curEnd < capSub ? curEnd : capSub;
|
|
1246
|
+
actualEndSubByLane.set(lid, minEnd > sStart ? minEnd : sStart);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
publicEpkSubtrees.clear();
|
|
1250
|
+
for (const laneHdr of lanes) {
|
|
1251
|
+
const l = laneHdr.laneId;
|
|
1252
|
+
const laneState = params.store.lanes[l];
|
|
1253
|
+
const finalizedCount = finalizedByLane.get(l) ?? 0n;
|
|
1254
|
+
const frontierRem = frontierRemByLane.get(l) ?? 0;
|
|
1255
|
+
const startLeaf = scanStartLeafByLane.get(l) ?? laneState.nextMemoLeaf;
|
|
1256
|
+
const startSub = startSubByLane.get(l) ?? 0n;
|
|
1257
|
+
const scannedLeaf = scannedWatermarkByLane.get(l) ?? startLeaf;
|
|
1258
|
+
const actualEndSub = actualEndSubByLane.get(l) ?? startSub;
|
|
1259
|
+
windowedRangesByLane.push({ laneId: l, startSeq: startSub, sealedCount: actualEndSub });
|
|
1260
|
+
windowSealedSubtrees += actualEndSub - startSub;
|
|
1261
|
+
if (frontierRem > 0) {
|
|
1262
|
+
addNeededSubtree(l, finalizedCount);
|
|
1263
|
+
}
|
|
1264
|
+
// Uniform sealed-frontier freeze (scheduled BEFORE hits/notes so it is registered in
|
|
1265
|
+
// `publicSealedSubtrees`): ONLY when this wallet had previously memo-scanned leaves inside
|
|
1266
|
+
// `frontierSubSeq` (`nextMemoLeaf > frontierSubSeq * 256 && frontierSubSeq >= startSub`) AND
|
|
1267
|
+
// that frontier page has sealed on-chain (`frontierSubSeq < finalizedCount`), fetch it
|
|
1268
|
+
// uniformly across BOTH 0-note and N-note wallets and mark it public so it never cannibalizes
|
|
1269
|
+
// the private 16-subtree decoy budget.
|
|
1270
|
+
const frontierSeq = laneState.frontierSubSeq;
|
|
1271
|
+
const hasScannedSealedFrontier = laneState.frontierLeaves.length > 0 &&
|
|
1272
|
+
frontierSeq < finalizedCount &&
|
|
1273
|
+
laneState.nextMemoLeaf > frontierSeq * subSize &&
|
|
1274
|
+
frontierSeq >= startSub;
|
|
1275
|
+
const allowPass1aCatchupSealedFrontier = srPagesFetched >= MAX_SYNC_PAGES_PER_CALL &&
|
|
1276
|
+
!anyPass1aRpcLag &&
|
|
1277
|
+
memoPagesFetched >= MAX_SYNC_PAGES_PER_CALL &&
|
|
1278
|
+
!anyPass1cRpcDrop &&
|
|
1279
|
+
Boolean(lookupVerifiedSubroot(l, frontierSeq));
|
|
1280
|
+
if (hasScannedSealedFrontier &&
|
|
1281
|
+
((privacyMode === 'fast' && Boolean(lookupVerifiedSubroot(l, frontierSeq))) ||
|
|
1282
|
+
(privacyMode === 'strict' &&
|
|
1283
|
+
((scannedLeaf > startLeaf && frontierSeq < actualEndSub) ||
|
|
1284
|
+
allowPass1aCatchupSealedFrontier)))) {
|
|
1285
|
+
addNeededSubtree(l, frontierSeq);
|
|
1286
|
+
publicSealedSubtrees.set(`${l}:${frontierSeq.toString()}`, { laneId: l, subSeq: frontierSeq });
|
|
1287
|
+
}
|
|
1288
|
+
const hits = hitsByLane.get(l);
|
|
1289
|
+
if (hits) {
|
|
1290
|
+
for (const hit of hits) {
|
|
1291
|
+
const hitSubSeq = hit.leafIdx / subSize;
|
|
1292
|
+
if (strictSubtreeAtomic && hitSubSeq < finalizedCount) {
|
|
1293
|
+
// Defer hits in an incompletely scanned tail or dup-capped sealed subtree to the next
|
|
1294
|
+
// sync (`verifiedWatermark` is capped at `actualEndSub * 256` so zero notes are lost).
|
|
1295
|
+
if (hitSubSeq >= actualEndSub) {
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
addNeededSubtree(l, hitSubSeq);
|
|
1300
|
+
if (hitSubSeq < finalizedCount && !publicSealedSubtrees.has(`${l}:${hitSubSeq.toString()}`)) {
|
|
1301
|
+
hasHitCorrelatedSealedSubtree = true;
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
// Unfrozen `store.notes` guard: in `'strict'` mode, ONLY schedule unfrozen sealed notes that
|
|
1306
|
+
// EITHER (a) were ALREADY locally finalized & scanned in `store` prior to this sync AND ALL
|
|
1307
|
+
// locally persisted lanes are non-lagging (`allLocalLanesNonLagging`, blocking O(log N)
|
|
1308
|
+
// lagging-`nextLeaf` binary-search & decoy-domain shrink oracles), OR (b) lie strictly inside
|
|
1309
|
+
// this sync's verified Pass 1C scanned window `[startSub .. actualEndSub)` with
|
|
1310
|
+
// `scannedLeaf > startLeaf`.
|
|
1311
|
+
const strictUnfrozenOk = scannedLeaf > startLeaf;
|
|
1312
|
+
const localFinalizedLen = BigInt(laneState.finalizedSubroots.length);
|
|
1313
|
+
const localNextMemoLeaf = laneState.nextMemoLeaf;
|
|
1314
|
+
for (const note of params.store.notes) {
|
|
1315
|
+
if (note.laneId === l && !note.frozenIntraSiblings) {
|
|
1316
|
+
const noteSubSeq = note.leafIndex / subSize;
|
|
1317
|
+
const locallyFinalizedUnfrozen = allLocalLanesNonLagging &&
|
|
1318
|
+
noteSubSeq < localFinalizedLen &&
|
|
1319
|
+
noteSubSeq < localNextMemoLeaf / subSize;
|
|
1320
|
+
const newlyScannedUnfrozen = strictUnfrozenOk &&
|
|
1321
|
+
noteSubSeq >= startSub &&
|
|
1322
|
+
noteSubSeq < actualEndSub &&
|
|
1323
|
+
(privacyMode === 'strict' || Boolean(lookupVerifiedSubroot(l, noteSubSeq)));
|
|
1324
|
+
if (noteSubSeq < finalizedCount &&
|
|
1325
|
+
(locallyFinalizedUnfrozen ||
|
|
1326
|
+
newlyScannedUnfrozen ||
|
|
1327
|
+
(privacyMode === 'fast' && Boolean(lookupVerifiedSubroot(l, noteSubSeq))))) {
|
|
1328
|
+
addNeededSubtree(l, noteSubSeq);
|
|
1329
|
+
if (!publicSealedSubtrees.has(`${l}:${noteSubSeq.toString()}`)) {
|
|
1330
|
+
hasHitCorrelatedSealedSubtree = true;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
const persistedWatermarks = Array.from({ length: NUM_LANES }, (_, l) => ({ laneId: l, startLeaf: params.store.lanes[l].nextMemoLeaf }));
|
|
1337
|
+
const epochBucket = params.decoyEpochBucket ?? 0n;
|
|
1338
|
+
// Rendezvous (HRW) wallet-keyed decoy padding for `'strict'` mode:
|
|
1339
|
+
// - Sizes the private anonymity bucket strictly ON TOP of `publicSealedSubtrees`
|
|
1340
|
+
// (`uniformNewSubtrees` sealed entries + `hasScannedSealedFrontier` old frontiers) so
|
|
1341
|
+
// publicly-known returning frontiers or uniform incremental pages NEVER cannibalize the
|
|
1342
|
+
// 16-subtree decoy budget.
|
|
1343
|
+
// - Windowed strictly to the actual hit-independent Pass 1C scanned ceiling
|
|
1344
|
+
// `[startSub_l .. actualEndSub_l)` derived from `scannedWatermarkByLane`.
|
|
1345
|
+
// - Scoped strictly to ALL 16 persisted `store.lanes[0..NUM_LANES].nextMemoLeaf` watermarks.
|
|
1346
|
+
const shouldDecoyPad = privacyMode === 'strict' &&
|
|
1347
|
+
totalSealedSubtrees > 0n &&
|
|
1348
|
+
(hasHitCorrelatedSealedSubtree || (!fetchNewSubtreesUniformly && totalNewMemoPages > 0n));
|
|
1349
|
+
if (shouldDecoyPad) {
|
|
1350
|
+
const syncScope = makeSyncDecoyScope(persistedWatermarks);
|
|
1351
|
+
const laneCount = BigInt(Math.max(1, lanes.length));
|
|
1352
|
+
const perLaneMaxSpan = BigInt(MAX_HRW_SEALED_SUBTREES) / laneCount;
|
|
1353
|
+
const batchUnit = STRICT_DECOY_SEALED_SUBTREE_TARGET;
|
|
1354
|
+
const countAllSealedNeeded = () => {
|
|
1355
|
+
let c = 0n;
|
|
1356
|
+
for (const req of neededSubtrees.values()) {
|
|
1357
|
+
if (req.subSeq < (finalizedByLane.get(req.laneId) ?? 0n))
|
|
1358
|
+
c++;
|
|
1359
|
+
}
|
|
1360
|
+
return c;
|
|
1361
|
+
};
|
|
1362
|
+
let hasOutsideWindowSealed = false;
|
|
1363
|
+
for (const [key, req] of neededSubtrees.entries()) {
|
|
1364
|
+
const fc = finalizedByLane.get(req.laneId) ?? 0n;
|
|
1365
|
+
if (req.subSeq < fc && !publicSealedSubtrees.has(key)) {
|
|
1366
|
+
const sStart = startSubByLane.get(req.laneId) ?? 0n;
|
|
1367
|
+
const sEnd = actualEndSubByLane.get(req.laneId) ?? sStart;
|
|
1368
|
+
if (req.subSeq < sStart || req.subSeq >= sEnd) {
|
|
1369
|
+
hasOutsideWindowSealed = true;
|
|
1370
|
+
break;
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
const padScannedWindow = () => {
|
|
1375
|
+
let winPublicCount = 0;
|
|
1376
|
+
for (const pub of publicSealedSubtrees.values()) {
|
|
1377
|
+
const sStart = startSubByLane.get(pub.laneId) ?? 0n;
|
|
1378
|
+
const sEnd = actualEndSubByLane.get(pub.laneId) ?? sStart;
|
|
1379
|
+
if (pub.subSeq >= sStart && pub.subSeq < sEnd)
|
|
1380
|
+
winPublicCount++;
|
|
1381
|
+
}
|
|
1382
|
+
let winAlreadyCount = 0;
|
|
1383
|
+
for (const req of neededSubtrees.values()) {
|
|
1384
|
+
const sStart = startSubByLane.get(req.laneId) ?? 0n;
|
|
1385
|
+
const sEnd = actualEndSubByLane.get(req.laneId) ?? sStart;
|
|
1386
|
+
if (req.subSeq >= sStart && req.subSeq < sEnd)
|
|
1387
|
+
winAlreadyCount++;
|
|
1388
|
+
}
|
|
1389
|
+
const winPrivateCount = Math.max(0, winAlreadyCount - winPublicCount);
|
|
1390
|
+
const winPrivateBuckets = Math.max(1, Math.ceil(winPrivateCount / batchUnit));
|
|
1391
|
+
const winPrivateTarget = BigInt(winPrivateBuckets) * BigInt(batchUnit);
|
|
1392
|
+
const winDesiredTotal = BigInt(winPublicCount) + winPrivateTarget;
|
|
1393
|
+
const rawNeedBig = winDesiredTotal > BigInt(winAlreadyCount)
|
|
1394
|
+
? winDesiredTotal - BigInt(winAlreadyCount)
|
|
1395
|
+
: 0n;
|
|
1396
|
+
const globalAvailBig = totalSealedSubtrees > countAllSealedNeeded()
|
|
1397
|
+
? totalSealedSubtrees - countAllSealedNeeded()
|
|
1398
|
+
: 0n;
|
|
1399
|
+
const winNeedNew = Number(rawNeedBig < globalAvailBig ? rawNeedBig : globalAvailBig);
|
|
1400
|
+
if (winNeedNew <= 0)
|
|
1401
|
+
return;
|
|
1402
|
+
const winAvailable = windowSealedSubtrees > BigInt(winAlreadyCount)
|
|
1403
|
+
? windowSealedSubtrees - BigInt(winAlreadyCount)
|
|
1404
|
+
: 0n;
|
|
1405
|
+
if (winAvailable >= BigInt(winNeedNew)) {
|
|
1406
|
+
if (windowSealedSubtrees > BigInt(MAX_HRW_SEALED_SUBTREES)) {
|
|
1407
|
+
throw new RangeError(`Total sealed subtrees (${windowSealedSubtrees}) exceeds HRW operational bound (${MAX_HRW_SEALED_SUBTREES})`);
|
|
1408
|
+
}
|
|
1409
|
+
const decoys = selectHrwSealedDecoys({
|
|
1410
|
+
viewSk: params.fvk.viewSk,
|
|
1411
|
+
scope: syncScope,
|
|
1412
|
+
epochBucket,
|
|
1413
|
+
sealedByLane: windowedRangesByLane,
|
|
1414
|
+
alreadySelected: new Set(neededSubtrees.keys()),
|
|
1415
|
+
targetSealed: winAlreadyCount + winNeedNew,
|
|
1416
|
+
});
|
|
1417
|
+
for (const d of decoys) {
|
|
1418
|
+
addNeededSubtree(d.laneId, d.pageSeq);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
else {
|
|
1422
|
+
// Step 2a: include EVERY sealed subtree in the RPC-visible scanned window uniformly.
|
|
1423
|
+
let addedTotal = 0;
|
|
1424
|
+
for (const r of windowedRangesByLane) {
|
|
1425
|
+
for (let seq = r.startSeq; seq < r.sealedCount; seq++) {
|
|
1426
|
+
if (addNeededSubtree(r.laneId, seq))
|
|
1427
|
+
addedTotal++;
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
const scaledTail = winDesiredTotal * 64n;
|
|
1431
|
+
const minTail = scaledTail > 1024n ? scaledTail : 1024n;
|
|
1432
|
+
const tailPerLane = minTail < perLaneMaxSpan ? minTail : perLaneMaxSpan;
|
|
1433
|
+
if (addedTotal < winNeedNew) {
|
|
1434
|
+
// Step 2b: bounded downward tail `[startSub - tail .. startSub)`
|
|
1435
|
+
const remainingDown = winNeedNew - addedTotal;
|
|
1436
|
+
const tailRanges = lanes.map((h) => {
|
|
1437
|
+
const startSub = startSubByLane.get(h.laneId) ?? 0n;
|
|
1438
|
+
const low = startSub > tailPerLane ? startSub - tailPerLane : 0n;
|
|
1439
|
+
return { laneId: h.laneId, startSeq: low, sealedCount: startSub };
|
|
1440
|
+
});
|
|
1441
|
+
let inTailAlready = 0;
|
|
1442
|
+
for (const req of neededSubtrees.values()) {
|
|
1443
|
+
for (const r of tailRanges) {
|
|
1444
|
+
if (req.laneId === r.laneId && req.subSeq >= r.startSeq && req.subSeq < r.sealedCount) {
|
|
1445
|
+
inTailAlready++;
|
|
1446
|
+
break;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
const decoys = selectHrwSealedDecoys({
|
|
1451
|
+
viewSk: params.fvk.viewSk,
|
|
1452
|
+
scope: syncScope,
|
|
1453
|
+
epochBucket,
|
|
1454
|
+
sealedByLane: tailRanges,
|
|
1455
|
+
alreadySelected: new Set(neededSubtrees.keys()),
|
|
1456
|
+
targetSealed: inTailAlready + remainingDown,
|
|
1457
|
+
});
|
|
1458
|
+
for (const d of decoys) {
|
|
1459
|
+
if (addNeededSubtree(d.laneId, d.pageSeq))
|
|
1460
|
+
addedTotal++;
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
if (addedTotal < winNeedNew) {
|
|
1464
|
+
// Step 2c: bounded upward tail `[actualEndSub .. min(fc, actualEndSub + tail))`
|
|
1465
|
+
const remainingUp = winNeedNew - addedTotal;
|
|
1466
|
+
const upRanges = lanes.map((h) => {
|
|
1467
|
+
const fc = finalizedByLane.get(h.laneId) ?? 0n;
|
|
1468
|
+
const sEnd = actualEndSubByLane.get(h.laneId) ?? 0n;
|
|
1469
|
+
const hiCand = sEnd + tailPerLane;
|
|
1470
|
+
return { laneId: h.laneId, startSeq: sEnd, sealedCount: hiCand < fc ? hiCand : fc };
|
|
1471
|
+
});
|
|
1472
|
+
let inUpAlready = 0;
|
|
1473
|
+
for (const req of neededSubtrees.values()) {
|
|
1474
|
+
for (const r of upRanges) {
|
|
1475
|
+
if (req.laneId === r.laneId && req.subSeq >= r.startSeq && req.subSeq < r.sealedCount) {
|
|
1476
|
+
inUpAlready++;
|
|
1477
|
+
break;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
const decoys = selectHrwSealedDecoys({
|
|
1482
|
+
viewSk: params.fvk.viewSk,
|
|
1483
|
+
scope: syncScope,
|
|
1484
|
+
epochBucket,
|
|
1485
|
+
sealedByLane: upRanges,
|
|
1486
|
+
alreadySelected: new Set(neededSubtrees.keys()),
|
|
1487
|
+
targetSealed: inUpAlready + remainingUp,
|
|
1488
|
+
});
|
|
1489
|
+
for (const d of decoys) {
|
|
1490
|
+
addNeededSubtree(d.laneId, d.pageSeq);
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
};
|
|
1495
|
+
if (!hasOutsideWindowSealed) {
|
|
1496
|
+
padScannedWindow();
|
|
1497
|
+
}
|
|
1498
|
+
else {
|
|
1499
|
+
// Branch 3 (`hasOutsideWindowSealed === true`): only reachable via locally persisted
|
|
1500
|
+
// `locallyFinalizedUnfrozen` legacy notes (`noteSubSeq < localFc_l` and
|
|
1501
|
+
// `note.leafIndex < localNextMemoLeaf <= startLeaf`).
|
|
1502
|
+
// Partition strictly into TWO disjoint domains whenever Pass 1C also scanned a non-uniform
|
|
1503
|
+
// sealed window (`willPadWindow`):
|
|
1504
|
+
// - `L' = ⋃_l [0 .. legacyFc_l)` where `legacyFc_l = min(localFc_l, startSub_l)` on lanes
|
|
1505
|
+
// with `actualEndSub_l > startSub_l` (and `localFc_l` otherwise). Disjoint from `W` by
|
|
1506
|
+
// construction AND covers every outside-window legacy note.
|
|
1507
|
+
// - `W = ⋃_l [startSub_l .. actualEndSub_l)` padded independently via `padScannedWindow`.
|
|
1508
|
+
// Neither `uniformNewSubtrees`, returning frontiers, nor in-window hits can ever cannibalize
|
|
1509
|
+
// `L'`, and forged `laneHdr.nextLeaf = 2^19..2^26` with empty Pass 1C (`windowSealedSubtrees === 0n`)
|
|
1510
|
+
// leaves `willPadWindow === false` and 0% decoy rotation.
|
|
1511
|
+
const willPadWindow = !fetchNewSubtreesUniformly && windowSealedSubtrees > 0n;
|
|
1512
|
+
const localFcByLane = new Map();
|
|
1513
|
+
const localFinalizedRanges = [];
|
|
1514
|
+
let localFinalizedTotal = 0n;
|
|
1515
|
+
for (const h of lanes) {
|
|
1516
|
+
const fc = finalizedByLane.get(h.laneId) ?? 0n;
|
|
1517
|
+
const sStart = startSubByLane.get(h.laneId) ?? 0n;
|
|
1518
|
+
const sEnd = actualEndSubByLane.get(h.laneId) ?? sStart;
|
|
1519
|
+
const laneState = params.store.lanes[h.laneId];
|
|
1520
|
+
// Bound `L'` strictly by full-subtree floor `localScannedFc = nextMemoLeaf / subSize`
|
|
1521
|
+
// (matching `locallyFinalizedUnfrozen` & `padScannedWindow` Step 2b `[0..startSub)`):
|
|
1522
|
+
// guarantees `L' ⊆ [0..startSub)` is unconditionally disjoint from `W`, eliminates
|
|
1523
|
+
// unscanned-lane dilution AND mid-subtree boundary singleton pinpoint / rotation.
|
|
1524
|
+
const localScannedFc = laneState.nextMemoLeaf / subSize;
|
|
1525
|
+
const storedLen = BigInt(laneState.finalizedSubroots.length);
|
|
1526
|
+
const minStoredFc = storedLen < fc ? storedLen : fc;
|
|
1527
|
+
const rawLocalFc = minStoredFc < localScannedFc ? minStoredFc : localScannedFc;
|
|
1528
|
+
const legacyFc = willPadWindow && sEnd > sStart && sStart < rawLocalFc ? sStart : rawLocalFc;
|
|
1529
|
+
localFcByLane.set(h.laneId, legacyFc);
|
|
1530
|
+
localFinalizedRanges.push({ laneId: h.laneId, startSeq: 0n, sealedCount: legacyFc });
|
|
1531
|
+
localFinalizedTotal += legacyFc;
|
|
1532
|
+
}
|
|
1533
|
+
let publicInLocal = 0;
|
|
1534
|
+
for (const pub of publicSealedSubtrees.values()) {
|
|
1535
|
+
if (pub.subSeq < (localFcByLane.get(pub.laneId) ?? 0n))
|
|
1536
|
+
publicInLocal++;
|
|
1537
|
+
}
|
|
1538
|
+
let alreadyInLocal = 0;
|
|
1539
|
+
for (const req of neededSubtrees.values()) {
|
|
1540
|
+
if (req.subSeq < (localFcByLane.get(req.laneId) ?? 0n))
|
|
1541
|
+
alreadyInLocal++;
|
|
1542
|
+
}
|
|
1543
|
+
const privateInLocal = Math.max(0, alreadyInLocal - publicInLocal);
|
|
1544
|
+
const localPrivateBuckets = Math.max(1, Math.ceil(privateInLocal / batchUnit));
|
|
1545
|
+
const localPrivateTarget = BigInt(localPrivateBuckets) * BigInt(batchUnit);
|
|
1546
|
+
const localTargetBig = BigInt(publicInLocal) + localPrivateTarget;
|
|
1547
|
+
if (localFinalizedTotal >= localTargetBig) {
|
|
1548
|
+
const localTarget = Number(localTargetBig);
|
|
1549
|
+
if (alreadyInLocal < localTarget) {
|
|
1550
|
+
const decoys = localFinalizedTotal <= BigInt(MAX_HRW_SEALED_SUBTREES)
|
|
1551
|
+
? selectHrwSealedDecoys({
|
|
1552
|
+
viewSk: params.fvk.viewSk,
|
|
1553
|
+
scope: syncScope,
|
|
1554
|
+
epochBucket,
|
|
1555
|
+
sealedByLane: localFinalizedRanges,
|
|
1556
|
+
alreadySelected: new Set(neededSubtrees.keys()),
|
|
1557
|
+
targetSealed: localTarget,
|
|
1558
|
+
})
|
|
1559
|
+
: selectLargePoolHrwSealedDecoys({
|
|
1560
|
+
viewSk: params.fvk.viewSk,
|
|
1561
|
+
scope: syncScope,
|
|
1562
|
+
epochBucket,
|
|
1563
|
+
sealedByLane: lanes.map((h) => ({
|
|
1564
|
+
laneId: h.laneId,
|
|
1565
|
+
sealedCount: localFcByLane.get(h.laneId) ?? 0n,
|
|
1566
|
+
})),
|
|
1567
|
+
alreadySelected: new Set(neededSubtrees.keys()),
|
|
1568
|
+
targetSealed: localTarget,
|
|
1569
|
+
});
|
|
1570
|
+
for (const d of decoys) {
|
|
1571
|
+
addNeededSubtree(d.laneId, d.pageSeq);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
if (willPadWindow) {
|
|
1575
|
+
padScannedWindow();
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
else {
|
|
1579
|
+
// Tiny legacy store (`localFinalizedTotal < localTarget`): include ALL of `L'` uniformly;
|
|
1580
|
+
// if a non-uniform Pass 1C window was also scanned, pad `W` FIRST so Step 3A's upward
|
|
1581
|
+
// fallback never overlaps `W` or splits `W`'s 16-subtree bucket.
|
|
1582
|
+
for (const r of localFinalizedRanges) {
|
|
1583
|
+
for (let seq = 0n; seq < r.sealedCount; seq++) {
|
|
1584
|
+
addNeededSubtree(r.laneId, seq);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
if (willPadWindow) {
|
|
1588
|
+
padScannedWindow();
|
|
1589
|
+
}
|
|
1590
|
+
const allSealedNow = countAllSealedNeeded();
|
|
1591
|
+
const nonPublicSealedNow = allSealedNow > BigInt(publicSealedSubtrees.size)
|
|
1592
|
+
? allSealedNow - BigInt(publicSealedSubtrees.size)
|
|
1593
|
+
: 0n;
|
|
1594
|
+
const rawLegacyNeed = localPrivateTarget > nonPublicSealedNow ? localPrivateTarget - nonPublicSealedNow : 0n;
|
|
1595
|
+
const globalAvail = totalSealedSubtrees > allSealedNow ? totalSealedSubtrees - allSealedNow : 0n;
|
|
1596
|
+
let remainingLegacy = Number(rawLegacyNeed < globalAvail ? rawLegacyNeed : globalAvail);
|
|
1597
|
+
if (remainingLegacy > 0) {
|
|
1598
|
+
const scaledTail = localPrivateTarget * 64n;
|
|
1599
|
+
const minTail = scaledTail > 1024n ? scaledTail : 1024n;
|
|
1600
|
+
const tailPerLane = minTail < perLaneMaxSpan ? minTail : perLaneMaxSpan;
|
|
1601
|
+
const upRanges = lanes.map((h) => {
|
|
1602
|
+
const fc = finalizedByLane.get(h.laneId) ?? 0n;
|
|
1603
|
+
const lfc = localFcByLane.get(h.laneId) ?? 0n;
|
|
1604
|
+
const hiCand = lfc + tailPerLane;
|
|
1605
|
+
return { laneId: h.laneId, startSeq: lfc, sealedCount: hiCand < fc ? hiCand : fc };
|
|
1606
|
+
});
|
|
1607
|
+
let inUpCount = 0;
|
|
1608
|
+
for (const req of neededSubtrees.values()) {
|
|
1609
|
+
for (const r of upRanges) {
|
|
1610
|
+
if (req.laneId === r.laneId && req.subSeq >= r.startSeq && req.subSeq < r.sealedCount) {
|
|
1611
|
+
inUpCount++;
|
|
1612
|
+
break;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
const decoys = selectHrwSealedDecoys({
|
|
1617
|
+
viewSk: params.fvk.viewSk,
|
|
1618
|
+
scope: syncScope,
|
|
1619
|
+
epochBucket,
|
|
1620
|
+
sealedByLane: upRanges,
|
|
1621
|
+
alreadySelected: new Set(neededSubtrees.keys()),
|
|
1622
|
+
targetSealed: inUpCount + remainingLegacy,
|
|
1623
|
+
});
|
|
1624
|
+
for (const d of decoys) {
|
|
1625
|
+
if (addNeededSubtree(d.laneId, d.pageSeq) && remainingLegacy > 0) {
|
|
1626
|
+
remainingLegacy--;
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
if (remainingLegacy > 0) {
|
|
1631
|
+
const sealedAfterUp = Number(countAllSealedNeeded());
|
|
1632
|
+
const decoys = selectLargePoolHrwSealedDecoys({
|
|
1633
|
+
viewSk: params.fvk.viewSk,
|
|
1634
|
+
scope: syncScope,
|
|
1635
|
+
epochBucket,
|
|
1636
|
+
sealedByLane: lanes.map((h) => ({
|
|
1637
|
+
laneId: h.laneId,
|
|
1638
|
+
sealedCount: finalizedByLane.get(h.laneId) ?? 0n,
|
|
1639
|
+
})),
|
|
1640
|
+
alreadySelected: new Set(neededSubtrees.keys()),
|
|
1641
|
+
targetSealed: sealedAfterUp + remainingLegacy,
|
|
1642
|
+
});
|
|
1643
|
+
for (const d of decoys) {
|
|
1644
|
+
addNeededSubtree(d.laneId, d.pageSeq);
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
const fetchedSubtrees = new Map();
|
|
1651
|
+
// Canonical public 32-byte PDA order (matching Rust `scanner.rs` bit-for-bit): reveals 0 bits of
|
|
1652
|
+
// insertion order (hits vs decoys vs frontiers) and 0 bits of `viewSk` wallet identity.
|
|
1653
|
+
const subListWithKeys = [...neededSubtrees.entries()]
|
|
1654
|
+
.map(([key, req]) => ({ key, req }))
|
|
1655
|
+
.sort((a, b) => compareBytes32(a.req.addrBytes, b.req.addrBytes));
|
|
1656
|
+
// Privacy & integrity invariant (R2-C1): uniformly validate EVERY fetched SubtreePage (both
|
|
1657
|
+
// hits AND decoys) for exact header `(poolId, laneId, pageSeq)`, strict canonical Fr on ALL
|
|
1658
|
+
// `0..count` leaves, and exact Poseidon root parity against Pass 1A's verified SubtreeRootPage
|
|
1659
|
+
// BEFORE any store mutation and BEFORE Pass 2 executes.
|
|
1660
|
+
let anyPass1dRpcMissing = false;
|
|
1661
|
+
let anyPass1dSubrootUnavailable = false;
|
|
1662
|
+
for (let off = 0; off < subListWithKeys.length; off += RPC_BATCH_CHUNK) {
|
|
1663
|
+
const chunk = subListWithKeys.slice(off, off + RPC_BATCH_CHUNK);
|
|
1664
|
+
const raws = await params.fetchBatch(chunk.map((item) => item.req.addr));
|
|
1665
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
1666
|
+
const item = chunk[i];
|
|
1667
|
+
const raw = raws[i];
|
|
1668
|
+
if (!raw) {
|
|
1669
|
+
anyPass1dRpcMissing = true;
|
|
1670
|
+
continue;
|
|
1671
|
+
}
|
|
1672
|
+
const sub = decodeSubtreePage(raw);
|
|
1673
|
+
if (sub.poolId !== poolId ||
|
|
1674
|
+
sub.laneId !== item.req.laneId ||
|
|
1675
|
+
sub.pageSeq !== item.req.subSeq) {
|
|
1676
|
+
throw new Error(`SubtreePage header mismatch (expected pool=${poolId}, lane=${item.req.laneId}, seq=${item.req.subSeq})`);
|
|
1677
|
+
}
|
|
1678
|
+
const frLeaves = sub.leaves.map((b) => frFromBeBytesStrict(b));
|
|
1679
|
+
// Enforce append-only prefix immutability against persisted `frontierLeaves` and
|
|
1680
|
+
// `prevSealedLeaves` (note-independent; blocks single-leaf frontier rewrite oracles and
|
|
1681
|
+
// permanent `finalizedSubroots` poisoning while remaining safe on honest lagging RPC
|
|
1682
|
+
// replicas whose truncated prefix still matches).
|
|
1683
|
+
const laneStore = params.store.lanes[item.req.laneId];
|
|
1684
|
+
if (laneStore.frontierLeaves.length > 0 && item.req.subSeq === laneStore.frontierSubSeq) {
|
|
1685
|
+
const prefixLen = Math.min(sub.leaves.length, laneStore.frontierLeaves.length);
|
|
1686
|
+
for (let k = 0; k < prefixLen; k++) {
|
|
1687
|
+
if (compareBytes32(sub.leaves[k], laneStore.frontierLeaves[k]) !== 0) {
|
|
1688
|
+
throw new Error('SubtreePage frontier prefix mismatch against persisted frontierLeaves');
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
if (laneStore.prevSealedLeaves.length > 0 &&
|
|
1693
|
+
laneStore.prevSealedSubSeq === item.req.subSeq) {
|
|
1694
|
+
const prefixLen = Math.min(sub.leaves.length, laneStore.prevSealedLeaves.length);
|
|
1695
|
+
for (let k = 0; k < prefixLen; k++) {
|
|
1696
|
+
if (compareBytes32(sub.leaves[k], laneStore.prevSealedLeaves[k]) !== 0) {
|
|
1697
|
+
throw new Error('SubtreePage prefix mismatch against persisted prevSealedLeaves');
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
const fc = finalizedByLane.get(item.req.laneId) ?? 0n;
|
|
1702
|
+
const expectedMinLeaves = item.req.subSeq < fc ? SUBTREE_LEAVES : (frontierRemByLane.get(item.req.laneId) ?? 0);
|
|
1703
|
+
if (sub.leaves.length < expectedMinLeaves) {
|
|
1704
|
+
anyPass1dRpcMissing = true;
|
|
1705
|
+
continue;
|
|
1706
|
+
}
|
|
1707
|
+
else if (item.req.subSeq < fc) {
|
|
1708
|
+
const expectedSubrootBe = lookupVerifiedSubroot(item.req.laneId, item.req.subSeq);
|
|
1709
|
+
if (!expectedSubrootBe) {
|
|
1710
|
+
anyPass1dSubrootUnavailable = true;
|
|
1711
|
+
continue;
|
|
1712
|
+
}
|
|
1713
|
+
const expectedSubrootFr = frFromBeBytesStrict(expectedSubrootBe);
|
|
1714
|
+
if (computeSubtree256Root(frLeaves, SUBTREE_LEAVES) !== expectedSubrootFr) {
|
|
1715
|
+
throw new Error('SubtreePage root mismatch against SubtreeRootPage');
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
else if (sub.leaves.length === SUBTREE_LEAVES &&
|
|
1719
|
+
item.req.subSeq < BigInt(laneStore.finalizedSubroots.length)) {
|
|
1720
|
+
// Even if Phase 0 `laneHdr.nextLeaf` lagged below persisted `finalizedSubroots`, any
|
|
1721
|
+
// fetched 256-leaf page covering an immutable local subroot MUST match it.
|
|
1722
|
+
const expectedSubrootFr = frFromBeBytesStrict(laneStore.finalizedSubroots[Number(item.req.subSeq)]);
|
|
1723
|
+
if (computeSubtree256Root(frLeaves, SUBTREE_LEAVES) !== expectedSubrootFr) {
|
|
1724
|
+
throw new Error('SubtreePage root mismatch against persisted finalizedSubroots');
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
if (item.req.subSeq >= fc) {
|
|
1728
|
+
// Cap live-advancing frontier SubtreePage to Phase 0 `frontierRem` so unverified trailing
|
|
1729
|
+
// leaves beyond `laneHdr.nextLeaf` are never exposed to memo verification or committed.
|
|
1730
|
+
fetchedSubtrees.set(item.key, {
|
|
1731
|
+
leaves: sub.leaves.slice(0, expectedMinLeaves),
|
|
1732
|
+
frLeaves: frLeaves.slice(0, expectedMinLeaves),
|
|
1733
|
+
});
|
|
1734
|
+
}
|
|
1735
|
+
else {
|
|
1736
|
+
fetchedSubtrees.set(item.key, { leaves: sub.leaves, frLeaves });
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
// Cryptographic lane-root verification: before verifying memos or committing Pass 1A/1D state
|
|
1741
|
+
// to `store`, verify EVERY active lane with `nextLeaf > 0` by rolling up
|
|
1742
|
+
// `allFinalizedSubroots[..finalizedCount]` + `frontierFrLeaves[..frontierRem]` against Phase 0
|
|
1743
|
+
// `LaneTreeState.currentRoot`. If Pass 1A stopped short of `finalizedCount` (transient RPC lag),
|
|
1744
|
+
// withhold committing Pass 1A/1D for this sync cycle rather than committing unverified leaves.
|
|
1745
|
+
let anyPass1aIncomplete = false;
|
|
1746
|
+
const pass1aVerifiedLanes = new Set();
|
|
1747
|
+
for (const laneHdr of lanes) {
|
|
1748
|
+
const l = laneHdr.laneId;
|
|
1749
|
+
const finalizedCount = laneHdr.nextLeaf / subSize;
|
|
1750
|
+
const frontierRem = Number(laneHdr.nextLeaf % subSize);
|
|
1751
|
+
if (finalizedCount === 0n && frontierRem === 0) {
|
|
1752
|
+
const expectedEmpty = frFromBeBytesStrict(laneHdr.currentRoot);
|
|
1753
|
+
if (expectedEmpty !== ZERO_HASHES_4ARY[LANE_DEPTH_4ARY]) {
|
|
1754
|
+
throw new Error(`Empty lane ${l} carries non-zero currentRoot`);
|
|
1755
|
+
}
|
|
1756
|
+
pass1aVerifiedLanes.add(l);
|
|
1757
|
+
continue;
|
|
1758
|
+
}
|
|
1759
|
+
const expectedLaneRootFr = frFromBeBytesStrict(laneHdr.currentRoot);
|
|
1760
|
+
const existingSubroots = params.store.lanes[l].finalizedSubroots;
|
|
1761
|
+
const pass1aBuf = pass1aNewSubroots.get(l) ?? [];
|
|
1762
|
+
const totalAvailable = BigInt(existingSubroots.length + pass1aBuf.length);
|
|
1763
|
+
if (totalAvailable < finalizedCount) {
|
|
1764
|
+
anyPass1aIncomplete = true;
|
|
1765
|
+
continue;
|
|
1766
|
+
}
|
|
1767
|
+
let frontierFrSlice;
|
|
1768
|
+
if (frontierRem > 0) {
|
|
1769
|
+
const frontierFetched = fetchedSubtrees.get(`${l}:${finalizedCount.toString()}`);
|
|
1770
|
+
if (!frontierFetched || frontierFetched.frLeaves.length < frontierRem) {
|
|
1771
|
+
anyPass1dRpcMissing = true;
|
|
1772
|
+
continue;
|
|
1773
|
+
}
|
|
1774
|
+
frontierFrSlice = frontierFetched.frLeaves.slice(0, frontierRem);
|
|
1775
|
+
}
|
|
1776
|
+
const fcNum = Number(finalizedCount);
|
|
1777
|
+
const allFinalizedFr = new Array(fcNum);
|
|
1778
|
+
const takeExisting = Math.min(existingSubroots.length, fcNum);
|
|
1779
|
+
for (let k = 0; k < takeExisting; k++) {
|
|
1780
|
+
allFinalizedFr[k] = frFromBeBytesStrict(existingSubroots[k]);
|
|
1781
|
+
}
|
|
1782
|
+
for (let k = takeExisting; k < fcNum; k++) {
|
|
1783
|
+
allFinalizedFr[k] = frFromBeBytesStrict(pass1aBuf[k - existingSubroots.length]);
|
|
1784
|
+
}
|
|
1785
|
+
const computedLaneRootFr = computeLaneRootFromSubrootsAndFrontier(allFinalizedFr, frontierFrSlice, frontierRem);
|
|
1786
|
+
if (computedLaneRootFr !== expectedLaneRootFr) {
|
|
1787
|
+
throw new Error(`Lane #${l} root mismatch against LaneTreeState.currentRoot`);
|
|
1788
|
+
}
|
|
1789
|
+
pass1aVerifiedLanes.add(l);
|
|
1790
|
+
}
|
|
1791
|
+
let discoveredNotes = 0;
|
|
1792
|
+
const pendingVerifiedMemos = [];
|
|
1793
|
+
const pendingWatermarks = new Map();
|
|
1794
|
+
const publicWatermarks = new Map();
|
|
1795
|
+
const holdSealedFrontierLanes = new Set();
|
|
1796
|
+
for (const laneHdr of lanes) {
|
|
1797
|
+
const l = laneHdr.laneId;
|
|
1798
|
+
const laneState = params.store.lanes[l];
|
|
1799
|
+
const oldFrontierSubSeq = laneState.frontierSubSeq;
|
|
1800
|
+
const oldFrontierLeaves = laneState.frontierLeaves;
|
|
1801
|
+
const oldNextMemoLeaf = laneState.nextMemoLeaf;
|
|
1802
|
+
const finalizedCount = laneHdr.nextLeaf / subSize;
|
|
1803
|
+
const startLeaf = scanStartLeafByLane.get(l) ?? oldNextMemoLeaf;
|
|
1804
|
+
const startSub = startSubByLane.get(l) ?? 0n;
|
|
1805
|
+
// Returning-wallet privacy & liveness invariant: ONLY hold a sealed frontier page if this
|
|
1806
|
+
// wallet had actually memo-scanned leaves inside `oldFrontierSubSeq` prior to this sync
|
|
1807
|
+
// (`oldNextMemoLeaf > oldFrontierSubSeq * 256 && oldFrontierSubSeq >= startSub`) AND
|
|
1808
|
+
// `(l, oldFrontierSubSeq)` was not fetched in Pass 1D. Never hold a never-memo-scanned
|
|
1809
|
+
// frontier (eliminates permanent livelocks on `> 786k`-note fresh catch-ups and Pass 1B
|
|
1810
|
+
// `birthdaySlot` skips while preserving 100% 0-note vs N-note uniformity).
|
|
1811
|
+
const holdSealedFrontier = oldFrontierLeaves.length > 0 &&
|
|
1812
|
+
oldFrontierSubSeq < finalizedCount &&
|
|
1813
|
+
oldNextMemoLeaf > oldFrontierSubSeq * subSize &&
|
|
1814
|
+
oldFrontierSubSeq >= startSub &&
|
|
1815
|
+
!fetchedSubtrees.has(`${l}:${oldFrontierSubSeq.toString()}`);
|
|
1816
|
+
if (holdSealedFrontier) {
|
|
1817
|
+
holdSealedFrontierLanes.add(l);
|
|
1818
|
+
}
|
|
1819
|
+
// Verify all view-tag candidates for this lane in ascending leaf order into a temporary buffer;
|
|
1820
|
+
// `store` is ONLY mutated below when `!anyPass1dSubtreeMissing` so any dropped Pass 1D page
|
|
1821
|
+
// (hit OR decoy) leaves `store` and `discoveredNotes` 100% untouched.
|
|
1822
|
+
let verifiedWatermark = scannedWatermarkByLane.get(l) ?? oldNextMemoLeaf;
|
|
1823
|
+
if (strictSubtreeAtomic) {
|
|
1824
|
+
const finalizedLeaves = finalizedCount * subSize;
|
|
1825
|
+
if (dupEndSubCap.has(l) || verifiedWatermark < finalizedLeaves) {
|
|
1826
|
+
const actualEndSub = actualEndSubByLane.get(l) ?? 0n;
|
|
1827
|
+
const endLeaf = actualEndSub * subSize;
|
|
1828
|
+
const atomicCap = endLeaf > startLeaf ? endLeaf : startLeaf;
|
|
1829
|
+
if (verifiedWatermark > atomicCap) {
|
|
1830
|
+
verifiedWatermark = atomicCap;
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
if (holdSealedFrontier && verifiedWatermark > oldNextMemoLeaf) {
|
|
1835
|
+
verifiedWatermark = oldNextMemoLeaf;
|
|
1836
|
+
}
|
|
1837
|
+
if (pass1bRoundedDownStartMemo.has(l) && !roundedDownCreatedSlots.has(l)) {
|
|
1838
|
+
verifiedWatermark = oldNextMemoLeaf;
|
|
1839
|
+
}
|
|
1840
|
+
// Snapshot hit-independent public watermark BEFORE inspecting private view-tag hits so Pass 2
|
|
1841
|
+
// and `committedBirthdayFloor` can NEVER leak a 1-bit hit/drop oracle.
|
|
1842
|
+
publicWatermarks.set(l, verifiedWatermark);
|
|
1843
|
+
const hits = hitsByLane.get(l) ?? [];
|
|
1844
|
+
for (const hit of hits) {
|
|
1845
|
+
if (hit.leafIdx >= verifiedWatermark)
|
|
1846
|
+
break;
|
|
1847
|
+
const memoPage = fetchedFullMemos.get(`${l}:${hit.memoSeq.toString()}`);
|
|
1848
|
+
const subSeq = hit.leafIdx / subSize;
|
|
1849
|
+
const subSlot = Number(hit.leafIdx % subSize);
|
|
1850
|
+
const subLeaves = fetchedSubtrees.get(`${l}:${subSeq.toString()}`)?.leaves ??
|
|
1851
|
+
(subSeq === oldFrontierSubSeq ? oldFrontierLeaves : undefined);
|
|
1852
|
+
if (!memoPage ||
|
|
1853
|
+
hit.slot >= memoPage.entries.length ||
|
|
1854
|
+
!subLeaves ||
|
|
1855
|
+
subSlot >= subLeaves.length) {
|
|
1856
|
+
// Cap nextMemoLeaf watermark on transient RPC miss (never skip Pass 2!).
|
|
1857
|
+
if (hit.leafIdx < verifiedWatermark)
|
|
1858
|
+
verifiedWatermark = hit.leafIdx;
|
|
1859
|
+
break;
|
|
1860
|
+
}
|
|
1861
|
+
const entry = memoPage.entries[hit.slot];
|
|
1862
|
+
const cmBe = subLeaves[subSlot];
|
|
1863
|
+
const dec = tryDecryptAndVerifyMemoEntry(params.fvk, entry.viewTag, entry.ephemeralPk, entry.ciphertext, cmBe);
|
|
1864
|
+
if (dec) {
|
|
1865
|
+
pendingVerifiedMemos.push({
|
|
1866
|
+
laneId: l,
|
|
1867
|
+
leafIdx: hit.leafIdx,
|
|
1868
|
+
decrypted: dec,
|
|
1869
|
+
cmBe,
|
|
1870
|
+
});
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
pendingWatermarks.set(l, verifiedWatermark);
|
|
1874
|
+
}
|
|
1875
|
+
// Privacy & atomicity invariant: if ANY Pass 1A `SubtreeRootPage` stopped short of
|
|
1876
|
+
// `finalizedCount` OR ANY Pass 1D `SubtreePage` fetch returned `null` (or truncated) —
|
|
1877
|
+
// whether for a hit page OR a decoy/batch page — uniformly withhold ALL Pass 1A/1B/1D store
|
|
1878
|
+
// mutations (`finalizedSubroots`, `notes`, `discoveredNotes`, `nextMemoLeaf`, note freezing,
|
|
1879
|
+
// and frontier updates) across ALL lanes. Precompute ALL frozen intra-subtree witnesses BEFORE
|
|
1880
|
+
// mutating `store` so a validation error can NEVER leave partially mutated store state!
|
|
1881
|
+
const pass1Incomplete = anyPass1dRpcMissing || anyPass1dSubrootUnavailable || anyPass1aIncomplete;
|
|
1882
|
+
if (pass1Incomplete &&
|
|
1883
|
+
anyPass1aIncomplete &&
|
|
1884
|
+
srPagesFetched >= MAX_SYNC_PAGES_PER_CALL &&
|
|
1885
|
+
!anyPass1aRpcLag &&
|
|
1886
|
+
!anyPass1dRpcMissing) {
|
|
1887
|
+
// Public, note-independent Pass 1A forward progress: when total unsynced `SubtreeRootPage`s
|
|
1888
|
+
// across active lanes exceed `MAX_SYNC_PAGES_PER_CALL` (4,096), commit `finalizedSubroots`
|
|
1889
|
+
// for every lane whose full `SubtreeRootPage` set already passed cryptographic verification
|
|
1890
|
+
// against `LaneTreeState.currentRoot` and does not hold an unverified sealed frontier
|
|
1891
|
+
// (preserving `frontierLeaves` prefix immutability before persisting the sealed subroot).
|
|
1892
|
+
for (const laneHdr of lanes) {
|
|
1893
|
+
const l = laneHdr.laneId;
|
|
1894
|
+
if (!pass1aVerifiedLanes.has(l) || holdSealedFrontierLanes.has(l))
|
|
1895
|
+
continue;
|
|
1896
|
+
if (laneHdr.nextLeaf / subSize < BigInt(params.store.lanes[l].finalizedSubroots.length)) {
|
|
1897
|
+
continue;
|
|
1898
|
+
}
|
|
1899
|
+
const newRoots = pass1aNewSubroots.get(l);
|
|
1900
|
+
if (newRoots && newRoots.length > 0) {
|
|
1901
|
+
params.store.lanes[l].finalizedSubroots.push(...newRoots);
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
if (!pass1Incomplete) {
|
|
1906
|
+
if (pendingVerifiedMemos.length > 0) {
|
|
1907
|
+
frFromBeBytesStrict(params.fvk.spendPk);
|
|
1908
|
+
frFromBeBytesStrict(params.fvk.nk);
|
|
1909
|
+
}
|
|
1910
|
+
const precomputedExistingFreezes = [];
|
|
1911
|
+
for (let ni = 0; ni < params.store.notes.length; ni++) {
|
|
1912
|
+
const note = params.store.notes[ni];
|
|
1913
|
+
if (note.frozenIntraSiblings)
|
|
1914
|
+
continue;
|
|
1915
|
+
const subSeq = note.leafIndex / subSize;
|
|
1916
|
+
const fc = finalizedByLane.get(note.laneId) ?? 0n;
|
|
1917
|
+
if (subSeq >= fc)
|
|
1918
|
+
continue;
|
|
1919
|
+
const fetched = fetchedSubtrees.get(`${note.laneId}:${subSeq.toString()}`);
|
|
1920
|
+
if (fetched && fetched.frLeaves.length === SUBTREE_LEAVES) {
|
|
1921
|
+
const offset = Number(note.leafIndex % subSize);
|
|
1922
|
+
if (offset < fetched.leaves.length &&
|
|
1923
|
+
compareBytes32(fetched.leaves[offset], note.commitment) === 0) {
|
|
1924
|
+
const { siblings, positions } = extractIntraSubtreeSiblings(fetched.frLeaves, SUBTREE_LEAVES, offset);
|
|
1925
|
+
precomputedExistingFreezes.push({
|
|
1926
|
+
noteIndex: ni,
|
|
1927
|
+
siblingsBe: siblings.map((lvl) => lvl.map((x) => frToBeBytes(x))),
|
|
1928
|
+
positions,
|
|
1929
|
+
});
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
const precomputedNewFreezes = new Map();
|
|
1934
|
+
for (const m of pendingVerifiedMemos) {
|
|
1935
|
+
const subSeq = m.leafIdx / subSize;
|
|
1936
|
+
const fc = finalizedByLane.get(m.laneId) ?? 0n;
|
|
1937
|
+
if (subSeq >= fc)
|
|
1938
|
+
continue;
|
|
1939
|
+
const fetched = fetchedSubtrees.get(`${m.laneId}:${subSeq.toString()}`);
|
|
1940
|
+
if (fetched && fetched.frLeaves.length === SUBTREE_LEAVES) {
|
|
1941
|
+
const offset = Number(m.leafIdx % subSize);
|
|
1942
|
+
if (offset < fetched.leaves.length &&
|
|
1943
|
+
compareBytes32(fetched.leaves[offset], m.cmBe) === 0) {
|
|
1944
|
+
const { siblings, positions } = extractIntraSubtreeSiblings(fetched.frLeaves, SUBTREE_LEAVES, offset);
|
|
1945
|
+
precomputedNewFreezes.set(`${m.laneId}:${m.leafIdx.toString()}`, {
|
|
1946
|
+
siblingsBe: siblings.map((lvl) => lvl.map((x) => frToBeBytes(x))),
|
|
1947
|
+
positions,
|
|
1948
|
+
});
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
// Public, note-independent lagging-lane guard: never commit newly verified memos or advance
|
|
1953
|
+
// `nextMemoLeaf` for a lane whose Phase 0 `finalizedCount` lags behind already-persisted
|
|
1954
|
+
// immutable `finalizedSubroots` (blocks forged unsealed-frontier note injection inside an
|
|
1955
|
+
// already-finalized subtree).
|
|
1956
|
+
const laggingLanes = new Set();
|
|
1957
|
+
for (const laneHdr of lanes) {
|
|
1958
|
+
if (laneHdr.nextLeaf / subSize <
|
|
1959
|
+
BigInt(params.store.lanes[laneHdr.laneId].finalizedSubroots.length)) {
|
|
1960
|
+
laggingLanes.add(laneHdr.laneId);
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
// All validations & precomputations succeeded: commit atomically to `store`.
|
|
1964
|
+
for (const laneHdr of lanes) {
|
|
1965
|
+
const l = laneHdr.laneId;
|
|
1966
|
+
if (holdSealedFrontierLanes.has(l) || laggingLanes.has(l))
|
|
1967
|
+
continue;
|
|
1968
|
+
const newRoots = pass1aNewSubroots.get(l);
|
|
1969
|
+
if (newRoots && newRoots.length > 0) {
|
|
1970
|
+
params.store.lanes[l].finalizedSubroots.push(...newRoots);
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
for (const f of precomputedExistingFreezes) {
|
|
1974
|
+
const note = params.store.notes[f.noteIndex];
|
|
1975
|
+
note.frozenIntraSiblings = f.siblingsBe;
|
|
1976
|
+
note.frozenIntraPositions = f.positions;
|
|
1977
|
+
}
|
|
1978
|
+
for (const m of pendingVerifiedMemos) {
|
|
1979
|
+
if (laggingLanes.has(m.laneId))
|
|
1980
|
+
continue;
|
|
1981
|
+
if (params.store.recordVerifiedMemo({
|
|
1982
|
+
fvk: params.fvk,
|
|
1983
|
+
laneId: m.laneId,
|
|
1984
|
+
leafIdx: m.leafIdx,
|
|
1985
|
+
decrypted: m.decrypted,
|
|
1986
|
+
cmBe: m.cmBe,
|
|
1987
|
+
})) {
|
|
1988
|
+
discoveredNotes++;
|
|
1989
|
+
const frozen = precomputedNewFreezes.get(`${m.laneId}:${m.leafIdx.toString()}`);
|
|
1990
|
+
if (frozen) {
|
|
1991
|
+
const added = params.store.notes[params.store.notes.length - 1];
|
|
1992
|
+
added.frozenIntraSiblings = frozen.siblingsBe;
|
|
1993
|
+
added.frozenIntraPositions = frozen.positions;
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
// Public, note-independent birthday-slot floor persistence (placed after all fallible Fr /
|
|
1998
|
+
// witness precomputation, matching Rust `scanner.rs`): lower `store.birthdaySlot` only for
|
|
1999
|
+
// rounded-down lanes whose `startMemo` was actually fetched and advanced in Pass 1C.
|
|
2000
|
+
let committedBirthdayFloor = birthdaySlot;
|
|
2001
|
+
for (const lid of pass1bRoundedDownStartMemo.keys()) {
|
|
2002
|
+
const wm = publicWatermarks.get(lid) ?? 0n;
|
|
2003
|
+
if (wm > 0n && !laggingLanes.has(lid)) {
|
|
2004
|
+
const cs = roundedDownCreatedSlots.get(lid);
|
|
2005
|
+
if (cs === undefined) {
|
|
2006
|
+
committedBirthdayFloor = 0n;
|
|
2007
|
+
break;
|
|
2008
|
+
}
|
|
2009
|
+
if (cs < committedBirthdayFloor) {
|
|
2010
|
+
committedBirthdayFloor = cs;
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
if (storeWasGenesis &&
|
|
2015
|
+
params.birthdaySlot !== undefined &&
|
|
2016
|
+
params.store.birthdaySlot === 0n &&
|
|
2017
|
+
birthdaySlot > 0n) {
|
|
2018
|
+
params.store.birthdaySlot = committedBirthdayFloor;
|
|
2019
|
+
}
|
|
2020
|
+
else if (params.store.birthdaySlot > committedBirthdayFloor) {
|
|
2021
|
+
params.store.birthdaySlot = committedBirthdayFloor;
|
|
2022
|
+
}
|
|
2023
|
+
for (const [laneId, verifiedWatermark] of pendingWatermarks) {
|
|
2024
|
+
if (laggingLanes.has(laneId))
|
|
2025
|
+
continue;
|
|
2026
|
+
const laneState = params.store.lanes[laneId];
|
|
2027
|
+
if (verifiedWatermark > laneState.nextMemoLeaf) {
|
|
2028
|
+
laneState.nextMemoLeaf = verifiedWatermark;
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
for (const laneHdr of lanes) {
|
|
2032
|
+
const l = laneHdr.laneId;
|
|
2033
|
+
if (holdSealedFrontierLanes.has(l))
|
|
2034
|
+
continue;
|
|
2035
|
+
const laneState = params.store.lanes[l];
|
|
2036
|
+
const oldFrontierSubSeq = laneState.frontierSubSeq;
|
|
2037
|
+
const oldFrontierLeaves = laneState.frontierLeaves;
|
|
2038
|
+
const finalizedCount = laneHdr.nextLeaf / subSize;
|
|
2039
|
+
const frontierRem = Number(laneHdr.nextLeaf % subSize);
|
|
2040
|
+
const finalizedSubrootsLen = BigInt(laneState.finalizedSubroots.length);
|
|
2041
|
+
// Retain at most 1 just-sealed page (`prevSealedSubSeq`/`prevSealedLeaves`) for pre-seal root snapshots
|
|
2042
|
+
// (monotonicity-guarded so lagging RPC replicas never regress `prevSealedSubSeq`).
|
|
2043
|
+
if (finalizedCount > 0n) {
|
|
2044
|
+
const latestSealedSeq = finalizedCount - 1n;
|
|
2045
|
+
const prevSealedAdvances = (laneState.prevSealedSubSeq === null || latestSealedSeq >= laneState.prevSealedSubSeq) &&
|
|
2046
|
+
finalizedCount >= oldFrontierSubSeq &&
|
|
2047
|
+
finalizedCount >= finalizedSubrootsLen;
|
|
2048
|
+
if (prevSealedAdvances) {
|
|
2049
|
+
const latestSealedLeaves = fetchedSubtrees.get(`${l}:${latestSealedSeq.toString()}`)?.leaves;
|
|
2050
|
+
if (latestSealedLeaves && latestSealedLeaves.length === SUBTREE_LEAVES) {
|
|
2051
|
+
laneState.prevSealedSubSeq = latestSealedSeq;
|
|
2052
|
+
laneState.prevSealedLeaves = latestSealedLeaves.map((b) => new Uint8Array(b));
|
|
2053
|
+
}
|
|
2054
|
+
else if (oldFrontierSubSeq === latestSealedSeq &&
|
|
2055
|
+
oldFrontierLeaves.length > 0 &&
|
|
2056
|
+
laneState.prevSealedSubSeq !== latestSealedSeq) {
|
|
2057
|
+
laneState.prevSealedSubSeq = oldFrontierSubSeq;
|
|
2058
|
+
laneState.prevSealedLeaves = oldFrontierLeaves;
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
// Update live unsealed frontier (monotonicity-guarded against lagging RPC replicas).
|
|
2063
|
+
if (frontierRem > 0) {
|
|
2064
|
+
const frontierAdvances = finalizedCount >= finalizedSubrootsLen &&
|
|
2065
|
+
(finalizedCount > laneState.frontierSubSeq ||
|
|
2066
|
+
(finalizedCount === laneState.frontierSubSeq &&
|
|
2067
|
+
frontierRem > laneState.frontierLeaves.length));
|
|
2068
|
+
if (frontierAdvances) {
|
|
2069
|
+
const frontierLeaves = fetchedSubtrees.get(`${l}:${finalizedCount.toString()}`)?.leaves;
|
|
2070
|
+
if (frontierLeaves && frontierLeaves.length >= frontierRem) {
|
|
2071
|
+
laneState.frontierSubSeq = finalizedCount;
|
|
2072
|
+
laneState.frontierLeaves = frontierLeaves
|
|
2073
|
+
.slice(0, frontierRem)
|
|
2074
|
+
.map((b) => new Uint8Array(b));
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
else if (finalizedCount > laneState.frontierSubSeq &&
|
|
2079
|
+
finalizedCount >= finalizedSubrootsLen) {
|
|
2080
|
+
laneState.frontierSubSeq = finalizedCount;
|
|
2081
|
+
laneState.frontierLeaves = [];
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
if (!pass1Incomplete && params.latestRootHistory !== undefined) {
|
|
2086
|
+
params.store.pruneSealedBeforeSnapshot(params.latestRootHistory);
|
|
2087
|
+
}
|
|
2088
|
+
// =========================================================================
|
|
2089
|
+
// PASS 2: ALWAYS stream ALL new `NullifierPage`s unconditionally (ZERO oracle!)
|
|
2090
|
+
// =========================================================================
|
|
2091
|
+
// Even if Pass 1D experienced a transient `SubtreePage` miss, Pass 2 MUST STILL fetch every
|
|
2092
|
+
// `NullifierPage` uniformly so an adversarial RPC cannot drop a `SubtreePage` and observe
|
|
2093
|
+
// whether Pass 2 was skipped. If ANY Pass 1A/1D page was missing OR any lane had an
|
|
2094
|
+
// unverified miss, we guarantee unconditional rollback of `nextNfIndex` across ALL lanes on
|
|
2095
|
+
// BOTH normal return and error exits.
|
|
2096
|
+
// Public, note-independent completeness & Phase 0 monotonicity gate across ALL `0..NUM_LANES`:
|
|
2097
|
+
// never commit `nextNfIndex` if ANY lane still has persisted on-chain leaves ahead of
|
|
2098
|
+
// `nextMemoLeaf` OR if Phase 0 lags behind ANY lane's previously observed monotonic high-water
|
|
2099
|
+
// marks (`activeLanes`, `nextLeaf`, `nfCount`). Blocks permanent cross-lane spend-detection
|
|
2100
|
+
// loss for BOTH interrupted catch-up wallets AND caught-up returning wallets.
|
|
2101
|
+
let allPersistedLeavesScanned = true;
|
|
2102
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2103
|
+
const lane = params.store.lanes[l];
|
|
2104
|
+
const persistedSealed = BigInt(lane.finalizedSubroots.length) * subSize;
|
|
2105
|
+
const persistedFrontier = lane.frontierLeaves.length === 0
|
|
2106
|
+
? 0n
|
|
2107
|
+
: lane.frontierSubSeq * subSize + BigInt(lane.frontierLeaves.length);
|
|
2108
|
+
const persistedCeil = persistedSealed > persistedFrontier ? persistedSealed : persistedFrontier;
|
|
2109
|
+
if (lane.nextMemoLeaf < persistedCeil) {
|
|
2110
|
+
allPersistedLeavesScanned = false;
|
|
2111
|
+
break;
|
|
2112
|
+
}
|
|
2113
|
+
const localLeafHwm = persistedCeil > lane.nextMemoLeaf ? persistedCeil : lane.nextMemoLeaf;
|
|
2114
|
+
if (localLeafHwm > 0n || lane.nextNfIndex > 0n) {
|
|
2115
|
+
const hdr = lanes.find((h) => h.laneId === l);
|
|
2116
|
+
if (!hdr || hdr.nextLeaf < localLeafHwm || hdr.nfCount < lane.nextNfIndex) {
|
|
2117
|
+
allPersistedLeavesScanned = false;
|
|
2118
|
+
break;
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
const allLanesCaughtUp = !pass1Incomplete &&
|
|
2123
|
+
allPersistedLeavesScanned &&
|
|
2124
|
+
lanes.every((h) => params.store.lanes[h.laneId].nextMemoLeaf >= h.nextLeaf);
|
|
2125
|
+
const savedNextNfIndex = new Map();
|
|
2126
|
+
for (const laneHdr of lanes) {
|
|
2127
|
+
savedNextNfIndex.set(laneHdr.laneId, params.store.lanes[laneHdr.laneId].nextNfIndex);
|
|
2128
|
+
}
|
|
2129
|
+
const savedSpent = params.store.notes.map((n) => n.spent);
|
|
2130
|
+
let pass2Succeeded = false;
|
|
2131
|
+
try {
|
|
2132
|
+
const nfStartIdxByLane = new Map();
|
|
2133
|
+
for (const laneHdr of lanes) {
|
|
2134
|
+
nfStartIdxByLane.set(laneHdr.laneId, params.store.lanes[laneHdr.laneId].nextNfIndex);
|
|
2135
|
+
}
|
|
2136
|
+
// Optional birthdaySlot binary search on `64 B` NullifierPage headers for fresh wallets
|
|
2137
|
+
// (runs uniformly regardless of owned-note balance so RPC cannot infer first receipt;
|
|
2138
|
+
// keeps working start index local so Pass 2 errors never leak mutated `nextNfIndex`).
|
|
2139
|
+
// When Pass 1B subtree-boundary alignment rounded any lane down to an earlier `256`-leaf
|
|
2140
|
+
// boundary, lower `effectiveNfBirthdaySlot` to the minimum `createdSlot` across those
|
|
2141
|
+
// rounded-down starting MemoPages so cross-lane and multi-NullifierPage spends are never skipped.
|
|
2142
|
+
let effectiveNfBirthdaySlot = birthdaySlot;
|
|
2143
|
+
if (effectiveNfBirthdaySlot > 0n && pass1bRoundedDownStartMemo.size > 0) {
|
|
2144
|
+
for (const lid of pass1bRoundedDownStartMemo.keys()) {
|
|
2145
|
+
const wm = publicWatermarks.get(lid) ?? 0n;
|
|
2146
|
+
const laneLagging = (finalizedByLane.get(lid) ?? 0n) < BigInt(params.store.lanes[lid].finalizedSubroots.length);
|
|
2147
|
+
if (wm === 0n || laneLagging)
|
|
2148
|
+
continue;
|
|
2149
|
+
const cs = roundedDownCreatedSlots.get(lid);
|
|
2150
|
+
if (cs === undefined) {
|
|
2151
|
+
effectiveNfBirthdaySlot = 0n;
|
|
2152
|
+
break;
|
|
2153
|
+
}
|
|
2154
|
+
if (cs < effectiveNfBirthdaySlot) {
|
|
2155
|
+
effectiveNfBirthdaySlot = cs;
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
if (effectiveNfBirthdaySlot > 0n) {
|
|
2160
|
+
const nfBsStates = [];
|
|
2161
|
+
for (const laneHdr of lanes) {
|
|
2162
|
+
const l = laneHdr.laneId;
|
|
2163
|
+
const startIdx = nfStartIdxByLane.get(l) ?? params.store.lanes[l].nextNfIndex;
|
|
2164
|
+
if (laneHdr.nfCount > 0n && startIdx === 0n) {
|
|
2165
|
+
const targetNfMax = (laneHdr.nfCount - 1n) / nfSize;
|
|
2166
|
+
if (targetNfMax > 2n) {
|
|
2167
|
+
nfBsStates.push({ laneId: l, nfCount: laneHdr.nfCount, lo: 0n, hi: targetNfMax + 1n });
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
while (nfBsStates.some((s) => s.lo < s.hi)) {
|
|
2172
|
+
const active = nfBsStates.filter((s) => s.lo < s.hi);
|
|
2173
|
+
const mids = active.map((s) => s.lo + ((s.hi - s.lo) >> 1n));
|
|
2174
|
+
const addrs = active.map((s, i) => deriveNfPagePdaSync(poolId, s.laneId, mids[i], programId).address);
|
|
2175
|
+
const raws = await params.fetchBatch(addrs, {
|
|
2176
|
+
dataSlice: { offset: 0, length: NF_PAGE_HEADER_LEN },
|
|
2177
|
+
});
|
|
2178
|
+
for (let i = 0; i < active.length; i++) {
|
|
2179
|
+
const st = active[i];
|
|
2180
|
+
const mid = mids[i];
|
|
2181
|
+
const raw = raws[i];
|
|
2182
|
+
if (raw) {
|
|
2183
|
+
const hdr = decodeNullifierPageHeader(raw);
|
|
2184
|
+
if (hdr.poolId !== poolId || hdr.laneId !== st.laneId || hdr.pageSeq !== mid) {
|
|
2185
|
+
throw new Error(`NullifierPage header mismatch (expected pool=${poolId}, lane=${st.laneId}, seq=${mid})`);
|
|
2186
|
+
}
|
|
2187
|
+
if (hdr.count === NF_PER_PAGE &&
|
|
2188
|
+
hdr.closedSlot > 0n &&
|
|
2189
|
+
hdr.closedSlot < effectiveNfBirthdaySlot) {
|
|
2190
|
+
st.lo = mid + 1n;
|
|
2191
|
+
}
|
|
2192
|
+
else {
|
|
2193
|
+
st.hi = mid;
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
else {
|
|
2197
|
+
st.hi = mid;
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
for (const st of nfBsStates) {
|
|
2202
|
+
if (st.lo > 0n) {
|
|
2203
|
+
const skipTo = st.lo * nfSize;
|
|
2204
|
+
nfStartIdxByLane.set(st.laneId, skipTo < st.nfCount ? skipTo : st.nfCount);
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
// Advance `nextNfIndex` to each lane's verified birthday-skip watermark before streaming
|
|
2209
|
+
// contiguous NullifierPages (rolled back unconditionally on Pass 2 error or `!allLanesCaughtUp`).
|
|
2210
|
+
for (const [l, startIdx] of nfStartIdxByLane) {
|
|
2211
|
+
const laneState = params.store.lanes[l];
|
|
2212
|
+
if (startIdx > laneState.nextNfIndex) {
|
|
2213
|
+
laneState.nextNfIndex = startIdx;
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
const nfCursors = [];
|
|
2217
|
+
for (const laneHdr of lanes) {
|
|
2218
|
+
const l = laneHdr.laneId;
|
|
2219
|
+
const startIdx = nfStartIdxByLane.get(l) ?? params.store.lanes[l].nextNfIndex;
|
|
2220
|
+
if (laneHdr.nfCount === 0n || startIdx >= laneHdr.nfCount)
|
|
2221
|
+
continue;
|
|
2222
|
+
nfCursors.push({
|
|
2223
|
+
laneId: l,
|
|
2224
|
+
nextNf: startIdx / nfSize,
|
|
2225
|
+
endNf: (laneHdr.nfCount - 1n) / nfSize,
|
|
2226
|
+
maxNfIndex: laneHdr.nfCount,
|
|
2227
|
+
stopped: false,
|
|
2228
|
+
});
|
|
2229
|
+
}
|
|
2230
|
+
let nfPagesFetched = 0;
|
|
2231
|
+
while (nfPagesFetched < MAX_SYNC_PAGES_PER_CALL) {
|
|
2232
|
+
const chunk = [];
|
|
2233
|
+
for (const cursor of nfCursors) {
|
|
2234
|
+
while (!cursor.stopped &&
|
|
2235
|
+
cursor.nextNf <= cursor.endNf &&
|
|
2236
|
+
chunk.length < RPC_BATCH_CHUNK &&
|
|
2237
|
+
nfPagesFetched + chunk.length < MAX_SYNC_PAGES_PER_CALL) {
|
|
2238
|
+
const n = cursor.nextNf;
|
|
2239
|
+
cursor.nextNf = n + 1n;
|
|
2240
|
+
chunk.push({
|
|
2241
|
+
cursor,
|
|
2242
|
+
pageSeq: n,
|
|
2243
|
+
addr: deriveNfPagePdaSync(poolId, cursor.laneId, n, programId).address,
|
|
2244
|
+
});
|
|
2245
|
+
}
|
|
2246
|
+
if (chunk.length >= RPC_BATCH_CHUNK ||
|
|
2247
|
+
nfPagesFetched + chunk.length >= MAX_SYNC_PAGES_PER_CALL) {
|
|
2248
|
+
break;
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
if (chunk.length === 0)
|
|
2252
|
+
break;
|
|
2253
|
+
nfPagesFetched += chunk.length;
|
|
2254
|
+
const raws = await params.fetchBatch(chunk.map((q) => q.addr));
|
|
2255
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
2256
|
+
const item = chunk[i];
|
|
2257
|
+
const cursor = item.cursor;
|
|
2258
|
+
if (cursor.stopped)
|
|
2259
|
+
continue;
|
|
2260
|
+
const raw = raws[i];
|
|
2261
|
+
if (!raw) {
|
|
2262
|
+
cursor.stopped = true;
|
|
2263
|
+
continue;
|
|
2264
|
+
}
|
|
2265
|
+
const hdr = decodeNullifierPageHeader(raw);
|
|
2266
|
+
if (hdr.poolId !== poolId ||
|
|
2267
|
+
hdr.laneId !== cursor.laneId ||
|
|
2268
|
+
hdr.pageSeq !== item.pageSeq) {
|
|
2269
|
+
throw new Error(`NullifierPage header mismatch (expected pool=${poolId}, lane=${cursor.laneId}, seq=${item.pageSeq})`);
|
|
2270
|
+
}
|
|
2271
|
+
const pageBase = item.pageSeq * nfSize;
|
|
2272
|
+
const expectedCap = Math.min(NF_PER_PAGE, cursor.maxNfIndex > pageBase ? Number(cursor.maxNfIndex - pageBase) : 0);
|
|
2273
|
+
params.store.ingestNullifierPage({
|
|
2274
|
+
laneId: cursor.laneId,
|
|
2275
|
+
pageSeq: item.pageSeq,
|
|
2276
|
+
raw,
|
|
2277
|
+
maxNfIndex: cursor.maxNfIndex,
|
|
2278
|
+
});
|
|
2279
|
+
if (hdr.count < expectedCap) {
|
|
2280
|
+
cursor.stopped = true;
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
pass2Succeeded = true;
|
|
2285
|
+
}
|
|
2286
|
+
finally {
|
|
2287
|
+
// On Pass 2 error, roll back BOTH `nextNfIndex` and `note.spent` atomically across all lanes.
|
|
2288
|
+
// On Pass 1 incomplete (`!allLanesCaughtUp`), unconditionally restore `nextNfIndex`.
|
|
2289
|
+
if (!pass2Succeeded) {
|
|
2290
|
+
for (const [l, prevIdx] of savedNextNfIndex) {
|
|
2291
|
+
params.store.lanes[l].nextNfIndex = prevIdx;
|
|
2292
|
+
}
|
|
2293
|
+
for (let i = 0; i < savedSpent.length && i < params.store.notes.length; i++) {
|
|
2294
|
+
params.store.notes[i].spent = savedSpent[i];
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
else if (!allLanesCaughtUp) {
|
|
2298
|
+
for (const [l, prevIdx] of savedNextNfIndex) {
|
|
2299
|
+
params.store.lanes[l].nextNfIndex = prevIdx;
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
const allNullifiersCaughtUp = lanes.every((h) => params.store.lanes[h.laneId].nextNfIndex >= h.nfCount);
|
|
2304
|
+
return {
|
|
2305
|
+
pool,
|
|
2306
|
+
lanes,
|
|
2307
|
+
discoveredNotes,
|
|
2308
|
+
incomplete: pass1Incomplete || !allLanesCaughtUp || !allNullifiersCaughtUp,
|
|
2309
|
+
};
|
|
2310
|
+
}
|
|
2311
|
+
const U32_MAX = 0xffff_ffff;
|
|
2312
|
+
const U64_MAX = 0xffffffffffffffffn;
|
|
2313
|
+
const ZERO_LANE_ROOT_BE = frToBeBytes(ZERO_HASHES_4ARY[LANE_DEPTH_4ARY]);
|
|
2314
|
+
function isAllZero32(b) {
|
|
2315
|
+
if (!(b instanceof Uint8Array) || b.byteLength !== 32)
|
|
2316
|
+
return true;
|
|
2317
|
+
for (let i = 0; i < 32; i++) {
|
|
2318
|
+
if (b[i] !== 0)
|
|
2319
|
+
return false;
|
|
2320
|
+
}
|
|
2321
|
+
return true;
|
|
2322
|
+
}
|
|
2323
|
+
function verifyRootSnapshotIntegrity(superRoot, laneRoots) {
|
|
2324
|
+
if (!(superRoot instanceof Uint8Array) || superRoot.byteLength !== 32 || isAllZero32(superRoot)) {
|
|
2325
|
+
throw new Error('GlobalRootHistory superRoot must not be all-zero');
|
|
2326
|
+
}
|
|
2327
|
+
if (!Array.isArray(laneRoots) || laneRoots.length !== NUM_LANES) {
|
|
2328
|
+
throw new RangeError(`Root snapshot must have ${NUM_LANES} laneRoots`);
|
|
2329
|
+
}
|
|
2330
|
+
const superRootFr = frFromBeBytesStrict(superRoot);
|
|
2331
|
+
const laneRootsFr = laneRoots.map((b, l) => {
|
|
2332
|
+
if (!(b instanceof Uint8Array) || b.byteLength !== 32) {
|
|
2333
|
+
throw new RangeError(`Root snapshot laneRoots[${l}] must be 32 bytes`);
|
|
2334
|
+
}
|
|
2335
|
+
return frFromBeBytesStrict(b);
|
|
2336
|
+
});
|
|
2337
|
+
if (computeSuperRoot4Ary(laneRootsFr) !== superRootFr) {
|
|
2338
|
+
throw new Error('Reconstructed Merkle root mismatch');
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
/**
|
|
2342
|
+
* Strictly validate a decoded `GlobalRootHistory` before trusting any root or lane count from an
|
|
2343
|
+
* untrusted RPC: enforces u32 `poolId`, ring cursor/count and ring-array bounds, `epochInterval`,
|
|
2344
|
+
* `stableSlot <= latestSlot`, `stableEpochId === stableSlot / epochInterval`, `NUM_LANES` arrays,
|
|
2345
|
+
* `0..=MAX_LEAVES_PER_LANE` counts, `stableLaneCounts[l] <= latestLaneCounts[l]`, non-zero
|
|
2346
|
+
* `latest`/`stable` super-roots, ring cursor `superRoot` & `slot` equality, full canonical BN254
|
|
2347
|
+
* `Fr` + 4-ary super-root integrity for BOTH `latest` and `stable` snapshots, zero-count
|
|
2348
|
+
* `ZERO_HASHES_4ARY[18]` lane roots, and equal-count lane-root equality.
|
|
2349
|
+
*/
|
|
2350
|
+
export function validateGlobalRootHistory(history, poolId) {
|
|
2351
|
+
if (!Number.isInteger(poolId) || poolId < 0 || poolId > U32_MAX) {
|
|
2352
|
+
throw new RangeError(`Invalid poolId ${String(poolId)}`);
|
|
2353
|
+
}
|
|
2354
|
+
if (!history || typeof history !== 'object') {
|
|
2355
|
+
throw new RangeError('GlobalRootHistory must be an object');
|
|
2356
|
+
}
|
|
2357
|
+
if (!Number.isInteger(history.poolId) ||
|
|
2358
|
+
history.poolId < 0 ||
|
|
2359
|
+
history.poolId > U32_MAX ||
|
|
2360
|
+
history.poolId !== poolId) {
|
|
2361
|
+
throw new Error(`GlobalRootHistory header mismatch (expected pool=${poolId}, got pool=${String(history.poolId)})`);
|
|
2362
|
+
}
|
|
2363
|
+
if (!Number.isInteger(history.slotCount) ||
|
|
2364
|
+
history.slotCount < 1 ||
|
|
2365
|
+
history.slotCount > SLOT_RING_LEN ||
|
|
2366
|
+
!Number.isInteger(history.slotCursor) ||
|
|
2367
|
+
history.slotCursor < 0 ||
|
|
2368
|
+
history.slotCursor >= history.slotCount ||
|
|
2369
|
+
!Number.isInteger(history.epochCount) ||
|
|
2370
|
+
history.epochCount < 1 ||
|
|
2371
|
+
history.epochCount > EPOCH_RING_LEN ||
|
|
2372
|
+
!Number.isInteger(history.epochCursor) ||
|
|
2373
|
+
history.epochCursor < 0 ||
|
|
2374
|
+
history.epochCursor >= history.epochCount ||
|
|
2375
|
+
!Array.isArray(history.slotRing) ||
|
|
2376
|
+
history.slotRing.length < history.slotCount ||
|
|
2377
|
+
!Array.isArray(history.epochRing) ||
|
|
2378
|
+
history.epochRing.length < history.epochCount) {
|
|
2379
|
+
throw new Error('GlobalRootHistory ring cursor or count out of bounds');
|
|
2380
|
+
}
|
|
2381
|
+
if (typeof history.epochInterval !== 'bigint' ||
|
|
2382
|
+
history.epochInterval < 1n ||
|
|
2383
|
+
history.epochInterval > MAX_ROOT_EPOCH_INTERVAL) {
|
|
2384
|
+
throw new RangeError(`GlobalRootHistory epochInterval out of range: ${String(history.epochInterval)}`);
|
|
2385
|
+
}
|
|
2386
|
+
if (typeof history.latestSlot !== 'bigint' ||
|
|
2387
|
+
history.latestSlot < 0n ||
|
|
2388
|
+
history.latestSlot > U64_MAX ||
|
|
2389
|
+
typeof history.stableSlot !== 'bigint' ||
|
|
2390
|
+
history.stableSlot < 0n ||
|
|
2391
|
+
history.stableSlot > U64_MAX ||
|
|
2392
|
+
typeof history.stableEpochId !== 'bigint' ||
|
|
2393
|
+
history.stableEpochId < 0n ||
|
|
2394
|
+
history.stableEpochId > U64_MAX) {
|
|
2395
|
+
throw new RangeError('GlobalRootHistory slot/epoch header fields must be u64 bigints');
|
|
2396
|
+
}
|
|
2397
|
+
if (history.stableSlot > history.latestSlot) {
|
|
2398
|
+
throw new Error(`GlobalRootHistory stableSlot (${history.stableSlot}) exceeds latestSlot (${history.latestSlot})`);
|
|
2399
|
+
}
|
|
2400
|
+
if (history.stableEpochId !== history.stableSlot / history.epochInterval) {
|
|
2401
|
+
throw new Error(`GlobalRootHistory stableEpochId mismatch (expected ${history.stableSlot / history.epochInterval}, got ${history.stableEpochId})`);
|
|
2402
|
+
}
|
|
2403
|
+
if (!Array.isArray(history.latestLaneRoots) ||
|
|
2404
|
+
history.latestLaneRoots.length !== NUM_LANES ||
|
|
2405
|
+
!Array.isArray(history.stableLaneRoots) ||
|
|
2406
|
+
history.stableLaneRoots.length !== NUM_LANES ||
|
|
2407
|
+
!Array.isArray(history.latestLaneCounts) ||
|
|
2408
|
+
history.latestLaneCounts.length !== NUM_LANES ||
|
|
2409
|
+
!Array.isArray(history.stableLaneCounts) ||
|
|
2410
|
+
history.stableLaneCounts.length !== NUM_LANES) {
|
|
2411
|
+
throw new RangeError(`GlobalRootHistory must have ${NUM_LANES} lanes`);
|
|
2412
|
+
}
|
|
2413
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2414
|
+
const lr = history.latestLaneRoots[l];
|
|
2415
|
+
const sr = history.stableLaneRoots[l];
|
|
2416
|
+
if (!(lr instanceof Uint8Array) || lr.byteLength !== 32) {
|
|
2417
|
+
throw new RangeError(`GlobalRootHistory latestLaneRoots[${l}] must be 32 bytes`);
|
|
2418
|
+
}
|
|
2419
|
+
if (!(sr instanceof Uint8Array) || sr.byteLength !== 32) {
|
|
2420
|
+
throw new RangeError(`GlobalRootHistory stableLaneRoots[${l}] must be 32 bytes`);
|
|
2421
|
+
}
|
|
2422
|
+
const lc = history.latestLaneCounts[l];
|
|
2423
|
+
if (typeof lc !== 'bigint' || lc < 0n || lc > MAX_LEAVES_PER_LANE) {
|
|
2424
|
+
throw new RangeError(`GlobalRootHistory latestLaneCounts[${l}] out of range: ${String(lc)}`);
|
|
2425
|
+
}
|
|
2426
|
+
const sc = history.stableLaneCounts[l];
|
|
2427
|
+
if (typeof sc !== 'bigint' || sc < 0n || sc > MAX_LEAVES_PER_LANE) {
|
|
2428
|
+
throw new RangeError(`GlobalRootHistory stableLaneCounts[${l}] out of range: ${String(sc)}`);
|
|
2429
|
+
}
|
|
2430
|
+
if (sc > lc) {
|
|
2431
|
+
throw new Error(`GlobalRootHistory stableLaneCounts[${l}] (${sc}) exceeds latestLaneCounts[${l}] (${lc})`);
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
if (!(history.latestSuperRoot instanceof Uint8Array) ||
|
|
2435
|
+
history.latestSuperRoot.byteLength !== 32 ||
|
|
2436
|
+
isAllZero32(history.latestSuperRoot)) {
|
|
2437
|
+
throw new Error('GlobalRootHistory latestSuperRoot must be a non-zero 32-byte root');
|
|
2438
|
+
}
|
|
2439
|
+
if (!(history.stableSuperRoot instanceof Uint8Array) ||
|
|
2440
|
+
history.stableSuperRoot.byteLength !== 32 ||
|
|
2441
|
+
isAllZero32(history.stableSuperRoot)) {
|
|
2442
|
+
throw new Error('GlobalRootHistory stableSuperRoot must be a non-zero 32-byte root');
|
|
2443
|
+
}
|
|
2444
|
+
const latestEntry = history.slotRing[history.slotCursor];
|
|
2445
|
+
if (!latestEntry ||
|
|
2446
|
+
typeof latestEntry !== 'object' ||
|
|
2447
|
+
!(latestEntry.superRoot instanceof Uint8Array) ||
|
|
2448
|
+
latestEntry.superRoot.byteLength !== 32 ||
|
|
2449
|
+
compareBytes32(latestEntry.superRoot, history.latestSuperRoot) !== 0) {
|
|
2450
|
+
throw new Error('GlobalRootHistory slotRing[slotCursor] superRoot mismatch');
|
|
2451
|
+
}
|
|
2452
|
+
if (typeof latestEntry.slot !== 'bigint' || latestEntry.slot !== history.latestSlot) {
|
|
2453
|
+
throw new Error('GlobalRootHistory slotRing[slotCursor] slot mismatch');
|
|
2454
|
+
}
|
|
2455
|
+
const stableEntry = history.epochRing[history.epochCursor];
|
|
2456
|
+
if (!stableEntry ||
|
|
2457
|
+
typeof stableEntry !== 'object' ||
|
|
2458
|
+
!(stableEntry.superRoot instanceof Uint8Array) ||
|
|
2459
|
+
stableEntry.superRoot.byteLength !== 32 ||
|
|
2460
|
+
compareBytes32(stableEntry.superRoot, history.stableSuperRoot) !== 0) {
|
|
2461
|
+
throw new Error('GlobalRootHistory epochRing[epochCursor] superRoot mismatch');
|
|
2462
|
+
}
|
|
2463
|
+
if (typeof stableEntry.slot !== 'bigint' || stableEntry.slot !== history.stableSlot) {
|
|
2464
|
+
throw new Error('GlobalRootHistory epochRing[epochCursor] slot mismatch');
|
|
2465
|
+
}
|
|
2466
|
+
verifyRootSnapshotIntegrity(history.latestSuperRoot, history.latestLaneRoots);
|
|
2467
|
+
verifyRootSnapshotIntegrity(history.stableSuperRoot, history.stableLaneRoots);
|
|
2468
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2469
|
+
const lc = history.latestLaneCounts[l];
|
|
2470
|
+
const sc = history.stableLaneCounts[l];
|
|
2471
|
+
const lr = history.latestLaneRoots[l];
|
|
2472
|
+
const sr = history.stableLaneRoots[l];
|
|
2473
|
+
if ((lc === 0n) !== (compareBytes32(lr, ZERO_LANE_ROOT_BE) === 0)) {
|
|
2474
|
+
throw new Error(`GlobalRootHistory latestLaneRoots[${l}] must equal ZERO_HASHES_4ARY[18] iff count is 0`);
|
|
2475
|
+
}
|
|
2476
|
+
if ((sc === 0n) !== (compareBytes32(sr, ZERO_LANE_ROOT_BE) === 0)) {
|
|
2477
|
+
throw new Error(`GlobalRootHistory stableLaneRoots[${l}] must equal ZERO_HASHES_4ARY[18] iff count is 0`);
|
|
2478
|
+
}
|
|
2479
|
+
if ((sc === lc) !== (compareBytes32(sr, lr) === 0)) {
|
|
2480
|
+
throw new Error(`GlobalRootHistory stableLaneRoots[${l}] must equal latestLaneRoots[${l}] iff counts match`);
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
/**
|
|
2485
|
+
* Strictly validate a `RootSnapshotChoice`: runtime shape, ring kind/index bounds, u64 `slot`,
|
|
2486
|
+
* non-zero canonical BN254 `Fr` `superRoot` & `laneRoots`, `computeSuperRoot4Ary(laneRoots) === superRoot`,
|
|
2487
|
+
* `laneCounts[l]` in `0n..=MAX_LEAVES_PER_LANE`, and `laneCounts[l] === 0n <=> laneRoots[l] === ZERO_HASHES_4ARY[18]`.
|
|
2488
|
+
*/
|
|
2489
|
+
export function validateRootSnapshotChoice(snapshot) {
|
|
2490
|
+
if (!snapshot || typeof snapshot !== 'object') {
|
|
2491
|
+
throw new RangeError('RootSnapshotChoice must be an object');
|
|
2492
|
+
}
|
|
2493
|
+
if (snapshot.ringKind === ROOT_RING_SLOT) {
|
|
2494
|
+
if (!Number.isInteger(snapshot.ringIdx) || snapshot.ringIdx < 0 || snapshot.ringIdx >= SLOT_RING_LEN) {
|
|
2495
|
+
throw new RangeError(`Invalid RootSnapshotChoice ringIdx=${String(snapshot.ringIdx)} for ROOT_RING_SLOT`);
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
else if (snapshot.ringKind === ROOT_RING_EPOCH) {
|
|
2499
|
+
if (!Number.isInteger(snapshot.ringIdx) || snapshot.ringIdx < 0 || snapshot.ringIdx >= EPOCH_RING_LEN) {
|
|
2500
|
+
throw new RangeError(`Invalid RootSnapshotChoice ringIdx=${String(snapshot.ringIdx)} for ROOT_RING_EPOCH`);
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
else {
|
|
2504
|
+
throw new RangeError(`Invalid RootSnapshotChoice ringKind=${String(snapshot.ringKind)}`);
|
|
2505
|
+
}
|
|
2506
|
+
if (typeof snapshot.slot !== 'bigint' || snapshot.slot < 0n || snapshot.slot > U64_MAX) {
|
|
2507
|
+
throw new RangeError(`Invalid RootSnapshotChoice slot=${String(snapshot.slot)}`);
|
|
2508
|
+
}
|
|
2509
|
+
if (!(snapshot.superRoot instanceof Uint8Array) ||
|
|
2510
|
+
snapshot.superRoot.byteLength !== 32 ||
|
|
2511
|
+
isAllZero32(snapshot.superRoot)) {
|
|
2512
|
+
throw new RangeError('RootSnapshotChoice superRoot must be a non-zero 32-byte root');
|
|
2513
|
+
}
|
|
2514
|
+
if (!Array.isArray(snapshot.laneRoots) ||
|
|
2515
|
+
snapshot.laneRoots.length !== NUM_LANES ||
|
|
2516
|
+
!Array.isArray(snapshot.laneCounts) ||
|
|
2517
|
+
snapshot.laneCounts.length !== NUM_LANES) {
|
|
2518
|
+
throw new RangeError(`RootSnapshotChoice must have ${NUM_LANES} lanes`);
|
|
2519
|
+
}
|
|
2520
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2521
|
+
const lr = snapshot.laneRoots[l];
|
|
2522
|
+
if (!(lr instanceof Uint8Array) || lr.byteLength !== 32) {
|
|
2523
|
+
throw new RangeError(`RootSnapshotChoice laneRoots[${l}] must be 32 bytes`);
|
|
2524
|
+
}
|
|
2525
|
+
const c = snapshot.laneCounts[l];
|
|
2526
|
+
if (typeof c !== 'bigint' || c < 0n || c > MAX_LEAVES_PER_LANE) {
|
|
2527
|
+
throw new RangeError(`RootSnapshotChoice laneCounts[${l}] out of range: ${String(c)}`);
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
verifyRootSnapshotIntegrity(snapshot.superRoot, snapshot.laneRoots);
|
|
2531
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2532
|
+
if ((snapshot.laneCounts[l] === 0n) !== (compareBytes32(snapshot.laneRoots[l], ZERO_LANE_ROOT_BE) === 0)) {
|
|
2533
|
+
throw new Error(`RootSnapshotChoice laneRoots[${l}] must equal ZERO_HASHES_4ARY[18] iff count is 0`);
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
/**
|
|
2538
|
+
* Fetch and strictly validate `GlobalRootHistory` using a `finalized`-first + `confirmed`-fallback
|
|
2539
|
+
* strategy:
|
|
2540
|
+
* - Reads `finalized` first for maximum reorg-proof proving stability (`ROOT_RING_EPOCH` when
|
|
2541
|
+
* covered, else `ROOT_RING_SLOT`).
|
|
2542
|
+
* - Seamlessly falls back to `confirmed` when a freshly deposited note in `requiredNotes` is not
|
|
2543
|
+
* yet included in the `finalized` root history (enabling instant 0-slot spendability).
|
|
2544
|
+
*/
|
|
2545
|
+
export async function fetchGlobalRootHistory(params) {
|
|
2546
|
+
const poolId = params.poolId ?? 0;
|
|
2547
|
+
if (!Number.isInteger(poolId) || poolId < 0 || poolId > U32_MAX) {
|
|
2548
|
+
throw new RangeError(`Invalid poolId ${poolId}`);
|
|
2549
|
+
}
|
|
2550
|
+
const programId = params.programId ?? AUDREN_PROGRAM_ID;
|
|
2551
|
+
const requiredNotes = params.requiredNotes ?? [];
|
|
2552
|
+
for (const n of requiredNotes) {
|
|
2553
|
+
if (!Number.isInteger(n.laneId) || n.laneId < 0 || n.laneId >= NUM_LANES) {
|
|
2554
|
+
throw new RangeError(`Invalid requiredNotes laneId ${n.laneId}`);
|
|
2555
|
+
}
|
|
2556
|
+
if (typeof n.leafIndex !== 'bigint' || n.leafIndex < 0n) {
|
|
2557
|
+
throw new RangeError(`Invalid requiredNotes leafIndex ${String(n.leafIndex)}`);
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
const fetchFinalized = params.fetchFinalized ??
|
|
2561
|
+
(params.rpcUrl ? createSolanaRpcBatchFetcher(params.rpcUrl, 'finalized') : undefined);
|
|
2562
|
+
const fetchConfirmed = params.fetchConfirmed ??
|
|
2563
|
+
(params.rpcUrl ? createSolanaRpcBatchFetcher(params.rpcUrl, 'confirmed') : undefined);
|
|
2564
|
+
if (!fetchFinalized && !fetchConfirmed) {
|
|
2565
|
+
throw new Error('fetchGlobalRootHistory requires rpcUrl or fetchFinalized/fetchConfirmed');
|
|
2566
|
+
}
|
|
2567
|
+
const rootsAddr = deriveRootsPdaSync(poolId, programId).address;
|
|
2568
|
+
const decodeAndSelect = (raw) => {
|
|
2569
|
+
const history = decodeGlobalRootHistory(raw);
|
|
2570
|
+
validateGlobalRootHistory(history, poolId);
|
|
2571
|
+
const snapshot = selectRootSnapshotForNotes(history, requiredNotes);
|
|
2572
|
+
return { history, snapshot };
|
|
2573
|
+
};
|
|
2574
|
+
let finalizedHistory = null;
|
|
2575
|
+
let finalizedSlotFallback = null;
|
|
2576
|
+
if (fetchFinalized) {
|
|
2577
|
+
const [raw] = await fetchFinalized([rootsAddr]);
|
|
2578
|
+
if (raw) {
|
|
2579
|
+
const { history, snapshot } = decodeAndSelect(raw);
|
|
2580
|
+
finalizedHistory = history;
|
|
2581
|
+
if (snapshot) {
|
|
2582
|
+
if (snapshot.ringKind === ROOT_RING_EPOCH) {
|
|
2583
|
+
return { history, snapshot, commitment: 'finalized' };
|
|
2584
|
+
}
|
|
2585
|
+
finalizedSlotFallback = { history, snapshot };
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
if (fetchConfirmed) {
|
|
2590
|
+
const [raw] = await fetchConfirmed([rootsAddr]);
|
|
2591
|
+
if (!raw) {
|
|
2592
|
+
if (finalizedSlotFallback) {
|
|
2593
|
+
return { ...finalizedSlotFallback, commitment: 'finalized' };
|
|
2594
|
+
}
|
|
2595
|
+
throw new Error(`GlobalRootHistory missing at ${rootsAddr}`);
|
|
2596
|
+
}
|
|
2597
|
+
const { history: confirmedHistory, snapshot: confirmedSnapshot } = decodeAndSelect(raw);
|
|
2598
|
+
if (!confirmedSnapshot) {
|
|
2599
|
+
if (finalizedSlotFallback) {
|
|
2600
|
+
return { ...finalizedSlotFallback, commitment: 'finalized' };
|
|
2601
|
+
}
|
|
2602
|
+
throw new Error('Required notes not yet included in GlobalRootHistory');
|
|
2603
|
+
}
|
|
2604
|
+
if (finalizedHistory) {
|
|
2605
|
+
let confirmedNotBehind = confirmedHistory.epochInterval === finalizedHistory.epochInterval &&
|
|
2606
|
+
confirmedHistory.latestSlot >= finalizedHistory.latestSlot &&
|
|
2607
|
+
confirmedHistory.stableSlot >= finalizedHistory.stableSlot;
|
|
2608
|
+
let confirmedStrictlyAhead = confirmedHistory.latestSlot > finalizedHistory.latestSlot;
|
|
2609
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2610
|
+
const confLatest = confirmedHistory.latestLaneCounts[l];
|
|
2611
|
+
const finLatest = finalizedHistory.latestLaneCounts[l];
|
|
2612
|
+
const confStable = confirmedHistory.stableLaneCounts[l];
|
|
2613
|
+
const finStable = finalizedHistory.stableLaneCounts[l];
|
|
2614
|
+
const confLatestRoot = confirmedHistory.latestLaneRoots[l];
|
|
2615
|
+
const finLatestRoot = finalizedHistory.latestLaneRoots[l];
|
|
2616
|
+
const confStableRoot = confirmedHistory.stableLaneRoots[l];
|
|
2617
|
+
const finStableRoot = finalizedHistory.stableLaneRoots[l];
|
|
2618
|
+
if (confLatest < finLatest ||
|
|
2619
|
+
confStable < finStable ||
|
|
2620
|
+
(confLatest === finLatest && compareBytes32(confLatestRoot, finLatestRoot) !== 0) ||
|
|
2621
|
+
(confStable === finStable && compareBytes32(confStableRoot, finStableRoot) !== 0) ||
|
|
2622
|
+
(confStable === finLatest && compareBytes32(confStableRoot, finLatestRoot) !== 0) ||
|
|
2623
|
+
(confLatest === finStable && compareBytes32(confLatestRoot, finStableRoot) !== 0)) {
|
|
2624
|
+
confirmedNotBehind = false;
|
|
2625
|
+
}
|
|
2626
|
+
if (confLatest > finLatest) {
|
|
2627
|
+
confirmedStrictlyAhead = true;
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
if (finalizedSlotFallback) {
|
|
2631
|
+
const finChoice = finalizedSlotFallback.snapshot;
|
|
2632
|
+
const confirmedSlotEntry = confirmedHistory.slotRing[finChoice.ringIdx];
|
|
2633
|
+
const slotEntryEvicted = !confirmedSlotEntry ||
|
|
2634
|
+
compareBytes32(confirmedSlotEntry.superRoot, finChoice.superRoot) !== 0;
|
|
2635
|
+
const upgradeToConfirmed = confirmedNotBehind &&
|
|
2636
|
+
confirmedStrictlyAhead &&
|
|
2637
|
+
(confirmedSnapshot.ringKind === ROOT_RING_EPOCH ||
|
|
2638
|
+
(confirmedSnapshot.ringKind === ROOT_RING_SLOT &&
|
|
2639
|
+
(confirmedSnapshot.slot > finChoice.slot ||
|
|
2640
|
+
confirmedSnapshot.ringIdx !== finChoice.ringIdx ||
|
|
2641
|
+
slotEntryEvicted)));
|
|
2642
|
+
if (upgradeToConfirmed) {
|
|
2643
|
+
return {
|
|
2644
|
+
history: confirmedHistory,
|
|
2645
|
+
snapshot: confirmedSnapshot,
|
|
2646
|
+
commitment: 'confirmed',
|
|
2647
|
+
};
|
|
2648
|
+
}
|
|
2649
|
+
return { ...finalizedSlotFallback, commitment: 'finalized' };
|
|
2650
|
+
}
|
|
2651
|
+
if (!confirmedNotBehind) {
|
|
2652
|
+
throw new Error('Confirmed GlobalRootHistory lags behind finalized snapshot');
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
return {
|
|
2656
|
+
history: confirmedHistory,
|
|
2657
|
+
snapshot: confirmedSnapshot,
|
|
2658
|
+
commitment: 'confirmed',
|
|
2659
|
+
};
|
|
2660
|
+
}
|
|
2661
|
+
if (finalizedSlotFallback) {
|
|
2662
|
+
return { ...finalizedSlotFallback, commitment: 'finalized' };
|
|
2663
|
+
}
|
|
2664
|
+
throw new Error(finalizedHistory
|
|
2665
|
+
? 'Required notes not yet included in finalized GlobalRootHistory'
|
|
2666
|
+
: `GlobalRootHistory missing at ${rootsAddr}`);
|
|
2667
|
+
}
|
|
2668
|
+
/**
|
|
2669
|
+
* Reconstruct 4-ary Depth-20 Merkle witnesses for one or more notes in a SINGLE uniform,
|
|
2670
|
+
* decoy-padded `getMultipleAccounts` batch matching Rust
|
|
2671
|
+
* `crates/client/src/scanner.rs::reconstruct_witness_for_notes_with_batch` bit-for-bit.
|
|
2672
|
+
*
|
|
2673
|
+
* Eliminates multi-note input-count leakage (`1` vs `2` vs `2k`) on RPC fallback by combining
|
|
2674
|
+
* all notes into one canonical byte-sorted batch with order-independent HRW decoy scope.
|
|
2675
|
+
*/
|
|
2676
|
+
export async function reconstructWitnessesForNotes(params) {
|
|
2677
|
+
if (!params || typeof params !== 'object') {
|
|
2678
|
+
throw new RangeError('reconstructWitnessesForNotes params must be an object');
|
|
2679
|
+
}
|
|
2680
|
+
if (!Array.isArray(params.notes) || params.notes.length === 0) {
|
|
2681
|
+
throw new RangeError('reconstructWitnessesForNotes requires a non-empty notes array');
|
|
2682
|
+
}
|
|
2683
|
+
const programId = params.programId ?? AUDREN_PROGRAM_ID;
|
|
2684
|
+
const privacyMode = params.privacyMode === undefined ? 'strict' : params.privacyMode;
|
|
2685
|
+
if (privacyMode !== 'strict' && privacyMode !== 'fast') {
|
|
2686
|
+
throw new RangeError(`Invalid privacyMode: ${String(privacyMode)}`);
|
|
2687
|
+
}
|
|
2688
|
+
if (!Number.isInteger(params.poolId) || params.poolId < 0 || params.poolId > U32_MAX) {
|
|
2689
|
+
throw new RangeError(`Invalid poolId ${params.poolId}`);
|
|
2690
|
+
}
|
|
2691
|
+
for (const n of params.notes) {
|
|
2692
|
+
if (!n || typeof n !== 'object') {
|
|
2693
|
+
throw new RangeError('Each note must be an object with laneId and leafIndex');
|
|
2694
|
+
}
|
|
2695
|
+
if (!Number.isInteger(n.laneId) || n.laneId < 0 || n.laneId >= NUM_LANES) {
|
|
2696
|
+
throw new RangeError(`Invalid laneId ${String(n.laneId)}`);
|
|
2697
|
+
}
|
|
2698
|
+
if (typeof n.leafIndex !== 'bigint' || n.leafIndex < 0n) {
|
|
2699
|
+
throw new RangeError(`Invalid leafIndex ${String(n.leafIndex)}`);
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
if (params.allInputNotes) {
|
|
2703
|
+
for (const n of params.allInputNotes) {
|
|
2704
|
+
if (!Number.isInteger(n.laneId) || n.laneId < 0 || n.laneId >= NUM_LANES) {
|
|
2705
|
+
throw new RangeError(`Invalid allInputNotes laneId ${n.laneId}`);
|
|
2706
|
+
}
|
|
2707
|
+
if (typeof n.leafIndex !== 'bigint' || n.leafIndex < 0n) {
|
|
2708
|
+
throw new RangeError(`Invalid allInputNotes leafIndex ${String(n.leafIndex)}`);
|
|
2709
|
+
}
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
if (params.rootSnapshot !== undefined) {
|
|
2713
|
+
validateRootSnapshotChoice(params.rootSnapshot);
|
|
2714
|
+
}
|
|
2715
|
+
if (privacyMode === 'strict') {
|
|
2716
|
+
if (!(params.viewSk instanceof Uint8Array) || params.viewSk.byteLength !== 32) {
|
|
2717
|
+
throw new RangeError("reconstructWitness requires a 32-byte Uint8Array viewSk in 'strict' mode (use privacyMode: 'fast' for trusted/local RPCs)");
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
if (params.decoyEpochBucket !== undefined &&
|
|
2721
|
+
(typeof params.decoyEpochBucket !== 'bigint' ||
|
|
2722
|
+
params.decoyEpochBucket < 0n ||
|
|
2723
|
+
params.decoyEpochBucket > U64_MAX)) {
|
|
2724
|
+
throw new RangeError(`Invalid decoyEpochBucket: ${String(params.decoyEpochBucket)}`);
|
|
2725
|
+
}
|
|
2726
|
+
const subSize = BigInt(SUBTREE_LEAVES);
|
|
2727
|
+
const srSize = BigInt(SUBROOTS_PER_PAGE);
|
|
2728
|
+
let roots = params.rootHistory ?? null;
|
|
2729
|
+
let chosen;
|
|
2730
|
+
const notesToCover = [
|
|
2731
|
+
...params.notes,
|
|
2732
|
+
...(params.allInputNotes ?? []),
|
|
2733
|
+
];
|
|
2734
|
+
if (params.rootSnapshot !== undefined) {
|
|
2735
|
+
if (params.rootHistory !== undefined) {
|
|
2736
|
+
validateGlobalRootHistory(params.rootHistory, params.poolId);
|
|
2737
|
+
const ringEntries = params.rootSnapshot.ringKind === ROOT_RING_SLOT
|
|
2738
|
+
? params.rootHistory.slotRing
|
|
2739
|
+
: params.rootHistory.epochRing;
|
|
2740
|
+
const ringEntry = ringEntries[params.rootSnapshot.ringIdx];
|
|
2741
|
+
let rootMatches = Boolean(ringEntry) &&
|
|
2742
|
+
ringEntry.slot === params.rootSnapshot.slot &&
|
|
2743
|
+
ringEntry.superRoot.byteLength === params.rootSnapshot.superRoot.byteLength;
|
|
2744
|
+
if (rootMatches) {
|
|
2745
|
+
for (let i = 0; i < ringEntry.superRoot.byteLength; i++) {
|
|
2746
|
+
if (ringEntry.superRoot[i] !== params.rootSnapshot.superRoot[i]) {
|
|
2747
|
+
rootMatches = false;
|
|
2748
|
+
break;
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
if (!rootMatches) {
|
|
2753
|
+
throw new Error('Supplied rootSnapshot is stale or mismatched against supplied rootHistory ring entry');
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
chosen = params.rootSnapshot;
|
|
2757
|
+
for (const n of notesToCover) {
|
|
2758
|
+
if (n.leafIndex >= chosen.laneCounts[n.laneId]) {
|
|
2759
|
+
throw new Error('leafIdx >= snapshot lane count');
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
else {
|
|
2764
|
+
if (params.rootHistory === undefined) {
|
|
2765
|
+
const rootsAddr = deriveRootsPdaSync(params.poolId, programId).address;
|
|
2766
|
+
const [rootsRaw] = await params.fetchBatch([rootsAddr]);
|
|
2767
|
+
if (!rootsRaw)
|
|
2768
|
+
throw new Error(`GlobalRootHistory missing at ${rootsAddr}`);
|
|
2769
|
+
roots = decodeGlobalRootHistory(rootsRaw);
|
|
2770
|
+
}
|
|
2771
|
+
validateGlobalRootHistory(roots, params.poolId);
|
|
2772
|
+
const selected = selectRootSnapshotForNotes(roots, notesToCover);
|
|
2773
|
+
if (!selected) {
|
|
2774
|
+
throw new Error('leafIdx >= GlobalRootHistory lane count');
|
|
2775
|
+
}
|
|
2776
|
+
chosen = selected;
|
|
2777
|
+
}
|
|
2778
|
+
for (const n of params.notes) {
|
|
2779
|
+
if (n.leafIndex >= chosen.laneCounts[n.laneId]) {
|
|
2780
|
+
throw new Error('leafIdx >= snapshot lane count');
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
const snapLaneRootsFr = chosen.laneRoots.map((b) => frFromBeBytesStrict(b));
|
|
2784
|
+
const superRoot = frFromBeBytesStrict(chosen.superRoot);
|
|
2785
|
+
if (computeSuperRoot4Ary(snapLaneRootsFr) !== superRoot) {
|
|
2786
|
+
throw new Error('Reconstructed Merkle root mismatch');
|
|
2787
|
+
}
|
|
2788
|
+
if (privacyMode === 'strict') {
|
|
2789
|
+
let totalSrPages = 0;
|
|
2790
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2791
|
+
const laneSealed = chosen.laneCounts[l] / subSize;
|
|
2792
|
+
if (laneSealed > 0n) {
|
|
2793
|
+
totalSrPages += Math.ceil(Number(laneSealed) / SUBROOTS_PER_PAGE);
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
if (totalSrPages > MAX_WITNESS_SR_PAGES) {
|
|
2797
|
+
throw new RangeError(`Root snapshot requires ${totalSrPages} SubtreeRootPages across active lanes (exceeds witness bound ${MAX_WITNESS_SR_PAGES})`);
|
|
2798
|
+
}
|
|
2799
|
+
}
|
|
2800
|
+
const srExpected = new Map();
|
|
2801
|
+
const subExpected = new Map();
|
|
2802
|
+
const seenTargetLanes = new Set();
|
|
2803
|
+
let targetSrPagesBound = 0;
|
|
2804
|
+
for (const n of params.notes) {
|
|
2805
|
+
const snapCount = chosen.laneCounts[n.laneId];
|
|
2806
|
+
const targetPageIdx = n.leafIndex / subSize;
|
|
2807
|
+
const frontierPageIdx = snapCount / subSize;
|
|
2808
|
+
const frontierRem = Number(snapCount % subSize);
|
|
2809
|
+
if (!seenTargetLanes.has(n.laneId)) {
|
|
2810
|
+
seenTargetLanes.add(n.laneId);
|
|
2811
|
+
const neededSrPages = Math.ceil(Number(frontierPageIdx) / SUBROOTS_PER_PAGE);
|
|
2812
|
+
targetSrPagesBound += neededSrPages;
|
|
2813
|
+
if (targetSrPagesBound > MAX_WITNESS_SR_PAGES) {
|
|
2814
|
+
throw new RangeError(`Root snapshot requires ${targetSrPagesBound} SubtreeRootPages (exceeds witness bound ${MAX_WITNESS_SR_PAGES})`);
|
|
2815
|
+
}
|
|
2816
|
+
for (let rp = 0; rp < neededSrPages; rp++) {
|
|
2817
|
+
const rpBig = BigInt(rp);
|
|
2818
|
+
const rem = frontierPageIdx - rpBig * srSize;
|
|
2819
|
+
const expectedMin = Number(rem < srSize ? rem : srSize);
|
|
2820
|
+
const addr = deriveSubrootPdaSync(params.poolId, n.laneId, rpBig, programId).address;
|
|
2821
|
+
if (!srExpected.has(addr)) {
|
|
2822
|
+
srExpected.set(addr, { laneId: n.laneId, rootPageSeq: rpBig, expectedMin });
|
|
2823
|
+
}
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
const targetSubAddr = deriveSubtreePdaSync(params.poolId, n.laneId, targetPageIdx, programId).address;
|
|
2827
|
+
const targetExpectedMin = targetPageIdx < frontierPageIdx ? SUBTREE_LEAVES : frontierRem;
|
|
2828
|
+
const prevTarget = subExpected.get(targetSubAddr);
|
|
2829
|
+
subExpected.set(targetSubAddr, {
|
|
2830
|
+
laneId: n.laneId,
|
|
2831
|
+
pageSeq: targetPageIdx,
|
|
2832
|
+
expectedMin: prevTarget ? Math.max(prevTarget.expectedMin, targetExpectedMin) : targetExpectedMin,
|
|
2833
|
+
});
|
|
2834
|
+
if (frontierRem > 0 && frontierPageIdx !== targetPageIdx) {
|
|
2835
|
+
const frontierSubAddr = deriveSubtreePdaSync(params.poolId, n.laneId, frontierPageIdx, programId).address;
|
|
2836
|
+
const prevF = subExpected.get(frontierSubAddr);
|
|
2837
|
+
subExpected.set(frontierSubAddr, {
|
|
2838
|
+
laneId: n.laneId,
|
|
2839
|
+
pageSeq: frontierPageIdx,
|
|
2840
|
+
expectedMin: prevF ? Math.max(prevF.expectedMin, frontierRem) : frontierRem,
|
|
2841
|
+
});
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
if (privacyMode === 'strict') {
|
|
2845
|
+
const sealedByLane = [];
|
|
2846
|
+
const alreadySealed = new Set();
|
|
2847
|
+
for (const n of params.notes) {
|
|
2848
|
+
const frontierPageIdx = chosen.laneCounts[n.laneId] / subSize;
|
|
2849
|
+
const targetPageIdx = n.leafIndex / subSize;
|
|
2850
|
+
if (targetPageIdx < frontierPageIdx) {
|
|
2851
|
+
alreadySealed.add(`${n.laneId}:${targetPageIdx.toString()}`);
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2854
|
+
let totalSealed = 0n;
|
|
2855
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2856
|
+
const cnt = chosen.laneCounts[l];
|
|
2857
|
+
const laneSealed = cnt / subSize;
|
|
2858
|
+
const laneFrontierRem = Number(cnt % subSize);
|
|
2859
|
+
sealedByLane.push({ laneId: l, sealedCount: laneSealed });
|
|
2860
|
+
totalSealed += laneSealed;
|
|
2861
|
+
if (laneSealed > 0n) {
|
|
2862
|
+
const laneSrPages = Math.ceil(Number(laneSealed) / SUBROOTS_PER_PAGE);
|
|
2863
|
+
for (let rp = 0; rp < laneSrPages; rp++) {
|
|
2864
|
+
const rpBig = BigInt(rp);
|
|
2865
|
+
const rem = laneSealed - rpBig * srSize;
|
|
2866
|
+
const expectedMin = Number(rem < srSize ? rem : srSize);
|
|
2867
|
+
const addr = deriveSubrootPdaSync(params.poolId, l, rpBig, programId).address;
|
|
2868
|
+
if (!srExpected.has(addr)) {
|
|
2869
|
+
srExpected.set(addr, { laneId: l, rootPageSeq: rpBig, expectedMin });
|
|
2870
|
+
}
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
if (laneFrontierRem > 0) {
|
|
2874
|
+
const addr = deriveSubtreePdaSync(params.poolId, l, laneSealed, programId).address;
|
|
2875
|
+
if (!subExpected.has(addr)) {
|
|
2876
|
+
subExpected.set(addr, {
|
|
2877
|
+
laneId: l,
|
|
2878
|
+
pageSeq: laneSealed,
|
|
2879
|
+
expectedMin: laneFrontierRem,
|
|
2880
|
+
});
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
if (totalSealed > 0n) {
|
|
2885
|
+
const buckets = Math.max(1, Math.ceil(alreadySealed.size / STRICT_DECOY_SEALED_SUBTREE_TARGET));
|
|
2886
|
+
const desiredBig = BigInt(buckets * STRICT_DECOY_SEALED_SUBTREE_TARGET);
|
|
2887
|
+
const targetSealed = Number(totalSealed < desiredBig ? totalSealed : desiredBig);
|
|
2888
|
+
const epochBucket = params.decoyEpochBucket ?? 0n;
|
|
2889
|
+
const witnessScope = makeWitnessDecoyScopeForNotes(params.notes, subSize);
|
|
2890
|
+
const decoys = totalSealed <= BigInt(MAX_HRW_SEALED_SUBTREES)
|
|
2891
|
+
? selectHrwSealedDecoys({
|
|
2892
|
+
viewSk: params.viewSk,
|
|
2893
|
+
scope: witnessScope,
|
|
2894
|
+
epochBucket,
|
|
2895
|
+
sealedByLane,
|
|
2896
|
+
alreadySelected: alreadySealed,
|
|
2897
|
+
targetSealed,
|
|
2898
|
+
})
|
|
2899
|
+
: selectLargePoolHrwSealedDecoys({
|
|
2900
|
+
viewSk: params.viewSk,
|
|
2901
|
+
scope: witnessScope,
|
|
2902
|
+
epochBucket,
|
|
2903
|
+
sealedByLane,
|
|
2904
|
+
alreadySelected: alreadySealed,
|
|
2905
|
+
targetSealed,
|
|
2906
|
+
});
|
|
2907
|
+
for (const d of decoys) {
|
|
2908
|
+
const addr = deriveSubtreePdaSync(params.poolId, d.laneId, d.pageSeq, programId).address;
|
|
2909
|
+
if (!subExpected.has(addr)) {
|
|
2910
|
+
subExpected.set(addr, {
|
|
2911
|
+
laneId: d.laneId,
|
|
2912
|
+
pageSeq: d.pageSeq,
|
|
2913
|
+
expectedMin: SUBTREE_LEAVES,
|
|
2914
|
+
});
|
|
2915
|
+
}
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
// Canonical public 32-byte PDA order: reveals 0 bits of target vs decoy vs frontier roles
|
|
2920
|
+
// and 0 bits of `viewSk`, while staying 100% deterministic across retries.
|
|
2921
|
+
const addrsWithBytes = [...srExpected.keys(), ...subExpected.keys()]
|
|
2922
|
+
.map((addr) => ({ addr, bytes: base58Decode(addr) }))
|
|
2923
|
+
.sort((a, b) => compareBytes32(a.bytes, b.bytes));
|
|
2924
|
+
const addrs = addrsWithBytes.map((x) => x.addr);
|
|
2925
|
+
const rawByAddr = new Map();
|
|
2926
|
+
for (let off = 0; off < addrs.length; off += RPC_BATCH_CHUNK) {
|
|
2927
|
+
const chunk = addrs.slice(off, off + RPC_BATCH_CHUNK);
|
|
2928
|
+
const raws = await params.fetchBatch(chunk);
|
|
2929
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
2930
|
+
rawByAddr.set(chunk[i], raws[i] ?? null);
|
|
2931
|
+
}
|
|
2932
|
+
}
|
|
2933
|
+
const decodedSrFrByKey = new Map();
|
|
2934
|
+
const decodedSubFrByKey = new Map();
|
|
2935
|
+
for (const addr of addrs) {
|
|
2936
|
+
const srExp = srExpected.get(addr);
|
|
2937
|
+
if (srExp) {
|
|
2938
|
+
const srRaw = rawByAddr.get(addr);
|
|
2939
|
+
if (!srRaw)
|
|
2940
|
+
throw new Error('SubtreeRootPage missing');
|
|
2941
|
+
const sr = decodeSubtreeRootPage(srRaw);
|
|
2942
|
+
if (sr.poolId !== params.poolId ||
|
|
2943
|
+
sr.laneId !== srExp.laneId ||
|
|
2944
|
+
sr.rootPageSeq !== srExp.rootPageSeq) {
|
|
2945
|
+
throw new Error('SubtreeRootPage header mismatch');
|
|
2946
|
+
}
|
|
2947
|
+
if (sr.count < srExp.expectedMin) {
|
|
2948
|
+
throw new Error('SubtreeRootPage truncated');
|
|
2949
|
+
}
|
|
2950
|
+
decodedSrFrByKey.set(`${srExp.laneId}:${srExp.rootPageSeq.toString()}`, sr.roots.map((b) => frFromBeBytesStrict(b)));
|
|
2951
|
+
continue;
|
|
2952
|
+
}
|
|
2953
|
+
const subExp = subExpected.get(addr);
|
|
2954
|
+
if (subExp) {
|
|
2955
|
+
const subRaw = rawByAddr.get(addr);
|
|
2956
|
+
if (!subRaw)
|
|
2957
|
+
throw new Error('SubtreePage missing');
|
|
2958
|
+
const sub = decodeSubtreePage(subRaw);
|
|
2959
|
+
if (sub.poolId !== params.poolId ||
|
|
2960
|
+
sub.laneId !== subExp.laneId ||
|
|
2961
|
+
sub.pageSeq !== subExp.pageSeq) {
|
|
2962
|
+
throw new Error('SubtreePage header mismatch');
|
|
2963
|
+
}
|
|
2964
|
+
if (sub.count < subExp.expectedMin) {
|
|
2965
|
+
throw new Error('SubtreePage truncated');
|
|
2966
|
+
}
|
|
2967
|
+
decodedSubFrByKey.set(`${subExp.laneId}:${subExp.pageSeq.toString()}`, sub.leaves.map((b) => frFromBeBytesStrict(b)));
|
|
2968
|
+
}
|
|
2969
|
+
}
|
|
2970
|
+
if (privacyMode === 'strict') {
|
|
2971
|
+
for (const subExp of subExpected.values()) {
|
|
2972
|
+
const laneSealed = chosen.laneCounts[subExp.laneId] / subSize;
|
|
2973
|
+
if (subExp.pageSeq < laneSealed) {
|
|
2974
|
+
const leavesFr = decodedSubFrByKey.get(`${subExp.laneId}:${subExp.pageSeq.toString()}`);
|
|
2975
|
+
const srSeq = subExp.pageSeq / srSize;
|
|
2976
|
+
const srSlot = Number(subExp.pageSeq % srSize);
|
|
2977
|
+
const srRootsFr = decodedSrFrByKey.get(`${subExp.laneId}:${srSeq.toString()}`);
|
|
2978
|
+
if (!leavesFr ||
|
|
2979
|
+
leavesFr.length < SUBTREE_LEAVES ||
|
|
2980
|
+
!srRootsFr ||
|
|
2981
|
+
srSlot >= srRootsFr.length) {
|
|
2982
|
+
throw new Error('Reconstructed Merkle root mismatch');
|
|
2983
|
+
}
|
|
2984
|
+
if (computeSubtree256Root(leavesFr, SUBTREE_LEAVES) !== srRootsFr[srSlot]) {
|
|
2985
|
+
throw new Error('Reconstructed Merkle root mismatch');
|
|
2986
|
+
}
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
2990
|
+
const cnt = chosen.laneCounts[l];
|
|
2991
|
+
if (cnt === 0n) {
|
|
2992
|
+
if (snapLaneRootsFr[l] !== ZERO_HASHES_4ARY[LANE_DEPTH_4ARY]) {
|
|
2993
|
+
throw new Error('Reconstructed Merkle root mismatch');
|
|
2994
|
+
}
|
|
2995
|
+
continue;
|
|
2996
|
+
}
|
|
2997
|
+
const laneSealed = cnt / subSize;
|
|
2998
|
+
const laneFrontierRem = Number(cnt % subSize);
|
|
2999
|
+
const laneSrPages = Math.ceil(Number(laneSealed) / SUBROOTS_PER_PAGE);
|
|
3000
|
+
const laneFinalizedRoots = [];
|
|
3001
|
+
for (let rp = 0; rp < laneSrPages; rp++) {
|
|
3002
|
+
const srRootsFr = decodedSrFrByKey.get(`${l}:${rp}`);
|
|
3003
|
+
if (!srRootsFr)
|
|
3004
|
+
throw new Error('SubtreeRootPage missing');
|
|
3005
|
+
for (const r of srRootsFr) {
|
|
3006
|
+
if (laneFinalizedRoots.length === Number(laneSealed))
|
|
3007
|
+
break;
|
|
3008
|
+
laneFinalizedRoots.push(r);
|
|
3009
|
+
}
|
|
3010
|
+
}
|
|
3011
|
+
if (laneFinalizedRoots.length !== Number(laneSealed)) {
|
|
3012
|
+
throw new Error('SubtreeRootPage missing finalized roots');
|
|
3013
|
+
}
|
|
3014
|
+
const laneFrontierLeaves = laneFrontierRem > 0
|
|
3015
|
+
? decodedSubFrByKey.get(`${l}:${laneSealed.toString()}`)
|
|
3016
|
+
: undefined;
|
|
3017
|
+
const computedLaneRoot = computeLaneRootFromSubrootsAndFrontier(laneFinalizedRoots, laneFrontierLeaves, laneFrontierRem);
|
|
3018
|
+
if (computedLaneRoot !== snapLaneRootsFr[l]) {
|
|
3019
|
+
throw new Error('Reconstructed Merkle root mismatch');
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
const paths = [];
|
|
3024
|
+
for (const n of params.notes) {
|
|
3025
|
+
const snapCount = chosen.laneCounts[n.laneId];
|
|
3026
|
+
const targetPageIdx = n.leafIndex / subSize;
|
|
3027
|
+
const targetOffset = Number(n.leafIndex % subSize);
|
|
3028
|
+
const frontierPageIdx = snapCount / subSize;
|
|
3029
|
+
const frontierRem = Number(snapCount % subSize);
|
|
3030
|
+
const neededSrPages = Math.ceil(Number(frontierPageIdx) / SUBROOTS_PER_PAGE);
|
|
3031
|
+
const finalizedRoots = [];
|
|
3032
|
+
for (let rp = 0; rp < neededSrPages; rp++) {
|
|
3033
|
+
const srRootsFr = decodedSrFrByKey.get(`${n.laneId}:${rp}`);
|
|
3034
|
+
if (!srRootsFr)
|
|
3035
|
+
throw new Error('SubtreeRootPage missing');
|
|
3036
|
+
for (const r of srRootsFr) {
|
|
3037
|
+
if (finalizedRoots.length === Number(frontierPageIdx))
|
|
3038
|
+
break;
|
|
3039
|
+
finalizedRoots.push(r);
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
if (finalizedRoots.length !== Number(frontierPageIdx)) {
|
|
3043
|
+
throw new Error('SubtreeRootPage missing finalized roots');
|
|
3044
|
+
}
|
|
3045
|
+
const targetLeaves = decodedSubFrByKey.get(`${n.laneId}:${targetPageIdx.toString()}`);
|
|
3046
|
+
const targetExpectedMin = targetPageIdx < frontierPageIdx ? SUBTREE_LEAVES : frontierRem;
|
|
3047
|
+
if (!targetLeaves)
|
|
3048
|
+
throw new Error('SubtreePage missing');
|
|
3049
|
+
if (targetLeaves.length < targetExpectedMin || targetOffset >= targetExpectedMin) {
|
|
3050
|
+
throw new Error('SubtreePage truncated');
|
|
3051
|
+
}
|
|
3052
|
+
let frontierLeaves;
|
|
3053
|
+
if (frontierRem > 0) {
|
|
3054
|
+
frontierLeaves = decodedSubFrByKey.get(`${n.laneId}:${frontierPageIdx.toString()}`);
|
|
3055
|
+
if (!frontierLeaves)
|
|
3056
|
+
throw new Error('SubtreePage missing');
|
|
3057
|
+
if (frontierLeaves.length < frontierRem) {
|
|
3058
|
+
throw new Error('SubtreePage truncated');
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
const path = buildHistoricalWitness4Ary({
|
|
3062
|
+
laneId: n.laneId,
|
|
3063
|
+
targetLeafIdx: n.leafIndex,
|
|
3064
|
+
laneRoots: snapLaneRootsFr,
|
|
3065
|
+
laneLeafCount: snapCount,
|
|
3066
|
+
finalizedSubtreeRoots: finalizedRoots,
|
|
3067
|
+
targetPageLeaves: targetLeaves,
|
|
3068
|
+
frontierPageLeaves: frontierLeaves,
|
|
3069
|
+
});
|
|
3070
|
+
if (computeMerkleRoot4Ary(path, targetLeaves[targetOffset]) !== superRoot) {
|
|
3071
|
+
throw new Error('Reconstructed Merkle root mismatch');
|
|
3072
|
+
}
|
|
3073
|
+
paths.push(path);
|
|
3074
|
+
}
|
|
3075
|
+
return {
|
|
3076
|
+
roots,
|
|
3077
|
+
snapshot: chosen,
|
|
3078
|
+
rootRingKind: chosen.ringKind,
|
|
3079
|
+
rootRingIdx: chosen.ringIdx,
|
|
3080
|
+
superRoot,
|
|
3081
|
+
snapshotSlot: chosen.slot,
|
|
3082
|
+
laneRoots: chosen.laneRoots,
|
|
3083
|
+
laneCounts: chosen.laneCounts,
|
|
3084
|
+
paths,
|
|
3085
|
+
};
|
|
3086
|
+
}
|
|
3087
|
+
/**
|
|
3088
|
+
* Reconstruct a 4-ary Depth-20 Merkle witness for a single note (thin wrapper around
|
|
3089
|
+
* `reconstructWitnessesForNotes`). For multi-note spends, prefer calling
|
|
3090
|
+
* `reconstructWitnessesForNotes` directly so all inputs share ONE decoy-padded RPC batch.
|
|
3091
|
+
*/
|
|
3092
|
+
export async function reconstructWitness(params) {
|
|
3093
|
+
if (!params || typeof params !== 'object') {
|
|
3094
|
+
throw new RangeError('reconstructWitness params must be an object');
|
|
3095
|
+
}
|
|
3096
|
+
const batch = await reconstructWitnessesForNotes({
|
|
3097
|
+
fetchBatch: params.fetchBatch,
|
|
3098
|
+
poolId: params.poolId,
|
|
3099
|
+
notes: [{ laneId: params.laneId, leafIndex: params.leafIdx }],
|
|
3100
|
+
allInputNotes: params.allInputNotes,
|
|
3101
|
+
rootSnapshot: params.rootSnapshot,
|
|
3102
|
+
rootHistory: params.rootHistory,
|
|
3103
|
+
programId: params.programId,
|
|
3104
|
+
privacyMode: params.privacyMode,
|
|
3105
|
+
viewSk: params.viewSk,
|
|
3106
|
+
decoyEpochBucket: params.decoyEpochBucket,
|
|
3107
|
+
});
|
|
3108
|
+
return {
|
|
3109
|
+
roots: batch.roots,
|
|
3110
|
+
snapshot: batch.snapshot,
|
|
3111
|
+
rootRingKind: batch.rootRingKind,
|
|
3112
|
+
rootRingIdx: batch.rootRingIdx,
|
|
3113
|
+
superRoot: batch.superRoot,
|
|
3114
|
+
snapshotSlot: batch.snapshotSlot,
|
|
3115
|
+
laneRoots: batch.laneRoots,
|
|
3116
|
+
laneCounts: batch.laneCounts,
|
|
3117
|
+
path: batch.paths[0],
|
|
3118
|
+
};
|
|
3119
|
+
}
|