@aztec/world-state 0.0.0-test.0 → 0.0.1-commit.023c3e5

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 (63) 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 +1 -1
  9. package/dest/native/fork_checkpoint.d.ts.map +1 -1
  10. package/dest/native/index.d.ts +1 -1
  11. package/dest/native/merkle_trees_facade.d.ts +19 -7
  12. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  13. package/dest/native/merkle_trees_facade.js +76 -14
  14. package/dest/native/message.d.ts +74 -52
  15. package/dest/native/message.d.ts.map +1 -1
  16. package/dest/native/message.js +61 -61
  17. package/dest/native/native_world_state.d.ts +27 -19
  18. package/dest/native/native_world_state.d.ts.map +1 -1
  19. package/dest/native/native_world_state.js +103 -41
  20. package/dest/native/native_world_state_instance.d.ts +20 -4
  21. package/dest/native/native_world_state_instance.d.ts.map +1 -1
  22. package/dest/native/native_world_state_instance.js +42 -3
  23. package/dest/native/world_state_ops_queue.d.ts +1 -1
  24. package/dest/native/world_state_ops_queue.d.ts.map +1 -1
  25. package/dest/native/world_state_ops_queue.js +1 -1
  26. package/dest/synchronizer/config.d.ts +12 -4
  27. package/dest/synchronizer/config.d.ts.map +1 -1
  28. package/dest/synchronizer/config.js +27 -7
  29. package/dest/synchronizer/errors.d.ts +4 -0
  30. package/dest/synchronizer/errors.d.ts.map +1 -0
  31. package/dest/synchronizer/errors.js +5 -0
  32. package/dest/synchronizer/factory.d.ts +11 -3
  33. package/dest/synchronizer/factory.d.ts.map +1 -1
  34. package/dest/synchronizer/factory.js +13 -8
  35. package/dest/synchronizer/index.d.ts +1 -1
  36. package/dest/synchronizer/server_world_state_synchronizer.d.ts +21 -31
  37. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  38. package/dest/synchronizer/server_world_state_synchronizer.js +144 -92
  39. package/dest/test/index.d.ts +1 -1
  40. package/dest/test/utils.d.ts +12 -5
  41. package/dest/test/utils.d.ts.map +1 -1
  42. package/dest/test/utils.js +54 -47
  43. package/dest/testing.d.ts +3 -3
  44. package/dest/testing.d.ts.map +1 -1
  45. package/dest/testing.js +7 -11
  46. package/dest/world-state-db/index.d.ts +1 -1
  47. package/dest/world-state-db/merkle_tree_db.d.ts +12 -9
  48. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  49. package/package.json +24 -24
  50. package/src/instrumentation/instrumentation.ts +31 -43
  51. package/src/native/bench_metrics.ts +91 -0
  52. package/src/native/merkle_trees_facade.ts +83 -18
  53. package/src/native/message.ts +94 -74
  54. package/src/native/native_world_state.ts +132 -52
  55. package/src/native/native_world_state_instance.ts +62 -9
  56. package/src/native/world_state_ops_queue.ts +1 -1
  57. package/src/synchronizer/config.ts +48 -16
  58. package/src/synchronizer/errors.ts +5 -0
  59. package/src/synchronizer/factory.ts +38 -9
  60. package/src/synchronizer/server_world_state_synchronizer.ts +170 -117
  61. package/src/test/utils.ts +92 -82
  62. package/src/testing.ts +4 -8
  63. package/src/world-state-db/merkle_tree_db.ts +16 -8
@@ -1,19 +1,19 @@
1
- import { L1_TO_L2_MSG_SUBTREE_HEIGHT } from '@aztec/constants';
2
- import type { Fr } from '@aztec/foundation/fields';
3
- import { createLogger } from '@aztec/foundation/log';
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';
3
+ import type { Fr } from '@aztec/foundation/curves/bn254';
4
+ import { type Logger, createLogger } from '@aztec/foundation/log';
4
5
  import { promiseWithResolvers } from '@aztec/foundation/promise';
5
6
  import { elapsed } from '@aztec/foundation/timer';
6
- import { MerkleTreeCalculator } from '@aztec/foundation/trees';
7
- import { SHA256Trunc } from '@aztec/merkle-tree';
8
- import type {
9
- L2Block,
10
- L2BlockId,
11
- L2BlockSource,
7
+ import {
8
+ GENESIS_CHECKPOINT_HEADER_HASH,
9
+ type L2Block,
10
+ type L2BlockId,
11
+ type L2BlockSource,
12
12
  L2BlockStream,
13
- L2BlockStreamEvent,
14
- L2BlockStreamEventHandler,
15
- L2BlockStreamLocalDataProvider,
16
- L2Tips,
13
+ type L2BlockStreamEvent,
14
+ type L2BlockStreamEventHandler,
15
+ type L2BlockStreamLocalDataProvider,
16
+ type L2Tips,
17
17
  } from '@aztec/stdlib/block';
18
18
  import {
19
19
  WorldStateRunningState,
@@ -22,14 +22,18 @@ import {
22
22
  type WorldStateSynchronizerStatus,
23
23
  } from '@aztec/stdlib/interfaces/server';
24
24
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
25
+ import type { SnapshotDataKeys } from '@aztec/stdlib/snapshots';
25
26
  import type { L2BlockHandledStats } from '@aztec/stdlib/stats';
26
27
  import { MerkleTreeId, type MerkleTreeReadOperations, type MerkleTreeWriteOperations } from '@aztec/stdlib/trees';
27
- import { TraceableL2BlockStream, getTelemetryClient } from '@aztec/telemetry-client';
28
+ import { getTelemetryClient } from '@aztec/telemetry-client';
28
29
 
29
30
  import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js';
30
31
  import type { WorldStateStatusFull } from '../native/message.js';
31
32
  import type { MerkleTreeAdminDatabase } from '../world-state-db/merkle_tree_db.js';
32
33
  import type { WorldStateConfig } from './config.js';
34
+ import { WorldStateSynchronizerError } from './errors.js';
35
+
36
+ export type { SnapshotDataKeys };
33
37
 
34
38
  /**
35
39
  * Synchronizes the world state with the L2 blocks from a L2BlockSource via a block stream.
@@ -41,20 +45,23 @@ export class ServerWorldStateSynchronizer
41
45
  {
42
46
  private readonly merkleTreeCommitted: MerkleTreeReadOperations;
43
47
 
44
- private latestBlockNumberAtStart = 0;
48
+ private latestBlockNumberAtStart = BlockNumber.ZERO;
45
49
  private historyToKeep: number | undefined;
46
50
  private currentState: WorldStateRunningState = WorldStateRunningState.IDLE;
47
- private latestBlockHashQuery: { blockNumber: number; hash: string | undefined } | undefined = undefined;
48
51
 
49
52
  private syncPromise = promiseWithResolvers<void>();
50
53
  protected blockStream: L2BlockStream | undefined;
51
54
 
55
+ // WorldState doesn't track the proven block number, it only tracks the latest tips of the pending chain and the finalized chain
56
+ // store the proven block number here, in the synchronizer, so that we don't end up spamming the logs with 'chain-proved' events
57
+ private provenBlockNumber: BlockNumber | undefined;
58
+
52
59
  constructor(
53
60
  private readonly merkleTreeDb: MerkleTreeAdminDatabase,
54
61
  private readonly l2BlockSource: L2BlockSource & L1ToL2MessageSource,
55
62
  private readonly config: WorldStateConfig,
56
63
  private instrumentation = new WorldStateInstrumentation(getTelemetryClient()),
57
- private readonly log = createLogger('world_state'),
64
+ private readonly log: Logger = createLogger('world_state'),
58
65
  ) {
59
66
  this.merkleTreeCommitted = this.merkleTreeDb.getCommitted();
60
67
  this.historyToKeep = config.worldStateBlockHistory < 1 ? undefined : config.worldStateBlockHistory;
@@ -69,12 +76,20 @@ export class ServerWorldStateSynchronizer
69
76
  return this.merkleTreeDb.getCommitted();
70
77
  }
71
78
 
72
- public getSnapshot(blockNumber: number): MerkleTreeReadOperations {
79
+ public getSnapshot(blockNumber: BlockNumber): MerkleTreeReadOperations {
73
80
  return this.merkleTreeDb.getSnapshot(blockNumber);
74
81
  }
75
82
 
76
- public fork(blockNumber?: number): Promise<MerkleTreeWriteOperations> {
77
- return this.merkleTreeDb.fork(blockNumber);
83
+ public fork(blockNumber?: BlockNumber, opts?: { closeDelayMs?: number }): Promise<MerkleTreeWriteOperations> {
84
+ return this.merkleTreeDb.fork(blockNumber, opts);
85
+ }
86
+
87
+ public backupTo(dstPath: string, compact?: boolean): Promise<Record<Exclude<SnapshotDataKeys, 'archiver'>, string>> {
88
+ return this.merkleTreeDb.backupTo(dstPath, compact);
89
+ }
90
+
91
+ public clear(): Promise<void> {
92
+ return this.merkleTreeDb.clear();
78
93
  }
79
94
 
80
95
  public async start() {
@@ -86,9 +101,7 @@ export class ServerWorldStateSynchronizer
86
101
  }
87
102
 
88
103
  // Get the current latest block number
89
- this.latestBlockNumberAtStart = await (this.config.worldStateProvenBlocksOnly
90
- ? this.l2BlockSource.getProvenBlockNumber()
91
- : this.l2BlockSource.getBlockNumber());
104
+ this.latestBlockNumberAtStart = BlockNumber(await this.l2BlockSource.getBlockNumber());
92
105
 
93
106
  const blockToDownloadFrom = (await this.getLatestBlockNumber()) + 1;
94
107
 
@@ -110,12 +123,11 @@ export class ServerWorldStateSynchronizer
110
123
  }
111
124
 
112
125
  protected createBlockStream(): L2BlockStream {
113
- const tracer = this.instrumentation.telemetry.getTracer('WorldStateL2BlockStream');
114
126
  const logger = createLogger('world-state:block_stream');
115
- return new TraceableL2BlockStream(this.l2BlockSource, this, this, tracer, 'WorldStateL2BlockStream', logger, {
116
- proven: this.config.worldStateProvenBlocksOnly,
127
+ return new L2BlockStream(this.l2BlockSource, this, this, logger, {
117
128
  pollIntervalMS: this.config.worldStateBlockCheckIntervalMS,
118
129
  batchSize: this.config.worldStateBlockRequestBatchSize,
130
+ ignoreCheckpoints: true,
119
131
  });
120
132
  }
121
133
 
@@ -131,10 +143,10 @@ export class ServerWorldStateSynchronizer
131
143
  public async status(): Promise<WorldStateSynchronizerStatus> {
132
144
  const summary = await this.merkleTreeDb.getStatusSummary();
133
145
  const status: WorldStateSyncStatus = {
134
- latestBlockNumber: Number(summary.unfinalisedBlockNumber),
135
- latestBlockHash: (await this.getL2BlockHash(Number(summary.unfinalisedBlockNumber))) ?? '',
136
- finalisedBlockNumber: Number(summary.finalisedBlockNumber),
137
- oldestHistoricBlockNumber: Number(summary.oldestHistoricalBlock),
146
+ latestBlockNumber: summary.unfinalizedBlockNumber,
147
+ latestBlockHash: (await this.getL2BlockHash(summary.unfinalizedBlockNumber)) ?? '',
148
+ finalizedBlockNumber: summary.finalizedBlockNumber,
149
+ oldestHistoricBlockNumber: summary.oldestHistoricalBlock,
138
150
  treesAreSynched: summary.treesAreSynched,
139
151
  };
140
152
  return {
@@ -144,19 +156,42 @@ export class ServerWorldStateSynchronizer
144
156
  }
145
157
 
146
158
  public async getLatestBlockNumber() {
147
- return (await this.getL2Tips()).latest.number;
159
+ return (await this.getL2Tips()).proposed.number;
160
+ }
161
+
162
+ public async stopSync() {
163
+ this.log.debug('Stopping sync...');
164
+ await this.blockStream?.stop();
165
+ this.log.info('Stopped sync');
166
+ }
167
+
168
+ public resumeSync() {
169
+ if (!this.blockStream) {
170
+ throw new Error('Cannot resume sync as block stream is not initialized');
171
+ }
172
+ this.log.debug('Resuming sync...');
173
+ this.blockStream.start();
174
+ this.log.info('Resumed sync');
148
175
  }
149
176
 
150
177
  /**
151
178
  * Forces an immediate sync.
152
- * @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it. Throws if cannot be reached.
179
+ * @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.
153
181
  * @returns A promise that resolves with the block number the world state was synced to
154
182
  */
155
- public async syncImmediate(targetBlockNumber?: number): Promise<number> {
156
- if (this.currentState !== WorldStateRunningState.RUNNING || this.blockStream === undefined) {
183
+ public async syncImmediate(
184
+ targetBlockNumber?: BlockNumber,
185
+ skipThrowIfTargetNotReached?: boolean,
186
+ ): Promise<BlockNumber> {
187
+ if (this.currentState !== WorldStateRunningState.RUNNING) {
157
188
  throw new Error(`World State is not running. Unable to perform sync.`);
158
189
  }
159
190
 
191
+ if (this.blockStream === undefined) {
192
+ throw new Error('Block stream is not initialized. Unable to perform sync.');
193
+ }
194
+
160
195
  // If we have been given a block number to sync to and we have reached that number then return
161
196
  const currentBlockNumber = await this.getLatestBlockNumber();
162
197
  if (targetBlockNumber !== undefined && targetBlockNumber <= currentBlockNumber) {
@@ -164,66 +199,98 @@ export class ServerWorldStateSynchronizer
164
199
  }
165
200
  this.log.debug(`World State at ${currentBlockNumber} told to sync to ${targetBlockNumber ?? 'latest'}`);
166
201
 
202
+ // If the archiver is behind the target block, force an archiver sync
203
+ if (targetBlockNumber) {
204
+ const archiverLatestBlock = BlockNumber(await this.l2BlockSource.getBlockNumber());
205
+ if (archiverLatestBlock < targetBlockNumber) {
206
+ this.log.debug(`Archiver is at ${archiverLatestBlock} behind target block ${targetBlockNumber}.`);
207
+ await this.l2BlockSource.syncImmediate();
208
+ }
209
+ }
210
+
167
211
  // Force the block stream to sync against the archiver now
168
212
  await this.blockStream.sync();
169
213
 
170
214
  // If we have been given a block number to sync to and we have not reached that number then fail
171
215
  const updatedBlockNumber = await this.getLatestBlockNumber();
172
- if (targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
173
- throw new Error(`Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`);
216
+ if (!skipThrowIfTargetNotReached && targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
217
+ throw new WorldStateSynchronizerError(
218
+ `Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`,
219
+ {
220
+ cause: {
221
+ reason: 'block_not_available',
222
+ previousBlockNumber: currentBlockNumber,
223
+ updatedBlockNumber,
224
+ targetBlockNumber,
225
+ },
226
+ },
227
+ );
174
228
  }
175
229
 
176
230
  return updatedBlockNumber;
177
231
  }
178
232
 
179
233
  /** Returns the L2 block hash for a given number. Used by the L2BlockStream for detecting reorgs. */
180
- public async getL2BlockHash(number: number): Promise<string | undefined> {
181
- if (number === 0) {
234
+ public async getL2BlockHash(number: BlockNumber): Promise<string | undefined> {
235
+ if (number === BlockNumber.ZERO) {
182
236
  return (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
183
237
  }
184
- if (this.latestBlockHashQuery?.hash === undefined || number !== this.latestBlockHashQuery.blockNumber) {
185
- this.latestBlockHashQuery = {
186
- hash: await this.merkleTreeCommitted
187
- .getLeafValue(MerkleTreeId.ARCHIVE, BigInt(number))
188
- .then(leaf => leaf?.toString()),
189
- blockNumber: number,
190
- };
191
- }
192
- return this.latestBlockHashQuery.hash;
238
+ return this.merkleTreeCommitted.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(number)).then(leaf => leaf?.toString());
193
239
  }
194
240
 
195
241
  /** Returns the latest L2 block number for each tip of the chain (latest, proven, finalized). */
196
242
  public async getL2Tips(): Promise<L2Tips> {
197
243
  const status = await this.merkleTreeDb.getStatusSummary();
198
- const unfinalisedBlockHash = await this.getL2BlockHash(Number(status.unfinalisedBlockNumber));
199
- const latestBlockId: L2BlockId = { number: Number(status.unfinalisedBlockNumber), hash: unfinalisedBlockHash! };
200
-
244
+ const unfinalizedBlockHashPromise = this.getL2BlockHash(status.unfinalizedBlockNumber);
245
+ const finalizedBlockHashPromise = this.getL2BlockHash(status.finalizedBlockNumber);
246
+
247
+ const provenBlockNumber = this.provenBlockNumber ?? status.finalizedBlockNumber;
248
+ const provenBlockHashPromise =
249
+ this.provenBlockNumber === undefined ? finalizedBlockHashPromise : this.getL2BlockHash(this.provenBlockNumber);
250
+
251
+ const [unfinalizedBlockHash, finalizedBlockHash, provenBlockHash] = await Promise.all([
252
+ unfinalizedBlockHashPromise,
253
+ finalizedBlockHashPromise,
254
+ provenBlockHashPromise,
255
+ ]);
256
+ const latestBlockId: L2BlockId = { number: status.unfinalizedBlockNumber, hash: unfinalizedBlockHash! };
257
+
258
+ // World state doesn't track checkpointed blocks or checkpoints themselves.
259
+ // but we use a block stream so we need to provide 'local' L2Tips.
260
+ // We configure the block stream to ignore checkpoints and set checkpoint values to genesis here.
261
+ const genesisCheckpointHeaderHash = GENESIS_CHECKPOINT_HEADER_HASH.toString();
201
262
  return {
202
- latest: latestBlockId,
203
- finalized: { number: Number(status.finalisedBlockNumber), hash: '' },
204
- proven: { number: Number(status.finalisedBlockNumber), hash: '' }, // TODO(palla/reorg): Using finalised as proven for now
263
+ proposed: latestBlockId,
264
+ checkpointed: {
265
+ block: { number: INITIAL_L2_BLOCK_NUM, hash: GENESIS_BLOCK_HEADER_HASH.toString() },
266
+ checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
267
+ },
268
+ finalized: {
269
+ block: { number: status.finalizedBlockNumber, hash: finalizedBlockHash ?? '' },
270
+ checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
271
+ },
272
+ proven: {
273
+ block: { number: provenBlockNumber, hash: provenBlockHash ?? '' },
274
+ checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
275
+ },
205
276
  };
206
277
  }
207
278
 
208
279
  /** Handles an event emitted by the block stream. */
209
280
  public async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise<void> {
210
- try {
211
- switch (event.type) {
212
- case 'blocks-added':
213
- await this.handleL2Blocks(event.blocks);
214
- break;
215
- case 'chain-pruned':
216
- await this.handleChainPruned(event.blockNumber);
217
- break;
218
- case 'chain-proven':
219
- await this.handleChainProven(event.blockNumber);
220
- break;
221
- case 'chain-finalized':
222
- await this.handleChainFinalized(event.blockNumber);
223
- break;
224
- }
225
- } catch (err) {
226
- this.log.error('Error processing block stream', err);
281
+ switch (event.type) {
282
+ case 'blocks-added':
283
+ await this.handleL2Blocks(event.blocks);
284
+ break;
285
+ case 'chain-pruned':
286
+ await this.handleChainPruned(event.block.number);
287
+ break;
288
+ case 'chain-proven':
289
+ await this.handleChainProven(event.block.number);
290
+ break;
291
+ case 'chain-finalized':
292
+ await this.handleChainFinalized(event.block.number);
293
+ break;
227
294
  }
228
295
  }
229
296
 
@@ -233,21 +300,31 @@ export class ServerWorldStateSynchronizer
233
300
  * @returns Whether the block handled was produced by this same node.
234
301
  */
235
302
  private async handleL2Blocks(l2Blocks: L2Block[]) {
236
- this.log.trace(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1)!.number}`);
303
+ this.log.debug(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1)!.number}`);
304
+
305
+ // Fetch the L1->L2 messages for the first block in a checkpoint.
306
+ const messagesForBlocks = new Map<BlockNumber, Fr[]>();
307
+ await Promise.all(
308
+ l2Blocks
309
+ .filter(b => b.indexWithinCheckpoint === 0)
310
+ .map(async block => {
311
+ const l1ToL2Messages = await this.l2BlockSource.getL1ToL2Messages(block.checkpointNumber);
312
+ messagesForBlocks.set(block.number, l1ToL2Messages);
313
+ }),
314
+ );
237
315
 
238
- const messagePromises = l2Blocks.map(block => this.l2BlockSource.getL1ToL2Messages(BigInt(block.number)));
239
- const l1ToL2Messages: Fr[][] = await Promise.all(messagePromises);
240
316
  let updateStatus: WorldStateStatusFull | undefined = undefined;
241
-
242
- for (let i = 0; i < l2Blocks.length; i++) {
243
- const [duration, result] = await elapsed(() => this.handleL2Block(l2Blocks[i], l1ToL2Messages[i]));
244
- this.log.verbose(`World state updated with L2 block ${l2Blocks[i].number}`, {
317
+ for (const block of l2Blocks) {
318
+ const [duration, result] = await elapsed(() =>
319
+ this.handleL2Block(block, messagesForBlocks.get(block.number) ?? []),
320
+ );
321
+ this.log.info(`World state updated with L2 block ${block.number}`, {
245
322
  eventName: 'l2-block-handled',
246
323
  duration,
247
- unfinalisedBlockNumber: result.summary.unfinalisedBlockNumber,
248
- finalisedBlockNumber: result.summary.finalisedBlockNumber,
249
- oldestHistoricBlock: result.summary.oldestHistoricalBlock,
250
- ...l2Blocks[i].getStats(),
324
+ unfinalizedBlockNumber: BigInt(result.summary.unfinalizedBlockNumber),
325
+ finalizedBlockNumber: BigInt(result.summary.finalizedBlockNumber),
326
+ oldestHistoricBlock: BigInt(result.summary.oldestHistoricalBlock),
327
+ ...block.getStats(),
251
328
  } satisfies L2BlockHandledStats);
252
329
  updateStatus = result;
253
330
  }
@@ -264,17 +341,12 @@ export class ServerWorldStateSynchronizer
264
341
  * @returns Whether the block handled was produced by this same node.
265
342
  */
266
343
  private async handleL2Block(l2Block: L2Block, l1ToL2Messages: Fr[]): Promise<WorldStateStatusFull> {
267
- // First we check that the L1 to L2 messages hash to the block inHash.
268
- // Note that we cannot optimize this check by checking the root of the subtree after inserting the messages
269
- // to the real L1_TO_L2_MESSAGE_TREE (like we do in merkleTreeDb.handleL2BlockAndMessages(...)) because that
270
- // tree uses pedersen and we don't have access to the converted root.
271
- await this.verifyMessagesHashToInHash(l1ToL2Messages, l2Block.header.contentCommitment.inHash);
272
-
273
- // If the above check succeeds, we can proceed to handle the block.
274
- this.log.trace(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
344
+ this.log.debug(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
275
345
  blockNumber: l2Block.number,
276
346
  blockHash: await l2Block.hash().then(h => h.toString()),
277
347
  l1ToL2Messages: l1ToL2Messages.map(msg => msg.toString()),
348
+ blockHeader: l2Block.header.toInspect(),
349
+ blockStats: l2Block.getStats(),
278
350
  });
279
351
  const result = await this.merkleTreeDb.handleL2BlockAndMessages(l2Block, l1ToL2Messages);
280
352
 
@@ -286,30 +358,31 @@ export class ServerWorldStateSynchronizer
286
358
  return result;
287
359
  }
288
360
 
289
- private async handleChainFinalized(blockNumber: number) {
361
+ private async handleChainFinalized(blockNumber: BlockNumber) {
290
362
  this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
291
- const summary = await this.merkleTreeDb.setFinalised(BigInt(blockNumber));
363
+ const summary = await this.merkleTreeDb.setFinalized(blockNumber);
292
364
  if (this.historyToKeep === undefined) {
293
365
  return;
294
366
  }
295
- const newHistoricBlock = summary.finalisedBlockNumber - BigInt(this.historyToKeep) + 1n;
367
+ const newHistoricBlock = summary.finalizedBlockNumber - this.historyToKeep + 1;
296
368
  if (newHistoricBlock <= 1) {
297
369
  return;
298
370
  }
299
371
  this.log.verbose(`Pruning historic blocks to ${newHistoricBlock}`);
300
- const status = await this.merkleTreeDb.removeHistoricalBlocks(newHistoricBlock);
372
+ const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock));
301
373
  this.log.debug(`World state summary `, status.summary);
302
374
  }
303
375
 
304
- private handleChainProven(blockNumber: number) {
376
+ private handleChainProven(blockNumber: BlockNumber) {
377
+ this.provenBlockNumber = blockNumber;
305
378
  this.log.debug(`Proven chain is now at block ${blockNumber}`);
306
379
  return Promise.resolve();
307
380
  }
308
381
 
309
- private async handleChainPruned(blockNumber: number) {
382
+ private async handleChainPruned(blockNumber: BlockNumber) {
310
383
  this.log.warn(`Chain pruned to block ${blockNumber}`);
311
- const status = await this.merkleTreeDb.unwindBlocks(BigInt(blockNumber));
312
- this.latestBlockHashQuery = undefined;
384
+ const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
385
+ this.provenBlockNumber = undefined;
313
386
  this.instrumentation.updateWorldStateMetrics(status);
314
387
  }
315
388
 
@@ -321,24 +394,4 @@ export class ServerWorldStateSynchronizer
321
394
  this.currentState = newState;
322
395
  this.log.debug(`Moved to state ${WorldStateRunningState[this.currentState]}`);
323
396
  }
324
-
325
- /**
326
- * Verifies that the L1 to L2 messages hash to the block inHash.
327
- * @param l1ToL2Messages - The L1 to L2 messages for the block.
328
- * @param inHash - The inHash of the block.
329
- * @throws If the L1 to L2 messages do not hash to the block inHash.
330
- */
331
- protected async verifyMessagesHashToInHash(l1ToL2Messages: Fr[], inHash: Buffer) {
332
- const treeCalculator = await MerkleTreeCalculator.create(
333
- L1_TO_L2_MSG_SUBTREE_HEIGHT,
334
- Buffer.alloc(32),
335
- (lhs, rhs) => Promise.resolve(new SHA256Trunc().hash(lhs, rhs)),
336
- );
337
-
338
- const root = await treeCalculator.computeTreeRoot(l1ToL2Messages.map(msg => msg.toBuffer()));
339
-
340
- if (!root.equals(inHash)) {
341
- throw new Error('Obtained L1 to L2 messages failed to be hashed to the block inHash');
342
- }
343
- }
344
397
  }
package/src/test/utils.ts CHANGED
@@ -4,107 +4,100 @@ import {
4
4
  NULLIFIER_SUBTREE_HEIGHT,
5
5
  NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
6
6
  } from '@aztec/constants';
7
+ import { asyncMap } from '@aztec/foundation/async-map';
8
+ import { BlockNumber, type CheckpointNumber, IndexWithinCheckpoint } from '@aztec/foundation/branded-types';
7
9
  import { padArrayEnd } from '@aztec/foundation/collection';
8
- import { Fr } from '@aztec/foundation/fields';
10
+ import { Fr } from '@aztec/foundation/curves/bn254';
9
11
  import { L2Block } from '@aztec/stdlib/block';
10
- import type { MerkleTreeReadOperations, MerkleTreeWriteOperations } from '@aztec/stdlib/interfaces/server';
12
+ import type {
13
+ IndexedTreeId,
14
+ MerkleTreeReadOperations,
15
+ MerkleTreeWriteOperations,
16
+ } from '@aztec/stdlib/interfaces/server';
17
+ import { mockCheckpointAndMessages, mockL1ToL2Messages } from '@aztec/stdlib/testing';
11
18
  import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
19
+ import { BlockHeader } from '@aztec/stdlib/tx';
12
20
 
13
21
  import type { NativeWorldStateService } from '../native/native_world_state.js';
14
22
 
15
- export async function mockBlock(blockNum: number, size: number, fork: MerkleTreeWriteOperations) {
16
- const l2Block = await L2Block.random(blockNum, size);
17
- const l1ToL2Messages = Array(16).fill(0).map(Fr.random);
18
-
19
- // Sync the append only trees
20
- {
21
- const noteHashesPadded = l2Block.body.txEffects.flatMap(txEffect =>
22
- padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
23
- );
24
- await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
25
-
26
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
27
- await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
28
- }
29
-
30
- // Sync the indexed trees
31
- {
32
- // We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
33
- for (const txEffect of l2Block.body.txEffects) {
34
- await fork.batchInsert(
35
- MerkleTreeId.PUBLIC_DATA_TREE,
36
- txEffect.publicDataWrites.map(write => write.toBuffer()),
37
- 0,
38
- );
39
-
40
- const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
41
-
42
- await fork.batchInsert(
43
- MerkleTreeId.NULLIFIER_TREE,
44
- nullifiersPadded.map(nullifier => nullifier.toBuffer()),
45
- NULLIFIER_SUBTREE_HEIGHT,
46
- );
23
+ export async function updateBlockState(block: L2Block, l1ToL2Messages: Fr[], fork: MerkleTreeWriteOperations) {
24
+ const insertData = async (
25
+ treeId: IndexedTreeId,
26
+ data: Buffer[][],
27
+ subTreeHeight: number,
28
+ fork: MerkleTreeWriteOperations,
29
+ ) => {
30
+ for (const dataBatch of data) {
31
+ await fork.batchInsert(treeId, dataBatch, subTreeHeight);
47
32
  }
48
- }
33
+ };
34
+
35
+ const publicDataInsert = insertData(
36
+ MerkleTreeId.PUBLIC_DATA_TREE,
37
+ block.body.txEffects.map(txEffect => txEffect.publicDataWrites.map(write => write.toBuffer())),
38
+ 0,
39
+ fork,
40
+ );
41
+ const nullifierInsert = insertData(
42
+ MerkleTreeId.NULLIFIER_TREE,
43
+ block.body.txEffects.map(txEffect =>
44
+ padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map(nullifier => nullifier.toBuffer()),
45
+ ),
46
+ NULLIFIER_SUBTREE_HEIGHT,
47
+ fork,
48
+ );
49
+ const noteHashesPadded = block.body.txEffects.flatMap(txEffect =>
50
+ padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
51
+ );
52
+
53
+ const l1ToL2MessagesPadded =
54
+ block.indexWithinCheckpoint === 0
55
+ ? padArrayEnd<Fr, number>(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP)
56
+ : l1ToL2Messages;
57
+
58
+ const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
59
+ const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
60
+ await Promise.all([publicDataInsert, nullifierInsert, noteHashInsert, messageInsert]);
49
61
 
50
62
  const state = await fork.getStateReference();
51
- l2Block.header.state = state;
52
- await fork.updateArchive(l2Block.header);
63
+ block.header = BlockHeader.from({ ...block.header, state });
64
+ await fork.updateArchive(block.header);
53
65
 
54
66
  const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
55
67
 
56
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
68
+ block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
69
+ }
70
+
71
+ export async function mockBlock(
72
+ blockNum: BlockNumber,
73
+ size: number,
74
+ fork: MerkleTreeWriteOperations,
75
+ maxEffects: number | undefined = 1000, // Defaults to the maximum tx effects.
76
+ numL1ToL2Messages: number = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
77
+ isFirstBlockInCheckpoint: boolean = true,
78
+ ) {
79
+ const block = await L2Block.random(blockNum, {
80
+ indexWithinCheckpoint: isFirstBlockInCheckpoint ? IndexWithinCheckpoint(0) : IndexWithinCheckpoint(1),
81
+ txsPerBlock: size,
82
+ txOptions: { maxEffects },
83
+ });
84
+ const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
85
+
86
+ await updateBlockState(block, l1ToL2Messages, fork);
57
87
 
58
88
  return {
59
- block: l2Block,
89
+ block,
60
90
  messages: l1ToL2Messages,
61
91
  };
62
92
  }
63
93
 
64
- export async function mockEmptyBlock(blockNum: number, fork: MerkleTreeWriteOperations) {
94
+ export async function mockEmptyBlock(blockNum: BlockNumber, fork: MerkleTreeWriteOperations) {
65
95
  const l2Block = L2Block.empty();
66
96
  const l1ToL2Messages = Array(16).fill(0).map(Fr.zero);
67
97
 
68
- l2Block.header.globalVariables.blockNumber = new Fr(blockNum);
98
+ l2Block.header.globalVariables.blockNumber = blockNum;
69
99
 
70
- // Sync the append only trees
71
- {
72
- const noteHashesPadded = l2Block.body.txEffects.flatMap(txEffect =>
73
- padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
74
- );
75
- await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
76
-
77
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
78
- await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
79
- }
80
-
81
- // Sync the indexed trees
82
- {
83
- // We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
84
- for (const txEffect of l2Block.body.txEffects) {
85
- await fork.batchInsert(
86
- MerkleTreeId.PUBLIC_DATA_TREE,
87
- txEffect.publicDataWrites.map(write => write.toBuffer()),
88
- 0,
89
- );
90
-
91
- const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
92
-
93
- await fork.batchInsert(
94
- MerkleTreeId.NULLIFIER_TREE,
95
- nullifiersPadded.map(nullifier => nullifier.toBuffer()),
96
- NULLIFIER_SUBTREE_HEIGHT,
97
- );
98
- }
99
- }
100
-
101
- const state = await fork.getStateReference();
102
- l2Block.header.state = state;
103
- await fork.updateArchive(l2Block.header);
104
-
105
- const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
106
-
107
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
100
+ await updateBlockState(l2Block, l1ToL2Messages, fork);
108
101
 
109
102
  return {
110
103
  block: l2Block,
@@ -112,13 +105,18 @@ export async function mockEmptyBlock(blockNum: number, fork: MerkleTreeWriteOper
112
105
  };
113
106
  }
114
107
 
115
- export async function mockBlocks(from: number, count: number, numTxs: number, worldState: NativeWorldStateService) {
116
- const tempFork = await worldState.fork(from - 1);
108
+ export async function mockBlocks(
109
+ from: BlockNumber,
110
+ count: number,
111
+ numTxs: number,
112
+ worldState: NativeWorldStateService,
113
+ ) {
114
+ const tempFork = await worldState.fork(BlockNumber(from - 1));
117
115
 
118
116
  const blocks = [];
119
117
  const messagesArray = [];
120
118
  for (let blockNumber = from; blockNumber < from + count; blockNumber++) {
121
- const { block, messages } = await mockBlock(blockNumber, numTxs, tempFork);
119
+ const { block, messages } = await mockBlock(BlockNumber(blockNumber), numTxs, tempFork);
122
120
  blocks.push(block);
123
121
  messagesArray.push(messages);
124
122
  }
@@ -128,6 +126,18 @@ export async function mockBlocks(from: number, count: number, numTxs: number, wo
128
126
  return { blocks, messages: messagesArray };
129
127
  }
130
128
 
129
+ export async function mockCheckpoint(
130
+ checkpointNumber: CheckpointNumber,
131
+ fork: MerkleTreeWriteOperations,
132
+ options: Partial<Parameters<typeof mockCheckpointAndMessages>[1]> = {},
133
+ ) {
134
+ const { checkpoint, messages } = await mockCheckpointAndMessages(checkpointNumber, options);
135
+ await asyncMap(checkpoint.blocks, async (block, i) => {
136
+ await updateBlockState(block, i === 0 ? messages : [], fork);
137
+ });
138
+ return { checkpoint, messages };
139
+ }
140
+
131
141
  export async function assertSameState(forkA: MerkleTreeReadOperations, forkB: MerkleTreeReadOperations) {
132
142
  const nativeStateRef = await forkA.getStateReference();
133
143
  const nativeArchive = await forkA.getTreeInfo(MerkleTreeId.ARCHIVE);