@aztec/world-state 0.0.1-commit.b655e406 → 0.0.1-commit.d3ec352c

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 (50) hide show
  1. package/dest/index.d.ts +1 -1
  2. package/dest/instrumentation/instrumentation.d.ts +1 -1
  3. package/dest/instrumentation/instrumentation.d.ts.map +1 -1
  4. package/dest/native/bench_metrics.d.ts +1 -1
  5. package/dest/native/bench_metrics.d.ts.map +1 -1
  6. package/dest/native/fork_checkpoint.d.ts +1 -1
  7. package/dest/native/fork_checkpoint.d.ts.map +1 -1
  8. package/dest/native/index.d.ts +1 -1
  9. package/dest/native/merkle_trees_facade.d.ts +5 -4
  10. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  11. package/dest/native/merkle_trees_facade.js +4 -2
  12. package/dest/native/message.d.ts +11 -10
  13. package/dest/native/message.d.ts.map +1 -1
  14. package/dest/native/message.js +13 -12
  15. package/dest/native/native_world_state.d.ts +9 -8
  16. package/dest/native/native_world_state.d.ts.map +1 -1
  17. package/dest/native/native_world_state.js +11 -8
  18. package/dest/native/native_world_state_instance.d.ts +10 -1
  19. package/dest/native/native_world_state_instance.d.ts.map +1 -1
  20. package/dest/native/native_world_state_instance.js +21 -0
  21. package/dest/native/world_state_ops_queue.d.ts +1 -1
  22. package/dest/native/world_state_ops_queue.d.ts.map +1 -1
  23. package/dest/synchronizer/config.d.ts +1 -1
  24. package/dest/synchronizer/errors.d.ts +1 -1
  25. package/dest/synchronizer/errors.d.ts.map +1 -1
  26. package/dest/synchronizer/factory.d.ts +1 -1
  27. package/dest/synchronizer/index.d.ts +1 -1
  28. package/dest/synchronizer/server_world_state_synchronizer.d.ts +7 -25
  29. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  30. package/dest/synchronizer/server_world_state_synchronizer.js +35 -52
  31. package/dest/synchronizer/utils.d.ts +11 -0
  32. package/dest/synchronizer/utils.d.ts.map +1 -0
  33. package/dest/synchronizer/utils.js +59 -0
  34. package/dest/test/index.d.ts +1 -1
  35. package/dest/test/utils.d.ts +21 -8
  36. package/dest/test/utils.d.ts.map +1 -1
  37. package/dest/test/utils.js +51 -10
  38. package/dest/testing.d.ts +1 -1
  39. package/dest/world-state-db/index.d.ts +1 -1
  40. package/dest/world-state-db/merkle_tree_db.d.ts +9 -8
  41. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  42. package/package.json +13 -12
  43. package/src/native/merkle_trees_facade.ts +6 -5
  44. package/src/native/message.ts +22 -21
  45. package/src/native/native_world_state.ts +28 -17
  46. package/src/native/native_world_state_instance.ts +28 -0
  47. package/src/synchronizer/server_world_state_synchronizer.ts +58 -75
  48. package/src/synchronizer/utils.ts +83 -0
  49. package/src/test/utils.ts +66 -13
  50. package/src/world-state-db/merkle_tree_db.ts +12 -7
@@ -1,13 +1,11 @@
1
- import { L1_TO_L2_MSG_SUBTREE_HEIGHT } from '@aztec/constants';
2
- import { SHA256Trunc } from '@aztec/foundation/crypto';
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
3
2
  import type { Fr } from '@aztec/foundation/fields';
4
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
5
4
  import { promiseWithResolvers } from '@aztec/foundation/promise';
6
5
  import { elapsed } from '@aztec/foundation/timer';
7
- import { MerkleTreeCalculator } from '@aztec/foundation/trees';
8
6
  import type {
9
- L2Block,
10
7
  L2BlockId,
8
+ L2BlockNew,
11
9
  L2BlockSource,
12
10
  L2BlockStream,
13
11
  L2BlockStreamEvent,
@@ -32,6 +30,7 @@ import type { WorldStateStatusFull } from '../native/message.js';
32
30
  import type { MerkleTreeAdminDatabase } from '../world-state-db/merkle_tree_db.js';
33
31
  import type { WorldStateConfig } from './config.js';
34
32
  import { WorldStateSynchronizerError } from './errors.js';
33
+ import { findFirstBlocksInCheckpoints } from './utils.js';
35
34
 
36
35
  export type { SnapshotDataKeys };
37
36
 
@@ -45,17 +44,17 @@ export class ServerWorldStateSynchronizer
45
44
  {
46
45
  private readonly merkleTreeCommitted: MerkleTreeReadOperations;
47
46
 
48
- private latestBlockNumberAtStart = 0;
47
+ private latestBlockNumberAtStart = BlockNumber.ZERO;
49
48
  private historyToKeep: number | undefined;
50
49
  private currentState: WorldStateRunningState = WorldStateRunningState.IDLE;
51
- private latestBlockHashQuery: { blockNumber: number; hash: string | undefined } | undefined = undefined;
50
+ private latestBlockHashQuery: { blockNumber: BlockNumber; hash: string | undefined } | undefined = undefined;
52
51
 
53
52
  private syncPromise = promiseWithResolvers<void>();
54
53
  protected blockStream: L2BlockStream | undefined;
55
54
 
56
55
  // WorldState doesn't track the proven block number, it only tracks the latest tips of the pending chain and the finalized chain
57
56
  // store the proven block number here, in the synchronizer, so that we don't end up spamming the logs with 'chain-proved' events
58
- private provenBlockNumber: bigint | undefined;
57
+ private provenBlockNumber: BlockNumber | undefined;
59
58
 
60
59
  constructor(
61
60
  private readonly merkleTreeDb: MerkleTreeAdminDatabase,
@@ -77,11 +76,11 @@ export class ServerWorldStateSynchronizer
77
76
  return this.merkleTreeDb.getCommitted();
78
77
  }
79
78
 
80
- public getSnapshot(blockNumber: number): MerkleTreeReadOperations {
79
+ public getSnapshot(blockNumber: BlockNumber): MerkleTreeReadOperations {
81
80
  return this.merkleTreeDb.getSnapshot(blockNumber);
82
81
  }
83
82
 
84
- public fork(blockNumber?: number): Promise<MerkleTreeWriteOperations> {
83
+ public fork(blockNumber?: BlockNumber): Promise<MerkleTreeWriteOperations> {
85
84
  return this.merkleTreeDb.fork(blockNumber);
86
85
  }
87
86
 
@@ -102,9 +101,11 @@ export class ServerWorldStateSynchronizer
102
101
  }
103
102
 
104
103
  // Get the current latest block number
105
- this.latestBlockNumberAtStart = await (this.config.worldStateProvenBlocksOnly
106
- ? this.l2BlockSource.getProvenBlockNumber()
107
- : this.l2BlockSource.getBlockNumber());
104
+ this.latestBlockNumberAtStart = BlockNumber(
105
+ await (this.config.worldStateProvenBlocksOnly
106
+ ? this.l2BlockSource.getProvenBlockNumber()
107
+ : this.l2BlockSource.getBlockNumber()),
108
+ );
108
109
 
109
110
  const blockToDownloadFrom = (await this.getLatestBlockNumber()) + 1;
110
111
 
@@ -147,10 +148,10 @@ export class ServerWorldStateSynchronizer
147
148
  public async status(): Promise<WorldStateSynchronizerStatus> {
148
149
  const summary = await this.merkleTreeDb.getStatusSummary();
149
150
  const status: WorldStateSyncStatus = {
150
- latestBlockNumber: Number(summary.unfinalizedBlockNumber),
151
- latestBlockHash: (await this.getL2BlockHash(Number(summary.unfinalizedBlockNumber))) ?? '',
152
- finalizedBlockNumber: Number(summary.finalizedBlockNumber),
153
- oldestHistoricBlockNumber: Number(summary.oldestHistoricalBlock),
151
+ latestBlockNumber: summary.unfinalizedBlockNumber,
152
+ latestBlockHash: (await this.getL2BlockHash(summary.unfinalizedBlockNumber)) ?? '',
153
+ finalizedBlockNumber: summary.finalizedBlockNumber,
154
+ oldestHistoricBlockNumber: summary.oldestHistoricalBlock,
154
155
  treesAreSynched: summary.treesAreSynched,
155
156
  };
156
157
  return {
@@ -184,7 +185,10 @@ export class ServerWorldStateSynchronizer
184
185
  * @param skipThrowIfTargetNotReached - Whether to skip throwing if the target block number is not reached.
185
186
  * @returns A promise that resolves with the block number the world state was synced to
186
187
  */
187
- public async syncImmediate(targetBlockNumber?: number, skipThrowIfTargetNotReached?: boolean): Promise<number> {
188
+ public async syncImmediate(
189
+ targetBlockNumber?: BlockNumber,
190
+ skipThrowIfTargetNotReached?: boolean,
191
+ ): Promise<BlockNumber> {
188
192
  if (this.currentState !== WorldStateRunningState.RUNNING) {
189
193
  throw new Error(`World State is not running. Unable to perform sync.`);
190
194
  }
@@ -202,7 +206,7 @@ export class ServerWorldStateSynchronizer
202
206
 
203
207
  // If the archiver is behind the target block, force an archiver sync
204
208
  if (targetBlockNumber) {
205
- const archiverLatestBlock = await this.l2BlockSource.getBlockNumber();
209
+ const archiverLatestBlock = BlockNumber(await this.l2BlockSource.getBlockNumber());
206
210
  if (archiverLatestBlock < targetBlockNumber) {
207
211
  this.log.debug(`Archiver is at ${archiverLatestBlock} behind target block ${targetBlockNumber}.`);
208
212
  await this.l2BlockSource.syncImmediate();
@@ -232,8 +236,8 @@ export class ServerWorldStateSynchronizer
232
236
  }
233
237
 
234
238
  /** Returns the L2 block hash for a given number. Used by the L2BlockStream for detecting reorgs. */
235
- public async getL2BlockHash(number: number): Promise<string | undefined> {
236
- if (number === 0) {
239
+ public async getL2BlockHash(number: BlockNumber): Promise<string | undefined> {
240
+ if (number === BlockNumber.ZERO) {
237
241
  return (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
238
242
  }
239
243
  if (this.latestBlockHashQuery?.hash === undefined || number !== this.latestBlockHashQuery.blockNumber) {
@@ -250,13 +254,13 @@ export class ServerWorldStateSynchronizer
250
254
  /** Returns the latest L2 block number for each tip of the chain (latest, proven, finalized). */
251
255
  public async getL2Tips(): Promise<L2Tips> {
252
256
  const status = await this.merkleTreeDb.getStatusSummary();
253
- const unfinalizedBlockHash = await this.getL2BlockHash(Number(status.unfinalizedBlockNumber));
254
- const latestBlockId: L2BlockId = { number: Number(status.unfinalizedBlockNumber), hash: unfinalizedBlockHash! };
257
+ const unfinalizedBlockHash = await this.getL2BlockHash(status.unfinalizedBlockNumber);
258
+ const latestBlockId: L2BlockId = { number: status.unfinalizedBlockNumber, hash: unfinalizedBlockHash! };
255
259
 
256
260
  return {
257
261
  latest: latestBlockId,
258
- finalized: { number: Number(status.finalizedBlockNumber), hash: '' },
259
- proven: { number: Number(this.provenBlockNumber ?? status.finalizedBlockNumber), hash: '' }, // TODO(palla/reorg): Using finalized as proven for now
262
+ finalized: { number: status.finalizedBlockNumber, hash: '' },
263
+ proven: { number: this.provenBlockNumber ?? status.finalizedBlockNumber, hash: '' }, // TODO(palla/reorg): Using finalized as proven for now
260
264
  };
261
265
  }
262
266
 
@@ -264,16 +268,16 @@ export class ServerWorldStateSynchronizer
264
268
  public async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise<void> {
265
269
  switch (event.type) {
266
270
  case 'blocks-added':
267
- await this.handleL2Blocks(event.blocks.map(b => b.block));
271
+ await this.handleL2Blocks(event.blocks.map(b => b.block.toL2Block()));
268
272
  break;
269
273
  case 'chain-pruned':
270
- await this.handleChainPruned(event.block.number);
274
+ await this.handleChainPruned(BlockNumber(event.block.number));
271
275
  break;
272
276
  case 'chain-proven':
273
- await this.handleChainProven(event.block.number);
277
+ await this.handleChainProven(BlockNumber(event.block.number));
274
278
  break;
275
279
  case 'chain-finalized':
276
- await this.handleChainFinalized(event.block.number);
280
+ await this.handleChainFinalized(BlockNumber(event.block.number));
277
281
  break;
278
282
  }
279
283
  }
@@ -283,22 +287,23 @@ export class ServerWorldStateSynchronizer
283
287
  * @param l2Blocks - The L2 blocks to handle.
284
288
  * @returns Whether the block handled was produced by this same node.
285
289
  */
286
- private async handleL2Blocks(l2Blocks: L2Block[]) {
290
+ private async handleL2Blocks(l2Blocks: L2BlockNew[]) {
287
291
  this.log.trace(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1)!.number}`);
288
292
 
289
- const messagePromises = l2Blocks.map(block => this.l2BlockSource.getL1ToL2Messages(block.number));
290
- const l1ToL2Messages: Fr[][] = await Promise.all(messagePromises);
291
- let updateStatus: WorldStateStatusFull | undefined = undefined;
293
+ const firstBlocksInCheckpoints = await findFirstBlocksInCheckpoints(l2Blocks, this.l2BlockSource);
292
294
 
293
- for (let i = 0; i < l2Blocks.length; i++) {
294
- const [duration, result] = await elapsed(() => this.handleL2Block(l2Blocks[i], l1ToL2Messages[i]));
295
- this.log.info(`World state updated with L2 block ${l2Blocks[i].number}`, {
295
+ let updateStatus: WorldStateStatusFull | undefined = undefined;
296
+ for (const block of l2Blocks) {
297
+ const l1ToL2Messages = firstBlocksInCheckpoints.get(block.number) ?? [];
298
+ const isFirstBlock = firstBlocksInCheckpoints.has(block.number);
299
+ const [duration, result] = await elapsed(() => this.handleL2Block(block, l1ToL2Messages, isFirstBlock));
300
+ this.log.info(`World state updated with L2 block ${block.number}`, {
296
301
  eventName: 'l2-block-handled',
297
302
  duration,
298
- unfinalizedBlockNumber: result.summary.unfinalizedBlockNumber,
299
- finalizedBlockNumber: result.summary.finalizedBlockNumber,
300
- oldestHistoricBlock: result.summary.oldestHistoricalBlock,
301
- ...l2Blocks[i].getStats(),
303
+ unfinalizedBlockNumber: BigInt(result.summary.unfinalizedBlockNumber),
304
+ finalizedBlockNumber: BigInt(result.summary.finalizedBlockNumber),
305
+ oldestHistoricBlock: BigInt(result.summary.oldestHistoricalBlock),
306
+ ...block.getStats(),
302
307
  } satisfies L2BlockHandledStats);
303
308
  updateStatus = result;
304
309
  }
@@ -314,20 +319,18 @@ export class ServerWorldStateSynchronizer
314
319
  * @param l1ToL2Messages - The L1 to L2 messages for the block.
315
320
  * @returns Whether the block handled was produced by this same node.
316
321
  */
317
- private async handleL2Block(l2Block: L2Block, l1ToL2Messages: Fr[]): Promise<WorldStateStatusFull> {
318
- // First we check that the L1 to L2 messages hash to the block inHash.
319
- // Note that we cannot optimize this check by checking the root of the subtree after inserting the messages
320
- // to the real L1_TO_L2_MESSAGE_TREE (like we do in merkleTreeDb.handleL2BlockAndMessages(...)) because that
321
- // tree uses pedersen and we don't have access to the converted root.
322
- await this.verifyMessagesHashToInHash(l1ToL2Messages, l2Block.header.contentCommitment.inHash);
323
-
322
+ private async handleL2Block(
323
+ l2Block: L2BlockNew,
324
+ l1ToL2Messages: Fr[],
325
+ isFirstBlock: boolean,
326
+ ): Promise<WorldStateStatusFull> {
324
327
  // If the above check succeeds, we can proceed to handle the block.
325
328
  this.log.trace(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
326
329
  blockNumber: l2Block.number,
327
330
  blockHash: await l2Block.hash().then(h => h.toString()),
328
331
  l1ToL2Messages: l1ToL2Messages.map(msg => msg.toString()),
329
332
  });
330
- const result = await this.merkleTreeDb.handleL2BlockAndMessages(l2Block, l1ToL2Messages);
333
+ const result = await this.merkleTreeDb.handleL2BlockAndMessages(l2Block, l1ToL2Messages, isFirstBlock);
331
334
 
332
335
  if (this.currentState === WorldStateRunningState.SYNCHING && l2Block.number >= this.latestBlockNumberAtStart) {
333
336
  this.setCurrentState(WorldStateRunningState.RUNNING);
@@ -337,14 +340,14 @@ export class ServerWorldStateSynchronizer
337
340
  return result;
338
341
  }
339
342
 
340
- private async handleChainFinalized(blockNumber: number) {
343
+ private async handleChainFinalized(blockNumber: BlockNumber) {
341
344
  this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
342
- const summary = await this.merkleTreeDb.setFinalized(BigInt(blockNumber));
345
+ const summary = await this.merkleTreeDb.setFinalized(blockNumber);
343
346
  if (this.historyToKeep === undefined) {
344
347
  return;
345
348
  }
346
- const newHistoricBlock = summary.finalizedBlockNumber - BigInt(this.historyToKeep) + 1n;
347
- if (newHistoricBlock <= 1) {
349
+ const newHistoricBlock = BlockNumber(summary.finalizedBlockNumber - this.historyToKeep + 1);
350
+ if (newHistoricBlock <= BlockNumber(1)) {
348
351
  return;
349
352
  }
350
353
  this.log.verbose(`Pruning historic blocks to ${newHistoricBlock}`);
@@ -352,15 +355,15 @@ export class ServerWorldStateSynchronizer
352
355
  this.log.debug(`World state summary `, status.summary);
353
356
  }
354
357
 
355
- private handleChainProven(blockNumber: number) {
356
- this.provenBlockNumber = BigInt(blockNumber);
358
+ private handleChainProven(blockNumber: BlockNumber) {
359
+ this.provenBlockNumber = blockNumber;
357
360
  this.log.debug(`Proven chain is now at block ${blockNumber}`);
358
361
  return Promise.resolve();
359
362
  }
360
363
 
361
- private async handleChainPruned(blockNumber: number) {
364
+ private async handleChainPruned(blockNumber: BlockNumber) {
362
365
  this.log.warn(`Chain pruned to block ${blockNumber}`);
363
- const status = await this.merkleTreeDb.unwindBlocks(BigInt(blockNumber));
366
+ const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
364
367
  this.latestBlockHashQuery = undefined;
365
368
  this.provenBlockNumber = undefined;
366
369
  this.instrumentation.updateWorldStateMetrics(status);
@@ -374,24 +377,4 @@ export class ServerWorldStateSynchronizer
374
377
  this.currentState = newState;
375
378
  this.log.debug(`Moved to state ${WorldStateRunningState[this.currentState]}`);
376
379
  }
377
-
378
- /**
379
- * Verifies that the L1 to L2 messages hash to the block inHash.
380
- * @param l1ToL2Messages - The L1 to L2 messages for the block.
381
- * @param inHash - The inHash of the block.
382
- * @throws If the L1 to L2 messages do not hash to the block inHash.
383
- */
384
- protected async verifyMessagesHashToInHash(l1ToL2Messages: Fr[], inHash: Fr) {
385
- const treeCalculator = await MerkleTreeCalculator.create(
386
- L1_TO_L2_MSG_SUBTREE_HEIGHT,
387
- Buffer.alloc(32),
388
- (lhs, rhs) => Promise.resolve(new SHA256Trunc().hash(lhs, rhs)),
389
- );
390
-
391
- const root = await treeCalculator.computeTreeRoot(l1ToL2Messages.map(msg => msg.toBuffer()));
392
-
393
- if (!root.equals(inHash.toBuffer())) {
394
- throw new Error('Obtained L1 to L2 messages failed to be hashed to the block inHash');
395
- }
396
- }
397
380
  }
@@ -0,0 +1,83 @@
1
+ import { BlockNumber, type SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { Fr } from '@aztec/foundation/fields';
3
+ import type { L2BlockNew, L2BlockSource } from '@aztec/stdlib/block';
4
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
5
+ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
6
+
7
+ /**
8
+ * Determine which blocks in the given array are the first block in a checkpoint.
9
+ * @param blocks - The candidate blocks, sorted by block number in ascending order.
10
+ * @param l2BlockSource - The L2 block source to use to fetch the checkpoints, block headers and L1->L2 messages.
11
+ * @returns A map of block numbers that begin a checkpoint to the L1->L2 messages for that checkpoint.
12
+ */
13
+ export async function findFirstBlocksInCheckpoints(
14
+ blocks: L2BlockNew[],
15
+ l2BlockSource: L2BlockSource & L1ToL2MessageSource,
16
+ ): Promise<Map<number, Fr[]>> {
17
+ // Select the blocks that are the final block within each group of identical slot numbers.
18
+ let seenSlot: SlotNumber | undefined;
19
+ const maybeLastBlocks = [...blocks]
20
+ .reverse()
21
+ .filter(b => {
22
+ if (b.header.globalVariables.slotNumber !== seenSlot) {
23
+ seenSlot = b.header.globalVariables.slotNumber;
24
+ return true;
25
+ }
26
+ return false;
27
+ })
28
+ .reverse();
29
+
30
+ // Try to fetch the checkpoints for those blocks. If undefined (which should only occur for blocks.at(-1)),
31
+ // then the block is not the last one in a checkpoint.
32
+ // If we are not checking the inHashes below, only blocks.at(-1) would need its checkpoint header fetched.
33
+ const checkpointedBlocks = (
34
+ await Promise.all(
35
+ maybeLastBlocks.map(async b => ({
36
+ blockNumber: b.number,
37
+ // A checkpoint's archive root is the archive root of its last block.
38
+ checkpoint: await l2BlockSource.getCheckpointByArchive(b.archive.root),
39
+ })),
40
+ )
41
+ ).filter(b => b.checkpoint !== undefined) as { blockNumber: BlockNumber; checkpoint: Checkpoint }[];
42
+
43
+ // Verify that the L1->L2 messages hash to the checkpoint's inHash.
44
+ const checkpointedL1ToL2Messages: Fr[][] = await Promise.all(
45
+ checkpointedBlocks.map(b => l2BlockSource.getL1ToL2MessagesForCheckpoint(b.checkpoint!.number)),
46
+ );
47
+ checkpointedBlocks.forEach((b, i) => {
48
+ const computedInHash = computeInHashFromL1ToL2Messages(checkpointedL1ToL2Messages[i]);
49
+ const inHash = b.checkpoint.header.contentCommitment.inHash;
50
+ if (!computedInHash.equals(inHash)) {
51
+ throw new Error('Obtained L1 to L2 messages failed to be hashed to the checkpoint inHash');
52
+ }
53
+ });
54
+
55
+ // Compute the first block numbers, which should be right after each checkpointed block. Exclude blocks that haven't
56
+ // been added yet.
57
+ const firstBlockNumbers = checkpointedBlocks
58
+ .map(b => BlockNumber(b.blockNumber + 1))
59
+ .filter(n => n <= blocks.at(-1)!.number);
60
+ // Check if blocks[0] is the first block in a checkpoint.
61
+ if (blocks[0].number === 1) {
62
+ firstBlockNumbers.push(blocks[0].number);
63
+ } else {
64
+ const lastBlockHeader = await l2BlockSource.getBlockHeader(BlockNumber(blocks[0].number - 1));
65
+ if (!lastBlockHeader) {
66
+ throw new Error(`Failed to get block ${blocks[0].number - 1}`);
67
+ }
68
+ if (lastBlockHeader.globalVariables.slotNumber !== blocks[0].header.globalVariables.slotNumber) {
69
+ firstBlockNumbers.push(blocks[0].number);
70
+ }
71
+ }
72
+
73
+ // Fetch the L1->L2 messages for the first blocks and assign them to the map.
74
+ const messagesByBlockNumber = new Map<BlockNumber, Fr[]>();
75
+ await Promise.all(
76
+ firstBlockNumbers.map(async blockNumber => {
77
+ const l1ToL2Messages = await l2BlockSource.getL1ToL2Messages(blockNumber);
78
+ messagesByBlockNumber.set(blockNumber, l1ToL2Messages);
79
+ }),
80
+ );
81
+
82
+ return messagesByBlockNumber;
83
+ }
package/src/test/utils.ts CHANGED
@@ -4,26 +4,31 @@ import {
4
4
  NULLIFIER_SUBTREE_HEIGHT,
5
5
  NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
6
6
  } from '@aztec/constants';
7
+ import { BlockNumber, type CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
7
8
  import { padArrayEnd } from '@aztec/foundation/collection';
8
9
  import { Fr } from '@aztec/foundation/fields';
9
- import { L2Block } from '@aztec/stdlib/block';
10
+ import { L2BlockNew } from '@aztec/stdlib/block';
11
+ import { Checkpoint } from '@aztec/stdlib/checkpoint';
10
12
  import type {
11
13
  IndexedTreeId,
12
14
  MerkleTreeReadOperations,
13
15
  MerkleTreeWriteOperations,
14
16
  } from '@aztec/stdlib/interfaces/server';
17
+ import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
15
18
  import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
16
19
 
17
20
  import type { NativeWorldStateService } from '../native/native_world_state.js';
18
21
 
19
22
  export async function mockBlock(
20
- blockNum: number,
23
+ blockNum: BlockNumber,
21
24
  size: number,
22
25
  fork: MerkleTreeWriteOperations,
23
- maxEffects: number | undefined = undefined,
26
+ maxEffects: number | undefined = 1000, // Defaults to the maximum tx effects.
27
+ numL1ToL2Messages: number = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
28
+ isFirstBlock: boolean = true,
24
29
  ) {
25
- const l2Block = await L2Block.random(blockNum, size, maxEffects);
26
- const l1ToL2Messages = Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(0).map(Fr.random);
30
+ const l2Block = await L2BlockNew.random(blockNum, { txsPerBlock: size, txOptions: { maxEffects } });
31
+ const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
27
32
 
28
33
  {
29
34
  const insertData = async (
@@ -55,7 +60,9 @@ export async function mockBlock(
55
60
  padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
56
61
  );
57
62
 
58
- const l1ToL2MessagesPadded = padArrayEnd<Fr, number>(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
63
+ const l1ToL2MessagesPadded = isFirstBlock
64
+ ? padArrayEnd<Fr, number>(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP)
65
+ : l1ToL2Messages;
59
66
 
60
67
  const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
61
68
  const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
@@ -64,7 +71,7 @@ export async function mockBlock(
64
71
 
65
72
  const state = await fork.getStateReference();
66
73
  l2Block.header.state = state;
67
- await fork.updateArchive(l2Block.getBlockHeader());
74
+ await fork.updateArchive(l2Block.header);
68
75
 
69
76
  const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
70
77
 
@@ -76,8 +83,8 @@ export async function mockBlock(
76
83
  };
77
84
  }
78
85
 
79
- export async function mockEmptyBlock(blockNum: number, fork: MerkleTreeWriteOperations) {
80
- const l2Block = L2Block.empty();
86
+ export async function mockEmptyBlock(blockNum: BlockNumber, fork: MerkleTreeWriteOperations) {
87
+ const l2Block = L2BlockNew.empty();
81
88
  const l1ToL2Messages = Array(16).fill(0).map(Fr.zero);
82
89
 
83
90
  l2Block.header.globalVariables.blockNumber = blockNum;
@@ -115,7 +122,7 @@ export async function mockEmptyBlock(blockNum: number, fork: MerkleTreeWriteOper
115
122
 
116
123
  const state = await fork.getStateReference();
117
124
  l2Block.header.state = state;
118
- await fork.updateArchive(l2Block.getBlockHeader());
125
+ await fork.updateArchive(l2Block.header);
119
126
 
120
127
  const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
121
128
 
@@ -127,13 +134,18 @@ export async function mockEmptyBlock(blockNum: number, fork: MerkleTreeWriteOper
127
134
  };
128
135
  }
129
136
 
130
- export async function mockBlocks(from: number, count: number, numTxs: number, worldState: NativeWorldStateService) {
131
- const tempFork = await worldState.fork(from - 1);
137
+ export async function mockBlocks(
138
+ from: BlockNumber,
139
+ count: number,
140
+ numTxs: number,
141
+ worldState: NativeWorldStateService,
142
+ ) {
143
+ const tempFork = await worldState.fork(BlockNumber(from - 1));
132
144
 
133
145
  const blocks = [];
134
146
  const messagesArray = [];
135
147
  for (let blockNumber = from; blockNumber < from + count; blockNumber++) {
136
- const { block, messages } = await mockBlock(blockNumber, numTxs, tempFork);
148
+ const { block, messages } = await mockBlock(BlockNumber(blockNumber), numTxs, tempFork);
137
149
  blocks.push(block);
138
150
  messagesArray.push(messages);
139
151
  }
@@ -143,6 +155,47 @@ export async function mockBlocks(from: number, count: number, numTxs: number, wo
143
155
  return { blocks, messages: messagesArray };
144
156
  }
145
157
 
158
+ export function mockL1ToL2Messages(numL1ToL2Messages: number) {
159
+ return Array(numL1ToL2Messages).fill(0).map(Fr.random);
160
+ }
161
+
162
+ export async function mockCheckpoint(
163
+ checkpointNumber: CheckpointNumber,
164
+ {
165
+ startBlockNumber = BlockNumber(1),
166
+ numBlocks = 1,
167
+ numTxsPerBlock = 1,
168
+ numL1ToL2Messages = 1,
169
+ fork,
170
+ }: {
171
+ startBlockNumber?: BlockNumber;
172
+ numBlocks?: number;
173
+ numTxsPerBlock?: number;
174
+ numL1ToL2Messages?: number;
175
+ fork?: MerkleTreeWriteOperations;
176
+ } = {},
177
+ ) {
178
+ const slotNumber = SlotNumber(checkpointNumber * 10);
179
+ const blocksAndMessages = [];
180
+ for (let i = 0; i < numBlocks; i++) {
181
+ const blockNumber = BlockNumber(startBlockNumber + i);
182
+ const { block, messages } = fork
183
+ ? await mockBlock(blockNumber, numTxsPerBlock, fork, blockNumber === startBlockNumber ? numL1ToL2Messages : 0)
184
+ : {
185
+ block: await L2BlockNew.random(blockNumber, { txsPerBlock: numTxsPerBlock, slotNumber }),
186
+ messages: mockL1ToL2Messages(numL1ToL2Messages),
187
+ };
188
+ blocksAndMessages.push({ block, messages });
189
+ }
190
+
191
+ const messages = blocksAndMessages[0].messages;
192
+ const inHash = computeInHashFromL1ToL2Messages(messages);
193
+ const checkpoint = await Checkpoint.random(checkpointNumber, { numBlocks: 0, slotNumber, inHash });
194
+ checkpoint.blocks = blocksAndMessages.map(({ block }) => block);
195
+
196
+ return { checkpoint, messages };
197
+ }
198
+
146
199
  export async function assertSameState(forkA: MerkleTreeReadOperations, forkB: MerkleTreeReadOperations) {
147
200
  const nativeStateRef = await forkA.getStateReference();
148
201
  const nativeArchive = await forkA.getTreeInfo(MerkleTreeId.ARCHIVE);
@@ -1,7 +1,8 @@
1
1
  import { MAX_NULLIFIERS_PER_TX, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX } from '@aztec/constants';
2
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
3
  import type { Fr } from '@aztec/foundation/fields';
3
4
  import type { IndexedTreeSnapshot, TreeSnapshot } from '@aztec/merkle-tree';
4
- import type { L2Block } from '@aztec/stdlib/block';
5
+ import type { L2BlockNew } from '@aztec/stdlib/block';
5
6
  import type { ForkMerkleTreeOperations, MerkleTreeReadOperations } from '@aztec/stdlib/interfaces/server';
6
7
  import type { MerkleTreeId } from '@aztec/stdlib/trees';
7
8
 
@@ -39,10 +40,14 @@ export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations {
39
40
  * Handles a single L2 block (i.e. Inserts the new note hashes into the merkle tree).
40
41
  * @param block - The L2 block to handle.
41
42
  * @param l1ToL2Messages - The L1 to L2 messages for the block.
42
- * @param isFirstBlock - Whether the block is the first block in a checkpoint. Temporary hack to only insert l1 to l2
43
- * messages for the first block in a checkpoint. TODO(#17027) Remove this.
43
+ * @param isFirstBlock - Whether the block is the first block in a checkpoint. The messages are padded and inserted
44
+ * to the tree for the first block in a checkpoint.
44
45
  */
45
- handleL2BlockAndMessages(block: L2Block, l1ToL2Messages: Fr[], isFirstBlock?: boolean): Promise<WorldStateStatusFull>;
46
+ handleL2BlockAndMessages(
47
+ block: L2BlockNew,
48
+ l1ToL2Messages: Fr[],
49
+ isFirstBlock: boolean,
50
+ ): Promise<WorldStateStatusFull>;
46
51
 
47
52
  /**
48
53
  * Gets a handle that allows reading the latest committed state
@@ -54,21 +59,21 @@ export interface MerkleTreeAdminDatabase extends ForkMerkleTreeOperations {
54
59
  * @param toBlockNumber The block number of the new oldest historical block
55
60
  * @returns The new WorldStateStatus
56
61
  */
57
- removeHistoricalBlocks(toBlockNumber: bigint): Promise<WorldStateStatusFull>;
62
+ removeHistoricalBlocks(toBlockNumber: BlockNumber): Promise<WorldStateStatusFull>;
58
63
 
59
64
  /**
60
65
  * Removes all pending blocks down to but not including the given block number
61
66
  * @param toBlockNumber The block number of the new tip of the pending chain,
62
67
  * @returns The new WorldStateStatus
63
68
  */
64
- unwindBlocks(toBlockNumber: bigint): Promise<WorldStateStatusFull>;
69
+ unwindBlocks(toBlockNumber: BlockNumber): Promise<WorldStateStatusFull>;
65
70
 
66
71
  /**
67
72
  * Advances the finalized block number to be the number provided
68
73
  * @param toBlockNumber The block number that is now the tip of the finalized chain
69
74
  * @returns The new WorldStateStatus
70
75
  */
71
- setFinalized(toBlockNumber: bigint): Promise<WorldStateStatusSummary>;
76
+ setFinalized(toBlockNumber: BlockNumber): Promise<WorldStateStatusSummary>;
72
77
 
73
78
  /**
74
79
  * Gets the current status summary of the database.