@aztec/world-state 0.0.1-commit.e3c1de76 → 0.0.1-commit.e57c76e

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 (41) hide show
  1. package/dest/native/fork_checkpoint.d.ts +7 -1
  2. package/dest/native/fork_checkpoint.d.ts.map +1 -1
  3. package/dest/native/fork_checkpoint.js +15 -3
  4. package/dest/native/merkle_trees_facade.d.ts +9 -6
  5. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  6. package/dest/native/merkle_trees_facade.js +33 -13
  7. package/dest/native/message.d.ts +13 -6
  8. package/dest/native/message.d.ts.map +1 -1
  9. package/dest/native/native_world_state.d.ts +31 -5
  10. package/dest/native/native_world_state.d.ts.map +1 -1
  11. package/dest/native/native_world_state.js +80 -27
  12. package/dest/native/native_world_state_instance.d.ts +5 -4
  13. package/dest/native/native_world_state_instance.d.ts.map +1 -1
  14. package/dest/native/native_world_state_instance.js +33 -26
  15. package/dest/native/world_state_ops_queue.js +5 -5
  16. package/dest/synchronizer/config.d.ts +3 -3
  17. package/dest/synchronizer/config.d.ts.map +1 -1
  18. package/dest/synchronizer/config.js +15 -13
  19. package/dest/synchronizer/factory.d.ts +5 -5
  20. package/dest/synchronizer/factory.d.ts.map +1 -1
  21. package/dest/synchronizer/factory.js +7 -6
  22. package/dest/synchronizer/server_world_state_synchronizer.d.ts +4 -4
  23. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  24. package/dest/synchronizer/server_world_state_synchronizer.js +95 -21
  25. package/dest/testing.d.ts +4 -3
  26. package/dest/testing.d.ts.map +1 -1
  27. package/dest/testing.js +10 -6
  28. package/dest/world-state-db/merkle_tree_db.d.ts +1 -10
  29. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  30. package/package.json +12 -11
  31. package/src/native/fork_checkpoint.ts +19 -3
  32. package/src/native/merkle_trees_facade.ts +41 -16
  33. package/src/native/message.ts +14 -5
  34. package/src/native/native_world_state.ts +98 -34
  35. package/src/native/native_world_state_instance.ts +40 -30
  36. package/src/native/world_state_ops_queue.ts +5 -5
  37. package/src/synchronizer/config.ts +21 -15
  38. package/src/synchronizer/factory.ts +13 -11
  39. package/src/synchronizer/server_world_state_synchronizer.ts +99 -22
  40. package/src/testing.ts +8 -9
  41. package/src/world-state-db/merkle_tree_db.ts +0 -10
@@ -1,5 +1,5 @@
1
- import { GENESIS_BLOCK_HEADER_HASH, INITIAL_L2_BLOCK_NUM, INITIAL_L2_CHECKPOINT_NUM } from '@aztec/constants';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
1
+ import { INITIAL_CHECKPOINT_NUMBER } from '@aztec/constants';
2
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
3
3
  import { createLogger } from '@aztec/foundation/log';
4
4
  import { promiseWithResolvers } from '@aztec/foundation/promise';
5
5
  import { elapsed } from '@aztec/foundation/timer';
@@ -38,7 +38,7 @@ import { WorldStateSynchronizerError } from './errors.js';
38
38
  this.currentState = WorldStateRunningState.IDLE;
39
39
  this.syncPromise = promiseWithResolvers();
40
40
  this.merkleTreeCommitted = this.merkleTreeDb.getCommitted();
41
- this.historyToKeep = config.worldStateBlockHistory < 1 ? undefined : config.worldStateBlockHistory;
41
+ this.historyToKeep = config.worldStateCheckpointHistory < 1 ? undefined : config.worldStateCheckpointHistory;
42
42
  this.log.info(`Created world state synchroniser with block history of ${this.historyToKeep === undefined ? 'infinity' : this.historyToKeep}`);
43
43
  }
44
44
  getCommitted() {
@@ -130,9 +130,9 @@ import { WorldStateSynchronizerError } from './errors.js';
130
130
  /**
131
131
  * Forces an immediate sync.
132
132
  * @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
133
- * @param skipThrowIfTargetNotReached - Whether to skip throwing if the target block number is not reached.
133
+ * @param blockHash - If provided, verifies the block at targetBlockNumber matches this hash. On mismatch, triggers a resync (reorg detection).
134
134
  * @returns A promise that resolves with the block number the world state was synced to
135
- */ async syncImmediate(targetBlockNumber, skipThrowIfTargetNotReached) {
135
+ */ async syncImmediate(targetBlockNumber, blockHash) {
136
136
  if (this.currentState !== WorldStateRunningState.RUNNING) {
137
137
  throw new Error(`World State is not running. Unable to perform sync.`);
138
138
  }
@@ -142,7 +142,16 @@ import { WorldStateSynchronizerError } from './errors.js';
142
142
  // If we have been given a block number to sync to and we have reached that number then return
143
143
  const currentBlockNumber = await this.getLatestBlockNumber();
144
144
  if (targetBlockNumber !== undefined && targetBlockNumber <= currentBlockNumber) {
145
- return currentBlockNumber;
145
+ if (blockHash === undefined) {
146
+ return currentBlockNumber;
147
+ }
148
+ // If a block hash was provided, verify we're on the expected fork
149
+ const currentHash = await this.getL2BlockHash(targetBlockNumber);
150
+ if (currentHash === blockHash.toString()) {
151
+ return currentBlockNumber;
152
+ }
153
+ // Hash mismatch: a reorg may have occurred, fall through to trigger sync
154
+ this.log.debug(`World state block hash mismatch at ${targetBlockNumber} (expected ${blockHash}, got ${currentHash}). Triggering resync.`);
146
155
  }
147
156
  this.log.debug(`World State at ${currentBlockNumber} told to sync to ${targetBlockNumber ?? 'latest'}`);
148
157
  // If the archiver is behind the target block, force an archiver sync
@@ -157,7 +166,7 @@ import { WorldStateSynchronizerError } from './errors.js';
157
166
  await this.blockStream.sync();
158
167
  // If we have been given a block number to sync to and we have not reached that number then fail
159
168
  const updatedBlockNumber = await this.getLatestBlockNumber();
160
- if (!skipThrowIfTargetNotReached && targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
169
+ if (targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
161
170
  throw new WorldStateSynchronizerError(`Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`, {
162
171
  cause: {
163
172
  reason: 'block_not_available',
@@ -167,6 +176,20 @@ import { WorldStateSynchronizerError } from './errors.js';
167
176
  }
168
177
  });
169
178
  }
179
+ // If a block hash was provided, verify we're on the expected fork after syncing, throw otherwise
180
+ if (blockHash !== undefined && targetBlockNumber !== undefined) {
181
+ const updatedHash = await this.getL2BlockHash(targetBlockNumber);
182
+ if (updatedHash !== blockHash.toString()) {
183
+ throw new WorldStateSynchronizerError(`Block hash mismatch at block ${targetBlockNumber} (expected ${blockHash} but got ${updatedHash})`, {
184
+ cause: {
185
+ reason: 'block_hash_mismatch',
186
+ targetBlockNumber,
187
+ expectedHash: blockHash.toString(),
188
+ actualHash: updatedHash
189
+ }
190
+ });
191
+ }
192
+ }
170
193
  return updatedBlockNumber;
171
194
  }
172
195
  /** Returns the L2 block hash for a given number. Used by the L2BlockStream for detecting reorgs. */ async getL2BlockHash(number) {
@@ -194,15 +217,26 @@ import { WorldStateSynchronizerError } from './errors.js';
194
217
  // but we use a block stream so we need to provide 'local' L2Tips.
195
218
  // We configure the block stream to ignore checkpoints and set checkpoint values to genesis here.
196
219
  const genesisCheckpointHeaderHash = GENESIS_CHECKPOINT_HEADER_HASH.toString();
220
+ const initialBlockHash = (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
197
221
  return {
198
222
  proposed: latestBlockId,
199
223
  checkpointed: {
200
224
  block: {
201
- number: INITIAL_L2_BLOCK_NUM,
202
- hash: GENESIS_BLOCK_HEADER_HASH.toString()
225
+ number: BlockNumber.ZERO,
226
+ hash: initialBlockHash
227
+ },
228
+ checkpoint: {
229
+ number: INITIAL_CHECKPOINT_NUMBER,
230
+ hash: genesisCheckpointHeaderHash
231
+ }
232
+ },
233
+ proposedCheckpoint: {
234
+ block: {
235
+ number: BlockNumber.ZERO,
236
+ hash: initialBlockHash
203
237
  },
204
238
  checkpoint: {
205
- number: INITIAL_L2_CHECKPOINT_NUM,
239
+ number: INITIAL_CHECKPOINT_NUMBER,
206
240
  hash: genesisCheckpointHeaderHash
207
241
  }
208
242
  },
@@ -212,7 +246,7 @@ import { WorldStateSynchronizerError } from './errors.js';
212
246
  hash: finalizedBlockHash ?? ''
213
247
  },
214
248
  checkpoint: {
215
- number: INITIAL_L2_CHECKPOINT_NUM,
249
+ number: INITIAL_CHECKPOINT_NUMBER,
216
250
  hash: genesisCheckpointHeaderHash
217
251
  }
218
252
  },
@@ -222,7 +256,7 @@ import { WorldStateSynchronizerError } from './errors.js';
222
256
  hash: provenBlockHash ?? ''
223
257
  },
224
258
  checkpoint: {
225
- number: INITIAL_L2_CHECKPOINT_NUM,
259
+ number: INITIAL_CHECKPOINT_NUMBER,
226
260
  hash: genesisCheckpointHeaderHash
227
261
  }
228
262
  }
@@ -249,7 +283,7 @@ import { WorldStateSynchronizerError } from './errors.js';
249
283
  * @param l2Blocks - The L2 blocks to handle.
250
284
  * @returns Whether the block handled was produced by this same node.
251
285
  */ async handleL2Blocks(l2Blocks) {
252
- this.log.trace(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1).number}`);
286
+ this.log.debug(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1).number}`);
253
287
  // Fetch the L1->L2 messages for the first block in a checkpoint.
254
288
  const messagesForBlocks = new Map();
255
289
  await Promise.all(l2Blocks.filter((b)=>b.indexWithinCheckpoint === 0).map(async (block)=>{
@@ -280,10 +314,12 @@ import { WorldStateSynchronizerError } from './errors.js';
280
314
  * @param l1ToL2Messages - The L1 to L2 messages for the block.
281
315
  * @returns Whether the block handled was produced by this same node.
282
316
  */ async handleL2Block(l2Block, l1ToL2Messages) {
283
- this.log.trace(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
317
+ this.log.debug(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
284
318
  blockNumber: l2Block.number,
285
319
  blockHash: await l2Block.hash().then((h)=>h.toString()),
286
- l1ToL2Messages: l1ToL2Messages.map((msg)=>msg.toString())
320
+ l1ToL2Messages: l1ToL2Messages.map((msg)=>msg.toString()),
321
+ blockHeader: l2Block.header.toInspect(),
322
+ blockStats: l2Block.getStats()
287
323
  });
288
324
  const result = await this.merkleTreeDb.handleL2BlockAndMessages(l2Block, l1ToL2Messages);
289
325
  if (this.currentState === WorldStateRunningState.SYNCHING && l2Block.number >= this.latestBlockNumberAtStart) {
@@ -294,16 +330,52 @@ import { WorldStateSynchronizerError } from './errors.js';
294
330
  }
295
331
  async handleChainFinalized(blockNumber) {
296
332
  this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
333
+ // If the finalized block number is older than the oldest available block in world state,
334
+ // skip entirely. The finalized block number can jump backwards (e.g. when the finalization
335
+ // heuristic changes) and try to read block data that has already been pruned. When this
336
+ // happens, there is nothing useful to do — the native world state is already finalized
337
+ // past this point and pruning has already happened.
338
+ const currentSummary = await this.merkleTreeDb.getStatusSummary();
339
+ if (blockNumber < currentSummary.oldestHistoricalBlock || blockNumber < 1) {
340
+ this.log.trace(`Finalized block ${blockNumber} is older than the oldest available block ${currentSummary.oldestHistoricalBlock}. Skipping.`);
341
+ return;
342
+ }
297
343
  const summary = await this.merkleTreeDb.setFinalized(blockNumber);
298
344
  if (this.historyToKeep === undefined) {
299
345
  return;
300
346
  }
301
- const newHistoricBlock = summary.finalizedBlockNumber - this.historyToKeep + 1;
302
- if (newHistoricBlock <= 1) {
347
+ const finalisedBlockData = await this.l2BlockSource.getBlockData({
348
+ number: summary.finalizedBlockNumber
349
+ });
350
+ if (finalisedBlockData === undefined) {
351
+ this.log.warn(`Failed to retrieve checkpointed block for finalized block number: ${summary.finalizedBlockNumber}`);
352
+ return;
353
+ }
354
+ // Compute the required historic checkpoint number
355
+ const newHistoricCheckpointNumber = finalisedBlockData.checkpointNumber - this.historyToKeep + 1;
356
+ if (newHistoricCheckpointNumber <= 1) {
357
+ return;
358
+ }
359
+ // Retrieve the historic checkpoint
360
+ const historicCheckpoint = await this.l2BlockSource.getCheckpoint({
361
+ number: CheckpointNumber(newHistoricCheckpointNumber)
362
+ });
363
+ if (!historicCheckpoint) {
364
+ this.log.warn(`Failed to retrieve checkpoint number ${newHistoricCheckpointNumber} from Archiver`);
303
365
  return;
304
366
  }
305
- this.log.verbose(`Pruning historic blocks to ${newHistoricBlock}`);
306
- const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock));
367
+ if (historicCheckpoint.checkpoint.blocks.length === 0 || historicCheckpoint.checkpoint.blocks[0] === undefined) {
368
+ this.log.warn(`Retrieved checkpoint number ${newHistoricCheckpointNumber} has no blocks!`);
369
+ return;
370
+ }
371
+ // Find the block at the start of the checkpoint and remove blocks up to this one
372
+ const newHistoricBlock = historicCheckpoint.checkpoint.blocks[0];
373
+ if (newHistoricBlock.number <= currentSummary.oldestHistoricalBlock) {
374
+ this.log.debug(`Historic block ${newHistoricBlock.number} is not newer than oldest available ${currentSummary.oldestHistoricalBlock}. Skipping prune.`);
375
+ return;
376
+ }
377
+ this.log.verbose(`Pruning historic blocks to ${newHistoricBlock.number}`);
378
+ const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock.number));
307
379
  this.log.debug(`World state summary `, status.summary);
308
380
  }
309
381
  handleChainProven(blockNumber) {
@@ -312,9 +384,11 @@ import { WorldStateSynchronizerError } from './errors.js';
312
384
  return Promise.resolve();
313
385
  }
314
386
  async handleChainPruned(blockNumber) {
315
- this.log.warn(`Chain pruned to block ${blockNumber}`);
387
+ this.log.info(`Chain pruned to block ${blockNumber}`);
316
388
  const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
317
- this.provenBlockNumber = undefined;
389
+ if (this.provenBlockNumber !== undefined && this.provenBlockNumber > blockNumber) {
390
+ this.provenBlockNumber = undefined;
391
+ }
318
392
  this.instrumentation.updateWorldStateMetrics(status);
319
393
  }
320
394
  /**
package/dest/testing.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { Fr } from '@aztec/foundation/curves/bn254';
2
2
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
3
3
  import { PublicDataTreeLeaf } from '@aztec/stdlib/trees';
4
+ import type { GenesisData } from '@aztec/stdlib/world-state';
4
5
  export declare const defaultInitialAccountFeeJuice: Fr;
5
- export declare function getGenesisValues(initialAccounts: AztecAddress[], initialAccountFeeJuice?: Fr, genesisPublicData?: PublicDataTreeLeaf[]): Promise<{
6
+ export declare function getGenesisValues(initialAccounts: AztecAddress[], initialAccountFeeJuice?: Fr, genesisPublicData?: PublicDataTreeLeaf[], genesisTimestamp?: bigint): Promise<{
6
7
  genesisArchiveRoot: Fr;
7
- prefilledPublicData: PublicDataTreeLeaf[];
8
+ genesis: GenesisData;
8
9
  fundingNeeded: bigint;
9
10
  }>;
10
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdGluZy5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL3Rlc3RpbmcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsT0FBTyxFQUFFLEVBQUUsRUFBRSxNQUFNLGdDQUFnQyxDQUFDO0FBRXBELE9BQU8sS0FBSyxFQUFFLFlBQVksRUFBRSxNQUFNLDZCQUE2QixDQUFDO0FBQ2hFLE9BQU8sRUFBZ0Isa0JBQWtCLEVBQUUsTUFBTSxxQkFBcUIsQ0FBQztBQXlCdkUsZUFBTyxNQUFNLDZCQUE2QixJQUFxQixDQUFDO0FBRWhFLHdCQUFzQixnQkFBZ0IsQ0FDcEMsZUFBZSxFQUFFLFlBQVksRUFBRSxFQUMvQixzQkFBc0IsS0FBZ0MsRUFDdEQsaUJBQWlCLEdBQUUsa0JBQWtCLEVBQU87Ozs7R0FxQjdDIn0=
11
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdGluZy5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL3Rlc3RpbmcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsT0FBTyxFQUFFLEVBQUUsRUFBRSxNQUFNLGdDQUFnQyxDQUFDO0FBRXBELE9BQU8sS0FBSyxFQUFFLFlBQVksRUFBRSxNQUFNLDZCQUE2QixDQUFDO0FBQ2hFLE9BQU8sRUFBZ0Isa0JBQWtCLEVBQUUsTUFBTSxxQkFBcUIsQ0FBQztBQUN2RSxPQUFPLEtBQUssRUFBRSxXQUFXLEVBQUUsTUFBTSwyQkFBMkIsQ0FBQztBQXFCN0QsZUFBTyxNQUFNLDZCQUE2QixJQUFxQixDQUFDO0FBRWhFLHdCQUFzQixnQkFBZ0IsQ0FDcEMsZUFBZSxFQUFFLFlBQVksRUFBRSxFQUMvQixzQkFBc0IsS0FBZ0MsRUFDdEQsaUJBQWlCLEdBQUUsa0JBQWtCLEVBQU8sRUFDNUMsZ0JBQWdCLEdBQUUsTUFBVzs7OztHQXNCOUIifQ==
@@ -1 +1 @@
1
- {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAE,MAAM,gCAAgC,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAgB,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAyBvE,eAAO,MAAM,6BAA6B,IAAqB,CAAC;AAEhE,wBAAsB,gBAAgB,CACpC,eAAe,EAAE,YAAY,EAAE,EAC/B,sBAAsB,KAAgC,EACtD,iBAAiB,GAAE,kBAAkB,EAAO;;;;GAqB7C"}
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,EAAE,EAAE,MAAM,gCAAgC,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAgB,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAqB7D,eAAO,MAAM,6BAA6B,IAAqB,CAAC;AAEhE,wBAAsB,gBAAgB,CACpC,eAAe,EAAE,YAAY,EAAE,EAC/B,sBAAsB,KAAgC,EACtD,iBAAiB,GAAE,kBAAkB,EAAO,EAC5C,gBAAgB,GAAE,MAAW;;;;GAsB9B"}
package/dest/testing.js CHANGED
@@ -3,14 +3,14 @@ import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { computeFeePayerBalanceLeafSlot } from '@aztec/protocol-contracts/fee-juice';
4
4
  import { MerkleTreeId, PublicDataTreeLeaf } from '@aztec/stdlib/trees';
5
5
  import { NativeWorldStateService } from './native/index.js';
6
- async function generateGenesisValues(prefilledPublicData) {
7
- if (!prefilledPublicData.length) {
6
+ async function generateGenesisValues(genesis) {
7
+ if (!genesis.prefilledPublicData.length && genesis.genesisTimestamp === 0n) {
8
8
  return {
9
9
  genesisArchiveRoot: new Fr(GENESIS_ARCHIVE_ROOT)
10
10
  };
11
11
  }
12
12
  // Create a temporary world state to compute the genesis values.
13
- const ws = await NativeWorldStateService.tmp(undefined /* rollupAddress */ , true, prefilledPublicData);
13
+ const ws = await NativeWorldStateService.tmp(undefined /* rollupAddress */ , true, genesis);
14
14
  const genesisArchiveRoot = new Fr((await ws.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
15
15
  await ws.close();
16
16
  return {
@@ -18,16 +18,20 @@ async function generateGenesisValues(prefilledPublicData) {
18
18
  };
19
19
  }
20
20
  export const defaultInitialAccountFeeJuice = new Fr(10n ** 22n);
21
- export async function getGenesisValues(initialAccounts, initialAccountFeeJuice = defaultInitialAccountFeeJuice, genesisPublicData = []) {
21
+ export async function getGenesisValues(initialAccounts, initialAccountFeeJuice = defaultInitialAccountFeeJuice, genesisPublicData = [], genesisTimestamp = 0n) {
22
22
  // Top up the accounts with fee juice.
23
23
  let prefilledPublicData = await Promise.all(initialAccounts.map(async (address)=>new PublicDataTreeLeaf(await computeFeePayerBalanceLeafSlot(address), initialAccountFeeJuice)));
24
24
  // Add user-defined public data
25
25
  prefilledPublicData = prefilledPublicData.concat(genesisPublicData);
26
26
  prefilledPublicData.sort((a, b)=>b.slot.lt(a.slot) ? 1 : -1);
27
- const { genesisArchiveRoot } = await generateGenesisValues(prefilledPublicData);
27
+ const genesis = {
28
+ prefilledPublicData,
29
+ genesisTimestamp
30
+ };
31
+ const { genesisArchiveRoot } = await generateGenesisValues(genesis);
28
32
  return {
29
33
  genesisArchiveRoot,
30
- prefilledPublicData,
34
+ genesis,
31
35
  fundingNeeded: BigInt(initialAccounts.length) * initialAccountFeeJuice.toBigInt()
32
36
  };
33
37
  }
@@ -1,9 +1,7 @@
1
1
  import type { BlockNumber } from '@aztec/foundation/branded-types';
2
2
  import type { Fr } from '@aztec/foundation/curves/bn254';
3
- import type { IndexedTreeSnapshot, TreeSnapshot } from '@aztec/merkle-tree';
4
3
  import type { L2Block } from '@aztec/stdlib/block';
5
4
  import type { ForkMerkleTreeOperations, MerkleTreeReadOperations, ReadonlyWorldStateAccess } from '@aztec/stdlib/interfaces/server';
6
- import type { MerkleTreeId } from '@aztec/stdlib/trees';
7
5
  import type { WorldStateStatusFull, WorldStateStatusSummary } from '../native/message.js';
8
6
  /**
9
7
  *
@@ -22,13 +20,6 @@ import type { WorldStateStatusFull, WorldStateStatusSummary } from '../native/me
22
20
  */
23
21
  export declare const INITIAL_NULLIFIER_TREE_SIZE: number;
24
22
  export declare const INITIAL_PUBLIC_DATA_TREE_SIZE: number;
25
- export type TreeSnapshots = {
26
- [MerkleTreeId.NULLIFIER_TREE]: IndexedTreeSnapshot;
27
- [MerkleTreeId.NOTE_HASH_TREE]: TreeSnapshot<Fr>;
28
- [MerkleTreeId.PUBLIC_DATA_TREE]: IndexedTreeSnapshot;
29
- [MerkleTreeId.L1_TO_L2_MESSAGE_TREE]: TreeSnapshot<Fr>;
30
- [MerkleTreeId.ARCHIVE]: TreeSnapshot<Fr>;
31
- };
32
23
  export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations, ReadonlyWorldStateAccess {
33
24
  /**
34
25
  * Handles a single L2 block (i.e. Inserts the new note hashes into the merkle tree).
@@ -68,4 +59,4 @@ export interface MerkleTreeAdminDatabase extends For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CAAC;AACnE,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,gCAAgC,CAAC;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EACV,wBAAwB,EACxB,wBAAwB,EACxB,wBAAwB,EACzB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,KAAK,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAE1F;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,2BAA2B,QAA4B,CAAC;AAErE,eAAO,MAAM,6BAA6B,QAAmD,CAAC;AAE9F,MAAM,WAAW,uBAAwB,SAAQ,wBAAwB,EAAE,wBAAwB;IACjG;;;;OAIG;IACH,wBAAwB,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAE9F;;OAEG;IACH,YAAY,IAAI,wBAAwB,CAAC;IAEzC;;;;OAIG;IACH,sBAAsB,CAAC,aAAa,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAElF;;;;OAIG;IACH,YAAY,CAAC,aAAa,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAExE;;;;OAIG;IACH,YAAY,CAAC,aAAa,EAAE,WAAW,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC;IAE3E;;;OAGG;IACH,gBAAgB,IAAI,OAAO,CAAC,uBAAuB,CAAC,CAAC;IAErD,yBAAyB;IACzB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB,sBAAsB;IACtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/world-state",
3
- "version": "0.0.1-commit.e3c1de76",
3
+ "version": "0.0.1-commit.e57c76e",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js",
@@ -64,19 +64,20 @@
64
64
  ]
65
65
  },
66
66
  "dependencies": {
67
- "@aztec/constants": "0.0.1-commit.e3c1de76",
68
- "@aztec/foundation": "0.0.1-commit.e3c1de76",
69
- "@aztec/kv-store": "0.0.1-commit.e3c1de76",
70
- "@aztec/merkle-tree": "0.0.1-commit.e3c1de76",
71
- "@aztec/native": "0.0.1-commit.e3c1de76",
72
- "@aztec/protocol-contracts": "0.0.1-commit.e3c1de76",
73
- "@aztec/stdlib": "0.0.1-commit.e3c1de76",
74
- "@aztec/telemetry-client": "0.0.1-commit.e3c1de76",
67
+ "@aztec/bb.js": "0.0.1-commit.e57c76e",
68
+ "@aztec/constants": "0.0.1-commit.e57c76e",
69
+ "@aztec/foundation": "0.0.1-commit.e57c76e",
70
+ "@aztec/kv-store": "0.0.1-commit.e57c76e",
71
+ "@aztec/native": "0.0.1-commit.e57c76e",
72
+ "@aztec/protocol-contracts": "0.0.1-commit.e57c76e",
73
+ "@aztec/stdlib": "0.0.1-commit.e57c76e",
74
+ "@aztec/telemetry-client": "0.0.1-commit.e57c76e",
75
+ "msgpackr": "^1.11.2",
75
76
  "tslib": "^2.4.0",
76
- "zod": "^3.23.8"
77
+ "zod": "^4"
77
78
  },
78
79
  "devDependencies": {
79
- "@aztec/archiver": "0.0.1-commit.e3c1de76",
80
+ "@aztec/archiver": "0.0.1-commit.e57c76e",
80
81
  "@jest/globals": "^30.0.0",
81
82
  "@types/jest": "^30.0.0",
82
83
  "@types/node": "^22.15.17",
@@ -3,11 +3,14 @@ import type { MerkleTreeCheckpointOperations } from '@aztec/stdlib/interfaces/se
3
3
  export class ForkCheckpoint {
4
4
  private completed = false;
5
5
 
6
- private constructor(private readonly fork: MerkleTreeCheckpointOperations) {}
6
+ private constructor(
7
+ private readonly fork: MerkleTreeCheckpointOperations,
8
+ public readonly depth: number,
9
+ ) {}
7
10
 
8
11
  static async new(fork: MerkleTreeCheckpointOperations): Promise<ForkCheckpoint> {
9
- await fork.createCheckpoint();
10
- return new ForkCheckpoint(fork);
12
+ const depth = await fork.createCheckpoint();
13
+ return new ForkCheckpoint(fork, depth);
11
14
  }
12
15
 
13
16
  async commit(): Promise<void> {
@@ -27,4 +30,17 @@ export class ForkCheckpoint {
27
30
  await this.fork.revertCheckpoint();
28
31
  this.completed = true;
29
32
  }
33
+
34
+ /**
35
+ * Reverts this checkpoint and any nested checkpoints created on top of it,
36
+ * leaving the checkpoint depth at the level it was before this checkpoint was created.
37
+ */
38
+ async revertToCheckpoint(): Promise<void> {
39
+ if (this.completed) {
40
+ return;
41
+ }
42
+
43
+ await this.fork.revertAllCheckpointsTo(this.depth - 1);
44
+ this.completed = true;
45
+ }
30
46
  }
@@ -4,6 +4,7 @@ import { createLogger } from '@aztec/foundation/log';
4
4
  import { serializeToBuffer } from '@aztec/foundation/serialize';
5
5
  import { sleep } from '@aztec/foundation/sleep';
6
6
  import { type IndexedTreeLeafPreimage, SiblingPath } from '@aztec/foundation/trees';
7
+ import { BlockHash } from '@aztec/stdlib/block';
7
8
  import type {
8
9
  BatchInsertionResult,
9
10
  IndexedTreeId,
@@ -118,7 +119,7 @@ export class MerkleTreesFacade implements MerkleTreeReadOperations {
118
119
 
119
120
  const leaf = deserializeLeafValue(resp);
120
121
  if (leaf instanceof Fr) {
121
- return leaf as any;
122
+ return treeId === MerkleTreeId.ARCHIVE ? (new BlockHash(leaf) as any) : (leaf as any);
122
123
  } else {
123
124
  return leaf.toBuffer() as any;
124
125
  }
@@ -207,6 +208,7 @@ export class MerkleTreesFacade implements MerkleTreeReadOperations {
207
208
 
208
209
  export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTreeWriteOperations {
209
210
  private log = createLogger('world-state:merkle-trees-fork-facade');
211
+ private closePromise: Promise<void> | undefined;
210
212
 
211
213
  constructor(
212
214
  instance: NativeWorldStateInstance,
@@ -228,7 +230,7 @@ export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTr
228
230
 
229
231
  async appendLeaves<ID extends MerkleTreeId>(treeId: ID, leaves: MerkleTreeLeafType<ID>[]): Promise<void> {
230
232
  await this.instance.call(WorldStateMessageType.APPEND_LEAVES, {
231
- leaves: leaves.map(leaf => leaf as any),
233
+ leaves: leaves.map(leaf => serializeLeaf(hydrateLeaf(treeId, leaf as any))),
232
234
  forkId: this.revision.forkId,
233
235
  treeId,
234
236
  });
@@ -290,8 +292,17 @@ export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTr
290
292
  };
291
293
  }
292
294
 
293
- public async close(): Promise<void> {
295
+ public close(): Promise<void> {
294
296
  assert.notEqual(this.revision.forkId, 0, 'Fork ID must be set');
297
+ // Share the in-flight close promise across duplicate dispose calls so DELETE_FORK is sent at most once.
298
+ if (this.closePromise) {
299
+ return this.closePromise;
300
+ }
301
+ this.closePromise = this.doClose();
302
+ return this.closePromise;
303
+ }
304
+
305
+ private async doClose(): Promise<void> {
295
306
  try {
296
307
  await this.instance.call(WorldStateMessageType.DELETE_FORK, { forkId: this.revision.forkId });
297
308
  } catch (err: any) {
@@ -300,18 +311,21 @@ export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTr
300
311
  if (err?.message === 'Native instance is closed') {
301
312
  return;
302
313
  }
314
+ // Ignore "Fork not found": the native fork was already destroyed by a pending-chain unwind or a
315
+ // historical prune (both call C++ remove_forks_for_block). Fork IDs are monotonic and never reused,
316
+ // so swallowing this on close cannot mask a deletion of a different fork.
317
+ if (err?.message === 'Fork not found') {
318
+ return;
319
+ }
303
320
  throw err;
304
321
  }
305
322
  }
306
323
 
307
- async [Symbol.dispose](): Promise<void> {
324
+ async [Symbol.asyncDispose](): Promise<void> {
308
325
  if (this.opts.closeDelayMs) {
309
326
  void sleep(this.opts.closeDelayMs)
310
327
  .then(() => this.close())
311
328
  .catch(err => {
312
- if (err && 'message' in err && err.message === 'Native instance is closed') {
313
- return; // Ignore errors due to native instance being closed
314
- }
315
329
  this.log.warn('Error closing MerkleTreesForkFacade after delay', { err });
316
330
  });
317
331
  } else {
@@ -319,9 +333,10 @@ export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTr
319
333
  }
320
334
  }
321
335
 
322
- public async createCheckpoint(): Promise<void> {
336
+ public async createCheckpoint(): Promise<number> {
323
337
  assert.notEqual(this.revision.forkId, 0, 'Fork ID must be set');
324
- await this.instance.call(WorldStateMessageType.CREATE_CHECKPOINT, { forkId: this.revision.forkId });
338
+ const resp = await this.instance.call(WorldStateMessageType.CREATE_CHECKPOINT, { forkId: this.revision.forkId });
339
+ return resp.depth;
325
340
  }
326
341
 
327
342
  public async commitCheckpoint(): Promise<void> {
@@ -334,20 +349,28 @@ export class MerkleTreesForkFacade extends MerkleTreesFacade implements MerkleTr
334
349
  await this.instance.call(WorldStateMessageType.REVERT_CHECKPOINT, { forkId: this.revision.forkId });
335
350
  }
336
351
 
337
- public async commitAllCheckpoints(): Promise<void> {
352
+ public async commitAllCheckpointsTo(depth: number): Promise<void> {
338
353
  assert.notEqual(this.revision.forkId, 0, 'Fork ID must be set');
339
- await this.instance.call(WorldStateMessageType.COMMIT_ALL_CHECKPOINTS, { forkId: this.revision.forkId });
354
+ await this.instance.call(WorldStateMessageType.COMMIT_ALL_CHECKPOINTS, {
355
+ forkId: this.revision.forkId,
356
+ depth,
357
+ });
340
358
  }
341
359
 
342
- public async revertAllCheckpoints(): Promise<void> {
360
+ public async revertAllCheckpointsTo(depth: number): Promise<void> {
343
361
  assert.notEqual(this.revision.forkId, 0, 'Fork ID must be set');
344
- await this.instance.call(WorldStateMessageType.REVERT_ALL_CHECKPOINTS, { forkId: this.revision.forkId });
362
+ await this.instance.call(WorldStateMessageType.REVERT_ALL_CHECKPOINTS, {
363
+ forkId: this.revision.forkId,
364
+ depth,
365
+ });
345
366
  }
346
367
  }
347
368
 
348
- function hydrateLeaf<ID extends MerkleTreeId>(treeId: ID, leaf: Fr | Buffer) {
369
+ function hydrateLeaf(treeId: MerkleTreeId, leaf: Fr | BlockHash | Buffer) {
349
370
  if (leaf instanceof Fr) {
350
371
  return leaf;
372
+ } else if (leaf instanceof BlockHash) {
373
+ return leaf.toFr();
351
374
  } else if (treeId === MerkleTreeId.NULLIFIER_TREE) {
352
375
  return NullifierLeaf.fromBuffer(leaf);
353
376
  } else if (treeId === MerkleTreeId.PUBLIC_DATA_TREE) {
@@ -357,8 +380,10 @@ function hydrateLeaf<ID extends MerkleTreeId>(treeId: ID, leaf: Fr | Buffer) {
357
380
  }
358
381
  }
359
382
 
360
- export function serializeLeaf(leaf: Fr | NullifierLeaf | PublicDataTreeLeaf): SerializedLeafValue {
361
- if (leaf instanceof Fr) {
383
+ export function serializeLeaf(leaf: Fr | BlockHash | NullifierLeaf | PublicDataTreeLeaf): SerializedLeafValue {
384
+ if (leaf instanceof BlockHash) {
385
+ return leaf.toBuffer();
386
+ } else if (leaf instanceof Fr) {
362
387
  return leaf.toBuffer();
363
388
  } else if (leaf instanceof NullifierLeaf) {
364
389
  return { nullifier: leaf.nullifier.toBuffer() };
@@ -1,7 +1,6 @@
1
1
  import { BlockNumber } from '@aztec/foundation/branded-types';
2
2
  import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import type { Tuple } from '@aztec/foundation/serialize';
4
- import type { BlockHash } from '@aztec/stdlib/block';
5
4
  import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
6
5
  import type { StateReference } from '@aztec/stdlib/tx';
7
6
  import type { UInt32 } from '@aztec/stdlib/types';
@@ -284,6 +283,16 @@ interface WithForkId {
284
283
  forkId: number;
285
284
  }
286
285
 
286
+ interface CreateCheckpointResponse {
287
+ depth: number;
288
+ }
289
+
290
+ /** Request to commit/revert all checkpoints down to a target depth. The resulting depth after the operation equals the given depth. */
291
+ interface CheckpointDepthRequest extends WithForkId {
292
+ /** The target depth after the operation. All checkpoints above this depth are committed/reverted. */
293
+ depth: number;
294
+ }
295
+
287
296
  interface WithWorldStateRevision {
288
297
  revision: WorldStateRevision;
289
298
  }
@@ -413,7 +422,7 @@ interface UpdateArchiveRequest extends WithForkId {
413
422
  interface SyncBlockRequest extends WithCanonicalForkId {
414
423
  blockNumber: BlockNumber;
415
424
  blockStateRef: BlockStateReference;
416
- blockHeaderHash: BlockHash;
425
+ blockHeaderHash: Buffer;
417
426
  paddedNoteHashes: readonly SerializedLeafValue[];
418
427
  paddedL1ToL2Messages: readonly SerializedLeafValue[];
419
428
  paddedNullifiers: readonly SerializedLeafValue[];
@@ -487,8 +496,8 @@ export type WorldStateRequest = {
487
496
  [WorldStateMessageType.CREATE_CHECKPOINT]: WithForkId;
488
497
  [WorldStateMessageType.COMMIT_CHECKPOINT]: WithForkId;
489
498
  [WorldStateMessageType.REVERT_CHECKPOINT]: WithForkId;
490
- [WorldStateMessageType.COMMIT_ALL_CHECKPOINTS]: WithForkId;
491
- [WorldStateMessageType.REVERT_ALL_CHECKPOINTS]: WithForkId;
499
+ [WorldStateMessageType.COMMIT_ALL_CHECKPOINTS]: CheckpointDepthRequest;
500
+ [WorldStateMessageType.REVERT_ALL_CHECKPOINTS]: CheckpointDepthRequest;
492
501
 
493
502
  [WorldStateMessageType.COPY_STORES]: CopyStoresRequest;
494
503
 
@@ -529,7 +538,7 @@ export type WorldStateResponse = {
529
538
 
530
539
  [WorldStateMessageType.GET_STATUS]: WorldStateStatusSummary;
531
540
 
532
- [WorldStateMessageType.CREATE_CHECKPOINT]: void;
541
+ [WorldStateMessageType.CREATE_CHECKPOINT]: CreateCheckpointResponse;
533
542
  [WorldStateMessageType.COMMIT_CHECKPOINT]: void;
534
543
  [WorldStateMessageType.REVERT_CHECKPOINT]: void;
535
544
  [WorldStateMessageType.COMMIT_ALL_CHECKPOINTS]: void;