@aztec/world-state 0.0.1-commit.e6bd8901 → 0.0.1-commit.ec7ac5448

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 (45) hide show
  1. package/dest/instrumentation/instrumentation.d.ts +1 -1
  2. package/dest/instrumentation/instrumentation.d.ts.map +1 -1
  3. package/dest/instrumentation/instrumentation.js +9 -2
  4. package/dest/native/fork_checkpoint.d.ts +7 -1
  5. package/dest/native/fork_checkpoint.d.ts.map +1 -1
  6. package/dest/native/fork_checkpoint.js +15 -3
  7. package/dest/native/merkle_trees_facade.d.ts +5 -5
  8. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  9. package/dest/native/merkle_trees_facade.js +9 -6
  10. package/dest/native/message.d.ts +14 -5
  11. package/dest/native/message.d.ts.map +1 -1
  12. package/dest/native/native_world_state.d.ts +8 -6
  13. package/dest/native/native_world_state.d.ts.map +1 -1
  14. package/dest/native/native_world_state.js +18 -12
  15. package/dest/native/native_world_state_instance.d.ts +5 -5
  16. package/dest/native/native_world_state_instance.d.ts.map +1 -1
  17. package/dest/native/native_world_state_instance.js +8 -7
  18. package/dest/native/world_state_ops_queue.js +5 -5
  19. package/dest/synchronizer/config.d.ts +3 -3
  20. package/dest/synchronizer/config.d.ts.map +1 -1
  21. package/dest/synchronizer/config.js +6 -3
  22. package/dest/synchronizer/factory.d.ts +6 -5
  23. package/dest/synchronizer/factory.d.ts.map +1 -1
  24. package/dest/synchronizer/factory.js +6 -5
  25. package/dest/synchronizer/server_world_state_synchronizer.d.ts +4 -4
  26. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  27. package/dest/synchronizer/server_world_state_synchronizer.js +90 -19
  28. package/dest/testing.d.ts +4 -3
  29. package/dest/testing.d.ts.map +1 -1
  30. package/dest/testing.js +10 -6
  31. package/dest/world-state-db/merkle_tree_db.d.ts +1 -10
  32. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  33. package/package.json +9 -10
  34. package/src/instrumentation/instrumentation.ts +9 -1
  35. package/src/native/fork_checkpoint.ts +19 -3
  36. package/src/native/merkle_trees_facade.ts +14 -7
  37. package/src/native/message.ts +15 -4
  38. package/src/native/native_world_state.ts +20 -14
  39. package/src/native/native_world_state_instance.ts +14 -8
  40. package/src/native/world_state_ops_queue.ts +5 -5
  41. package/src/synchronizer/config.ts +7 -5
  42. package/src/synchronizer/factory.ts +13 -7
  43. package/src/synchronizer/server_world_state_synchronizer.ts +100 -21
  44. package/src/testing.ts +8 -9
  45. package/src/world-state-db/merkle_tree_db.ts +0 -10
@@ -1,10 +1,11 @@
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 { GENESIS_BLOCK_HEADER_HASH, INITIAL_CHECKPOINT_NUMBER, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
3
3
  import type { Fr } from '@aztec/foundation/curves/bn254';
4
4
  import { type Logger, createLogger } from '@aztec/foundation/log';
5
5
  import { promiseWithResolvers } from '@aztec/foundation/promise';
6
6
  import { elapsed } from '@aztec/foundation/timer';
7
7
  import {
8
+ type BlockHash,
8
9
  GENESIS_CHECKPOINT_HEADER_HASH,
9
10
  type L2Block,
10
11
  type L2BlockId,
@@ -64,7 +65,7 @@ export class ServerWorldStateSynchronizer
64
65
  private readonly log: Logger = createLogger('world_state'),
65
66
  ) {
66
67
  this.merkleTreeCommitted = this.merkleTreeDb.getCommitted();
67
- this.historyToKeep = config.worldStateBlockHistory < 1 ? undefined : config.worldStateBlockHistory;
68
+ this.historyToKeep = config.worldStateCheckpointHistory < 1 ? undefined : config.worldStateCheckpointHistory;
68
69
  this.log.info(
69
70
  `Created world state synchroniser with block history of ${
70
71
  this.historyToKeep === undefined ? 'infinity' : this.historyToKeep
@@ -177,13 +178,10 @@ export class ServerWorldStateSynchronizer
177
178
  /**
178
179
  * Forces an immediate sync.
179
180
  * @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
180
- * @param skipThrowIfTargetNotReached - Whether to skip throwing if the target block number is not reached.
181
+ * @param blockHash - If provided, verifies the block at targetBlockNumber matches this hash. On mismatch, triggers a resync (reorg detection).
181
182
  * @returns A promise that resolves with the block number the world state was synced to
182
183
  */
183
- public async syncImmediate(
184
- targetBlockNumber?: BlockNumber,
185
- skipThrowIfTargetNotReached?: boolean,
186
- ): Promise<BlockNumber> {
184
+ public async syncImmediate(targetBlockNumber?: BlockNumber, blockHash?: BlockHash): Promise<BlockNumber> {
187
185
  if (this.currentState !== WorldStateRunningState.RUNNING) {
188
186
  throw new Error(`World State is not running. Unable to perform sync.`);
189
187
  }
@@ -195,7 +193,19 @@ export class ServerWorldStateSynchronizer
195
193
  // If we have been given a block number to sync to and we have reached that number then return
196
194
  const currentBlockNumber = await this.getLatestBlockNumber();
197
195
  if (targetBlockNumber !== undefined && targetBlockNumber <= currentBlockNumber) {
198
- return currentBlockNumber;
196
+ if (blockHash === undefined) {
197
+ return currentBlockNumber;
198
+ }
199
+
200
+ // If a block hash was provided, verify we're on the expected fork
201
+ const currentHash = await this.getL2BlockHash(targetBlockNumber);
202
+ if (currentHash === blockHash.toString()) {
203
+ return currentBlockNumber;
204
+ }
205
+ // Hash mismatch: a reorg may have occurred, fall through to trigger sync
206
+ this.log.debug(
207
+ `World state block hash mismatch at ${targetBlockNumber} (expected ${blockHash}, got ${currentHash}). Triggering resync.`,
208
+ );
199
209
  }
200
210
  this.log.debug(`World State at ${currentBlockNumber} told to sync to ${targetBlockNumber ?? 'latest'}`);
201
211
 
@@ -213,7 +223,7 @@ export class ServerWorldStateSynchronizer
213
223
 
214
224
  // If we have been given a block number to sync to and we have not reached that number then fail
215
225
  const updatedBlockNumber = await this.getLatestBlockNumber();
216
- if (!skipThrowIfTargetNotReached && targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
226
+ if (targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
217
227
  throw new WorldStateSynchronizerError(
218
228
  `Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`,
219
229
  {
@@ -227,6 +237,24 @@ export class ServerWorldStateSynchronizer
227
237
  );
228
238
  }
229
239
 
240
+ // If a block hash was provided, verify we're on the expected fork after syncing, throw otherwise
241
+ if (blockHash !== undefined && targetBlockNumber !== undefined) {
242
+ const updatedHash = await this.getL2BlockHash(targetBlockNumber);
243
+ if (updatedHash !== blockHash.toString()) {
244
+ throw new WorldStateSynchronizerError(
245
+ `Block hash mismatch at block ${targetBlockNumber} (expected ${blockHash} but got ${updatedHash})`,
246
+ {
247
+ cause: {
248
+ reason: 'block_hash_mismatch',
249
+ targetBlockNumber,
250
+ expectedHash: blockHash.toString(),
251
+ actualHash: updatedHash,
252
+ },
253
+ },
254
+ );
255
+ }
256
+ }
257
+
230
258
  return updatedBlockNumber;
231
259
  }
232
260
 
@@ -263,15 +291,19 @@ export class ServerWorldStateSynchronizer
263
291
  proposed: latestBlockId,
264
292
  checkpointed: {
265
293
  block: { number: INITIAL_L2_BLOCK_NUM, hash: GENESIS_BLOCK_HEADER_HASH.toString() },
266
- checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
294
+ checkpoint: { number: INITIAL_CHECKPOINT_NUMBER, hash: genesisCheckpointHeaderHash },
295
+ },
296
+ proposedCheckpoint: {
297
+ block: { number: INITIAL_L2_BLOCK_NUM, hash: GENESIS_BLOCK_HEADER_HASH.toString() },
298
+ checkpoint: { number: INITIAL_CHECKPOINT_NUMBER, hash: genesisCheckpointHeaderHash },
267
299
  },
268
300
  finalized: {
269
301
  block: { number: status.finalizedBlockNumber, hash: finalizedBlockHash ?? '' },
270
- checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
302
+ checkpoint: { number: INITIAL_CHECKPOINT_NUMBER, hash: genesisCheckpointHeaderHash },
271
303
  },
272
304
  proven: {
273
305
  block: { number: provenBlockNumber, hash: provenBlockHash ?? '' },
274
- checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
306
+ checkpoint: { number: INITIAL_CHECKPOINT_NUMBER, hash: genesisCheckpointHeaderHash },
275
307
  },
276
308
  };
277
309
  }
@@ -300,7 +332,7 @@ export class ServerWorldStateSynchronizer
300
332
  * @returns Whether the block handled was produced by this same node.
301
333
  */
302
334
  private async handleL2Blocks(l2Blocks: L2Block[]) {
303
- this.log.trace(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1)!.number}`);
335
+ this.log.debug(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1)!.number}`);
304
336
 
305
337
  // Fetch the L1->L2 messages for the first block in a checkpoint.
306
338
  const messagesForBlocks = new Map<BlockNumber, Fr[]>();
@@ -341,10 +373,12 @@ export class ServerWorldStateSynchronizer
341
373
  * @returns Whether the block handled was produced by this same node.
342
374
  */
343
375
  private async handleL2Block(l2Block: L2Block, l1ToL2Messages: Fr[]): Promise<WorldStateStatusFull> {
344
- this.log.trace(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
376
+ this.log.debug(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
345
377
  blockNumber: l2Block.number,
346
378
  blockHash: await l2Block.hash().then(h => h.toString()),
347
379
  l1ToL2Messages: l1ToL2Messages.map(msg => msg.toString()),
380
+ blockHeader: l2Block.header.toInspect(),
381
+ blockStats: l2Block.getStats(),
348
382
  });
349
383
  const result = await this.merkleTreeDb.handleL2BlockAndMessages(l2Block, l1ToL2Messages);
350
384
 
@@ -358,16 +392,59 @@ export class ServerWorldStateSynchronizer
358
392
 
359
393
  private async handleChainFinalized(blockNumber: BlockNumber) {
360
394
  this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
395
+ // If the finalized block number is older than the oldest available block in world state,
396
+ // skip entirely. The finalized block number can jump backwards (e.g. when the finalization
397
+ // heuristic changes) and try to read block data that has already been pruned. When this
398
+ // happens, there is nothing useful to do — the native world state is already finalized
399
+ // past this point and pruning has already happened.
400
+ const currentSummary = await this.merkleTreeDb.getStatusSummary();
401
+ if (blockNumber < currentSummary.oldestHistoricalBlock || blockNumber < 1) {
402
+ this.log.trace(
403
+ `Finalized block ${blockNumber} is older than the oldest available block ${currentSummary.oldestHistoricalBlock}. Skipping.`,
404
+ );
405
+ return;
406
+ }
361
407
  const summary = await this.merkleTreeDb.setFinalized(blockNumber);
362
408
  if (this.historyToKeep === undefined) {
363
409
  return;
364
410
  }
365
- const newHistoricBlock = summary.finalizedBlockNumber - this.historyToKeep + 1;
366
- if (newHistoricBlock <= 1) {
411
+ // Get the checkpointed block for the finalized block number
412
+ const finalisedCheckpoint = await this.l2BlockSource.getCheckpointedBlock(summary.finalizedBlockNumber);
413
+ if (finalisedCheckpoint === undefined) {
414
+ this.log.warn(
415
+ `Failed to retrieve checkpointed block for finalized block number: ${summary.finalizedBlockNumber}`,
416
+ );
417
+ return;
418
+ }
419
+ // Compute the required historic checkpoint number
420
+ const newHistoricCheckpointNumber = finalisedCheckpoint.checkpointNumber - this.historyToKeep + 1;
421
+ if (newHistoricCheckpointNumber <= 1) {
422
+ return;
423
+ }
424
+ // Retrieve the historic checkpoint
425
+ const historicCheckpoints = await this.l2BlockSource.getCheckpoints(
426
+ CheckpointNumber(newHistoricCheckpointNumber),
427
+ 1,
428
+ );
429
+ if (historicCheckpoints.length === 0 || historicCheckpoints[0] === undefined) {
430
+ this.log.warn(`Failed to retrieve checkpoint number ${newHistoricCheckpointNumber} from Archiver`);
367
431
  return;
368
432
  }
369
- this.log.verbose(`Pruning historic blocks to ${newHistoricBlock}`);
370
- const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock));
433
+ const historicCheckpoint = historicCheckpoints[0];
434
+ if (historicCheckpoint.checkpoint.blocks.length === 0 || historicCheckpoint.checkpoint.blocks[0] === undefined) {
435
+ this.log.warn(`Retrieved checkpoint number ${newHistoricCheckpointNumber} has no blocks!`);
436
+ return;
437
+ }
438
+ // Find the block at the start of the checkpoint and remove blocks up to this one
439
+ const newHistoricBlock = historicCheckpoint.checkpoint.blocks[0];
440
+ if (newHistoricBlock.number <= currentSummary.oldestHistoricalBlock) {
441
+ this.log.debug(
442
+ `Historic block ${newHistoricBlock.number} is not newer than oldest available ${currentSummary.oldestHistoricalBlock}. Skipping prune.`,
443
+ );
444
+ return;
445
+ }
446
+ this.log.verbose(`Pruning historic blocks to ${newHistoricBlock.number}`);
447
+ const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock.number));
371
448
  this.log.debug(`World state summary `, status.summary);
372
449
  }
373
450
 
@@ -378,9 +455,11 @@ export class ServerWorldStateSynchronizer
378
455
  }
379
456
 
380
457
  private async handleChainPruned(blockNumber: BlockNumber) {
381
- this.log.warn(`Chain pruned to block ${blockNumber}`);
458
+ this.log.info(`Chain pruned to block ${blockNumber}`);
382
459
  const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
383
- this.provenBlockNumber = undefined;
460
+ if (this.provenBlockNumber !== undefined && this.provenBlockNumber > blockNumber) {
461
+ this.provenBlockNumber = undefined;
462
+ }
384
463
  this.instrumentation.updateWorldStateMetrics(status);
385
464
  }
386
465
 
package/src/testing.ts CHANGED
@@ -3,22 +3,19 @@ import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { computeFeePayerBalanceLeafSlot } from '@aztec/protocol-contracts/fee-juice';
4
4
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
5
5
  import { MerkleTreeId, PublicDataTreeLeaf } from '@aztec/stdlib/trees';
6
+ import type { GenesisData } from '@aztec/stdlib/world-state';
6
7
 
7
8
  import { NativeWorldStateService } from './native/index.js';
8
9
 
9
- async function generateGenesisValues(prefilledPublicData: PublicDataTreeLeaf[]) {
10
- if (!prefilledPublicData.length) {
10
+ async function generateGenesisValues(genesis: GenesisData) {
11
+ if (!genesis.prefilledPublicData.length && genesis.genesisTimestamp === 0n) {
11
12
  return {
12
13
  genesisArchiveRoot: new Fr(GENESIS_ARCHIVE_ROOT),
13
14
  };
14
15
  }
15
16
 
16
17
  // Create a temporary world state to compute the genesis values.
17
- const ws = await NativeWorldStateService.tmp(
18
- undefined /* rollupAddress */,
19
- true /* cleanupTmpDir */,
20
- prefilledPublicData,
21
- );
18
+ const ws = await NativeWorldStateService.tmp(undefined /* rollupAddress */, true /* cleanupTmpDir */, genesis);
22
19
  const genesisArchiveRoot = new Fr((await ws.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
23
20
  await ws.close();
24
21
 
@@ -33,6 +30,7 @@ export async function getGenesisValues(
33
30
  initialAccounts: AztecAddress[],
34
31
  initialAccountFeeJuice = defaultInitialAccountFeeJuice,
35
32
  genesisPublicData: PublicDataTreeLeaf[] = [],
33
+ genesisTimestamp: bigint = 0n,
36
34
  ) {
37
35
  // Top up the accounts with fee juice.
38
36
  let prefilledPublicData = await Promise.all(
@@ -46,11 +44,12 @@ export async function getGenesisValues(
46
44
 
47
45
  prefilledPublicData.sort((a, b) => (b.slot.lt(a.slot) ? 1 : -1));
48
46
 
49
- const { genesisArchiveRoot } = await generateGenesisValues(prefilledPublicData);
47
+ const genesis: GenesisData = { prefilledPublicData, genesisTimestamp };
48
+ const { genesisArchiveRoot } = await generateGenesisValues(genesis);
50
49
 
51
50
  return {
52
51
  genesisArchiveRoot,
53
- prefilledPublicData,
52
+ genesis,
54
53
  fundingNeeded: BigInt(initialAccounts.length) * initialAccountFeeJuice.toBigInt(),
55
54
  };
56
55
  }
@@ -1,14 +1,12 @@
1
1
  import { MAX_NULLIFIERS_PER_TX, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX } from '@aztec/constants';
2
2
  import type { BlockNumber } from '@aztec/foundation/branded-types';
3
3
  import type { Fr } from '@aztec/foundation/curves/bn254';
4
- import type { IndexedTreeSnapshot, TreeSnapshot } from '@aztec/merkle-tree';
5
4
  import type { L2Block } from '@aztec/stdlib/block';
6
5
  import type {
7
6
  ForkMerkleTreeOperations,
8
7
  MerkleTreeReadOperations,
9
8
  ReadonlyWorldStateAccess,
10
9
  } from '@aztec/stdlib/interfaces/server';
11
- import type { MerkleTreeId } from '@aztec/stdlib/trees';
12
10
 
13
11
  import type { WorldStateStatusFull, WorldStateStatusSummary } from '../native/message.js';
14
12
 
@@ -31,14 +29,6 @@ export const INITIAL_NULLIFIER_TREE_SIZE = 2 * MAX_NULLIFIERS_PER_TX;
31
29
 
32
30
  export const INITIAL_PUBLIC_DATA_TREE_SIZE = 2 * MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX;
33
31
 
34
- export type TreeSnapshots = {
35
- [MerkleTreeId.NULLIFIER_TREE]: IndexedTreeSnapshot;
36
- [MerkleTreeId.NOTE_HASH_TREE]: TreeSnapshot<Fr>;
37
- [MerkleTreeId.PUBLIC_DATA_TREE]: IndexedTreeSnapshot;
38
- [MerkleTreeId.L1_TO_L2_MESSAGE_TREE]: TreeSnapshot<Fr>;
39
- [MerkleTreeId.ARCHIVE]: TreeSnapshot<Fr>;
40
- };
41
-
42
32
  export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations, ReadonlyWorldStateAccess {
43
33
  /**
44
34
  * Handles a single L2 block (i.e. Inserts the new note hashes into the merkle tree).