@aztec/world-state 0.0.0-test.1 → 0.0.1-commit.017a351

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 (69) hide show
  1. package/dest/index.d.ts +1 -1
  2. package/dest/instrumentation/instrumentation.d.ts +6 -4
  3. package/dest/instrumentation/instrumentation.d.ts.map +1 -1
  4. package/dest/instrumentation/instrumentation.js +25 -41
  5. package/dest/native/bench_metrics.d.ts +23 -0
  6. package/dest/native/bench_metrics.d.ts.map +1 -0
  7. package/dest/native/bench_metrics.js +81 -0
  8. package/dest/native/fork_checkpoint.d.ts +7 -1
  9. package/dest/native/fork_checkpoint.d.ts.map +1 -1
  10. package/dest/native/fork_checkpoint.js +15 -3
  11. package/dest/native/index.d.ts +1 -1
  12. package/dest/native/ipc_world_state_instance.d.ts +45 -0
  13. package/dest/native/ipc_world_state_instance.d.ts.map +1 -0
  14. package/dest/native/ipc_world_state_instance.js +750 -0
  15. package/dest/native/merkle_trees_facade.d.ts +25 -9
  16. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  17. package/dest/native/merkle_trees_facade.js +109 -25
  18. package/dest/native/message.d.ts +87 -58
  19. package/dest/native/message.d.ts.map +1 -1
  20. package/dest/native/message.js +61 -61
  21. package/dest/native/native_world_state.d.ts +41 -21
  22. package/dest/native/native_world_state.d.ts.map +1 -1
  23. package/dest/native/native_world_state.js +177 -50
  24. package/dest/native/native_world_state_instance.d.ts +23 -25
  25. package/dest/native/native_world_state_instance.d.ts.map +1 -1
  26. package/dest/native/native_world_state_instance.js +8 -163
  27. package/dest/native/world_state_ops_queue.d.ts +1 -1
  28. package/dest/native/world_state_ops_queue.d.ts.map +1 -1
  29. package/dest/native/world_state_ops_queue.js +6 -6
  30. package/dest/synchronizer/config.d.ts +14 -6
  31. package/dest/synchronizer/config.d.ts.map +1 -1
  32. package/dest/synchronizer/config.js +36 -14
  33. package/dest/synchronizer/errors.d.ts +4 -0
  34. package/dest/synchronizer/errors.d.ts.map +1 -0
  35. package/dest/synchronizer/errors.js +5 -0
  36. package/dest/synchronizer/factory.d.ts +13 -5
  37. package/dest/synchronizer/factory.d.ts.map +1 -1
  38. package/dest/synchronizer/factory.js +15 -9
  39. package/dest/synchronizer/index.d.ts +1 -1
  40. package/dest/synchronizer/server_world_state_synchronizer.d.ts +21 -31
  41. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  42. package/dest/synchronizer/server_world_state_synchronizer.js +220 -96
  43. package/dest/test/index.d.ts +1 -1
  44. package/dest/test/utils.d.ts +12 -5
  45. package/dest/test/utils.d.ts.map +1 -1
  46. package/dest/test/utils.js +54 -47
  47. package/dest/testing.d.ts +6 -5
  48. package/dest/testing.d.ts.map +1 -1
  49. package/dest/testing.js +15 -15
  50. package/dest/world-state-db/index.d.ts +1 -1
  51. package/dest/world-state-db/merkle_tree_db.d.ts +12 -18
  52. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  53. package/package.json +27 -25
  54. package/src/instrumentation/instrumentation.ts +31 -43
  55. package/src/native/bench_metrics.ts +91 -0
  56. package/src/native/fork_checkpoint.ts +19 -3
  57. package/src/native/ipc_world_state_instance.ts +863 -0
  58. package/src/native/merkle_trees_facade.ts +127 -33
  59. package/src/native/message.ts +109 -80
  60. package/src/native/native_world_state.ts +207 -64
  61. package/src/native/native_world_state_instance.ts +28 -223
  62. package/src/native/world_state_ops_queue.ts +6 -6
  63. package/src/synchronizer/config.ts +58 -20
  64. package/src/synchronizer/errors.ts +5 -0
  65. package/src/synchronizer/factory.ts +48 -18
  66. package/src/synchronizer/server_world_state_synchronizer.ts +249 -121
  67. package/src/test/utils.ts +92 -82
  68. package/src/testing.ts +11 -16
  69. package/src/world-state-db/merkle_tree_db.ts +16 -18
@@ -1,238 +1,43 @@
1
- import {
2
- ARCHIVE_HEIGHT,
3
- GeneratorIndex,
4
- L1_TO_L2_MSG_TREE_HEIGHT,
5
- MAX_NULLIFIERS_PER_TX,
6
- MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
7
- NOTE_HASH_TREE_HEIGHT,
8
- NULLIFIER_TREE_HEIGHT,
9
- PUBLIC_DATA_TREE_HEIGHT,
10
- } from '@aztec/constants';
11
- import { createLogger } from '@aztec/foundation/log';
12
- import { NativeWorldState as BaseNativeWorldState, MsgpackChannel } from '@aztec/native';
13
- import { MerkleTreeId } from '@aztec/stdlib/trees';
14
- import type { PublicDataTreeLeaf } from '@aztec/stdlib/trees';
15
-
16
- import assert from 'assert';
17
- import { cpus } from 'os';
18
-
19
- import type { WorldStateInstrumentation } from '../instrumentation/instrumentation.js';
20
- import {
1
+ import type {
21
2
  WorldStateMessageType,
22
- type WorldStateRequest,
23
- type WorldStateRequestCategories,
24
- type WorldStateResponse,
25
- isWithCanonical,
26
- isWithForkId,
27
- isWithRevision,
3
+ WorldStateRequest,
4
+ WorldStateRequestCategories,
5
+ WorldStateResponse,
28
6
  } from './message.js';
29
- import { WorldStateOpsQueue } from './world_state_ops_queue.js';
30
-
31
- const MAX_WORLD_STATE_THREADS = +(process.env.HARDWARE_CONCURRENCY || '16');
32
7
 
8
+ /**
9
+ * Backend-agnostic handle to a running aztec-wsdb world state, accessed by the TS layer.
10
+ *
11
+ * Two implementations exist:
12
+ * - {@link IpcWorldState} — talks to a standalone aztec-wsdb process over UDS or shared memory.
13
+ *
14
+ * The legacy in-process NAPI implementation has been removed; the C++ AVM (NAPI) now connects to
15
+ * the same aztec-wsdb process via UDS using the socket path returned by {@link getSocketPath}.
16
+ */
33
17
  export interface NativeWorldStateInstance {
18
+ /**
19
+ * Send a typed msgpack message to the backing world state and await its response.
20
+ *
21
+ * @param responseHandler — optional pre-resolution hook executed on the per-fork queue, useful
22
+ * for caching responses while the queue still holds the fork lock.
23
+ * @param errorHandler — optional pre-rejection hook executed on the per-fork queue.
24
+ */
34
25
  call<T extends WorldStateMessageType>(
35
26
  messageType: T,
36
27
  body: WorldStateRequest[T] & WorldStateRequestCategories,
28
+ responseHandler?: (response: WorldStateResponse[T]) => WorldStateResponse[T],
29
+ errorHandler?: (error: string) => void,
37
30
  ): Promise<WorldStateResponse[T]>;
38
- }
39
-
40
- /**
41
- * Strongly-typed interface to access the WorldState class in the native world_state_napi module.
42
- */
43
- export class NativeWorldState implements NativeWorldStateInstance {
44
- private open = true;
45
-
46
- // We maintain a map of queue to fork
47
- private queues = new Map<number, WorldStateOpsQueue>();
48
-
49
- private instance: MsgpackChannel<WorldStateMessageType, WorldStateRequest, WorldStateResponse>;
50
-
51
- /** Creates a new native WorldState instance */
52
- constructor(
53
- dataDir: string,
54
- dbMapSizeKb: number,
55
- prefilledPublicData: PublicDataTreeLeaf[] = [],
56
- private instrumentation: WorldStateInstrumentation,
57
- private log = createLogger('world-state:database'),
58
- ) {
59
- const threads = Math.min(cpus().length, MAX_WORLD_STATE_THREADS);
60
- log.info(
61
- `Creating world state data store at directory ${dataDir} with map size ${dbMapSizeKb} KB and ${threads} threads.`,
62
- );
63
- const prefilledPublicDataBufferArray = prefilledPublicData.map(d => [d.slot.toBuffer(), d.value.toBuffer()]);
64
- const ws = new BaseNativeWorldState(
65
- dataDir,
66
- {
67
- [MerkleTreeId.NULLIFIER_TREE]: NULLIFIER_TREE_HEIGHT,
68
- [MerkleTreeId.NOTE_HASH_TREE]: NOTE_HASH_TREE_HEIGHT,
69
- [MerkleTreeId.PUBLIC_DATA_TREE]: PUBLIC_DATA_TREE_HEIGHT,
70
- [MerkleTreeId.L1_TO_L2_MESSAGE_TREE]: L1_TO_L2_MSG_TREE_HEIGHT,
71
- [MerkleTreeId.ARCHIVE]: ARCHIVE_HEIGHT,
72
- },
73
- {
74
- [MerkleTreeId.NULLIFIER_TREE]: 2 * MAX_NULLIFIERS_PER_TX,
75
- [MerkleTreeId.PUBLIC_DATA_TREE]: 2 * MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
76
- },
77
- prefilledPublicDataBufferArray,
78
- GeneratorIndex.BLOCK_HASH,
79
- dbMapSizeKb,
80
- threads,
81
- );
82
- this.instance = new MsgpackChannel(ws);
83
- // Manually create the queue for the canonical fork
84
- this.queues.set(0, new WorldStateOpsQueue());
85
- }
86
31
 
87
32
  /**
88
- * Sends a message to the native instance and returns the response.
89
- * @param messageType - The type of message to send
90
- * @param body - The message body
91
- * @param responseHandler - A callback accepting the response, executed on the job queue
92
- * @param errorHandler - A callback called on request error, executed on the job queue
93
- * @returns The response to the message
33
+ * UDS path the underlying aztec-wsdb process listens on. The C++ AVM uses this to attach to the
34
+ * same world state instance the TS layer is using.
94
35
  */
95
- public async call<T extends WorldStateMessageType>(
96
- messageType: T,
97
- body: WorldStateRequest[T] & WorldStateRequestCategories,
98
- // allows for the pre-processing of responses on the job queue before being passed back
99
- responseHandler = (response: WorldStateResponse[T]): WorldStateResponse[T] => response,
100
- errorHandler = (_: string) => {},
101
- ): Promise<WorldStateResponse[T]> {
102
- // Here we determine which fork the request is being executed against and whether it requires uncommitted data
103
- // We use the fork Id to select the appropriate request queue and the uncommitted data flag to pass to the queue
104
- let forkId = -1;
105
- // We assume it includes uncommitted unless explicitly told otherwise
106
- let committedOnly = false;
107
-
108
- // Canonical requests ALWAYS go against the canonical fork
109
- // These include things like block syncs/unwinds etc
110
- // These requests don't contain a fork ID
111
- if (isWithCanonical(body)) {
112
- forkId = 0;
113
- } else if (isWithForkId(body)) {
114
- forkId = body.forkId;
115
- } else if (isWithRevision(body)) {
116
- forkId = body.revision.forkId;
117
- committedOnly = body.revision.includeUncommitted === false;
118
- } else {
119
- const _: never = body;
120
- throw new Error(`Unable to determine forkId for message=${WorldStateMessageType[messageType]}`);
121
- }
122
-
123
- // Get the queue or create a new one
124
- let requestQueue = this.queues.get(forkId);
125
- if (requestQueue === undefined) {
126
- requestQueue = new WorldStateOpsQueue();
127
- this.queues.set(forkId, requestQueue);
128
- }
129
-
130
- // Enqueue the request and wait for the response
131
- const response = await requestQueue.execute(
132
- async () => {
133
- assert.notEqual(messageType, WorldStateMessageType.CLOSE, 'Use close() to close the native instance');
134
- assert.equal(this.open, true, 'Native instance is closed');
135
- let response: WorldStateResponse[T];
136
- try {
137
- response = await this._sendMessage(messageType, body);
138
- } catch (error: any) {
139
- errorHandler(error.message);
140
- throw error;
141
- }
142
- return responseHandler(response);
143
- },
144
- messageType,
145
- committedOnly,
146
- );
147
-
148
- // If the request was to delete the fork then we clean it up here
149
- if (messageType === WorldStateMessageType.DELETE_FORK) {
150
- await requestQueue.stop();
151
- this.queues.delete(forkId);
152
- }
153
- return response;
154
- }
36
+ getSocketPath(): string;
155
37
 
156
38
  /**
157
- * Stops the native instance.
39
+ * Shut down the world state instance. Cancels any in-flight queues, closes the IPC channel, and
40
+ * terminates the underlying aztec-wsdb process. Idempotent.
158
41
  */
159
- public async close(): Promise<void> {
160
- if (!this.open) {
161
- return;
162
- }
163
- this.open = false;
164
- const queue = this.queues.get(0)!;
165
-
166
- await queue.execute(
167
- async () => {
168
- await this._sendMessage(WorldStateMessageType.CLOSE, { canonical: true });
169
- },
170
- WorldStateMessageType.CLOSE,
171
- false,
172
- );
173
- await queue.stop();
174
- }
175
-
176
- private async _sendMessage<T extends WorldStateMessageType>(
177
- messageType: T,
178
- body: WorldStateRequest[T] & WorldStateRequestCategories,
179
- ): Promise<WorldStateResponse[T]> {
180
- let logMetadata: Record<string, any> = {};
181
-
182
- if (body) {
183
- if ('treeId' in body) {
184
- logMetadata['treeId'] = MerkleTreeId[body.treeId];
185
- }
186
-
187
- if ('revision' in body) {
188
- logMetadata = { ...logMetadata, ...body.revision };
189
- }
190
-
191
- if ('forkId' in body) {
192
- logMetadata['forkId'] = body.forkId;
193
- }
194
-
195
- if ('blockNumber' in body) {
196
- logMetadata['blockNumber'] = body.blockNumber;
197
- }
198
-
199
- if ('toBlockNumber' in body) {
200
- logMetadata['toBlockNumber'] = body.toBlockNumber;
201
- }
202
-
203
- if ('leafIndex' in body) {
204
- logMetadata['leafIndex'] = body.leafIndex;
205
- }
206
-
207
- if ('blockHeaderHash' in body) {
208
- logMetadata['blockHeaderHash'] = '0x' + body.blockHeaderHash.toString('hex');
209
- }
210
-
211
- if ('leaves' in body) {
212
- logMetadata['leavesCount'] = body.leaves.length;
213
- }
214
-
215
- // sync operation
216
- if ('paddedNoteHashes' in body) {
217
- logMetadata['notesCount'] = body.paddedNoteHashes.length;
218
- logMetadata['nullifiersCount'] = body.paddedNullifiers.length;
219
- logMetadata['l1ToL2MessagesCount'] = body.paddedL1ToL2Messages.length;
220
- logMetadata['publicDataWritesCount'] = body.publicDataWrites.length;
221
- }
222
- }
223
-
224
- try {
225
- const { duration, response } = await this.instance.sendMessage(messageType, body);
226
- this.log.trace(`Call ${WorldStateMessageType[messageType]} took (ms)`, {
227
- duration,
228
- ...logMetadata,
229
- });
230
-
231
- this.instrumentation.recordRoundTrip(duration.totalUs, messageType);
232
- return response;
233
- } catch (error) {
234
- this.log.error(`Call ${WorldStateMessageType[messageType]} failed: ${error}`, error, logMetadata);
235
- throw error;
236
- }
237
- }
42
+ close(): Promise<void>;
238
43
  }
@@ -35,7 +35,7 @@ export const MUTATING_MSG_TYPES = new Set([
35
35
  WorldStateMessageType.SYNC_BLOCK,
36
36
  WorldStateMessageType.CREATE_FORK,
37
37
  WorldStateMessageType.DELETE_FORK,
38
- WorldStateMessageType.FINALISE_BLOCKS,
38
+ WorldStateMessageType.FINALIZE_BLOCKS,
39
39
  WorldStateMessageType.UNWIND_BLOCKS,
40
40
  WorldStateMessageType.REMOVE_HISTORICAL_BLOCKS,
41
41
  WorldStateMessageType.CREATE_CHECKPOINT,
@@ -96,7 +96,7 @@ export class WorldStateOpsQueue {
96
96
  // then send the request immediately
97
97
  // If a mutating request is in flight then we must wait
98
98
  // If a mutating request is not in flight but something is queued then it must be a mutating request
99
- if (this.inFlightMutatingCount == 0 && this.requests.length == 0) {
99
+ if (this.inFlightMutatingCount === 0 && this.requests.length === 0) {
100
100
  this.sendEnqueuedRequest(op);
101
101
  } else {
102
102
  this.requests.push(op);
@@ -122,7 +122,7 @@ export class WorldStateOpsQueue {
122
122
  --this.inFlightCount;
123
123
 
124
124
  // If there are still requests in flight then do nothing further
125
- if (this.inFlightCount != 0) {
125
+ if (this.inFlightCount !== 0) {
126
126
  return;
127
127
  }
128
128
 
@@ -134,7 +134,7 @@ export class WorldStateOpsQueue {
134
134
  while (this.requests.length > 0) {
135
135
  const next = this.requests[0];
136
136
  if (next.mutating) {
137
- if (this.inFlightCount == 0) {
137
+ if (this.inFlightCount === 0) {
138
138
  // send the mutating request
139
139
  this.requests.shift();
140
140
  this.sendEnqueuedRequest(next);
@@ -149,7 +149,7 @@ export class WorldStateOpsQueue {
149
149
  }
150
150
 
151
151
  // If the queue is empty, there is nothing in flight and we have been told to stop, then resolve the stop promise
152
- if (this.inFlightCount == 0 && this.stopResolve !== undefined) {
152
+ if (this.inFlightCount === 0 && this.stopResolve !== undefined) {
153
153
  this.stopResolve();
154
154
  }
155
155
  }
@@ -182,7 +182,7 @@ export class WorldStateOpsQueue {
182
182
  });
183
183
 
184
184
  // If no outstanding requests then immediately resolve the promise
185
- if (this.requests.length == 0 && this.inFlightCount == 0 && this.stopResolve !== undefined) {
185
+ if (this.requests.length === 0 && this.inFlightCount === 0 && this.stopResolve !== undefined) {
186
186
  this.stopResolve();
187
187
  }
188
188
  return this.stopPromise;
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  type ConfigMappingsType,
3
- booleanConfigHelper,
4
3
  getConfigFromMappings,
5
4
  numberConfigHelper,
5
+ optionalNumberConfigHelper,
6
6
  } from '@aztec/foundation/config';
7
7
 
8
8
  /** World State synchronizer configuration values. */
@@ -10,51 +10,89 @@ export interface WorldStateConfig {
10
10
  /** The frequency in which to check. */
11
11
  worldStateBlockCheckIntervalMS: number;
12
12
 
13
- /** Whether to follow only the proven chain. */
14
- worldStateProvenBlocksOnly: boolean;
15
-
16
13
  /** Size of the batch for each get-blocks request from the synchronizer to the archiver. */
17
14
  worldStateBlockRequestBatchSize?: number;
18
15
 
19
- /** The map size to be provided to LMDB for each world state tree DB, optional, will inherit from the general dataStoreMapSizeKB if not specified*/
16
+ /** The map size to be provided to LMDB for each world state tree DB, optional, will inherit from the general dataStoreMapSizeKb if not specified*/
20
17
  worldStateDbMapSizeKb?: number;
21
18
 
19
+ /** The map size to be provided to LMDB for each world state archive tree, optional, will inherit from the general worldStateDbMapSizeKb if not specified*/
20
+ archiveTreeMapSizeKb?: number;
21
+
22
+ /** The map size to be provided to LMDB for each world state nullifier tree, optional, will inherit from the general worldStateDbMapSizeKb if not specified*/
23
+ nullifierTreeMapSizeKb?: number;
24
+
25
+ /** The map size to be provided to LMDB for each world state note hash tree, optional, will inherit from the general worldStateDbMapSizeKb if not specified*/
26
+ noteHashTreeMapSizeKb?: number;
27
+
28
+ /** The map size to be provided to LMDB for each world state message tree, optional, will inherit from the general worldStateDbMapSizeKb if not specified*/
29
+ messageTreeMapSizeKb?: number;
30
+
31
+ /** The map size to be provided to LMDB for each world state public data tree, optional, will inherit from the general worldStateDbMapSizeKb if not specified*/
32
+ publicDataTreeMapSizeKb?: number;
33
+
22
34
  /** Optional directory for the world state DB, if unspecified will default to the general data directory */
23
35
  worldStateDataDirectory?: string;
24
36
 
25
- /** The number of historic blocks to maintain */
26
- worldStateBlockHistory: number;
37
+ /** The number of historic checkpoints worth of blocks to maintain */
38
+ worldStateCheckpointHistory: number;
27
39
  }
28
40
 
29
41
  export const worldStateConfigMappings: ConfigMappingsType<WorldStateConfig> = {
30
42
  worldStateBlockCheckIntervalMS: {
31
43
  env: 'WS_BLOCK_CHECK_INTERVAL_MS',
32
- parseEnv: (val: string) => +val,
33
- defaultValue: 100,
44
+ ...numberConfigHelper(100),
34
45
  description: 'The frequency in which to check.',
35
46
  },
36
- worldStateProvenBlocksOnly: {
37
- env: 'WS_PROVEN_BLOCKS_ONLY',
38
- description: 'Whether to follow only the proven chain.',
39
- ...booleanConfigHelper(),
40
- },
41
47
  worldStateBlockRequestBatchSize: {
42
48
  env: 'WS_BLOCK_REQUEST_BATCH_SIZE',
43
- parseEnv: (val: string | undefined) => (val ? +val : undefined),
49
+ ...optionalNumberConfigHelper(),
44
50
  description: 'Size of the batch for each get-blocks request from the synchronizer to the archiver.',
45
51
  },
46
52
  worldStateDbMapSizeKb: {
47
53
  env: 'WS_DB_MAP_SIZE_KB',
48
- parseEnv: (val: string | undefined) => (val ? +val : undefined),
49
- description: 'The maximum possible size of the world state DB',
54
+ ...optionalNumberConfigHelper(),
55
+ description: 'The maximum possible size of the world state DB in KB. Overwrites the general dataStoreMapSizeKb.',
56
+ },
57
+ archiveTreeMapSizeKb: {
58
+ env: 'ARCHIVE_TREE_MAP_SIZE_KB',
59
+ ...optionalNumberConfigHelper(),
60
+ description:
61
+ 'The maximum possible size of the world state archive tree in KB. Overwrites the general worldStateDbMapSizeKb.',
62
+ },
63
+ nullifierTreeMapSizeKb: {
64
+ env: 'NULLIFIER_TREE_MAP_SIZE_KB',
65
+ ...optionalNumberConfigHelper(),
66
+ description:
67
+ 'The maximum possible size of the world state nullifier tree in KB. Overwrites the general worldStateDbMapSizeKb.',
68
+ },
69
+ noteHashTreeMapSizeKb: {
70
+ env: 'NOTE_HASH_TREE_MAP_SIZE_KB',
71
+ ...optionalNumberConfigHelper(),
72
+ description:
73
+ 'The maximum possible size of the world state note hash tree in KB. Overwrites the general worldStateDbMapSizeKb.',
74
+ },
75
+ messageTreeMapSizeKb: {
76
+ env: 'MESSAGE_TREE_MAP_SIZE_KB',
77
+ ...optionalNumberConfigHelper(),
78
+ description:
79
+ 'The maximum possible size of the world state message tree in KB. Overwrites the general worldStateDbMapSizeKb.',
80
+ },
81
+ publicDataTreeMapSizeKb: {
82
+ env: 'PUBLIC_DATA_TREE_MAP_SIZE_KB',
83
+ ...optionalNumberConfigHelper(),
84
+ description:
85
+ 'The maximum possible size of the world state public data tree in KB. Overwrites the general worldStateDbMapSizeKb.',
50
86
  },
51
87
  worldStateDataDirectory: {
52
88
  env: 'WS_DATA_DIRECTORY',
53
89
  description: 'Optional directory for the world state database',
54
90
  },
55
- worldStateBlockHistory: {
56
- env: 'WS_NUM_HISTORIC_BLOCKS',
57
- description: 'The number of historic blocks to maintain. Values less than 1 mean all history is maintained',
91
+ worldStateCheckpointHistory: {
92
+ env: 'WS_NUM_HISTORIC_CHECKPOINTS',
93
+ description:
94
+ 'The number of historic checkpoints worth of blocks to maintain. Values less than 1 mean all history is maintained',
95
+ fallback: ['WS_NUM_HISTORIC_BLOCKS'],
58
96
  ...numberConfigHelper(64),
59
97
  },
60
98
  };
@@ -0,0 +1,5 @@
1
+ export class WorldStateSynchronizerError extends Error {
2
+ constructor(message: string, options?: ErrorOptions) {
3
+ super(message, options);
4
+ }
5
+ }
@@ -1,7 +1,8 @@
1
- import type { DataStoreConfig } from '@aztec/kv-store/config';
1
+ import type { LoggerBindings } from '@aztec/foundation/log';
2
2
  import type { L2BlockSource } from '@aztec/stdlib/block';
3
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
3
4
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
4
- import type { PublicDataTreeLeaf } from '@aztec/stdlib/trees';
5
+ import { EMPTY_GENESIS_DATA, type GenesisData, isGenesisData } from '@aztec/stdlib/world-state';
5
6
  import { type TelemetryClient, getTelemetryClient } from '@aztec/telemetry-client';
6
7
 
7
8
  import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js';
@@ -9,44 +10,73 @@ import { NativeWorldStateService } from '../native/native_world_state.js';
9
10
  import type { WorldStateConfig } from './config.js';
10
11
  import { ServerWorldStateSynchronizer } from './server_world_state_synchronizer.js';
11
12
 
13
+ export interface WorldStateTreeMapSizes {
14
+ archiveTreeMapSizeKb: number;
15
+ nullifierTreeMapSizeKb: number;
16
+ noteHashTreeMapSizeKb: number;
17
+ messageTreeMapSizeKb: number;
18
+ publicDataTreeMapSizeKb: number;
19
+ }
20
+
12
21
  export async function createWorldStateSynchronizer(
13
22
  config: WorldStateConfig & DataStoreConfig,
14
23
  l2BlockSource: L2BlockSource & L1ToL2MessageSource,
15
- prefilledPublicData: PublicDataTreeLeaf[] = [],
24
+ genesisOrNativeWorldState: GenesisData | NativeWorldStateService,
16
25
  client: TelemetryClient = getTelemetryClient(),
26
+ bindings?: LoggerBindings,
17
27
  ) {
18
28
  const instrumentation = new WorldStateInstrumentation(client);
19
- const merkleTrees = await createWorldState(config, prefilledPublicData, instrumentation);
29
+ const merkleTrees = isGenesisData(genesisOrNativeWorldState)
30
+ ? await createWorldState(config, genesisOrNativeWorldState, instrumentation, bindings)
31
+ : genesisOrNativeWorldState;
20
32
  return new ServerWorldStateSynchronizer(merkleTrees, l2BlockSource, config, instrumentation);
21
33
  }
22
34
 
23
35
  export async function createWorldState(
24
- config: WorldStateConfig & DataStoreConfig,
25
- prefilledPublicData: PublicDataTreeLeaf[] = [],
36
+ config: Pick<
37
+ WorldStateConfig,
38
+ | 'worldStateDataDirectory'
39
+ | 'worldStateDbMapSizeKb'
40
+ | 'archiveTreeMapSizeKb'
41
+ | 'nullifierTreeMapSizeKb'
42
+ | 'noteHashTreeMapSizeKb'
43
+ | 'messageTreeMapSizeKb'
44
+ | 'publicDataTreeMapSizeKb'
45
+ > &
46
+ Pick<DataStoreConfig, 'dataDirectory' | 'dataStoreMapSizeKb' | 'rollupAddress'>,
47
+ genesis: GenesisData = EMPTY_GENESIS_DATA,
26
48
  instrumentation: WorldStateInstrumentation = new WorldStateInstrumentation(getTelemetryClient()),
49
+ bindings?: LoggerBindings,
27
50
  ) {
28
- const newConfig = {
29
- dataDirectory: config.worldStateDataDirectory ?? config.dataDirectory,
30
- dataStoreMapSizeKB: config.worldStateDbMapSizeKb ?? config.dataStoreMapSizeKB,
31
- } as DataStoreConfig;
51
+ const dataDirectory = config.worldStateDataDirectory ?? config.dataDirectory;
52
+ const dataStoreMapSizeKb = config.worldStateDbMapSizeKb ?? config.dataStoreMapSizeKb;
53
+ const wsTreeMapSizes: WorldStateTreeMapSizes = {
54
+ archiveTreeMapSizeKb: config.archiveTreeMapSizeKb ?? dataStoreMapSizeKb,
55
+ nullifierTreeMapSizeKb: config.nullifierTreeMapSizeKb ?? dataStoreMapSizeKb,
56
+ noteHashTreeMapSizeKb: config.noteHashTreeMapSizeKb ?? dataStoreMapSizeKb,
57
+ messageTreeMapSizeKb: config.messageTreeMapSizeKb ?? dataStoreMapSizeKb,
58
+ publicDataTreeMapSizeKb: config.publicDataTreeMapSizeKb ?? dataStoreMapSizeKb,
59
+ };
32
60
 
33
- if (!config.l1Contracts?.rollupAddress) {
61
+ if (!config.rollupAddress) {
34
62
  throw new Error('Rollup address is required to create a world state synchronizer.');
35
63
  }
36
64
 
37
65
  // If a data directory is provided in config, then create a persistent store.
38
- const merkleTrees = newConfig.dataDirectory
66
+ const merkleTrees = dataDirectory
39
67
  ? await NativeWorldStateService.new(
40
- config.l1Contracts.rollupAddress,
41
- newConfig.dataDirectory,
42
- newConfig.dataStoreMapSizeKB,
43
- prefilledPublicData,
68
+ config.rollupAddress,
69
+ dataDirectory,
70
+ wsTreeMapSizes,
71
+ genesis,
44
72
  instrumentation,
73
+ bindings,
45
74
  )
46
75
  : await NativeWorldStateService.tmp(
47
- config.l1Contracts.rollupAddress,
48
76
  !['true', '1'].includes(process.env.DEBUG_WORLD_STATE!),
49
- prefilledPublicData,
77
+ genesis,
78
+ instrumentation,
79
+ bindings,
50
80
  );
51
81
 
52
82
  return merkleTrees;