@audren-xyz/sdk 0.0.0-stage → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +515 -0
- package/dist/relayer.d.ts +336 -0
- package/dist/relayer.js +258 -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/store.js
ADDED
|
@@ -0,0 +1,1403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-indexer `CompactWalletStore` & 4-ary Depth-20 Merkle witness builder matching
|
|
3
|
+
* `crates/audren-circuits/src/merkle.rs` and `crates/client/src/store.rs` bit-for-bit.
|
|
4
|
+
*
|
|
5
|
+
* Discards every sealed `SubtreePage` (`8,256 B`), `MemoPage` (`10,240 B`), and stranger
|
|
6
|
+
* `NullifierPage` prefix immediately after scanning, persisting only frozen 12-sibling
|
|
7
|
+
* intra-subtree paths (`384 B` per owned note), `32 B` finalized level-4 subroots (`1.28 MB`
|
|
8
|
+
* at 10M pool notes), unsealed frontier tail leaves, and at most one just-sealed page per lane
|
|
9
|
+
* until `GlobalRootHistory.stable` crosses it.
|
|
10
|
+
*/
|
|
11
|
+
import { LANE_DEPTH_4ARY, MEMO_NOTES_PER_PAGE, MEMO_PAYMENT_ID_LEN, NF_PER_PAGE, NF_PREFIX_LEN, NUM_LANES, ROOT_RING_EPOCH, ROOT_RING_SLOT, SUBROOTS_PER_PAGE, SUBTREE_LEAVES, SUBTREE_LEVELS_4ARY, TOTAL_DEPTH_4ARY, ZERO_HASHES_4ARY, } from './constants.js';
|
|
12
|
+
import { tryDecryptAndVerifyMemoEntry } from './crypto.js';
|
|
13
|
+
import { fvkRealNullifier, fvkStealthOwner } from './keys.js';
|
|
14
|
+
import { MAX_LEAVES_PER_LANE, decodeMemoPage, decodeNullifierPage, decodeSubtreePage, decodeSubtreeRootPage, selectRootSnapshotForNotes, } from './layout.js';
|
|
15
|
+
const MAX_SUBROOTS_PER_LANE = MAX_LEAVES_PER_LANE / BigInt(SUBTREE_LEAVES);
|
|
16
|
+
const U32_MAX = 0xffff_ffff;
|
|
17
|
+
const U64_MAX = 0xffffffffffffffffn;
|
|
18
|
+
class MissingFrontierLeavesError extends Error {
|
|
19
|
+
constructor() {
|
|
20
|
+
super('Missing frontier SubtreePage leaves');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function laneCountsEqual(a, b) {
|
|
24
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
25
|
+
if (a[l] !== b[l])
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
import { computeNoteCommitment, computeSubtree256Root, computeSuperRoot4Ary, deriveAssetId, frFromBeBytesStrict, frToBeBytes, poseidon4, } from './poseidon.js';
|
|
31
|
+
import { validateGlobalRootHistory, validateRootSnapshotChoice } from './scanner.js';
|
|
32
|
+
export function emptyMerklePath4Ary() {
|
|
33
|
+
return {
|
|
34
|
+
siblings: Array.from({ length: TOTAL_DEPTH_4ARY }, () => [0n, 0n, 0n]),
|
|
35
|
+
positions: new Array(TOTAL_DEPTH_4ARY).fill(0),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export function computeMerkleRoot4Ary(path, leaf) {
|
|
39
|
+
let cur = leaf;
|
|
40
|
+
for (let h = 0; h < TOTAL_DEPTH_4ARY; h++) {
|
|
41
|
+
const s = path.siblings[h];
|
|
42
|
+
const pos = path.positions[h];
|
|
43
|
+
let c0, c1, c2, c3;
|
|
44
|
+
if (pos === 0) {
|
|
45
|
+
[c0, c1, c2, c3] = [cur, s[0], s[1], s[2]];
|
|
46
|
+
}
|
|
47
|
+
else if (pos === 1) {
|
|
48
|
+
[c0, c1, c2, c3] = [s[0], cur, s[1], s[2]];
|
|
49
|
+
}
|
|
50
|
+
else if (pos === 2) {
|
|
51
|
+
[c0, c1, c2, c3] = [s[0], s[1], cur, s[2]];
|
|
52
|
+
}
|
|
53
|
+
else if (pos === 3) {
|
|
54
|
+
[c0, c1, c2, c3] = [s[0], s[1], s[2], cur];
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
throw new RangeError(`Invalid 4-ary Merkle position at depth ${h}: ${pos}`);
|
|
58
|
+
}
|
|
59
|
+
cur = poseidon4(c0, c1, c2, c3);
|
|
60
|
+
}
|
|
61
|
+
return cur;
|
|
62
|
+
}
|
|
63
|
+
export function extractIntraSubtreeSiblings(pageLeaves, validLen, targetOffset) {
|
|
64
|
+
if (!Number.isInteger(validLen) ||
|
|
65
|
+
!Number.isInteger(targetOffset) ||
|
|
66
|
+
targetOffset < 0 ||
|
|
67
|
+
targetOffset >= validLen ||
|
|
68
|
+
validLen > SUBTREE_LEAVES ||
|
|
69
|
+
pageLeaves.length < validLen) {
|
|
70
|
+
throw new RangeError(`Invalid targetOffset=${targetOffset}, validLen=${validLen}, leaves=${pageLeaves.length}`);
|
|
71
|
+
}
|
|
72
|
+
const pageNodes = new Array(SUBTREE_LEAVES).fill(0n);
|
|
73
|
+
for (let i = 0; i < validLen; i++)
|
|
74
|
+
pageNodes[i] = pageLeaves[i];
|
|
75
|
+
const siblings = [];
|
|
76
|
+
const positions = [];
|
|
77
|
+
let curIdx = targetOffset;
|
|
78
|
+
let curLen = SUBTREE_LEAVES;
|
|
79
|
+
for (let h = 0; h < SUBTREE_LEVELS_4ARY; h++) {
|
|
80
|
+
const groupStart = Math.floor(curIdx / 4) * 4;
|
|
81
|
+
const pos = curIdx % 4;
|
|
82
|
+
positions.push(pos);
|
|
83
|
+
const sib = [];
|
|
84
|
+
for (let k = 0; k < 4; k++) {
|
|
85
|
+
if (k !== pos)
|
|
86
|
+
sib.push(pageNodes[groupStart + k]);
|
|
87
|
+
}
|
|
88
|
+
siblings.push(sib);
|
|
89
|
+
const nextLen = curLen >>> 2;
|
|
90
|
+
for (let j = 0; j < nextLen; j++) {
|
|
91
|
+
pageNodes[j] = poseidon4(pageNodes[4 * j], pageNodes[4 * j + 1], pageNodes[4 * j + 2], pageNodes[4 * j + 3]);
|
|
92
|
+
}
|
|
93
|
+
curIdx = Math.floor(curIdx / 4);
|
|
94
|
+
curLen = nextLen;
|
|
95
|
+
}
|
|
96
|
+
return { siblings, positions };
|
|
97
|
+
}
|
|
98
|
+
export function buildWitnessFromFrozenSubsiblings(params) {
|
|
99
|
+
const { laneId, targetLeafIdx, intraSiblings, intraPositions, laneRoots: snapLaneRoots, laneLeafCount: snapLaneLeafCount, finalizedSubtreeRoots, frontierPageLeaves, } = params;
|
|
100
|
+
if (!Number.isInteger(laneId) || laneId < 0 || laneId >= NUM_LANES) {
|
|
101
|
+
throw new RangeError(`Invalid laneId ${laneId}`);
|
|
102
|
+
}
|
|
103
|
+
if (!snapLaneRoots || snapLaneRoots.length !== NUM_LANES) {
|
|
104
|
+
throw new RangeError(`laneRoots must have ${NUM_LANES} entries`);
|
|
105
|
+
}
|
|
106
|
+
if (typeof snapLaneLeafCount !== 'bigint' || snapLaneLeafCount < 0n || snapLaneLeafCount > MAX_LEAVES_PER_LANE) {
|
|
107
|
+
throw new RangeError(`laneLeafCount out of range: ${String(snapLaneLeafCount)}`);
|
|
108
|
+
}
|
|
109
|
+
if (typeof targetLeafIdx !== 'bigint' || targetLeafIdx < 0n || targetLeafIdx >= snapLaneLeafCount) {
|
|
110
|
+
throw new RangeError('targetLeafIdx >= laneLeafCount');
|
|
111
|
+
}
|
|
112
|
+
const path = emptyMerklePath4Ary();
|
|
113
|
+
for (let h = 0; h < SUBTREE_LEVELS_4ARY; h++) {
|
|
114
|
+
path.siblings[h] = [...intraSiblings[h]];
|
|
115
|
+
path.positions[h] = intraPositions[h];
|
|
116
|
+
}
|
|
117
|
+
const targetPageIdx = Number(targetLeafIdx / BigInt(SUBTREE_LEAVES));
|
|
118
|
+
const frontierPageIdx = Number(snapLaneLeafCount / BigInt(SUBTREE_LEAVES));
|
|
119
|
+
const frontierRem = Number(snapLaneLeafCount % BigInt(SUBTREE_LEAVES));
|
|
120
|
+
if (finalizedSubtreeRoots.length < frontierPageIdx) {
|
|
121
|
+
throw new Error(`Missing finalizedSubtreeRoots: have ${finalizedSubtreeRoots.length}, need ${frontierPageIdx}`);
|
|
122
|
+
}
|
|
123
|
+
let levelNodes = [];
|
|
124
|
+
for (let p = 0; p < frontierPageIdx; p++) {
|
|
125
|
+
levelNodes.push(finalizedSubtreeRoots[p]);
|
|
126
|
+
}
|
|
127
|
+
if (frontierRem > 0) {
|
|
128
|
+
if (!frontierPageLeaves || frontierPageLeaves.length < frontierRem) {
|
|
129
|
+
throw new Error('Missing frontierPageLeaves for unsealed snapshot tail');
|
|
130
|
+
}
|
|
131
|
+
levelNodes.push(computeSubtree256Root(frontierPageLeaves, frontierRem));
|
|
132
|
+
}
|
|
133
|
+
let nodeIdx = targetPageIdx;
|
|
134
|
+
for (let h = SUBTREE_LEVELS_4ARY; h < LANE_DEPTH_4ARY; h++) {
|
|
135
|
+
const zeroAtH = ZERO_HASHES_4ARY[h];
|
|
136
|
+
const groupStart = Math.floor(nodeIdx / 4) * 4;
|
|
137
|
+
const pos = nodeIdx % 4;
|
|
138
|
+
path.positions[h] = pos;
|
|
139
|
+
const sib = [];
|
|
140
|
+
for (let k = 0; k < 4; k++) {
|
|
141
|
+
if (k !== pos) {
|
|
142
|
+
const childI = groupStart + k;
|
|
143
|
+
sib.push(childI < levelNodes.length ? levelNodes[childI] : zeroAtH);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
path.siblings[h] = sib;
|
|
147
|
+
const nextLen = Math.ceil(levelNodes.length / 4);
|
|
148
|
+
const nextLevel = [];
|
|
149
|
+
for (let g = 0; g < nextLen; g++) {
|
|
150
|
+
const base = g * 4;
|
|
151
|
+
nextLevel.push(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));
|
|
152
|
+
}
|
|
153
|
+
levelNodes = nextLevel;
|
|
154
|
+
nodeIdx = Math.floor(nodeIdx / 4);
|
|
155
|
+
}
|
|
156
|
+
const group4 = Math.floor(laneId / 4);
|
|
157
|
+
const pos18 = laneId % 4;
|
|
158
|
+
path.positions[LANE_DEPTH_4ARY] = pos18;
|
|
159
|
+
const sib18 = [];
|
|
160
|
+
for (let k = 0; k < 4; k++) {
|
|
161
|
+
if (k !== pos18)
|
|
162
|
+
sib18.push(snapLaneRoots[group4 * 4 + k]);
|
|
163
|
+
}
|
|
164
|
+
path.siblings[LANE_DEPTH_4ARY] = sib18;
|
|
165
|
+
const groupHashes = [
|
|
166
|
+
poseidon4(snapLaneRoots[0], snapLaneRoots[1], snapLaneRoots[2], snapLaneRoots[3]),
|
|
167
|
+
poseidon4(snapLaneRoots[4], snapLaneRoots[5], snapLaneRoots[6], snapLaneRoots[7]),
|
|
168
|
+
poseidon4(snapLaneRoots[8], snapLaneRoots[9], snapLaneRoots[10], snapLaneRoots[11]),
|
|
169
|
+
poseidon4(snapLaneRoots[12], snapLaneRoots[13], snapLaneRoots[14], snapLaneRoots[15]),
|
|
170
|
+
];
|
|
171
|
+
path.positions[LANE_DEPTH_4ARY + 1] = group4;
|
|
172
|
+
const sib19 = [];
|
|
173
|
+
for (let k = 0; k < 4; k++) {
|
|
174
|
+
if (k !== group4)
|
|
175
|
+
sib19.push(groupHashes[k]);
|
|
176
|
+
}
|
|
177
|
+
path.siblings[LANE_DEPTH_4ARY + 1] = sib19;
|
|
178
|
+
return path;
|
|
179
|
+
}
|
|
180
|
+
export function buildHistoricalWitness4Ary(params) {
|
|
181
|
+
const snapLaneRoots = params.laneRoots;
|
|
182
|
+
const snapLaneLeafCount = params.laneLeafCount;
|
|
183
|
+
if (typeof snapLaneLeafCount !== 'bigint' || snapLaneLeafCount < 0n || snapLaneLeafCount > MAX_LEAVES_PER_LANE) {
|
|
184
|
+
throw new RangeError(`laneLeafCount out of range: ${String(snapLaneLeafCount)}`);
|
|
185
|
+
}
|
|
186
|
+
if (typeof params.targetLeafIdx !== 'bigint' || params.targetLeafIdx < 0n || params.targetLeafIdx >= snapLaneLeafCount) {
|
|
187
|
+
throw new RangeError(`targetLeafIdx out of range: ${String(params.targetLeafIdx)}`);
|
|
188
|
+
}
|
|
189
|
+
const targetPageIdx = Number(params.targetLeafIdx / BigInt(SUBTREE_LEAVES));
|
|
190
|
+
const targetOffset = Number(params.targetLeafIdx % BigInt(SUBTREE_LEAVES));
|
|
191
|
+
const frontierPageIdx = Number(snapLaneLeafCount / BigInt(SUBTREE_LEAVES));
|
|
192
|
+
const frontierRem = Number(snapLaneLeafCount % BigInt(SUBTREE_LEAVES));
|
|
193
|
+
const validLen = targetPageIdx === frontierPageIdx ? frontierRem : SUBTREE_LEAVES;
|
|
194
|
+
const { siblings, positions } = extractIntraSubtreeSiblings(params.targetPageLeaves, validLen, targetOffset);
|
|
195
|
+
return buildWitnessFromFrozenSubsiblings({
|
|
196
|
+
laneId: params.laneId,
|
|
197
|
+
targetLeafIdx: params.targetLeafIdx,
|
|
198
|
+
intraSiblings: siblings,
|
|
199
|
+
intraPositions: positions,
|
|
200
|
+
laneRoots: snapLaneRoots,
|
|
201
|
+
laneLeafCount: snapLaneLeafCount,
|
|
202
|
+
finalizedSubtreeRoots: params.finalizedSubtreeRoots,
|
|
203
|
+
frontierPageLeaves: params.frontierPageLeaves,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const HEX_RE = /^[0-9a-fA-F]*$/;
|
|
207
|
+
const DEC_UINT_RE = /^\d+$/;
|
|
208
|
+
function bytesToHex(b) {
|
|
209
|
+
if (!(b instanceof Uint8Array)) {
|
|
210
|
+
throw new RangeError(`Expected Uint8Array, got ${String(b)}`);
|
|
211
|
+
}
|
|
212
|
+
let s = '';
|
|
213
|
+
for (let i = 0; i < b.byteLength; i++)
|
|
214
|
+
s += b[i].toString(16).padStart(2, '0');
|
|
215
|
+
return s;
|
|
216
|
+
}
|
|
217
|
+
function bytesEqual(a, b) {
|
|
218
|
+
if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array) || a.byteLength !== b.byteLength) {
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
for (let i = 0; i < a.byteLength; i++) {
|
|
222
|
+
if (a[i] !== b[i])
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
return true;
|
|
226
|
+
}
|
|
227
|
+
function hexOrBytesExact(h, expectedLen, label) {
|
|
228
|
+
if (Array.isArray(h)) {
|
|
229
|
+
if (h.length !== expectedLen) {
|
|
230
|
+
throw new Error(`Invalid CompactWalletStore JSON ${label}: expected ${expectedLen} bytes (or ${expectedLen * 2} hex characters)`);
|
|
231
|
+
}
|
|
232
|
+
const out = new Uint8Array(expectedLen);
|
|
233
|
+
for (let i = 0; i < expectedLen; i++) {
|
|
234
|
+
const v = h[i];
|
|
235
|
+
if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > 255) {
|
|
236
|
+
throw new Error(`Invalid CompactWalletStore JSON ${label}: invalid byte value at index ${i}`);
|
|
237
|
+
}
|
|
238
|
+
out[i] = v;
|
|
239
|
+
}
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
242
|
+
if (typeof h !== 'string' || h.length !== expectedLen * 2 || !HEX_RE.test(h)) {
|
|
243
|
+
throw new Error(`Invalid CompactWalletStore JSON ${label}: expected ${expectedLen * 2} hex characters`);
|
|
244
|
+
}
|
|
245
|
+
const out = new Uint8Array(expectedLen);
|
|
246
|
+
for (let i = 0; i < expectedLen; i++) {
|
|
247
|
+
out[i] = Number.parseInt(h.slice(i * 2, i * 2 + 2), 16);
|
|
248
|
+
}
|
|
249
|
+
return out;
|
|
250
|
+
}
|
|
251
|
+
function parseU64Decimal(v, label) {
|
|
252
|
+
if (typeof v === 'number') {
|
|
253
|
+
if (!Number.isSafeInteger(v) || v < 0) {
|
|
254
|
+
throw new Error(`Invalid CompactWalletStore JSON ${label}: expected unsigned decimal string or safe u64 integer`);
|
|
255
|
+
}
|
|
256
|
+
return BigInt(v);
|
|
257
|
+
}
|
|
258
|
+
if (typeof v !== 'string' || !DEC_UINT_RE.test(v)) {
|
|
259
|
+
throw new Error(`Invalid CompactWalletStore JSON ${label}: expected unsigned decimal string`);
|
|
260
|
+
}
|
|
261
|
+
const n = BigInt(v);
|
|
262
|
+
if (n < 0n || n > U64_MAX) {
|
|
263
|
+
throw new Error(`Invalid CompactWalletStore JSON ${label}: out of u64 range`);
|
|
264
|
+
}
|
|
265
|
+
return n;
|
|
266
|
+
}
|
|
267
|
+
export function exportSelectiveDisclosureProof(note) {
|
|
268
|
+
if (!note ||
|
|
269
|
+
typeof note !== 'object' ||
|
|
270
|
+
!(note.stealthOwner instanceof Uint8Array) ||
|
|
271
|
+
note.stealthOwner.byteLength !== 32 ||
|
|
272
|
+
!(note.mint instanceof Uint8Array) ||
|
|
273
|
+
note.mint.byteLength !== 32 ||
|
|
274
|
+
!(note.blinding instanceof Uint8Array) ||
|
|
275
|
+
note.blinding.byteLength !== 32 ||
|
|
276
|
+
!(note.commitment instanceof Uint8Array) ||
|
|
277
|
+
note.commitment.byteLength !== 32) {
|
|
278
|
+
throw new RangeError('OwnedNote must provide 32-byte Uint8Array stealthOwner, mint, blinding, and commitment');
|
|
279
|
+
}
|
|
280
|
+
return {
|
|
281
|
+
poolId: note.poolId,
|
|
282
|
+
laneId: note.laneId,
|
|
283
|
+
leafIndex: note.leafIndex,
|
|
284
|
+
stealthOwner: new Uint8Array(note.stealthOwner),
|
|
285
|
+
mint: new Uint8Array(note.mint),
|
|
286
|
+
amount: note.amount,
|
|
287
|
+
blinding: new Uint8Array(note.blinding),
|
|
288
|
+
commitment: new Uint8Array(note.commitment),
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
export class CompactWalletStore {
|
|
292
|
+
poolId;
|
|
293
|
+
birthdaySlot;
|
|
294
|
+
lanes;
|
|
295
|
+
notes;
|
|
296
|
+
constructor(poolId = 0, birthdaySlot = 0n) {
|
|
297
|
+
if (!Number.isInteger(poolId) || poolId < 0 || poolId > U32_MAX) {
|
|
298
|
+
throw new RangeError(`poolId must be a u32 integer in 0..=${U32_MAX}, got ${String(poolId)}`);
|
|
299
|
+
}
|
|
300
|
+
if (typeof birthdaySlot !== 'bigint' || birthdaySlot < 0n || birthdaySlot > U64_MAX) {
|
|
301
|
+
throw new RangeError(`birthdaySlot must be a u64 bigint, got ${String(birthdaySlot)}`);
|
|
302
|
+
}
|
|
303
|
+
this.poolId = poolId;
|
|
304
|
+
this.birthdaySlot = birthdaySlot;
|
|
305
|
+
this.lanes = Array.from({ length: NUM_LANES }, () => ({
|
|
306
|
+
finalizedSubroots: [],
|
|
307
|
+
frontierSubSeq: 0n,
|
|
308
|
+
frontierLeaves: [],
|
|
309
|
+
prevSealedSubSeq: null,
|
|
310
|
+
prevSealedLeaves: [],
|
|
311
|
+
nextMemoLeaf: 0n,
|
|
312
|
+
nextNfIndex: 0n,
|
|
313
|
+
}));
|
|
314
|
+
this.notes = [];
|
|
315
|
+
}
|
|
316
|
+
/** Clear all cached lane state and notes and optionally set a new `birthdaySlot` for clean rescanning. */
|
|
317
|
+
reset(birthdaySlot = 0n) {
|
|
318
|
+
if (typeof birthdaySlot !== 'bigint' || birthdaySlot < 0n || birthdaySlot > U64_MAX) {
|
|
319
|
+
throw new RangeError(`birthdaySlot must be a u64 bigint, got ${String(birthdaySlot)}`);
|
|
320
|
+
}
|
|
321
|
+
this.birthdaySlot = birthdaySlot;
|
|
322
|
+
this.lanes = Array.from({ length: NUM_LANES }, () => ({
|
|
323
|
+
finalizedSubroots: [],
|
|
324
|
+
frontierSubSeq: 0n,
|
|
325
|
+
frontierLeaves: [],
|
|
326
|
+
prevSealedSubSeq: null,
|
|
327
|
+
prevSealedLeaves: [],
|
|
328
|
+
nextMemoLeaf: 0n,
|
|
329
|
+
nextNfIndex: 0n,
|
|
330
|
+
}));
|
|
331
|
+
this.notes = [];
|
|
332
|
+
}
|
|
333
|
+
unspentNotes(mintHex) {
|
|
334
|
+
return this.notes.filter((n) => !n.spent && (!mintHex || bytesToHex(n.mint) === mintHex));
|
|
335
|
+
}
|
|
336
|
+
balancesByMintHex() {
|
|
337
|
+
const out = new Map();
|
|
338
|
+
for (const n of this.notes) {
|
|
339
|
+
if (n.spent)
|
|
340
|
+
continue;
|
|
341
|
+
const k = bytesToHex(n.mint);
|
|
342
|
+
out.set(k, (out.get(k) ?? 0n) + n.amount);
|
|
343
|
+
}
|
|
344
|
+
return out;
|
|
345
|
+
}
|
|
346
|
+
/** Record a decrypted and commitment-verified owned note if not already tracked. */
|
|
347
|
+
recordVerifiedMemo(params) {
|
|
348
|
+
if (!params || typeof params !== 'object') {
|
|
349
|
+
throw new RangeError('recordVerifiedMemo params must be an object');
|
|
350
|
+
}
|
|
351
|
+
const { fvk, laneId, leafIdx, decrypted, cmBe } = params;
|
|
352
|
+
if (!Number.isInteger(laneId) || laneId < 0 || laneId >= NUM_LANES) {
|
|
353
|
+
throw new RangeError(`Invalid laneId ${String(laneId)}`);
|
|
354
|
+
}
|
|
355
|
+
if (typeof leafIdx !== 'bigint' || leafIdx < 0n || leafIdx >= MAX_LEAVES_PER_LANE) {
|
|
356
|
+
throw new RangeError(`Invalid leafIdx ${String(leafIdx)}`);
|
|
357
|
+
}
|
|
358
|
+
if (!(cmBe instanceof Uint8Array) || cmBe.byteLength !== 32) {
|
|
359
|
+
throw new RangeError(`cmBe must be a 32-byte Uint8Array, got ${cmBe instanceof Uint8Array ? cmBe.byteLength : String(cmBe)}`);
|
|
360
|
+
}
|
|
361
|
+
if (!decrypted ||
|
|
362
|
+
typeof decrypted !== 'object' ||
|
|
363
|
+
!(decrypted.mint instanceof Uint8Array) ||
|
|
364
|
+
decrypted.mint.byteLength !== 32) {
|
|
365
|
+
throw new RangeError('decrypted memo must provide a 32-byte Uint8Array mint');
|
|
366
|
+
}
|
|
367
|
+
if (typeof decrypted.amount !== 'bigint' || decrypted.amount < 0n || decrypted.amount > U64_MAX) {
|
|
368
|
+
throw new RangeError(`decrypted.amount must be a u64 bigint, got ${String(decrypted.amount)}`);
|
|
369
|
+
}
|
|
370
|
+
if (decrypted.paymentId !== undefined &&
|
|
371
|
+
(!(decrypted.paymentId instanceof Uint8Array) ||
|
|
372
|
+
decrypted.paymentId.byteLength !== MEMO_PAYMENT_ID_LEN)) {
|
|
373
|
+
throw new RangeError(`decrypted.paymentId must be a ${MEMO_PAYMENT_ID_LEN}-byte Uint8Array, got ${decrypted.paymentId instanceof Uint8Array ? decrypted.paymentId.byteLength : String(decrypted.paymentId)}`);
|
|
374
|
+
}
|
|
375
|
+
if (this.notes.some((n) => n.laneId === laneId && n.leafIndex === leafIdx)) {
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
const globalLeaf = (BigInt(laneId) << 36n) | leafIdx;
|
|
379
|
+
const stealth = fvkStealthOwner(fvk, decrypted.tweak);
|
|
380
|
+
const cmFr = computeNoteCommitment(stealth, deriveAssetId(decrypted.mint), decrypted.amount, decrypted.blinding);
|
|
381
|
+
const computedCmBe = frToBeBytes(cmFr);
|
|
382
|
+
for (let i = 0; i < 32; i++) {
|
|
383
|
+
if (computedCmBe[i] !== cmBe[i]) {
|
|
384
|
+
throw new Error('Note commitment mismatch in recordVerifiedMemo');
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const nf = fvkRealNullifier(fvk, cmFr, globalLeaf);
|
|
388
|
+
this.notes.push({
|
|
389
|
+
poolId: this.poolId,
|
|
390
|
+
laneId,
|
|
391
|
+
leafIndex: leafIdx,
|
|
392
|
+
globalLeafIndex: globalLeaf,
|
|
393
|
+
mint: new Uint8Array(decrypted.mint),
|
|
394
|
+
amount: decrypted.amount,
|
|
395
|
+
tweak: frToBeBytes(decrypted.tweak),
|
|
396
|
+
blinding: frToBeBytes(decrypted.blinding),
|
|
397
|
+
stealthOwner: frToBeBytes(stealth),
|
|
398
|
+
commitment: new Uint8Array(cmBe),
|
|
399
|
+
nullifier: nf,
|
|
400
|
+
paymentId: decrypted.paymentId
|
|
401
|
+
? new Uint8Array(decrypted.paymentId)
|
|
402
|
+
: new Uint8Array(MEMO_PAYMENT_ID_LEN),
|
|
403
|
+
isDynamic: decrypted.isDynamic,
|
|
404
|
+
spent: false,
|
|
405
|
+
frozenIntraSiblings: null,
|
|
406
|
+
frozenIntraPositions: null,
|
|
407
|
+
});
|
|
408
|
+
return true;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Freeze 12-sibling intra-subtree Merkle paths for every owned note in sealed
|
|
412
|
+
* `(laneId, subSeq)` so the `8,256 B` `SubtreePage` can be permanently discarded.
|
|
413
|
+
*/
|
|
414
|
+
freezeOwnedNotesInSubtreePage(laneId, subSeq, leaves) {
|
|
415
|
+
if (!Number.isInteger(laneId) || laneId < 0 || laneId >= NUM_LANES) {
|
|
416
|
+
throw new RangeError(`Invalid laneId ${String(laneId)}`);
|
|
417
|
+
}
|
|
418
|
+
if (typeof subSeq !== 'bigint' || subSeq < 0n || subSeq >= MAX_SUBROOTS_PER_LANE) {
|
|
419
|
+
throw new RangeError(`Invalid subSeq ${String(subSeq)}`);
|
|
420
|
+
}
|
|
421
|
+
if (!Array.isArray(leaves)) {
|
|
422
|
+
throw new RangeError('leaves must be an array of 32-byte Uint8Arrays');
|
|
423
|
+
}
|
|
424
|
+
if (leaves.length !== SUBTREE_LEAVES)
|
|
425
|
+
return;
|
|
426
|
+
let frLeaves = null;
|
|
427
|
+
for (const note of this.notes) {
|
|
428
|
+
if (note.laneId === laneId &&
|
|
429
|
+
note.leafIndex / BigInt(SUBTREE_LEAVES) === subSeq &&
|
|
430
|
+
!note.frozenIntraSiblings) {
|
|
431
|
+
const offset = Number(note.leafIndex % BigInt(SUBTREE_LEAVES));
|
|
432
|
+
if (!bytesEqual(leaves[offset], note.commitment)) {
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
if (!frLeaves)
|
|
436
|
+
frLeaves = leaves.map((b) => frFromBeBytesStrict(b));
|
|
437
|
+
const { siblings, positions } = extractIntraSubtreeSiblings(frLeaves, SUBTREE_LEAVES, offset);
|
|
438
|
+
note.frozenIntraSiblings = siblings.map((lvl) => lvl.map((x) => frToBeBytes(x)));
|
|
439
|
+
note.frozenIntraPositions = positions;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Ingest one or more `SubtreeRootPage` accounts (`9,664 B`, 300 finalized subroots each)
|
|
445
|
+
* without downloading sealed `SubtreePage` accounts for subtrees containing no owned notes.
|
|
446
|
+
*
|
|
447
|
+
* Validates every page in sorted sequence order and enforces strict contiguity (zero
|
|
448
|
+
* zero-filled gaps, zero sparse amplification DoS, zero partial mutation on error) BEFORE
|
|
449
|
+
* writing any subroots into `finalizedSubroots`.
|
|
450
|
+
*/
|
|
451
|
+
ingestSubrootPages(params) {
|
|
452
|
+
const { laneId, subrootPages, finalizedCount } = params;
|
|
453
|
+
if (!Number.isInteger(laneId) || laneId < 0 || laneId >= NUM_LANES) {
|
|
454
|
+
throw new RangeError(`Invalid laneId ${laneId}`);
|
|
455
|
+
}
|
|
456
|
+
if (finalizedCount !== undefined && typeof finalizedCount !== 'bigint') {
|
|
457
|
+
throw new RangeError(`Invalid finalizedCount=${String(finalizedCount)}`);
|
|
458
|
+
}
|
|
459
|
+
const lane = this.lanes[laneId];
|
|
460
|
+
const maxRootsBig = finalizedCount !== undefined
|
|
461
|
+
? finalizedCount < 0n
|
|
462
|
+
? 0n
|
|
463
|
+
: finalizedCount > MAX_SUBROOTS_PER_LANE
|
|
464
|
+
? MAX_SUBROOTS_PER_LANE
|
|
465
|
+
: finalizedCount
|
|
466
|
+
: MAX_SUBROOTS_PER_LANE;
|
|
467
|
+
const srPerPageBig = BigInt(SUBROOTS_PER_PAGE);
|
|
468
|
+
const dedupPages = new Map();
|
|
469
|
+
for (const entry of subrootPages) {
|
|
470
|
+
if (typeof entry.rootPageSeq !== 'bigint' || entry.rootPageSeq < 0n) {
|
|
471
|
+
throw new RangeError(`Invalid SubtreeRootPage rootPageSeq=${String(entry.rootPageSeq)}`);
|
|
472
|
+
}
|
|
473
|
+
const dec = decodeSubtreeRootPage(entry.raw);
|
|
474
|
+
if (dec.poolId !== this.poolId ||
|
|
475
|
+
dec.laneId !== laneId ||
|
|
476
|
+
dec.rootPageSeq !== entry.rootPageSeq) {
|
|
477
|
+
throw new Error(`SubtreeRootPage header mismatch (expected pool=${this.poolId}, lane=${laneId}, seq=${entry.rootPageSeq}; got pool=${dec.poolId}, lane=${dec.laneId}, seq=${dec.rootPageSeq})`);
|
|
478
|
+
}
|
|
479
|
+
const baseIdxBig = entry.rootPageSeq * srPerPageBig;
|
|
480
|
+
if (baseIdxBig > MAX_SUBROOTS_PER_LANE) {
|
|
481
|
+
throw new RangeError(`SubtreeRootPage rootPageSeq out of range: ${entry.rootPageSeq}`);
|
|
482
|
+
}
|
|
483
|
+
const baseIdx = Number(baseIdxBig);
|
|
484
|
+
for (let i = 0; i < dec.roots.length; i++) {
|
|
485
|
+
frFromBeBytesStrict(dec.roots[i]);
|
|
486
|
+
const subIdx = baseIdx + i;
|
|
487
|
+
if (subIdx < lane.finalizedSubroots.length &&
|
|
488
|
+
!bytesEqual(lane.finalizedSubroots[subIdx], dec.roots[i])) {
|
|
489
|
+
throw new Error(`SubtreeRootPage subroot mismatch against persisted finalizedSubroots at index ${subIdx}`);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
const existing = dedupPages.get(entry.rootPageSeq);
|
|
493
|
+
if (existing) {
|
|
494
|
+
const overlap = Math.min(existing.roots.length, dec.roots.length);
|
|
495
|
+
for (let i = 0; i < overlap; i++) {
|
|
496
|
+
if (!bytesEqual(existing.roots[i], dec.roots[i])) {
|
|
497
|
+
throw new Error(`Conflicting duplicate SubtreeRootPage entries at seq=${entry.rootPageSeq}`);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (dec.roots.length > existing.roots.length) {
|
|
501
|
+
dedupPages.set(entry.rootPageSeq, dec);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
else {
|
|
505
|
+
dedupPages.set(entry.rootPageSeq, dec);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
const sortedSeqs = [...dedupPages.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
509
|
+
let runningLen = lane.finalizedSubroots.length;
|
|
510
|
+
const validated = [];
|
|
511
|
+
for (const rootPageSeq of sortedSeqs) {
|
|
512
|
+
const dec = dedupPages.get(rootPageSeq);
|
|
513
|
+
const baseIdxBig = rootPageSeq * srPerPageBig;
|
|
514
|
+
if (baseIdxBig > MAX_SUBROOTS_PER_LANE) {
|
|
515
|
+
throw new RangeError(`SubtreeRootPage rootPageSeq out of range: ${rootPageSeq}`);
|
|
516
|
+
}
|
|
517
|
+
const baseIdx = Number(baseIdxBig);
|
|
518
|
+
if (baseIdx > runningLen) {
|
|
519
|
+
throw new RangeError(`SubtreeRootPage page_seq jump exceeds limit (sequence gap): ${rootPageSeq}`);
|
|
520
|
+
}
|
|
521
|
+
const endIdxBig = baseIdxBig + BigInt(dec.roots.length) < maxRootsBig
|
|
522
|
+
? baseIdxBig + BigInt(dec.roots.length)
|
|
523
|
+
: maxRootsBig;
|
|
524
|
+
if (endIdxBig <= baseIdxBig)
|
|
525
|
+
continue;
|
|
526
|
+
const writeCnt = Number(endIdxBig - baseIdxBig);
|
|
527
|
+
const roots = [];
|
|
528
|
+
for (let i = 0; i < writeCnt; i++) {
|
|
529
|
+
frFromBeBytesStrict(dec.roots[i]);
|
|
530
|
+
roots.push(new Uint8Array(dec.roots[i]));
|
|
531
|
+
}
|
|
532
|
+
const endIdx = Number(endIdxBig);
|
|
533
|
+
if (endIdx > runningLen)
|
|
534
|
+
runningLen = endIdx;
|
|
535
|
+
validated.push({ baseIdx, roots });
|
|
536
|
+
}
|
|
537
|
+
for (const { baseIdx, roots } of validated) {
|
|
538
|
+
for (let i = 0; i < roots.length; i++) {
|
|
539
|
+
lane.finalizedSubroots[baseIdx + i] = roots[i];
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Stream a single `NullifierPage` against our `O(owned_unspent_notes)` prefix index,
|
|
545
|
+
* marking matches `spent = true`, advancing `nextNfIndex`, and discarding stranger prefixes.
|
|
546
|
+
*/
|
|
547
|
+
ingestNullifierPage(params) {
|
|
548
|
+
return this.ingestNullifierPages({
|
|
549
|
+
laneId: params.laneId,
|
|
550
|
+
nfPages: [{ pageSeq: params.pageSeq, raw: params.raw }],
|
|
551
|
+
maxNfIndex: params.maxNfIndex,
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
_validateNullifierPages(params) {
|
|
555
|
+
const { laneId, nfPages, maxNfIndex } = params;
|
|
556
|
+
if (!Number.isInteger(laneId) || laneId < 0 || laneId >= NUM_LANES) {
|
|
557
|
+
throw new RangeError(`Invalid laneId ${String(laneId)}`);
|
|
558
|
+
}
|
|
559
|
+
if (maxNfIndex !== undefined &&
|
|
560
|
+
(typeof maxNfIndex !== 'bigint' || maxNfIndex < 0n || maxNfIndex > U64_MAX)) {
|
|
561
|
+
throw new RangeError(`NullifierPage maxNfIndex out of range: ${String(maxNfIndex)}`);
|
|
562
|
+
}
|
|
563
|
+
if (nfPages.length === 0)
|
|
564
|
+
return [];
|
|
565
|
+
const lane = this.lanes[laneId];
|
|
566
|
+
for (const entry of nfPages) {
|
|
567
|
+
if (typeof entry.pageSeq !== 'bigint' || entry.pageSeq < 0n || entry.pageSeq > U64_MAX) {
|
|
568
|
+
throw new RangeError(`NullifierPage pageSeq out of range: ${String(entry.pageSeq)}`);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
const sortedNfPages = [...nfPages].sort((a, b) => a.pageSeq < b.pageSeq ? -1 : a.pageSeq > b.pageSeq ? 1 : 0);
|
|
572
|
+
let runningNfIndex = lane.nextNfIndex;
|
|
573
|
+
const validated = [];
|
|
574
|
+
for (const { pageSeq, raw } of sortedNfPages) {
|
|
575
|
+
const nfPage = decodeNullifierPage(raw);
|
|
576
|
+
if (nfPage.poolId !== this.poolId || nfPage.laneId !== laneId || nfPage.pageSeq !== pageSeq) {
|
|
577
|
+
throw new Error(`NullifierPage header mismatch (expected pool=${this.poolId}, lane=${laneId}, seq=${pageSeq}; got pool=${nfPage.poolId}, lane=${nfPage.laneId}, seq=${nfPage.pageSeq})`);
|
|
578
|
+
}
|
|
579
|
+
const pageBase = pageSeq * BigInt(NF_PER_PAGE);
|
|
580
|
+
if (pageBase + BigInt(nfPage.count) > U64_MAX) {
|
|
581
|
+
throw new RangeError(`NullifierPage pageSeq overflow: ${pageSeq}`);
|
|
582
|
+
}
|
|
583
|
+
if (pageBase > runningNfIndex) {
|
|
584
|
+
throw new RangeError(`NullifierPage sequence gap: pageSeq=${pageSeq} starts at ${pageBase} > nextNfIndex=${runningNfIndex}`);
|
|
585
|
+
}
|
|
586
|
+
const startSlot = runningNfIndex > pageBase
|
|
587
|
+
? Number(runningNfIndex - pageBase > BigInt(NF_PER_PAGE)
|
|
588
|
+
? BigInt(NF_PER_PAGE)
|
|
589
|
+
: runningNfIndex - pageBase)
|
|
590
|
+
: 0;
|
|
591
|
+
let limitSlot = nfPage.count;
|
|
592
|
+
if (maxNfIndex !== undefined) {
|
|
593
|
+
const capSlots = maxNfIndex > pageBase
|
|
594
|
+
? Number(maxNfIndex - pageBase > BigInt(NF_PER_PAGE)
|
|
595
|
+
? BigInt(NF_PER_PAGE)
|
|
596
|
+
: maxNfIndex - pageBase)
|
|
597
|
+
: 0;
|
|
598
|
+
if (capSlots < limitSlot)
|
|
599
|
+
limitSlot = capSlots;
|
|
600
|
+
}
|
|
601
|
+
if (limitSlot > startSlot) {
|
|
602
|
+
const endIdx = pageBase + BigInt(limitSlot);
|
|
603
|
+
if (endIdx > runningNfIndex)
|
|
604
|
+
runningNfIndex = endIdx;
|
|
605
|
+
}
|
|
606
|
+
validated.push({ pageBase, startSlot, limitSlot, prefixes: nfPage.prefixes });
|
|
607
|
+
}
|
|
608
|
+
return validated;
|
|
609
|
+
}
|
|
610
|
+
_applyValidatedNullifierPages(laneId, validated) {
|
|
611
|
+
if (validated.length === 0)
|
|
612
|
+
return 0;
|
|
613
|
+
const lane = this.lanes[laneId];
|
|
614
|
+
// Build an O(owned_unspent_notes) prefix lookup table across ALL lanes.
|
|
615
|
+
const unspentByPrefix = new Map();
|
|
616
|
+
for (const note of this.notes) {
|
|
617
|
+
if (note.spent)
|
|
618
|
+
continue;
|
|
619
|
+
const prefHex = bytesToHex(note.nullifier.subarray(0, NF_PREFIX_LEN));
|
|
620
|
+
const bucket = unspentByPrefix.get(prefHex);
|
|
621
|
+
if (bucket) {
|
|
622
|
+
bucket.push(note);
|
|
623
|
+
}
|
|
624
|
+
else {
|
|
625
|
+
unspentByPrefix.set(prefHex, [note]);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
let newlySpent = 0;
|
|
629
|
+
for (const { pageBase, startSlot, limitSlot, prefixes } of validated) {
|
|
630
|
+
for (let slot = startSlot; slot < limitSlot; slot++) {
|
|
631
|
+
if (unspentByPrefix.size > 0) {
|
|
632
|
+
const prefHex = bytesToHex(prefixes[slot]);
|
|
633
|
+
const matched = unspentByPrefix.get(prefHex);
|
|
634
|
+
if (matched) {
|
|
635
|
+
for (const note of matched) {
|
|
636
|
+
if (!note.spent) {
|
|
637
|
+
note.spent = true;
|
|
638
|
+
newlySpent++;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
unspentByPrefix.delete(prefHex);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
const nextIdx = pageBase + BigInt(slot) + 1n;
|
|
645
|
+
if (nextIdx > lane.nextNfIndex)
|
|
646
|
+
lane.nextNfIndex = nextIdx;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return newlySpent;
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* Stream `NullifierPage`s in ascending sequence order against an `O(owned_unspent_notes)`
|
|
653
|
+
* lookup map (across all lanes), marking matching notes `spent = true`, advancing
|
|
654
|
+
* `nextNfIndex`, and immediately discarding every stranger prefix.
|
|
655
|
+
*
|
|
656
|
+
* Pre-validates every page header, bounds, and strict contiguity (`pageBase <= runningNfIndex`)
|
|
657
|
+
* BEFORE mutating any note or advancing `nextNfIndex`.
|
|
658
|
+
*/
|
|
659
|
+
ingestNullifierPages(params) {
|
|
660
|
+
const validated = this._validateNullifierPages(params);
|
|
661
|
+
return this._applyValidatedNullifierPages(params.laneId, validated);
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Prune retained `prevSealedLeaves` on any lane whose `GlobalRootHistory.stable` snapshot
|
|
665
|
+
* (or `ROOT_RING_EPOCH` `RootSnapshotChoice`) has crossed past it.
|
|
666
|
+
* Validates `source` strictly (including `poolId` binding for `DecodedGlobalRootHistory`)
|
|
667
|
+
* before pruning any lane, and refuses to prune on `ROOT_RING_SLOT` (`latest`) snapshots so
|
|
668
|
+
* `prevSealedLeaves` needed for offline `stable` witness builds are never wiped prematurely.
|
|
669
|
+
*/
|
|
670
|
+
pruneSealedBeforeSnapshot(source) {
|
|
671
|
+
if (!source || typeof source !== 'object') {
|
|
672
|
+
throw new RangeError('pruneSealedBeforeSnapshot source must be an object');
|
|
673
|
+
}
|
|
674
|
+
let laneCounts;
|
|
675
|
+
if ('slotRing' in source || 'stableLaneCounts' in source) {
|
|
676
|
+
validateGlobalRootHistory(source, this.poolId);
|
|
677
|
+
laneCounts = source.stableLaneCounts;
|
|
678
|
+
}
|
|
679
|
+
else {
|
|
680
|
+
validateRootSnapshotChoice(source);
|
|
681
|
+
if (source.ringKind !== ROOT_RING_EPOCH) {
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
laneCounts = source.laneCounts;
|
|
685
|
+
}
|
|
686
|
+
for (let l = 0; l < NUM_LANES; l++) {
|
|
687
|
+
const lane = this.lanes[l];
|
|
688
|
+
const snapFrontierPage = laneCounts[l] / BigInt(SUBTREE_LEAVES);
|
|
689
|
+
if (lane.prevSealedSubSeq !== null && snapFrontierPage > lane.prevSealedSubSeq) {
|
|
690
|
+
lane.prevSealedSubSeq = null;
|
|
691
|
+
lane.prevSealedLeaves = [];
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
ingestLanePages(params) {
|
|
696
|
+
if (!params || typeof params !== 'object') {
|
|
697
|
+
throw new RangeError('ingestLanePages params must be an object');
|
|
698
|
+
}
|
|
699
|
+
const { fvk, laneId, subtreePages, memoPages, nfPages } = params;
|
|
700
|
+
if (!Number.isInteger(laneId) || laneId < 0 || laneId >= NUM_LANES) {
|
|
701
|
+
throw new RangeError(`Invalid laneId ${String(laneId)}`);
|
|
702
|
+
}
|
|
703
|
+
if (!Array.isArray(subtreePages)) {
|
|
704
|
+
throw new RangeError('ingestLanePages requires subtreePages array');
|
|
705
|
+
}
|
|
706
|
+
const lane = this.lanes[laneId];
|
|
707
|
+
// Phase 1: Pre-validate ALL SubtreePages (headers, counts, canonical BN254 Fr on BOTH sealed
|
|
708
|
+
// and unsealed leaves, and contiguous sealed pageSeq), ALL MemoPages, held frontier leaves,
|
|
709
|
+
// FVK scalars, and ALL NullifierPages BEFORE mutating ANY store state (100% atomic on error).
|
|
710
|
+
const pageLeavesMap = new Map();
|
|
711
|
+
for (const { pageSeq, raw } of subtreePages) {
|
|
712
|
+
const dec = decodeSubtreePage(raw);
|
|
713
|
+
if (typeof pageSeq !== 'bigint' || pageSeq < 0n || pageSeq > U64_MAX) {
|
|
714
|
+
throw new RangeError(`SubtreePage pageSeq out of range: ${String(pageSeq)}`);
|
|
715
|
+
}
|
|
716
|
+
if (dec.poolId !== this.poolId || dec.laneId !== laneId || dec.pageSeq !== pageSeq) {
|
|
717
|
+
throw new Error(`SubtreePage header mismatch (expected pool=${this.poolId}, lane=${laneId}, seq=${pageSeq}; got pool=${dec.poolId}, lane=${dec.laneId}, seq=${dec.pageSeq})`);
|
|
718
|
+
}
|
|
719
|
+
const frLeaves = dec.leaves.map((b) => frFromBeBytesStrict(b));
|
|
720
|
+
// Enforce append-only prefix immutability against persisted frontier & prevSealed leaves
|
|
721
|
+
if (lane.frontierLeaves.length > 0 && pageSeq === lane.frontierSubSeq) {
|
|
722
|
+
const prefixLen = Math.min(dec.leaves.length, lane.frontierLeaves.length);
|
|
723
|
+
for (let i = 0; i < prefixLen; i++) {
|
|
724
|
+
if (!bytesEqual(dec.leaves[i], lane.frontierLeaves[i])) {
|
|
725
|
+
throw new Error('SubtreePage frontier prefix mismatch against persisted frontierLeaves');
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
if (lane.prevSealedLeaves.length > 0 && lane.prevSealedSubSeq === pageSeq) {
|
|
730
|
+
const prefixLen = Math.min(dec.leaves.length, lane.prevSealedLeaves.length);
|
|
731
|
+
for (let i = 0; i < prefixLen; i++) {
|
|
732
|
+
if (!bytesEqual(dec.leaves[i], lane.prevSealedLeaves[i])) {
|
|
733
|
+
throw new Error('SubtreePage prefix mismatch against persisted prevSealedLeaves');
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
// Enforce immutability against already-persisted `finalizedSubroots[pageSeq]`
|
|
738
|
+
if (dec.leaves.length === SUBTREE_LEAVES && pageSeq < BigInt(lane.finalizedSubroots.length)) {
|
|
739
|
+
const seqNum = Number(pageSeq);
|
|
740
|
+
const subroot = frToBeBytes(computeSubtree256Root(frLeaves, SUBTREE_LEAVES));
|
|
741
|
+
if (!bytesEqual(subroot, lane.finalizedSubroots[seqNum])) {
|
|
742
|
+
throw new Error(`SubtreePage subroot mismatch against persisted finalizedSubroots at seq=${pageSeq}`);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
const existing = pageLeavesMap.get(pageSeq);
|
|
746
|
+
if (existing) {
|
|
747
|
+
const overlap = Math.min(existing.leaves.length, dec.leaves.length);
|
|
748
|
+
for (let i = 0; i < overlap; i++) {
|
|
749
|
+
if (!bytesEqual(existing.leaves[i], dec.leaves[i])) {
|
|
750
|
+
throw new Error(`Conflicting duplicate SubtreePage entries at seq=${pageSeq}`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
if (dec.leaves.length > existing.leaves.length) {
|
|
754
|
+
pageLeavesMap.set(pageSeq, { leaves: dec.leaves, frLeaves });
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
else {
|
|
758
|
+
pageLeavesMap.set(pageSeq, { leaves: dec.leaves, frLeaves });
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
if (!Array.isArray(memoPages)) {
|
|
762
|
+
throw new RangeError('ingestLanePages requires memoPages array');
|
|
763
|
+
}
|
|
764
|
+
const memoMap = new Map();
|
|
765
|
+
for (const { pageSeq, raw } of memoPages) {
|
|
766
|
+
const dec = decodeMemoPage(raw);
|
|
767
|
+
if (typeof pageSeq !== 'bigint' || pageSeq < 0n || pageSeq > U64_MAX) {
|
|
768
|
+
throw new RangeError(`MemoPage pageSeq out of range: ${String(pageSeq)}`);
|
|
769
|
+
}
|
|
770
|
+
if (dec.poolId !== this.poolId || dec.laneId !== laneId || dec.pageSeq !== pageSeq) {
|
|
771
|
+
throw new Error(`MemoPage header mismatch (expected pool=${this.poolId}, lane=${laneId}, seq=${pageSeq}; got pool=${dec.poolId}, lane=${dec.laneId}, seq=${dec.pageSeq})`);
|
|
772
|
+
}
|
|
773
|
+
const existing = memoMap.get(pageSeq);
|
|
774
|
+
if (!existing || dec.count > existing.count) {
|
|
775
|
+
memoMap.set(pageSeq, dec);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
if (!Array.isArray(nfPages)) {
|
|
779
|
+
throw new RangeError('ingestLanePages requires nfPages array');
|
|
780
|
+
}
|
|
781
|
+
const validatedNfPages = this._validateNullifierPages({ laneId, nfPages });
|
|
782
|
+
const sortedSeqs = [...pageLeavesMap.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
783
|
+
let runningSubrootLen = lane.finalizedSubroots.length;
|
|
784
|
+
const validatedSealed = new Map();
|
|
785
|
+
for (const seq of sortedSeqs) {
|
|
786
|
+
const { leaves, frLeaves } = pageLeavesMap.get(seq);
|
|
787
|
+
if (leaves.length < SUBTREE_LEAVES && seq < BigInt(lane.finalizedSubroots.length)) {
|
|
788
|
+
const hasFullHeldCopy = (seq === lane.frontierSubSeq && lane.frontierLeaves.length === SUBTREE_LEAVES) ||
|
|
789
|
+
(lane.prevSealedSubSeq === seq && lane.prevSealedLeaves.length === SUBTREE_LEAVES);
|
|
790
|
+
if (!hasFullHeldCopy) {
|
|
791
|
+
throw new Error(`Truncated SubtreePage at seq=${seq} cannot be verified against persisted finalizedSubroots`);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if (leaves.length === SUBTREE_LEAVES) {
|
|
795
|
+
if (seq < 0n || seq >= MAX_SUBROOTS_PER_LANE) {
|
|
796
|
+
throw new RangeError(`SubtreePage pageSeq out of range: ${seq}`);
|
|
797
|
+
}
|
|
798
|
+
const seqNum = Number(seq);
|
|
799
|
+
if (seqNum > runningSubrootLen) {
|
|
800
|
+
throw new RangeError(`SubtreePage page_seq jump exceeds limit (sequence gap): ${seq}`);
|
|
801
|
+
}
|
|
802
|
+
const subroot = frToBeBytes(computeSubtree256Root(frLeaves, SUBTREE_LEAVES));
|
|
803
|
+
if (seqNum + 1 > runningSubrootLen)
|
|
804
|
+
runningSubrootLen = seqNum + 1;
|
|
805
|
+
validatedSealed.set(seq, { frLeaves, subroot });
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const suppliedFrontier = pageLeavesMap.get(lane.frontierSubSeq);
|
|
809
|
+
const heldSealed = lane.frontierLeaves.length === SUBTREE_LEAVES &&
|
|
810
|
+
(!suppliedFrontier || suppliedFrontier.leaves.length < SUBTREE_LEAVES);
|
|
811
|
+
const heldFrLeaves = heldSealed
|
|
812
|
+
? lane.frontierLeaves.map((b) => frFromBeBytesStrict(b))
|
|
813
|
+
: null;
|
|
814
|
+
if (memoMap.size > 0) {
|
|
815
|
+
frFromBeBytesStrict(fvk.spendPk);
|
|
816
|
+
frFromBeBytesStrict(fvk.nk);
|
|
817
|
+
}
|
|
818
|
+
// Phase 2: All inputs validated cleanly — commit memos, subroots, freezes, frontiers, & NFs.
|
|
819
|
+
let discovered = 0;
|
|
820
|
+
for (;;) {
|
|
821
|
+
const leafIdx = lane.nextMemoLeaf;
|
|
822
|
+
if (leafIdx >= MAX_LEAVES_PER_LANE)
|
|
823
|
+
break;
|
|
824
|
+
const mSeq = leafIdx / BigInt(MEMO_NOTES_PER_PAGE);
|
|
825
|
+
const mSlot = Number(leafIdx % BigInt(MEMO_NOTES_PER_PAGE));
|
|
826
|
+
const mPage = memoMap.get(mSeq);
|
|
827
|
+
if (!mPage || mSlot >= mPage.count)
|
|
828
|
+
break;
|
|
829
|
+
const sSeq = leafIdx / BigInt(SUBTREE_LEAVES);
|
|
830
|
+
const sSlot = Number(leafIdx % BigInt(SUBTREE_LEAVES));
|
|
831
|
+
const supplied = pageLeavesMap.get(sSeq)?.leaves;
|
|
832
|
+
const bestLeaves = sSeq === lane.frontierSubSeq
|
|
833
|
+
? supplied && supplied.length > lane.frontierLeaves.length
|
|
834
|
+
? supplied
|
|
835
|
+
: lane.frontierLeaves
|
|
836
|
+
: supplied;
|
|
837
|
+
if (!bestLeaves || sSlot >= bestLeaves.length)
|
|
838
|
+
break;
|
|
839
|
+
const cmBe = bestLeaves[sSlot];
|
|
840
|
+
const entry = mPage.entries[mSlot];
|
|
841
|
+
const dec = tryDecryptAndVerifyMemoEntry(fvk, entry.viewTag, entry.ephemeralPk, entry.ciphertext, cmBe);
|
|
842
|
+
if (dec) {
|
|
843
|
+
if (this.recordVerifiedMemo({
|
|
844
|
+
fvk,
|
|
845
|
+
laneId,
|
|
846
|
+
leafIdx,
|
|
847
|
+
decrypted: dec,
|
|
848
|
+
cmBe: cmBe,
|
|
849
|
+
})) {
|
|
850
|
+
discovered++;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
lane.nextMemoLeaf = leafIdx + 1n;
|
|
854
|
+
}
|
|
855
|
+
const freezeNotesInPage = (seq, rawLeaves, frLeaves) => {
|
|
856
|
+
for (const note of this.notes) {
|
|
857
|
+
if (note.laneId === laneId &&
|
|
858
|
+
note.leafIndex / BigInt(SUBTREE_LEAVES) === seq &&
|
|
859
|
+
!note.frozenIntraSiblings) {
|
|
860
|
+
const offset = Number(note.leafIndex % BigInt(SUBTREE_LEAVES));
|
|
861
|
+
if (!bytesEqual(rawLeaves[offset], note.commitment)) {
|
|
862
|
+
continue;
|
|
863
|
+
}
|
|
864
|
+
const { siblings, positions } = extractIntraSubtreeSiblings(frLeaves, SUBTREE_LEAVES, offset);
|
|
865
|
+
note.frozenIntraSiblings = siblings.map((lvl) => lvl.map((x) => frToBeBytes(x)));
|
|
866
|
+
note.frozenIntraPositions = positions;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
if (heldSealed && heldFrLeaves) {
|
|
871
|
+
const heldSeq = lane.frontierSubSeq;
|
|
872
|
+
freezeNotesInPage(heldSeq, lane.frontierLeaves, heldFrLeaves);
|
|
873
|
+
const pageEndLeaf = (heldSeq + 1n) * BigInt(SUBTREE_LEAVES);
|
|
874
|
+
if (lane.nextMemoLeaf >= pageEndLeaf) {
|
|
875
|
+
lane.prevSealedSubSeq = heldSeq;
|
|
876
|
+
lane.prevSealedLeaves = lane.frontierLeaves;
|
|
877
|
+
lane.frontierSubSeq = heldSeq + 1n;
|
|
878
|
+
lane.frontierLeaves = [];
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
for (const seq of sortedSeqs) {
|
|
882
|
+
const { leaves } = pageLeavesMap.get(seq);
|
|
883
|
+
const memoSubSeq = lane.nextMemoLeaf / BigInt(SUBTREE_LEAVES);
|
|
884
|
+
if (leaves.length === SUBTREE_LEAVES) {
|
|
885
|
+
const seqNum = Number(seq);
|
|
886
|
+
const { frLeaves, subroot } = validatedSealed.get(seq);
|
|
887
|
+
lane.finalizedSubroots[seqNum] = subroot;
|
|
888
|
+
freezeNotesInPage(seq, leaves, frLeaves);
|
|
889
|
+
const pageEndLeaf = (seq + 1n) * BigInt(SUBTREE_LEAVES);
|
|
890
|
+
if (lane.nextMemoLeaf >= pageEndLeaf) {
|
|
891
|
+
if (seq >= lane.frontierSubSeq) {
|
|
892
|
+
lane.prevSealedSubSeq = seq;
|
|
893
|
+
lane.prevSealedLeaves = leaves.map((b) => new Uint8Array(b));
|
|
894
|
+
lane.frontierSubSeq = seq + 1n;
|
|
895
|
+
lane.frontierLeaves = [];
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
else if (seq === memoSubSeq &&
|
|
899
|
+
seq >= lane.frontierSubSeq &&
|
|
900
|
+
(seq > lane.frontierSubSeq || leaves.length > lane.frontierLeaves.length)) {
|
|
901
|
+
// Hold sealed page leaves until MemoPages finish scanning all 256 leaves in this page
|
|
902
|
+
lane.frontierSubSeq = seq;
|
|
903
|
+
lane.frontierLeaves = leaves.map((b) => new Uint8Array(b));
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
else if (seq >= BigInt(lane.finalizedSubroots.length) &&
|
|
907
|
+
seq >= lane.frontierSubSeq &&
|
|
908
|
+
seq <= memoSubSeq &&
|
|
909
|
+
(seq > lane.frontierSubSeq || leaves.length > lane.frontierLeaves.length)) {
|
|
910
|
+
lane.frontierSubSeq = seq;
|
|
911
|
+
lane.frontierLeaves = leaves.map((b) => new Uint8Array(b));
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
this._applyValidatedNullifierPages(laneId, validatedNfPages);
|
|
915
|
+
return discovered;
|
|
916
|
+
}
|
|
917
|
+
_buildSingleWitnessWithSnapshot(note, chosen) {
|
|
918
|
+
const lane = this.lanes[note.laneId];
|
|
919
|
+
const snapCount = chosen.laneCounts[note.laneId];
|
|
920
|
+
if (typeof snapCount !== 'bigint' || snapCount < 0n || snapCount > MAX_LEAVES_PER_LANE) {
|
|
921
|
+
throw new RangeError(`RootSnapshotChoice laneCounts[${note.laneId}] out of range: ${String(snapCount)}`);
|
|
922
|
+
}
|
|
923
|
+
if (note.leafIndex >= snapCount) {
|
|
924
|
+
throw new Error('Note not yet included in root snapshot');
|
|
925
|
+
}
|
|
926
|
+
const targetPage = note.leafIndex / BigInt(SUBTREE_LEAVES);
|
|
927
|
+
const targetOffset = Number(note.leafIndex % BigInt(SUBTREE_LEAVES));
|
|
928
|
+
const frontierPage = snapCount / BigInt(SUBTREE_LEAVES);
|
|
929
|
+
const frontierRem = Number(snapCount % BigInt(SUBTREE_LEAVES));
|
|
930
|
+
const resolveFrontierLeaves = () => {
|
|
931
|
+
if (lane.frontierSubSeq === frontierPage && lane.frontierLeaves.length >= frontierRem) {
|
|
932
|
+
return lane.frontierLeaves;
|
|
933
|
+
}
|
|
934
|
+
if (lane.prevSealedSubSeq !== null &&
|
|
935
|
+
lane.prevSealedSubSeq === frontierPage &&
|
|
936
|
+
lane.prevSealedLeaves.length >= frontierRem) {
|
|
937
|
+
return lane.prevSealedLeaves;
|
|
938
|
+
}
|
|
939
|
+
return null;
|
|
940
|
+
};
|
|
941
|
+
let intraSiblings;
|
|
942
|
+
let intraPositions;
|
|
943
|
+
if (targetPage < frontierPage) {
|
|
944
|
+
if (!note.frozenIntraSiblings || !note.frozenIntraPositions) {
|
|
945
|
+
throw new Error('Missing frozen intra-subtree siblings for sealed note');
|
|
946
|
+
}
|
|
947
|
+
if (note.frozenIntraSiblings.length !== SUBTREE_LEVELS_4ARY ||
|
|
948
|
+
note.frozenIntraPositions.length !== SUBTREE_LEVELS_4ARY) {
|
|
949
|
+
throw new Error('Malformed frozen intra-subtree witness');
|
|
950
|
+
}
|
|
951
|
+
for (const p of note.frozenIntraPositions) {
|
|
952
|
+
if (!Number.isInteger(p) || p < 0 || p > 3) {
|
|
953
|
+
throw new RangeError(`Invalid frozen intra-subtree position: ${p}`);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
intraSiblings = note.frozenIntraSiblings.map((lvl) => lvl.map((b) => frFromBeBytesStrict(b)));
|
|
957
|
+
intraPositions = [...note.frozenIntraPositions];
|
|
958
|
+
}
|
|
959
|
+
else {
|
|
960
|
+
const fLeaves = resolveFrontierLeaves();
|
|
961
|
+
if (!fLeaves) {
|
|
962
|
+
throw new MissingFrontierLeavesError();
|
|
963
|
+
}
|
|
964
|
+
const fFr = fLeaves.slice(0, frontierRem).map((b) => frFromBeBytesStrict(b));
|
|
965
|
+
const res = extractIntraSubtreeSiblings(fFr, frontierRem, targetOffset);
|
|
966
|
+
intraSiblings = res.siblings;
|
|
967
|
+
intraPositions = res.positions;
|
|
968
|
+
}
|
|
969
|
+
const snapRootsFr = chosen.laneRoots.map((b) => frFromBeBytesStrict(b));
|
|
970
|
+
if (lane.finalizedSubroots.length < Number(frontierPage)) {
|
|
971
|
+
throw new Error('Missing finalized subroots');
|
|
972
|
+
}
|
|
973
|
+
const finalizedFr = lane.finalizedSubroots
|
|
974
|
+
.slice(0, Number(frontierPage))
|
|
975
|
+
.map((b) => frFromBeBytesStrict(b));
|
|
976
|
+
let frontierFr;
|
|
977
|
+
if (frontierRem > 0) {
|
|
978
|
+
const fLeaves = resolveFrontierLeaves();
|
|
979
|
+
if (!fLeaves) {
|
|
980
|
+
throw new MissingFrontierLeavesError();
|
|
981
|
+
}
|
|
982
|
+
frontierFr = fLeaves.slice(0, frontierRem).map((b) => frFromBeBytesStrict(b));
|
|
983
|
+
}
|
|
984
|
+
const path = buildWitnessFromFrozenSubsiblings({
|
|
985
|
+
laneId: note.laneId,
|
|
986
|
+
targetLeafIdx: note.leafIndex,
|
|
987
|
+
intraSiblings,
|
|
988
|
+
intraPositions,
|
|
989
|
+
laneRoots: snapRootsFr,
|
|
990
|
+
laneLeafCount: snapCount,
|
|
991
|
+
finalizedSubtreeRoots: finalizedFr,
|
|
992
|
+
frontierPageLeaves: frontierFr,
|
|
993
|
+
});
|
|
994
|
+
const superRoot = frFromBeBytesStrict(chosen.superRoot);
|
|
995
|
+
const cm = frFromBeBytesStrict(note.commitment);
|
|
996
|
+
if (computeSuperRoot4Ary(snapRootsFr) !== superRoot ||
|
|
997
|
+
computeMerkleRoot4Ary(path, cm) !== superRoot) {
|
|
998
|
+
throw new Error('Reconstructed Merkle root mismatch');
|
|
999
|
+
}
|
|
1000
|
+
return { superRoot, path };
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Select ONE shared `RootSnapshotChoice` covering ALL `notes` (preferring `stable`
|
|
1004
|
+
* `ROOT_RING_EPOCH`, falling back to `latest` `ROOT_RING_SLOT` when any note is newer OR when
|
|
1005
|
+
* the local store lacks pre-seal frontier leaves for an older `stable` page) and build offline
|
|
1006
|
+
* 4-ary Depth-20 Merkle witnesses for every note against that shared snapshot.
|
|
1007
|
+
*/
|
|
1008
|
+
buildWitnessesForNotes(notes, rootSource) {
|
|
1009
|
+
if (!Array.isArray(notes) || notes.length === 0) {
|
|
1010
|
+
throw new RangeError('notes must be a non-empty array');
|
|
1011
|
+
}
|
|
1012
|
+
for (const note of notes) {
|
|
1013
|
+
if (!note || typeof note !== 'object') {
|
|
1014
|
+
throw new RangeError('OwnedNote must be an object');
|
|
1015
|
+
}
|
|
1016
|
+
if (note.poolId !== this.poolId) {
|
|
1017
|
+
throw new Error(`Note poolId mismatch (expected ${this.poolId}, got ${note.poolId})`);
|
|
1018
|
+
}
|
|
1019
|
+
if (!Number.isInteger(note.laneId) || note.laneId < 0 || note.laneId >= NUM_LANES) {
|
|
1020
|
+
throw new RangeError(`Invalid laneId ${note.laneId}`);
|
|
1021
|
+
}
|
|
1022
|
+
if (typeof note.leafIndex !== 'bigint' ||
|
|
1023
|
+
note.leafIndex < 0n ||
|
|
1024
|
+
note.leafIndex >= MAX_LEAVES_PER_LANE) {
|
|
1025
|
+
throw new RangeError(`Invalid leafIndex ${String(note.leafIndex)}`);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
if (!rootSource || typeof rootSource !== 'object') {
|
|
1029
|
+
throw new RangeError('rootSource must be a GlobalRootHistory or RootSnapshotChoice');
|
|
1030
|
+
}
|
|
1031
|
+
let chosen;
|
|
1032
|
+
let history = null;
|
|
1033
|
+
if ('slotRing' in rootSource || 'stableLaneCounts' in rootSource) {
|
|
1034
|
+
history = rootSource;
|
|
1035
|
+
validateGlobalRootHistory(history, this.poolId);
|
|
1036
|
+
const selected = selectRootSnapshotForNotes(history, notes.map((n) => ({ laneId: n.laneId, leafIndex: n.leafIndex })));
|
|
1037
|
+
if (!selected) {
|
|
1038
|
+
throw new Error(notes.length === 1
|
|
1039
|
+
? 'Note not yet included in GlobalRootHistory'
|
|
1040
|
+
: 'Notes not yet included in GlobalRootHistory');
|
|
1041
|
+
}
|
|
1042
|
+
chosen = selected;
|
|
1043
|
+
}
|
|
1044
|
+
else {
|
|
1045
|
+
validateRootSnapshotChoice(rootSource);
|
|
1046
|
+
chosen = rootSource;
|
|
1047
|
+
}
|
|
1048
|
+
const buildAll = (snap) => {
|
|
1049
|
+
const paths = [];
|
|
1050
|
+
let superRoot = 0n;
|
|
1051
|
+
for (const note of notes) {
|
|
1052
|
+
const res = this._buildSingleWitnessWithSnapshot(note, snap);
|
|
1053
|
+
superRoot = res.superRoot;
|
|
1054
|
+
paths.push(res.path);
|
|
1055
|
+
}
|
|
1056
|
+
return { superRoot, paths };
|
|
1057
|
+
};
|
|
1058
|
+
let built;
|
|
1059
|
+
try {
|
|
1060
|
+
built = buildAll(chosen);
|
|
1061
|
+
}
|
|
1062
|
+
catch (err) {
|
|
1063
|
+
if (err instanceof MissingFrontierLeavesError &&
|
|
1064
|
+
history !== null &&
|
|
1065
|
+
chosen.ringKind === ROOT_RING_EPOCH &&
|
|
1066
|
+
!laneCountsEqual(history.latestLaneCounts, history.stableLaneCounts) &&
|
|
1067
|
+
notes.every((n) => n.leafIndex < history.latestLaneCounts[n.laneId])) {
|
|
1068
|
+
const latestChoice = {
|
|
1069
|
+
ringKind: ROOT_RING_SLOT,
|
|
1070
|
+
ringIdx: history.slotCursor,
|
|
1071
|
+
slot: history.latestSlot,
|
|
1072
|
+
superRoot: history.latestSuperRoot,
|
|
1073
|
+
laneRoots: history.latestLaneRoots,
|
|
1074
|
+
laneCounts: history.latestLaneCounts,
|
|
1075
|
+
};
|
|
1076
|
+
built = buildAll(latestChoice);
|
|
1077
|
+
chosen = latestChoice;
|
|
1078
|
+
}
|
|
1079
|
+
else {
|
|
1080
|
+
throw err;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
const touchedLanes = new Set(notes.map((n) => n.laneId));
|
|
1084
|
+
for (const laneId of touchedLanes) {
|
|
1085
|
+
const lane = this.lanes[laneId];
|
|
1086
|
+
if (lane.prevSealedSubSeq !== null) {
|
|
1087
|
+
const stableFrontierPage = history
|
|
1088
|
+
? history.stableLaneCounts[laneId] / BigInt(SUBTREE_LEAVES)
|
|
1089
|
+
: chosen.ringKind === ROOT_RING_EPOCH
|
|
1090
|
+
? chosen.laneCounts[laneId] / BigInt(SUBTREE_LEAVES)
|
|
1091
|
+
: -1n;
|
|
1092
|
+
if (stableFrontierPage > lane.prevSealedSubSeq) {
|
|
1093
|
+
lane.prevSealedSubSeq = null;
|
|
1094
|
+
lane.prevSealedLeaves = [];
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
return {
|
|
1099
|
+
snapshot: chosen,
|
|
1100
|
+
superRoot: built.superRoot,
|
|
1101
|
+
paths: built.paths,
|
|
1102
|
+
rootRingKind: chosen.ringKind,
|
|
1103
|
+
rootRingIdx: chosen.ringIdx,
|
|
1104
|
+
snapshotSlot: chosen.slot,
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
buildWitnessForNote(note, rootSource) {
|
|
1108
|
+
const res = this.buildWitnessesForNotes([note], rootSource);
|
|
1109
|
+
return {
|
|
1110
|
+
superRoot: res.superRoot,
|
|
1111
|
+
path: res.paths[0],
|
|
1112
|
+
rootRingKind: res.rootRingKind,
|
|
1113
|
+
rootRingIdx: res.rootRingIdx,
|
|
1114
|
+
snapshotSlot: res.snapshotSlot,
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
toJSON() {
|
|
1118
|
+
return JSON.stringify({
|
|
1119
|
+
poolId: this.poolId,
|
|
1120
|
+
birthdaySlot: this.birthdaySlot.toString(),
|
|
1121
|
+
lanes: this.lanes.map((l) => ({
|
|
1122
|
+
finalizedSubroots: l.finalizedSubroots.map(bytesToHex),
|
|
1123
|
+
frontierSubSeq: l.frontierSubSeq.toString(),
|
|
1124
|
+
frontierLeaves: l.frontierLeaves.map(bytesToHex),
|
|
1125
|
+
...(l.prevSealedSubSeq !== null && l.prevSealedLeaves.length > 0
|
|
1126
|
+
? {
|
|
1127
|
+
prevSealedSubSeq: l.prevSealedSubSeq.toString(),
|
|
1128
|
+
prevSealedLeaves: l.prevSealedLeaves.map(bytesToHex),
|
|
1129
|
+
}
|
|
1130
|
+
: {}),
|
|
1131
|
+
nextMemoLeaf: l.nextMemoLeaf.toString(),
|
|
1132
|
+
nextNfIndex: l.nextNfIndex.toString(),
|
|
1133
|
+
})),
|
|
1134
|
+
notes: this.notes.map((n) => ({
|
|
1135
|
+
poolId: n.poolId,
|
|
1136
|
+
laneId: n.laneId,
|
|
1137
|
+
leafIndex: n.leafIndex.toString(),
|
|
1138
|
+
globalLeafIndex: n.globalLeafIndex.toString(),
|
|
1139
|
+
mint: bytesToHex(n.mint),
|
|
1140
|
+
amount: n.amount.toString(),
|
|
1141
|
+
tweak: bytesToHex(n.tweak),
|
|
1142
|
+
blinding: bytesToHex(n.blinding),
|
|
1143
|
+
stealthOwner: bytesToHex(n.stealthOwner),
|
|
1144
|
+
commitment: bytesToHex(n.commitment),
|
|
1145
|
+
nullifier: bytesToHex(n.nullifier),
|
|
1146
|
+
paymentId: bytesToHex(n.paymentId),
|
|
1147
|
+
isDynamic: n.isDynamic,
|
|
1148
|
+
spent: n.spent,
|
|
1149
|
+
frozenIntraSiblings: n.frozenIntraSiblings
|
|
1150
|
+
? n.frozenIntraSiblings.map((lvl) => lvl.map(bytesToHex))
|
|
1151
|
+
: null,
|
|
1152
|
+
frozenIntraPositions: n.frozenIntraPositions,
|
|
1153
|
+
})),
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
static fromJSON(json) {
|
|
1157
|
+
// Losslessly preserve bare >2^53-1 JSON u64 integers emitted by Rust/UniFFI stores before JSON.parse.
|
|
1158
|
+
const safeJson = json.replace(/(:\s*)(\d{16,20})(?=\s*[,}\]])/g, (full, prefix, digits) => {
|
|
1159
|
+
try {
|
|
1160
|
+
const n = BigInt(digits);
|
|
1161
|
+
if (n > BigInt(Number.MAX_SAFE_INTEGER) && n <= U64_MAX) {
|
|
1162
|
+
return `${prefix}"${digits}"`;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
catch {
|
|
1166
|
+
// leave unchanged
|
|
1167
|
+
}
|
|
1168
|
+
return full;
|
|
1169
|
+
});
|
|
1170
|
+
const raw = JSON.parse(safeJson);
|
|
1171
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
1172
|
+
throw new Error('Invalid CompactWalletStore JSON');
|
|
1173
|
+
}
|
|
1174
|
+
const rawPoolId = raw.poolId !== undefined ? raw.poolId : raw.pool_id;
|
|
1175
|
+
if (typeof rawPoolId !== 'number' ||
|
|
1176
|
+
!Number.isInteger(rawPoolId) ||
|
|
1177
|
+
rawPoolId < 0 ||
|
|
1178
|
+
rawPoolId > U32_MAX) {
|
|
1179
|
+
throw new Error(`Invalid CompactWalletStore JSON poolId=${String(rawPoolId)}`);
|
|
1180
|
+
}
|
|
1181
|
+
const rawBirthday = raw.birthdaySlot !== undefined ? raw.birthdaySlot : raw.birthday_slot;
|
|
1182
|
+
const birthdaySlot = parseU64Decimal(rawBirthday, 'birthdaySlot');
|
|
1183
|
+
if (!Array.isArray(raw.lanes) || raw.lanes.length !== NUM_LANES) {
|
|
1184
|
+
throw new Error(`Invalid CompactWalletStore JSON: expected ${NUM_LANES} lanes, got ${Array.isArray(raw.lanes) ? raw.lanes.length : typeof raw.lanes}`);
|
|
1185
|
+
}
|
|
1186
|
+
if (!Array.isArray(raw.notes)) {
|
|
1187
|
+
throw new Error('Invalid CompactWalletStore JSON: notes must be an array');
|
|
1188
|
+
}
|
|
1189
|
+
const store = new CompactWalletStore(rawPoolId, birthdaySlot);
|
|
1190
|
+
store.lanes = raw.lanes.map((laneRaw, laneIdx) => {
|
|
1191
|
+
if (!laneRaw || typeof laneRaw !== 'object' || Array.isArray(laneRaw)) {
|
|
1192
|
+
throw new Error(`Invalid CompactWalletStore JSON lane[${laneIdx}]`);
|
|
1193
|
+
}
|
|
1194
|
+
const l = laneRaw;
|
|
1195
|
+
const rawFinalizedSubroots = l.finalizedSubroots !== undefined ? l.finalizedSubroots : l.finalized_subroots;
|
|
1196
|
+
if (!Array.isArray(rawFinalizedSubroots)) {
|
|
1197
|
+
throw new Error(`Invalid CompactWalletStore JSON lane[${laneIdx}].finalizedSubroots`);
|
|
1198
|
+
}
|
|
1199
|
+
if (BigInt(rawFinalizedSubroots.length) > MAX_SUBROOTS_PER_LANE) {
|
|
1200
|
+
throw new Error(`Invalid CompactWalletStore JSON lane[${laneIdx}].finalizedSubroots exceeds limit`);
|
|
1201
|
+
}
|
|
1202
|
+
const rawFrontierLeaves = l.frontierLeaves !== undefined ? l.frontierLeaves : l.frontier_leaves;
|
|
1203
|
+
if (!Array.isArray(rawFrontierLeaves)) {
|
|
1204
|
+
throw new Error(`Invalid CompactWalletStore JSON lane[${laneIdx}].frontierLeaves`);
|
|
1205
|
+
}
|
|
1206
|
+
if (rawFrontierLeaves.length > SUBTREE_LEAVES) {
|
|
1207
|
+
throw new Error('Invalid CompactWalletStore JSON: lane leaves exceed SUBTREE_LEAVES');
|
|
1208
|
+
}
|
|
1209
|
+
const rawPrevSealedLeaves = l.prevSealedLeaves !== undefined ? l.prevSealedLeaves : l.prev_sealed_leaves;
|
|
1210
|
+
if (rawPrevSealedLeaves !== undefined && !Array.isArray(rawPrevSealedLeaves)) {
|
|
1211
|
+
throw new Error(`Invalid CompactWalletStore JSON lane[${laneIdx}].prevSealedLeaves`);
|
|
1212
|
+
}
|
|
1213
|
+
if (Array.isArray(rawPrevSealedLeaves) && rawPrevSealedLeaves.length > SUBTREE_LEAVES) {
|
|
1214
|
+
throw new Error('Invalid CompactWalletStore JSON: lane leaves exceed SUBTREE_LEAVES');
|
|
1215
|
+
}
|
|
1216
|
+
const finalizedSubroots = rawFinalizedSubroots.map((h, i) => {
|
|
1217
|
+
const b = hexOrBytesExact(h, 32, `lane[${laneIdx}].finalizedSubroots[${i}]`);
|
|
1218
|
+
frFromBeBytesStrict(b);
|
|
1219
|
+
return b;
|
|
1220
|
+
});
|
|
1221
|
+
const frontierLeaves = rawFrontierLeaves.map((h, i) => {
|
|
1222
|
+
const b = hexOrBytesExact(h, 32, `lane[${laneIdx}].frontierLeaves[${i}]`);
|
|
1223
|
+
frFromBeBytesStrict(b);
|
|
1224
|
+
return b;
|
|
1225
|
+
});
|
|
1226
|
+
const prevSealedLeaves = Array.isArray(rawPrevSealedLeaves)
|
|
1227
|
+
? rawPrevSealedLeaves.map((h, i) => {
|
|
1228
|
+
const b = hexOrBytesExact(h, 32, `lane[${laneIdx}].prevSealedLeaves[${i}]`);
|
|
1229
|
+
frFromBeBytesStrict(b);
|
|
1230
|
+
return b;
|
|
1231
|
+
})
|
|
1232
|
+
: [];
|
|
1233
|
+
const rawFrontierSubSeq = l.frontierSubSeq !== undefined ? l.frontierSubSeq : l.frontier_sub_seq;
|
|
1234
|
+
const frontierSubSeq = parseU64Decimal(rawFrontierSubSeq, `lane[${laneIdx}].frontierSubSeq`);
|
|
1235
|
+
if (frontierSubSeq > MAX_SUBROOTS_PER_LANE) {
|
|
1236
|
+
throw new Error(`Invalid CompactWalletStore JSON lane[${laneIdx}].frontierSubSeq out of range`);
|
|
1237
|
+
}
|
|
1238
|
+
const rawPrevSealedSubSeq = l.prevSealedSubSeq !== undefined ? l.prevSealedSubSeq : l.prev_sealed_sub_seq;
|
|
1239
|
+
const prevSealedSubSeq = rawPrevSealedSubSeq !== undefined && rawPrevSealedSubSeq !== null
|
|
1240
|
+
? parseU64Decimal(rawPrevSealedSubSeq, `lane[${laneIdx}].prevSealedSubSeq`)
|
|
1241
|
+
: null;
|
|
1242
|
+
if (prevSealedSubSeq !== null && prevSealedSubSeq >= MAX_SUBROOTS_PER_LANE) {
|
|
1243
|
+
throw new Error(`Invalid CompactWalletStore JSON lane[${laneIdx}].prevSealedSubSeq out of range`);
|
|
1244
|
+
}
|
|
1245
|
+
const rawNextMemoLeaf = l.nextMemoLeaf !== undefined ? l.nextMemoLeaf : l.next_memo_leaf;
|
|
1246
|
+
const nextMemoLeaf = parseU64Decimal(rawNextMemoLeaf, `lane[${laneIdx}].nextMemoLeaf`);
|
|
1247
|
+
if (nextMemoLeaf > MAX_LEAVES_PER_LANE) {
|
|
1248
|
+
throw new Error(`Invalid CompactWalletStore JSON lane[${laneIdx}].nextMemoLeaf out of range`);
|
|
1249
|
+
}
|
|
1250
|
+
const rawNextNfIndex = l.nextNfIndex !== undefined ? l.nextNfIndex : l.next_nf_index;
|
|
1251
|
+
const nextNfIndex = parseU64Decimal(rawNextNfIndex, `lane[${laneIdx}].nextNfIndex`);
|
|
1252
|
+
return {
|
|
1253
|
+
finalizedSubroots,
|
|
1254
|
+
frontierSubSeq,
|
|
1255
|
+
frontierLeaves,
|
|
1256
|
+
prevSealedSubSeq,
|
|
1257
|
+
prevSealedLeaves,
|
|
1258
|
+
nextMemoLeaf,
|
|
1259
|
+
nextNfIndex,
|
|
1260
|
+
};
|
|
1261
|
+
});
|
|
1262
|
+
const seenNotes = new Set();
|
|
1263
|
+
store.notes = raw.notes.map((noteRaw, noteIdx) => {
|
|
1264
|
+
if (!noteRaw || typeof noteRaw !== 'object' || Array.isArray(noteRaw)) {
|
|
1265
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}]`);
|
|
1266
|
+
}
|
|
1267
|
+
const n = noteRaw;
|
|
1268
|
+
const notePoolId = n.poolId !== undefined ? n.poolId : n.pool_id;
|
|
1269
|
+
if (typeof notePoolId !== 'number' ||
|
|
1270
|
+
!Number.isInteger(notePoolId) ||
|
|
1271
|
+
notePoolId < 0 ||
|
|
1272
|
+
notePoolId > U32_MAX) {
|
|
1273
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].poolId=${String(notePoolId)}`);
|
|
1274
|
+
}
|
|
1275
|
+
if (notePoolId !== rawPoolId) {
|
|
1276
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].poolId=${notePoolId} does not match store poolId=${rawPoolId}`);
|
|
1277
|
+
}
|
|
1278
|
+
const noteLaneId = n.laneId !== undefined ? n.laneId : n.lane_id;
|
|
1279
|
+
if (typeof noteLaneId !== 'number' ||
|
|
1280
|
+
!Number.isInteger(noteLaneId) ||
|
|
1281
|
+
noteLaneId < 0 ||
|
|
1282
|
+
noteLaneId >= NUM_LANES) {
|
|
1283
|
+
throw new Error(`Invalid CompactWalletStore JSON note laneId=${String(noteLaneId)}`);
|
|
1284
|
+
}
|
|
1285
|
+
const leafIndex = parseU64Decimal(n.leafIndex !== undefined ? n.leafIndex : n.leaf_index, `note[${noteIdx}].leafIndex`);
|
|
1286
|
+
if (leafIndex >= MAX_LEAVES_PER_LANE) {
|
|
1287
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].leafIndex out of range`);
|
|
1288
|
+
}
|
|
1289
|
+
const noteKey = `${noteLaneId}:${leafIndex.toString()}`;
|
|
1290
|
+
if (seenNotes.has(noteKey)) {
|
|
1291
|
+
throw new Error(`Invalid CompactWalletStore JSON: duplicate note at (laneId=${noteLaneId}, leafIndex=${leafIndex})`);
|
|
1292
|
+
}
|
|
1293
|
+
seenNotes.add(noteKey);
|
|
1294
|
+
const globalLeafIndex = parseU64Decimal(n.globalLeafIndex !== undefined ? n.globalLeafIndex : n.global_leaf_index, `note[${noteIdx}].globalLeafIndex`);
|
|
1295
|
+
const expectedGlobalLeaf = (BigInt(noteLaneId) << 36n) | leafIndex;
|
|
1296
|
+
if (globalLeafIndex !== expectedGlobalLeaf) {
|
|
1297
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].globalLeafIndex mismatch`);
|
|
1298
|
+
}
|
|
1299
|
+
const amount = parseU64Decimal(n.amount, `note[${noteIdx}].amount`);
|
|
1300
|
+
const isDynamic = n.isDynamic !== undefined ? n.isDynamic : n.is_dynamic;
|
|
1301
|
+
if (typeof isDynamic !== 'boolean') {
|
|
1302
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].isDynamic`);
|
|
1303
|
+
}
|
|
1304
|
+
if (typeof n.spent !== 'boolean') {
|
|
1305
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].spent`);
|
|
1306
|
+
}
|
|
1307
|
+
const rawPaymentId = n.paymentId !== undefined ? n.paymentId : n.payment_id;
|
|
1308
|
+
const paymentId = rawPaymentId === undefined
|
|
1309
|
+
? new Uint8Array(MEMO_PAYMENT_ID_LEN)
|
|
1310
|
+
: hexOrBytesExact(rawPaymentId, MEMO_PAYMENT_ID_LEN, `note[${noteIdx}].paymentId`);
|
|
1311
|
+
const rawFrozenSibs = n.frozenIntraSiblings !== undefined ? n.frozenIntraSiblings : n.frozen_intra_siblings;
|
|
1312
|
+
const rawFrozenPos = n.frozenIntraPositions !== undefined ? n.frozenIntraPositions : n.frozen_intra_positions;
|
|
1313
|
+
const hasSibs = rawFrozenSibs !== null && rawFrozenSibs !== undefined;
|
|
1314
|
+
const hasPos = rawFrozenPos !== null && rawFrozenPos !== undefined;
|
|
1315
|
+
if (hasSibs !== hasPos) {
|
|
1316
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}]: frozenIntraSiblings and frozenIntraPositions must both be present or both null`);
|
|
1317
|
+
}
|
|
1318
|
+
let frozenIntraSiblings = null;
|
|
1319
|
+
let frozenIntraPositions = null;
|
|
1320
|
+
if (hasSibs && hasPos) {
|
|
1321
|
+
if (!Array.isArray(rawFrozenSibs) ||
|
|
1322
|
+
rawFrozenSibs.length !== SUBTREE_LEVELS_4ARY) {
|
|
1323
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].frozenIntraSiblings length`);
|
|
1324
|
+
}
|
|
1325
|
+
frozenIntraSiblings = rawFrozenSibs.map((lvl, h) => {
|
|
1326
|
+
if (!Array.isArray(lvl) || lvl.length !== 3) {
|
|
1327
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].frozenIntraSiblings[${h}]`);
|
|
1328
|
+
}
|
|
1329
|
+
return lvl.map((entry, k) => {
|
|
1330
|
+
const b = hexOrBytesExact(entry, 32, `note[${noteIdx}].frozenIntraSiblings[${h}][${k}]`);
|
|
1331
|
+
frFromBeBytesStrict(b);
|
|
1332
|
+
return b;
|
|
1333
|
+
});
|
|
1334
|
+
});
|
|
1335
|
+
if (!Array.isArray(rawFrozenPos) ||
|
|
1336
|
+
rawFrozenPos.length !== SUBTREE_LEVELS_4ARY) {
|
|
1337
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].frozenIntraPositions length`);
|
|
1338
|
+
}
|
|
1339
|
+
frozenIntraPositions = rawFrozenPos.map((p, h) => {
|
|
1340
|
+
if (typeof p !== 'number' || !Number.isInteger(p) || p < 0 || p > 3) {
|
|
1341
|
+
throw new Error(`Invalid CompactWalletStore JSON note[${noteIdx}].frozenIntraPositions[${h}]=${String(p)}`);
|
|
1342
|
+
}
|
|
1343
|
+
return p;
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
const tweak = hexOrBytesExact(n.tweak, 32, `note[${noteIdx}].tweak`);
|
|
1347
|
+
const blinding = hexOrBytesExact(n.blinding, 32, `note[${noteIdx}].blinding`);
|
|
1348
|
+
const stealthOwner = hexOrBytesExact(n.stealthOwner !== undefined ? n.stealthOwner : n.stealth_owner, 32, `note[${noteIdx}].stealthOwner`);
|
|
1349
|
+
const commitment = hexOrBytesExact(n.commitment, 32, `note[${noteIdx}].commitment`);
|
|
1350
|
+
const nullifier = hexOrBytesExact(n.nullifier, 32, `note[${noteIdx}].nullifier`);
|
|
1351
|
+
frFromBeBytesStrict(tweak);
|
|
1352
|
+
frFromBeBytesStrict(blinding);
|
|
1353
|
+
frFromBeBytesStrict(stealthOwner);
|
|
1354
|
+
frFromBeBytesStrict(commitment);
|
|
1355
|
+
frFromBeBytesStrict(nullifier);
|
|
1356
|
+
return {
|
|
1357
|
+
poolId: notePoolId,
|
|
1358
|
+
laneId: noteLaneId,
|
|
1359
|
+
leafIndex,
|
|
1360
|
+
globalLeafIndex,
|
|
1361
|
+
mint: hexOrBytesExact(n.mint, 32, `note[${noteIdx}].mint`),
|
|
1362
|
+
amount,
|
|
1363
|
+
tweak,
|
|
1364
|
+
blinding,
|
|
1365
|
+
stealthOwner,
|
|
1366
|
+
commitment,
|
|
1367
|
+
nullifier,
|
|
1368
|
+
paymentId,
|
|
1369
|
+
isDynamic,
|
|
1370
|
+
spent: n.spent,
|
|
1371
|
+
frozenIntraSiblings,
|
|
1372
|
+
frozenIntraPositions,
|
|
1373
|
+
};
|
|
1374
|
+
});
|
|
1375
|
+
// Backwards-compatible migration: honor any legacy `seenNfPrefixes` / `seen_nf_prefixes`
|
|
1376
|
+
// against owned notes, then discard stranger prefixes permanently so RAM & disk stay bounded.
|
|
1377
|
+
const rawSeenNfPrefixes = raw.seenNfPrefixes !== undefined ? raw.seenNfPrefixes : raw.seen_nf_prefixes;
|
|
1378
|
+
if (Array.isArray(rawSeenNfPrefixes) && rawSeenNfPrefixes.length > 0) {
|
|
1379
|
+
const legacySet = new Set();
|
|
1380
|
+
for (const p of rawSeenNfPrefixes) {
|
|
1381
|
+
if (typeof p === 'string' && p.length === NF_PREFIX_LEN * 2 && HEX_RE.test(p)) {
|
|
1382
|
+
legacySet.add(p.toLowerCase());
|
|
1383
|
+
}
|
|
1384
|
+
else if (Array.isArray(p) && p.length === NF_PREFIX_LEN) {
|
|
1385
|
+
try {
|
|
1386
|
+
legacySet.add(bytesToHex(hexOrBytesExact(p, NF_PREFIX_LEN, 'seenNfPrefixes')));
|
|
1387
|
+
}
|
|
1388
|
+
catch {
|
|
1389
|
+
// ignore malformed legacy entry
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
for (const note of store.notes) {
|
|
1394
|
+
if (!note.spent) {
|
|
1395
|
+
const prefHex = bytesToHex(note.nullifier.subarray(0, NF_PREFIX_LEN));
|
|
1396
|
+
if (legacySet.has(prefHex))
|
|
1397
|
+
note.spent = true;
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
return store;
|
|
1402
|
+
}
|
|
1403
|
+
}
|