@aztec-labs/world-state 6.0.0-nightly.20260829

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.
Files changed (86) hide show
  1. package/README.md +40 -0
  2. package/dest/index.d.ts +6 -0
  3. package/dest/index.d.ts.map +1 -0
  4. package/dest/index.js +5 -0
  5. package/dest/instrumentation/instrumentation.d.ts +25 -0
  6. package/dest/instrumentation/instrumentation.d.ts.map +1 -0
  7. package/dest/instrumentation/instrumentation.js +96 -0
  8. package/dest/native/bench_metrics.d.ts +23 -0
  9. package/dest/native/bench_metrics.d.ts.map +1 -0
  10. package/dest/native/bench_metrics.js +81 -0
  11. package/dest/native/fork_checkpoint.d.ts +16 -0
  12. package/dest/native/fork_checkpoint.d.ts.map +1 -0
  13. package/dest/native/fork_checkpoint.js +38 -0
  14. package/dest/native/index.d.ts +4 -0
  15. package/dest/native/index.d.ts.map +1 -0
  16. package/dest/native/index.js +3 -0
  17. package/dest/native/ipc_world_state_instance.d.ts +91 -0
  18. package/dest/native/ipc_world_state_instance.d.ts.map +1 -0
  19. package/dest/native/ipc_world_state_instance.js +672 -0
  20. package/dest/native/merkle_trees_facade.d.ts +58 -0
  21. package/dest/native/merkle_trees_facade.d.ts.map +1 -0
  22. package/dest/native/merkle_trees_facade.js +250 -0
  23. package/dest/native/message.d.ts +145 -0
  24. package/dest/native/message.d.ts.map +1 -0
  25. package/dest/native/message.js +150 -0
  26. package/dest/native/native_world_state.d.ts +77 -0
  27. package/dest/native/native_world_state.d.ts.map +1 -0
  28. package/dest/native/native_world_state.js +350 -0
  29. package/dest/native/native_world_state_instance.d.ts +63 -0
  30. package/dest/native/native_world_state_instance.d.ts.map +1 -0
  31. package/dest/native/native_world_state_instance.js +1 -0
  32. package/dest/native/world_state_operation.d.ts +7 -0
  33. package/dest/native/world_state_operation.d.ts.map +1 -0
  34. package/dest/native/world_state_operation.js +5 -0
  35. package/dest/synchronizer/config.d.ts +31 -0
  36. package/dest/synchronizer/config.d.ts.map +1 -0
  37. package/dest/synchronizer/config.js +61 -0
  38. package/dest/synchronizer/errors.d.ts +11 -0
  39. package/dest/synchronizer/errors.d.ts.map +1 -0
  40. package/dest/synchronizer/errors.js +12 -0
  41. package/dest/synchronizer/factory.d.ts +20 -0
  42. package/dest/synchronizer/factory.d.ts.map +1 -0
  43. package/dest/synchronizer/factory.js +30 -0
  44. package/dest/synchronizer/index.d.ts +4 -0
  45. package/dest/synchronizer/index.d.ts.map +1 -0
  46. package/dest/synchronizer/index.js +3 -0
  47. package/dest/synchronizer/server_world_state_synchronizer.d.ts +83 -0
  48. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -0
  49. package/dest/synchronizer/server_world_state_synchronizer.js +434 -0
  50. package/dest/test/index.d.ts +2 -0
  51. package/dest/test/index.d.ts.map +1 -0
  52. package/dest/test/index.js +1 -0
  53. package/dest/test/utils.d.ts +35 -0
  54. package/dest/test/utils.d.ts.map +1 -0
  55. package/dest/test/utils.js +118 -0
  56. package/dest/testing.d.ts +11 -0
  57. package/dest/testing.d.ts.map +1 -0
  58. package/dest/testing.js +48 -0
  59. package/dest/world-state-db/index.d.ts +3 -0
  60. package/dest/world-state-db/index.d.ts.map +1 -0
  61. package/dest/world-state-db/index.js +1 -0
  62. package/dest/world-state-db/merkle_tree_db.d.ts +65 -0
  63. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -0
  64. package/dest/world-state-db/merkle_tree_db.js +17 -0
  65. package/package.json +98 -0
  66. package/src/index.ts +5 -0
  67. package/src/instrumentation/instrumentation.ts +150 -0
  68. package/src/native/bench_metrics.ts +91 -0
  69. package/src/native/fork_checkpoint.ts +46 -0
  70. package/src/native/index.ts +3 -0
  71. package/src/native/ipc_world_state_instance.ts +849 -0
  72. package/src/native/merkle_trees_facade.ts +375 -0
  73. package/src/native/message.ts +287 -0
  74. package/src/native/native_world_state.ts +435 -0
  75. package/src/native/native_world_state_instance.ts +104 -0
  76. package/src/native/world_state_operation.ts +33 -0
  77. package/src/synchronizer/config.ts +106 -0
  78. package/src/synchronizer/errors.ts +13 -0
  79. package/src/synchronizer/factory.ts +83 -0
  80. package/src/synchronizer/index.ts +3 -0
  81. package/src/synchronizer/server_world_state_synchronizer.ts +525 -0
  82. package/src/test/index.ts +1 -0
  83. package/src/test/utils.ts +184 -0
  84. package/src/testing.ts +65 -0
  85. package/src/world-state-db/index.ts +3 -0
  86. package/src/world-state-db/merkle_tree_db.ts +80 -0
@@ -0,0 +1,672 @@
1
+ import { WsdbService } from '@aztec/wsdb';
2
+ import { ARCHIVE_HEIGHT, DomainSeparator, L1_TO_L2_MSG_TREE_HEIGHT, MAX_NULLIFIERS_PER_TX, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, NOTE_HASH_TREE_HEIGHT, NULLIFIER_TREE_HEIGHT, PUBLIC_DATA_TREE_HEIGHT } from '@aztec-labs/constants';
3
+ import { createLogger } from '@aztec-labs/foundation/log';
4
+ import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
5
+ import { cpus } from 'node:os';
6
+ // ————— Request conversion helpers —————
7
+ function toWsdbRevision(rev) {
8
+ return {
9
+ forkId: rev.forkId,
10
+ blockNumber: Number(rev.blockNumber),
11
+ includeUncommitted: rev.includeUncommitted
12
+ };
13
+ }
14
+ function blockStateRefToMap(ref) {
15
+ return [
16
+ ...ref.entries()
17
+ ].map(([treeId, [root, size]])=>({
18
+ treeId,
19
+ root: new Uint8Array(root),
20
+ size: Number(size)
21
+ }));
22
+ }
23
+ function toPublicDataLeaf(leaf) {
24
+ if (leaf instanceof Buffer || !('slot' in leaf)) {
25
+ throw new Error('Expected public data leaf');
26
+ }
27
+ return {
28
+ slot: new Uint8Array(leaf.slot),
29
+ value: new Uint8Array(leaf.value)
30
+ };
31
+ }
32
+ function toNullifierLeaf(leaf) {
33
+ if (leaf instanceof Buffer || !('nullifier' in leaf)) {
34
+ throw new Error('Expected nullifier leaf');
35
+ }
36
+ return {
37
+ nullifier: new Uint8Array(leaf.nullifier)
38
+ };
39
+ }
40
+ function fromPublicDataLeaf(leaf) {
41
+ return {
42
+ slot: Buffer.from(leaf.slot),
43
+ value: Buffer.from(leaf.value)
44
+ };
45
+ }
46
+ function fromNullifierLeaf(leaf) {
47
+ return {
48
+ nullifier: Buffer.from(leaf.nullifier)
49
+ };
50
+ }
51
+ function fromIndexedLeaf(leaf, convertLeaf) {
52
+ return {
53
+ leaf: convertLeaf(leaf.leaf),
54
+ nextIndex: leaf.nextIndex,
55
+ nextKey: Buffer.from(leaf.nextKey)
56
+ };
57
+ }
58
+ function fromLeafUpdateWitnessData(data, convertLeaf) {
59
+ return {
60
+ leaf: fromIndexedLeaf(data.leaf, convertLeaf),
61
+ index: data.index,
62
+ path: data.path.map((p)=>Buffer.from(p))
63
+ };
64
+ }
65
+ function fromBatchInsertionResult(result, convertLeaf) {
66
+ return {
67
+ lowLeafWitnessData: result.lowLeafWitnessData.map((data)=>fromLeafUpdateWitnessData(data, convertLeaf)),
68
+ sortedLeaves: result.sortedLeaves.map(({ leaf, index })=>[
69
+ convertLeaf(leaf),
70
+ index
71
+ ]),
72
+ subtreePath: result.subtreePath.map((p)=>Buffer.from(p))
73
+ };
74
+ }
75
+ function fromSequentialInsertionResult(result, convertLeaf) {
76
+ return {
77
+ lowLeafWitnessData: result.lowLeafWitnessData.map((data)=>fromLeafUpdateWitnessData(data, convertLeaf)),
78
+ insertionWitnessData: result.insertionWitnessData.map((data)=>fromLeafUpdateWitnessData(data, convertLeaf))
79
+ };
80
+ }
81
+ function toFrLeaf(leaf) {
82
+ if (!(leaf instanceof Buffer)) {
83
+ throw new Error('Expected field leaf');
84
+ }
85
+ return new Uint8Array(leaf);
86
+ }
87
+ function formatMap(map) {
88
+ if (!map || Object.keys(map).length === 0) {
89
+ return undefined;
90
+ }
91
+ return `{${Object.entries(map).map(([key, value])=>`${key}:${value}`).join(',')}}`;
92
+ }
93
+ /** SHM request/response ring size for the spawned aztec-wsdb process (32 MiB). */ const WSDB_SHM_RING_SIZE = 32 * 1024 * 1024;
94
+ function getWsdbThreadCount() {
95
+ return Math.min(16, cpus().length);
96
+ }
97
+ function getWsdbExtraArgs(dataDir, wsTreeMapSizes, genesis, threads) {
98
+ const options = getWsdbOptions(dataDir, wsTreeMapSizes);
99
+ const args = [
100
+ '--data-dir',
101
+ dataDir,
102
+ '--threads',
103
+ threads.toString()
104
+ ];
105
+ // Size the SHM rings generously. Responses such as batch-insertion witnesses
106
+ // run to a few MB, and an SHM frame is capped at half the ring (the wrap
107
+ // handling needs that headroom), so 32 MiB rings give ~16 MiB per message.
108
+ // Ignored by the UDS transport. Pages are demand-faulted, so unused capacity
109
+ // is cheap.
110
+ args.push('--request-ring-size', WSDB_SHM_RING_SIZE.toString());
111
+ args.push('--response-ring-size', WSDB_SHM_RING_SIZE.toString());
112
+ const treeHeights = formatMap(options.treeHeights);
113
+ if (treeHeights) {
114
+ args.push('--tree-heights', treeHeights);
115
+ }
116
+ const treePrefill = formatMap(options.treePrefill);
117
+ if (treePrefill) {
118
+ args.push('--tree-prefill', treePrefill);
119
+ }
120
+ const mapSizes = formatMap(options.mapSizes);
121
+ if (mapSizes) {
122
+ args.push('--map-sizes', mapSizes);
123
+ }
124
+ args.push('--initial-header-generator-point', options.initialHeaderGeneratorPoint.toString());
125
+ if (genesis.prefilledPublicData.length > 0) {
126
+ const pairs = genesis.prefilledPublicData.map((data)=>[
127
+ data.slot.toBuffer().toString('hex'),
128
+ data.value.toBuffer().toString('hex')
129
+ ]);
130
+ args.push('--prefilled-public-data', JSON.stringify(pairs));
131
+ }
132
+ const prefilledNullifiers = genesis.prefilledNullifiers ?? [];
133
+ for(let i = 1; i < prefilledNullifiers.length; i++){
134
+ if (prefilledNullifiers[i].toBigInt() <= prefilledNullifiers[i - 1].toBigInt()) {
135
+ throw new Error('Prefilled genesis nullifiers must be unique and strictly increasing');
136
+ }
137
+ }
138
+ if (prefilledNullifiers.length > 0) {
139
+ args.push('--prefilled-nullifiers', JSON.stringify(prefilledNullifiers.map((nullifier)=>nullifier.toBuffer().toString('hex'))));
140
+ }
141
+ const genesisTimestamp = Number(genesis.genesisTimestamp);
142
+ if (genesisTimestamp !== 0) {
143
+ args.push('--genesis-timestamp', genesisTimestamp.toString());
144
+ }
145
+ return args;
146
+ }
147
+ // ————— Response conversion helpers —————
148
+ /** Convert Uint8Array fields to Buffer recursively (for opaque blob responses). */ function convertUint8ArraysToBuffers(obj) {
149
+ if (obj instanceof Uint8Array) {
150
+ return Buffer.from(obj);
151
+ }
152
+ if (Array.isArray(obj)) {
153
+ return obj.map(convertUint8ArraysToBuffers);
154
+ }
155
+ if (obj !== null && typeof obj === 'object') {
156
+ const result = {};
157
+ for (const [key, value] of Object.entries(obj)){
158
+ result[key] = convertUint8ArraysToBuffers(value);
159
+ }
160
+ return result;
161
+ }
162
+ return obj;
163
+ }
164
+ /** Convert Wsdb state reference (Record<number, [Uint8Array, number]>) to NAPI format. */ function convertStateRef(state) {
165
+ const result = {};
166
+ for (const { treeId, root, size } of state){
167
+ result[treeId] = [
168
+ Buffer.from(root),
169
+ BigInt(size)
170
+ ];
171
+ }
172
+ return result;
173
+ }
174
+ /** Convert Wsdb WorldStateStatusSummary to the native world-state format. */ function convertStatusSummary(s) {
175
+ return {
176
+ unfinalizedBlockNumber: s.unfinalizedBlockNumber,
177
+ finalizedBlockNumber: s.finalizedBlockNumber,
178
+ oldestHistoricalBlock: s.oldestHistoricalBlock,
179
+ treesAreSynched: s.treesAreSynched
180
+ };
181
+ }
182
+ function convertDBStats(s) {
183
+ return {
184
+ name: s.name,
185
+ numDataItems: s.numDataItems,
186
+ totalUsedSize: s.totalUsedSize
187
+ };
188
+ }
189
+ function convertTreeDBStats(s) {
190
+ return {
191
+ mapSize: s.mapSize,
192
+ physicalFileSize: s.physicalFileSize,
193
+ blocksDBStats: convertDBStats(s.blocksDBStats),
194
+ nodesDBStats: convertDBStats(s.nodesDBStats),
195
+ leafPreimagesDBStats: convertDBStats(s.leafPreimagesDBStats),
196
+ leafIndicesDBStats: convertDBStats(s.leafIndicesDBStats),
197
+ blockIndicesDBStats: convertDBStats(s.blockIndicesDBStats)
198
+ };
199
+ }
200
+ function convertWorldStateDBStats(s) {
201
+ return {
202
+ noteHashTreeStats: convertTreeDBStats(s.noteHashTreeStats),
203
+ messageTreeStats: convertTreeDBStats(s.messageTreeStats),
204
+ archiveTreeStats: convertTreeDBStats(s.archiveTreeStats),
205
+ publicDataTreeStats: convertTreeDBStats(s.publicDataTreeStats),
206
+ nullifierTreeStats: convertTreeDBStats(s.nullifierTreeStats)
207
+ };
208
+ }
209
+ function convertTreeMeta(m) {
210
+ return {
211
+ name: m.name,
212
+ depth: m.depth,
213
+ size: m.size,
214
+ committedSize: m.committedSize,
215
+ root: m.root,
216
+ initialSize: m.initialSize,
217
+ initialRoot: m.initialRoot,
218
+ oldestHistoricBlock: m.oldestHistoricBlock,
219
+ unfinalizedBlockHeight: m.unfinalizedBlockHeight,
220
+ finalizedBlockHeight: m.finalizedBlockHeight
221
+ };
222
+ }
223
+ function convertWorldStateMeta(m) {
224
+ return {
225
+ noteHashTreeMeta: convertTreeMeta(m.noteHashTreeMeta),
226
+ messageTreeMeta: convertTreeMeta(m.messageTreeMeta),
227
+ archiveTreeMeta: convertTreeMeta(m.archiveTreeMeta),
228
+ publicDataTreeMeta: convertTreeMeta(m.publicDataTreeMeta),
229
+ nullifierTreeMeta: convertTreeMeta(m.nullifierTreeMeta)
230
+ };
231
+ }
232
+ function convertStatusFull(s) {
233
+ return {
234
+ summary: convertStatusSummary(s.summary),
235
+ dbStats: convertWorldStateDBStats(s.dbStats),
236
+ meta: convertWorldStateMeta(s.meta)
237
+ };
238
+ }
239
+ /** Convert Wsdb SiblingPathAndIndex to NAPI format. */ function convertSiblingPathAndIndex(s) {
240
+ if (!s) {
241
+ return undefined;
242
+ }
243
+ return {
244
+ index: BigInt(s.index),
245
+ path: s.path.map((p)=>Buffer.from(p))
246
+ };
247
+ }
248
+ // ————— Public API —————
249
+ /**
250
+ * IPC-backed world state instance.
251
+ * Uses WsdbService (spawns aztec-wsdb binary) and the generated AsyncApi
252
+ * to communicate via the NamedUnion IPC protocol.
253
+ */ export class IpcWorldState {
254
+ wsdb;
255
+ instrumentation;
256
+ log;
257
+ open;
258
+ api;
259
+ /** Tracks checkpoint depth per fork (WSDB IPC doesn't return depth in response). */ checkpointDepths;
260
+ constructor(wsdb, instrumentation, bindings, log = createLogger('world-state:ipc-database', bindings)){
261
+ this.wsdb = wsdb;
262
+ this.instrumentation = instrumentation;
263
+ this.log = log;
264
+ this.open = true;
265
+ this.checkpointDepths = new Map();
266
+ this.api = wsdb;
267
+ this.log.info('Created IPC-backed world state instance');
268
+ }
269
+ /**
270
+ * Spawn an `aztec-wsdb` subprocess and return an IPC-backed world state wrapping it.
271
+ * Encapsulates wsdb binary discovery, service construction, and connection. wsdb listens before it
272
+ * initializes its database, so spawn resolves as soon as the socket is up and the first calls block
273
+ * until initialization completes.
274
+ */ static async spawn(dataDir, wsTreeMapSizes, genesis, instrumentation, bindings, threads = getWsdbThreadCount()) {
275
+ const transport = process.env.WSDB_TRANSPORT === 'shm' ? 'shm' : 'uds';
276
+ const wsdb = await WsdbService.spawn({
277
+ transport,
278
+ extraArgs: getWsdbExtraArgs(dataDir, wsTreeMapSizes, genesis, threads),
279
+ env: {
280
+ HARDWARE_CONCURRENCY: threads.toString()
281
+ }
282
+ });
283
+ return new IpcWorldState(wsdb, instrumentation, bindings);
284
+ }
285
+ getIpcPath() {
286
+ return this.wsdb.getIpcPath();
287
+ }
288
+ async close() {
289
+ if (!this.open) {
290
+ return;
291
+ }
292
+ this.open = false;
293
+ await this.wsdb.destroy();
294
+ }
295
+ getTreeInfo(treeId, revision) {
296
+ return this.execute('getTreeInfo', revision.forkId, revision.includeUncommitted === false, async ()=>{
297
+ const resp = await this.api.getTreeInfo({
298
+ treeId,
299
+ revision: toWsdbRevision(revision)
300
+ });
301
+ return {
302
+ treeId: resp.treeId,
303
+ root: Buffer.from(resp.root),
304
+ size: BigInt(resp.size),
305
+ depth: resp.depth
306
+ };
307
+ });
308
+ }
309
+ getStateReference(revision) {
310
+ return this.execute('getStateReference', revision.forkId, revision.includeUncommitted === false, async ()=>{
311
+ const resp = await this.api.getStateReference({
312
+ revision: toWsdbRevision(revision)
313
+ });
314
+ return convertStateRef(resp.state);
315
+ });
316
+ }
317
+ getInitialStateReference() {
318
+ return this.execute('getInitialStateReference', 0, false, async ()=>{
319
+ const resp = await this.api.getInitialStateReference({});
320
+ return convertStateRef(resp.state);
321
+ });
322
+ }
323
+ getLeafValue(treeId, revision, leafIndex) {
324
+ return this.execute('getLeafValue', revision.forkId, revision.includeUncommitted === false, async ()=>{
325
+ const wsdbRevision = toWsdbRevision(revision);
326
+ const wsdbLeafIndex = Number(leafIndex);
327
+ if (treeId === MerkleTreeId.PUBLIC_DATA_TREE) {
328
+ const resp = await this.api.getPublicDataLeafValue({
329
+ revision: wsdbRevision,
330
+ leafIndex: wsdbLeafIndex
331
+ });
332
+ return resp.value ? fromPublicDataLeaf(resp.value) : undefined;
333
+ }
334
+ if (treeId === MerkleTreeId.NULLIFIER_TREE) {
335
+ const resp = await this.api.getNullifierLeafValue({
336
+ revision: wsdbRevision,
337
+ leafIndex: wsdbLeafIndex
338
+ });
339
+ return resp.value ? fromNullifierLeaf(resp.value) : undefined;
340
+ }
341
+ const resp = await this.api.getLeafValue({
342
+ treeId,
343
+ revision: wsdbRevision,
344
+ leafIndex: wsdbLeafIndex
345
+ });
346
+ return resp.value ? Buffer.from(resp.value) : undefined;
347
+ });
348
+ }
349
+ getLeafPreimage(treeId, revision, leafIndex) {
350
+ return this.execute('getLeafPreimage', revision.forkId, revision.includeUncommitted === false, async ()=>{
351
+ const resp = treeId === MerkleTreeId.PUBLIC_DATA_TREE ? await this.api.getPublicDataLeafPreimage({
352
+ revision: toWsdbRevision(revision),
353
+ leafIndex: Number(leafIndex)
354
+ }) : await this.api.getNullifierLeafPreimage({
355
+ revision: toWsdbRevision(revision),
356
+ leafIndex: Number(leafIndex)
357
+ });
358
+ return resp.preimage ? convertUint8ArraysToBuffers(resp.preimage) : undefined;
359
+ });
360
+ }
361
+ getSiblingPath(treeId, revision, leafIndex) {
362
+ return this.execute('getSiblingPath', revision.forkId, revision.includeUncommitted === false, async ()=>{
363
+ const resp = await this.api.getSiblingPath({
364
+ treeId,
365
+ revision: toWsdbRevision(revision),
366
+ leafIndex: Number(leafIndex)
367
+ });
368
+ return resp.path.map((p)=>Buffer.from(p));
369
+ });
370
+ }
371
+ getBlockNumbersForLeafIndices(treeId, revision, leafIndices) {
372
+ return this.execute('getBlockNumbersForLeafIndices', revision.forkId, revision.includeUncommitted === false, async ()=>{
373
+ const resp = await this.api.getBlockNumbersForLeafIndices({
374
+ treeId,
375
+ revision: toWsdbRevision(revision),
376
+ leafIndices: leafIndices.map(Number)
377
+ });
378
+ return resp.blockNumbers.map((n)=>n != null ? BigInt(n) : undefined);
379
+ });
380
+ }
381
+ findLeafIndices(treeId, revision, leaves, startIndex) {
382
+ return this.execute('findLeafIndices', revision.forkId, revision.includeUncommitted === false, async ()=>{
383
+ const wsdbRevision = toWsdbRevision(revision);
384
+ const wsdbStartIndex = Number(startIndex);
385
+ const resp = treeId === MerkleTreeId.PUBLIC_DATA_TREE ? await this.api.findPublicDataLeafIndices({
386
+ revision: wsdbRevision,
387
+ leaves: leaves.map(toPublicDataLeaf),
388
+ startIndex: wsdbStartIndex
389
+ }) : treeId === MerkleTreeId.NULLIFIER_TREE ? await this.api.findNullifierLeafIndices({
390
+ revision: wsdbRevision,
391
+ leaves: leaves.map(toNullifierLeaf),
392
+ startIndex: wsdbStartIndex
393
+ }) : await this.api.findLeafIndices({
394
+ treeId,
395
+ revision: wsdbRevision,
396
+ leaves: leaves.map(toFrLeaf),
397
+ startIndex: wsdbStartIndex
398
+ });
399
+ return resp.indices.map((n)=>n != null ? BigInt(n) : undefined);
400
+ });
401
+ }
402
+ findLowLeaf(treeId, revision, key) {
403
+ return this.execute('findLowLeaf', revision.forkId, revision.includeUncommitted === false, async ()=>{
404
+ const resp = await this.api.findLowLeaf({
405
+ treeId,
406
+ revision: toWsdbRevision(revision),
407
+ key: new Uint8Array(key.toBuffer())
408
+ });
409
+ return {
410
+ alreadyPresent: resp.alreadyPresent,
411
+ index: BigInt(resp.index)
412
+ };
413
+ });
414
+ }
415
+ findSiblingPaths(treeId, revision, leaves) {
416
+ return this.execute('findSiblingPaths', revision.forkId, revision.includeUncommitted === false, async ()=>{
417
+ const wsdbRevision = toWsdbRevision(revision);
418
+ const resp = treeId === MerkleTreeId.PUBLIC_DATA_TREE ? await this.api.findPublicDataSiblingPaths({
419
+ revision: wsdbRevision,
420
+ leaves: leaves.map(toPublicDataLeaf)
421
+ }) : treeId === MerkleTreeId.NULLIFIER_TREE ? await this.api.findNullifierSiblingPaths({
422
+ revision: wsdbRevision,
423
+ leaves: leaves.map(toNullifierLeaf)
424
+ }) : await this.api.findSiblingPaths({
425
+ treeId,
426
+ revision: wsdbRevision,
427
+ leaves: leaves.map(toFrLeaf)
428
+ });
429
+ return resp.paths.map(convertSiblingPathAndIndex);
430
+ });
431
+ }
432
+ updateArchive(forkId, blockStateRef, blockHeaderHash) {
433
+ return this.execute('updateArchive', forkId, false, async ()=>{
434
+ await this.api.updateArchive({
435
+ blockStateRef: blockStateRefToMap(blockStateRef),
436
+ blockHeaderHash: new Uint8Array(blockHeaderHash),
437
+ forkId
438
+ });
439
+ });
440
+ }
441
+ appendLeaves(treeId, forkId, leaves) {
442
+ return this.execute('appendLeaves', forkId, false, async ()=>{
443
+ if (treeId === MerkleTreeId.PUBLIC_DATA_TREE) {
444
+ await this.api.appendPublicDataLeaves({
445
+ leaves: leaves.map(toPublicDataLeaf),
446
+ forkId
447
+ });
448
+ } else if (treeId === MerkleTreeId.NULLIFIER_TREE) {
449
+ await this.api.appendNullifierLeaves({
450
+ leaves: leaves.map(toNullifierLeaf),
451
+ forkId
452
+ });
453
+ } else {
454
+ await this.api.appendLeaves({
455
+ treeId,
456
+ leaves: leaves.map(toFrLeaf),
457
+ forkId
458
+ });
459
+ }
460
+ });
461
+ }
462
+ batchInsert(treeId, forkId, leaves, subtreeDepth) {
463
+ return this.execute('batchInsert', forkId, false, async ()=>{
464
+ const resp = treeId === MerkleTreeId.PUBLIC_DATA_TREE ? await this.api.batchInsertPublicData({
465
+ leaves: leaves.map(toPublicDataLeaf),
466
+ subtreeDepth,
467
+ forkId
468
+ }) : await this.api.batchInsertNullifier({
469
+ leaves: leaves.map(toNullifierLeaf),
470
+ subtreeDepth,
471
+ forkId
472
+ });
473
+ return treeId === MerkleTreeId.PUBLIC_DATA_TREE ? fromBatchInsertionResult(resp.result, fromPublicDataLeaf) : fromBatchInsertionResult(resp.result, fromNullifierLeaf);
474
+ });
475
+ }
476
+ sequentialInsert(treeId, forkId, leaves) {
477
+ return this.execute('sequentialInsert', forkId, false, async ()=>{
478
+ const resp = treeId === MerkleTreeId.PUBLIC_DATA_TREE ? await this.api.sequentialInsertPublicData({
479
+ leaves: leaves.map(toPublicDataLeaf),
480
+ forkId
481
+ }) : await this.api.sequentialInsertNullifier({
482
+ leaves: leaves.map(toNullifierLeaf),
483
+ forkId
484
+ });
485
+ return treeId === MerkleTreeId.PUBLIC_DATA_TREE ? fromSequentialInsertionResult(resp.result, fromPublicDataLeaf) : fromSequentialInsertionResult(resp.result, fromNullifierLeaf);
486
+ });
487
+ }
488
+ syncBlock(input) {
489
+ return this.execute('syncBlock', 0, false, async ()=>{
490
+ const resp = await this.api.syncBlock({
491
+ blockNumber: Number(input.blockNumber),
492
+ blockStateRef: blockStateRefToMap(input.blockStateRef),
493
+ blockHeaderHash: new Uint8Array(input.blockHeaderHash),
494
+ expectedArchiveRoot: new Uint8Array(input.expectedArchiveRoot),
495
+ expectedPreviousArchiveRoot: new Uint8Array(input.expectedPreviousArchiveRoot),
496
+ paddedNoteHashes: input.paddedNoteHashes.map(toFrLeaf),
497
+ paddedL1ToL2Messages: input.paddedL1ToL2Messages.map(toFrLeaf),
498
+ paddedNullifiers: input.paddedNullifiers.map(toNullifierLeaf),
499
+ publicDataWrites: input.publicDataWrites.map(toPublicDataLeaf)
500
+ });
501
+ return convertStatusFull(resp.status);
502
+ });
503
+ }
504
+ createFork(input) {
505
+ return this.execute('createFork', 0, false, async ()=>{
506
+ const resp = await this.api.createFork({
507
+ latest: input.latest,
508
+ blockNumber: Number(input.blockNumber)
509
+ });
510
+ return resp.forkId;
511
+ });
512
+ }
513
+ deleteFork(forkId) {
514
+ return this.execute('deleteFork', forkId, false, async ()=>{
515
+ await this.api.deleteFork({
516
+ forkId
517
+ });
518
+ });
519
+ }
520
+ finalizeBlocks(toBlockNumber) {
521
+ return this.execute('finalizeBlocks', 0, false, async ()=>{
522
+ const resp = await this.api.finalizeBlocks({
523
+ toBlockNumber: Number(toBlockNumber)
524
+ });
525
+ return convertStatusSummary(resp.status);
526
+ });
527
+ }
528
+ unwindBlocks(toBlockNumber) {
529
+ return this.execute('unwindBlocks', 0, false, async ()=>{
530
+ const resp = await this.api.unwindBlocks({
531
+ toBlockNumber: Number(toBlockNumber)
532
+ });
533
+ return convertStatusFull(resp.status);
534
+ });
535
+ }
536
+ removeHistoricalBlocks(toBlockNumber) {
537
+ return this.execute('removeHistoricalBlocks', 0, false, async ()=>{
538
+ const resp = await this.api.removeHistoricalBlocks({
539
+ toBlockNumber: Number(toBlockNumber)
540
+ });
541
+ return convertStatusFull(resp.status);
542
+ });
543
+ }
544
+ getStatus() {
545
+ return this.execute('getStatus', 0, false, async ()=>{
546
+ const resp = await this.api.getStatus({});
547
+ return convertStatusSummary(resp.status);
548
+ });
549
+ }
550
+ createCheckpoint(forkId) {
551
+ return this.execute('createCheckpoint', forkId, false, async ()=>{
552
+ await this.api.createCheckpoint({
553
+ forkId
554
+ });
555
+ const depth = (this.checkpointDepths.get(forkId) ?? 0) + 1;
556
+ this.checkpointDepths.set(forkId, depth);
557
+ return depth;
558
+ });
559
+ }
560
+ commitCheckpoint(forkId) {
561
+ return this.execute('commitCheckpoint', forkId, false, async ()=>{
562
+ await this.api.commitCheckpoint({
563
+ forkId
564
+ });
565
+ const depth = Math.max(0, (this.checkpointDepths.get(forkId) ?? 0) - 1);
566
+ this.checkpointDepths.set(forkId, depth);
567
+ });
568
+ }
569
+ revertCheckpoint(forkId) {
570
+ return this.execute('revertCheckpoint', forkId, false, async ()=>{
571
+ await this.api.revertCheckpoint({
572
+ forkId
573
+ });
574
+ const depth = Math.max(0, (this.checkpointDepths.get(forkId) ?? 0) - 1);
575
+ this.checkpointDepths.set(forkId, depth);
576
+ });
577
+ }
578
+ commitAllCheckpoints(forkId, depth) {
579
+ return this.execute('commitAllCheckpoints', forkId, false, async ()=>{
580
+ const currentDepth = this.checkpointDepths.get(forkId) ?? 0;
581
+ if (depth === 0) {
582
+ await this.api.commitAllCheckpoints({
583
+ forkId
584
+ });
585
+ } else {
586
+ for(let d = currentDepth; d > depth; d--){
587
+ await this.api.commitCheckpoint({
588
+ forkId
589
+ });
590
+ }
591
+ }
592
+ this.checkpointDepths.set(forkId, depth);
593
+ });
594
+ }
595
+ revertAllCheckpoints(forkId, depth) {
596
+ return this.execute('revertAllCheckpoints', forkId, false, async ()=>{
597
+ const currentDepth = this.checkpointDepths.get(forkId) ?? 0;
598
+ if (depth === 0) {
599
+ await this.api.revertAllCheckpoints({
600
+ forkId
601
+ });
602
+ } else {
603
+ for(let d = currentDepth; d > depth; d--){
604
+ await this.api.revertCheckpoint({
605
+ forkId
606
+ });
607
+ }
608
+ }
609
+ this.checkpointDepths.set(forkId, depth);
610
+ });
611
+ }
612
+ copyStores(dstPath, compact) {
613
+ return this.execute('copyStores', 0, false, async ()=>{
614
+ await this.api.copyStores({
615
+ dstPath,
616
+ compact
617
+ });
618
+ });
619
+ }
620
+ // Read/write ordering is enforced server-side by the wsdb per-fork scheduler,
621
+ // so the client no longer queues: every op is sent immediately and the server
622
+ // serializes writes per fork while running reads concurrently. `_forkId` and
623
+ // `_committedOnly` are retained in the signature (they describe the op) but are
624
+ // no longer needed for client-side ordering.
625
+ async execute(operation, _forkId, _committedOnly, request) {
626
+ if (!this.open) {
627
+ throw new Error('IPC instance is closed');
628
+ }
629
+ return await this.send(operation, request);
630
+ }
631
+ async send(operation, request) {
632
+ const start = performance.now();
633
+ try {
634
+ const response = await request();
635
+ const durationMs = performance.now() - start;
636
+ this.log.trace(`Call ${operation} took (ms)`, {
637
+ duration: durationMs
638
+ });
639
+ this.instrumentation.recordRoundTrip(durationMs * 1000, operation);
640
+ return response;
641
+ } catch (error) {
642
+ this.log.error(`Call ${operation} failed: ${error}`, error);
643
+ throw error;
644
+ }
645
+ }
646
+ }
647
+ /**
648
+ * Helper to create WsdbOptions from standard world state config.
649
+ * Returns the options needed to construct a wsdb service command line.
650
+ */ export function getWsdbOptions(dataDir, wsTreeMapSizes) {
651
+ return {
652
+ treeHeights: {
653
+ [MerkleTreeId.NULLIFIER_TREE]: NULLIFIER_TREE_HEIGHT,
654
+ [MerkleTreeId.NOTE_HASH_TREE]: NOTE_HASH_TREE_HEIGHT,
655
+ [MerkleTreeId.PUBLIC_DATA_TREE]: PUBLIC_DATA_TREE_HEIGHT,
656
+ [MerkleTreeId.L1_TO_L2_MESSAGE_TREE]: L1_TO_L2_MSG_TREE_HEIGHT,
657
+ [MerkleTreeId.ARCHIVE]: ARCHIVE_HEIGHT
658
+ },
659
+ treePrefill: {
660
+ [MerkleTreeId.NULLIFIER_TREE]: 2 * MAX_NULLIFIERS_PER_TX,
661
+ [MerkleTreeId.PUBLIC_DATA_TREE]: 2 * MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX
662
+ },
663
+ mapSizes: {
664
+ [MerkleTreeId.NULLIFIER_TREE]: wsTreeMapSizes.nullifierTreeMapSizeKb,
665
+ [MerkleTreeId.NOTE_HASH_TREE]: wsTreeMapSizes.noteHashTreeMapSizeKb,
666
+ [MerkleTreeId.PUBLIC_DATA_TREE]: wsTreeMapSizes.publicDataTreeMapSizeKb,
667
+ [MerkleTreeId.L1_TO_L2_MESSAGE_TREE]: wsTreeMapSizes.messageTreeMapSizeKb,
668
+ [MerkleTreeId.ARCHIVE]: wsTreeMapSizes.archiveTreeMapSizeKb
669
+ },
670
+ initialHeaderGeneratorPoint: DomainSeparator.BLOCK_HEADER_HASH
671
+ };
672
+ }