@aztec/world-state 0.0.0-test.0 → 0.0.1-commit.03f7ef2

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 +16 -8
  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 +62 -11
  14. package/dest/native/message.d.ts +72 -51
  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 +28 -20
  18. package/dest/native/native_world_state.d.ts.map +1 -1
  19. package/dest/native/native_world_state.js +97 -36
  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 -2
  27. package/dest/synchronizer/config.d.ts.map +1 -1
  28. package/dest/synchronizer/config.js +26 -1
  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 +9 -2
  33. package/dest/synchronizer/factory.d.ts.map +1 -1
  34. package/dest/synchronizer/factory.js +9 -4
  35. package/dest/synchronizer/index.d.ts +1 -1
  36. package/dest/synchronizer/server_world_state_synchronizer.d.ts +20 -29
  37. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  38. package/dest/synchronizer/server_world_state_synchronizer.js +94 -70
  39. package/dest/test/index.d.ts +1 -1
  40. package/dest/test/utils.d.ts +16 -9
  41. package/dest/test/utils.d.ts.map +1 -1
  42. package/dest/test/utils.js +56 -49
  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 +22 -10
  51. package/src/native/bench_metrics.ts +91 -0
  52. package/src/native/merkle_trees_facade.ts +73 -17
  53. package/src/native/message.ts +92 -73
  54. package/src/native/native_world_state.ts +118 -50
  55. package/src/native/native_world_state_instance.ts +59 -8
  56. package/src/native/world_state_ops_queue.ts +1 -1
  57. package/src/synchronizer/config.ts +47 -2
  58. package/src/synchronizer/errors.ts +5 -0
  59. package/src/synchronizer/factory.ts +31 -8
  60. package/src/synchronizer/server_world_state_synchronizer.ts +132 -93
  61. package/src/test/utils.ts +94 -84
  62. package/src/testing.ts +4 -8
  63. package/src/world-state-db/merkle_tree_db.ts +12 -8
@@ -1,13 +1,11 @@
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 { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import type { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { type Logger, createLogger } from '@aztec/foundation/log';
4
4
  import { promiseWithResolvers } from '@aztec/foundation/promise';
5
5
  import { elapsed } from '@aztec/foundation/timer';
6
- import { MerkleTreeCalculator } from '@aztec/foundation/trees';
7
- import { SHA256Trunc } from '@aztec/merkle-tree';
8
6
  import type {
9
- L2Block,
10
7
  L2BlockId,
8
+ L2BlockNew,
11
9
  L2BlockSource,
12
10
  L2BlockStream,
13
11
  L2BlockStreamEvent,
@@ -22,6 +20,7 @@ import {
22
20
  type WorldStateSynchronizerStatus,
23
21
  } from '@aztec/stdlib/interfaces/server';
24
22
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
23
+ import type { SnapshotDataKeys } from '@aztec/stdlib/snapshots';
25
24
  import type { L2BlockHandledStats } from '@aztec/stdlib/stats';
26
25
  import { MerkleTreeId, type MerkleTreeReadOperations, type MerkleTreeWriteOperations } from '@aztec/stdlib/trees';
27
26
  import { TraceableL2BlockStream, getTelemetryClient } from '@aztec/telemetry-client';
@@ -30,6 +29,9 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
30
29
  import type { WorldStateStatusFull } from '../native/message.js';
31
30
  import type { MerkleTreeAdminDatabase } from '../world-state-db/merkle_tree_db.js';
32
31
  import type { WorldStateConfig } from './config.js';
32
+ import { WorldStateSynchronizerError } from './errors.js';
33
+
34
+ export type { SnapshotDataKeys };
33
35
 
34
36
  /**
35
37
  * Synchronizes the world state with the L2 blocks from a L2BlockSource via a block stream.
@@ -41,20 +43,24 @@ export class ServerWorldStateSynchronizer
41
43
  {
42
44
  private readonly merkleTreeCommitted: MerkleTreeReadOperations;
43
45
 
44
- private latestBlockNumberAtStart = 0;
46
+ private latestBlockNumberAtStart = BlockNumber.ZERO;
45
47
  private historyToKeep: number | undefined;
46
48
  private currentState: WorldStateRunningState = WorldStateRunningState.IDLE;
47
- private latestBlockHashQuery: { blockNumber: number; hash: string | undefined } | undefined = undefined;
49
+ private latestBlockHashQuery: { blockNumber: BlockNumber; hash: string | undefined } | undefined = undefined;
48
50
 
49
51
  private syncPromise = promiseWithResolvers<void>();
50
52
  protected blockStream: L2BlockStream | undefined;
51
53
 
54
+ // WorldState doesn't track the proven block number, it only tracks the latest tips of the pending chain and the finalized chain
55
+ // store the proven block number here, in the synchronizer, so that we don't end up spamming the logs with 'chain-proved' events
56
+ private provenBlockNumber: BlockNumber | undefined;
57
+
52
58
  constructor(
53
59
  private readonly merkleTreeDb: MerkleTreeAdminDatabase,
54
60
  private readonly l2BlockSource: L2BlockSource & L1ToL2MessageSource,
55
61
  private readonly config: WorldStateConfig,
56
62
  private instrumentation = new WorldStateInstrumentation(getTelemetryClient()),
57
- private readonly log = createLogger('world_state'),
63
+ private readonly log: Logger = createLogger('world_state'),
58
64
  ) {
59
65
  this.merkleTreeCommitted = this.merkleTreeDb.getCommitted();
60
66
  this.historyToKeep = config.worldStateBlockHistory < 1 ? undefined : config.worldStateBlockHistory;
@@ -69,12 +75,20 @@ export class ServerWorldStateSynchronizer
69
75
  return this.merkleTreeDb.getCommitted();
70
76
  }
71
77
 
72
- public getSnapshot(blockNumber: number): MerkleTreeReadOperations {
78
+ public getSnapshot(blockNumber: BlockNumber): MerkleTreeReadOperations {
73
79
  return this.merkleTreeDb.getSnapshot(blockNumber);
74
80
  }
75
81
 
76
- public fork(blockNumber?: number): Promise<MerkleTreeWriteOperations> {
77
- return this.merkleTreeDb.fork(blockNumber);
82
+ public fork(blockNumber?: BlockNumber, opts?: { closeDelayMs?: number }): Promise<MerkleTreeWriteOperations> {
83
+ return this.merkleTreeDb.fork(blockNumber, opts);
84
+ }
85
+
86
+ public backupTo(dstPath: string, compact?: boolean): Promise<Record<Exclude<SnapshotDataKeys, 'archiver'>, string>> {
87
+ return this.merkleTreeDb.backupTo(dstPath, compact);
88
+ }
89
+
90
+ public clear(): Promise<void> {
91
+ return this.merkleTreeDb.clear();
78
92
  }
79
93
 
80
94
  public async start() {
@@ -86,9 +100,11 @@ export class ServerWorldStateSynchronizer
86
100
  }
87
101
 
88
102
  // Get the current latest block number
89
- this.latestBlockNumberAtStart = await (this.config.worldStateProvenBlocksOnly
90
- ? this.l2BlockSource.getProvenBlockNumber()
91
- : this.l2BlockSource.getBlockNumber());
103
+ this.latestBlockNumberAtStart = BlockNumber(
104
+ await (this.config.worldStateProvenBlocksOnly
105
+ ? this.l2BlockSource.getProvenBlockNumber()
106
+ : this.l2BlockSource.getBlockNumber()),
107
+ );
92
108
 
93
109
  const blockToDownloadFrom = (await this.getLatestBlockNumber()) + 1;
94
110
 
@@ -131,10 +147,10 @@ export class ServerWorldStateSynchronizer
131
147
  public async status(): Promise<WorldStateSynchronizerStatus> {
132
148
  const summary = await this.merkleTreeDb.getStatusSummary();
133
149
  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),
150
+ latestBlockNumber: summary.unfinalizedBlockNumber,
151
+ latestBlockHash: (await this.getL2BlockHash(summary.unfinalizedBlockNumber)) ?? '',
152
+ finalizedBlockNumber: summary.finalizedBlockNumber,
153
+ oldestHistoricBlockNumber: summary.oldestHistoricalBlock,
138
154
  treesAreSynched: summary.treesAreSynched,
139
155
  };
140
156
  return {
@@ -147,16 +163,39 @@ export class ServerWorldStateSynchronizer
147
163
  return (await this.getL2Tips()).latest.number;
148
164
  }
149
165
 
166
+ public async stopSync() {
167
+ this.log.debug('Stopping sync...');
168
+ await this.blockStream?.stop();
169
+ this.log.info('Stopped sync');
170
+ }
171
+
172
+ public resumeSync() {
173
+ if (!this.blockStream) {
174
+ throw new Error('Cannot resume sync as block stream is not initialized');
175
+ }
176
+ this.log.debug('Resuming sync...');
177
+ this.blockStream.start();
178
+ this.log.info('Resumed sync');
179
+ }
180
+
150
181
  /**
151
182
  * 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.
183
+ * @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
184
+ * @param skipThrowIfTargetNotReached - Whether to skip throwing if the target block number is not reached.
153
185
  * @returns A promise that resolves with the block number the world state was synced to
154
186
  */
155
- public async syncImmediate(targetBlockNumber?: number): Promise<number> {
156
- if (this.currentState !== WorldStateRunningState.RUNNING || this.blockStream === undefined) {
187
+ public async syncImmediate(
188
+ targetBlockNumber?: BlockNumber,
189
+ skipThrowIfTargetNotReached?: boolean,
190
+ ): Promise<BlockNumber> {
191
+ if (this.currentState !== WorldStateRunningState.RUNNING) {
157
192
  throw new Error(`World State is not running. Unable to perform sync.`);
158
193
  }
159
194
 
195
+ if (this.blockStream === undefined) {
196
+ throw new Error('Block stream is not initialized. Unable to perform sync.');
197
+ }
198
+
160
199
  // If we have been given a block number to sync to and we have reached that number then return
161
200
  const currentBlockNumber = await this.getLatestBlockNumber();
162
201
  if (targetBlockNumber !== undefined && targetBlockNumber <= currentBlockNumber) {
@@ -164,21 +203,40 @@ export class ServerWorldStateSynchronizer
164
203
  }
165
204
  this.log.debug(`World State at ${currentBlockNumber} told to sync to ${targetBlockNumber ?? 'latest'}`);
166
205
 
206
+ // If the archiver is behind the target block, force an archiver sync
207
+ if (targetBlockNumber) {
208
+ const archiverLatestBlock = BlockNumber(await this.l2BlockSource.getBlockNumber());
209
+ if (archiverLatestBlock < targetBlockNumber) {
210
+ this.log.debug(`Archiver is at ${archiverLatestBlock} behind target block ${targetBlockNumber}.`);
211
+ await this.l2BlockSource.syncImmediate();
212
+ }
213
+ }
214
+
167
215
  // Force the block stream to sync against the archiver now
168
216
  await this.blockStream.sync();
169
217
 
170
218
  // If we have been given a block number to sync to and we have not reached that number then fail
171
219
  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})`);
220
+ if (!skipThrowIfTargetNotReached && targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
221
+ throw new WorldStateSynchronizerError(
222
+ `Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`,
223
+ {
224
+ cause: {
225
+ reason: 'block_not_available',
226
+ previousBlockNumber: currentBlockNumber,
227
+ updatedBlockNumber,
228
+ targetBlockNumber,
229
+ },
230
+ },
231
+ );
174
232
  }
175
233
 
176
234
  return updatedBlockNumber;
177
235
  }
178
236
 
179
237
  /** 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) {
238
+ public async getL2BlockHash(number: BlockNumber): Promise<string | undefined> {
239
+ if (number === BlockNumber.ZERO) {
182
240
  return (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
183
241
  }
184
242
  if (this.latestBlockHashQuery?.hash === undefined || number !== this.latestBlockHashQuery.blockNumber) {
@@ -195,35 +253,31 @@ export class ServerWorldStateSynchronizer
195
253
  /** Returns the latest L2 block number for each tip of the chain (latest, proven, finalized). */
196
254
  public async getL2Tips(): Promise<L2Tips> {
197
255
  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! };
256
+ const unfinalizedBlockHash = await this.getL2BlockHash(status.unfinalizedBlockNumber);
257
+ const latestBlockId: L2BlockId = { number: status.unfinalizedBlockNumber, hash: unfinalizedBlockHash! };
200
258
 
201
259
  return {
202
260
  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
261
+ finalized: { number: status.finalizedBlockNumber, hash: '' },
262
+ proven: { number: this.provenBlockNumber ?? status.finalizedBlockNumber, hash: '' }, // TODO(palla/reorg): Using finalized as proven for now
205
263
  };
206
264
  }
207
265
 
208
266
  /** Handles an event emitted by the block stream. */
209
267
  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);
268
+ switch (event.type) {
269
+ case 'blocks-added':
270
+ await this.handleL2Blocks(event.blocks.map(b => b.block.toL2Block()));
271
+ break;
272
+ case 'chain-pruned':
273
+ await this.handleChainPruned(event.block.number);
274
+ break;
275
+ case 'chain-proven':
276
+ await this.handleChainProven(event.block.number);
277
+ break;
278
+ case 'chain-finalized':
279
+ await this.handleChainFinalized(event.block.number);
280
+ break;
227
281
  }
228
282
  }
229
283
 
@@ -232,22 +286,32 @@ export class ServerWorldStateSynchronizer
232
286
  * @param l2Blocks - The L2 blocks to handle.
233
287
  * @returns Whether the block handled was produced by this same node.
234
288
  */
235
- private async handleL2Blocks(l2Blocks: L2Block[]) {
289
+ private async handleL2Blocks(l2Blocks: L2BlockNew[]) {
236
290
  this.log.trace(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1)!.number}`);
237
291
 
238
- const messagePromises = l2Blocks.map(block => this.l2BlockSource.getL1ToL2Messages(BigInt(block.number)));
239
- const l1ToL2Messages: Fr[][] = await Promise.all(messagePromises);
240
- let updateStatus: WorldStateStatusFull | undefined = undefined;
292
+ // Fetch the L1->L2 messages for the first block in a checkpoint.
293
+ const messagesForBlocks = new Map<BlockNumber, Fr[]>();
294
+ await Promise.all(
295
+ l2Blocks
296
+ .filter(b => b.indexWithinCheckpoint === 0)
297
+ .map(async block => {
298
+ const l1ToL2Messages = await this.l2BlockSource.getL1ToL2Messages(block.checkpointNumber);
299
+ messagesForBlocks.set(block.number, l1ToL2Messages);
300
+ }),
301
+ );
241
302
 
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}`, {
303
+ let updateStatus: WorldStateStatusFull | undefined = undefined;
304
+ for (const block of l2Blocks) {
305
+ const [duration, result] = await elapsed(() =>
306
+ this.handleL2Block(block, messagesForBlocks.get(block.number) ?? []),
307
+ );
308
+ this.log.info(`World state updated with L2 block ${block.number}`, {
245
309
  eventName: 'l2-block-handled',
246
310
  duration,
247
- unfinalisedBlockNumber: result.summary.unfinalisedBlockNumber,
248
- finalisedBlockNumber: result.summary.finalisedBlockNumber,
249
- oldestHistoricBlock: result.summary.oldestHistoricalBlock,
250
- ...l2Blocks[i].getStats(),
311
+ unfinalizedBlockNumber: BigInt(result.summary.unfinalizedBlockNumber),
312
+ finalizedBlockNumber: BigInt(result.summary.finalizedBlockNumber),
313
+ oldestHistoricBlock: BigInt(result.summary.oldestHistoricalBlock),
314
+ ...block.getStats(),
251
315
  } satisfies L2BlockHandledStats);
252
316
  updateStatus = result;
253
317
  }
@@ -263,14 +327,7 @@ export class ServerWorldStateSynchronizer
263
327
  * @param l1ToL2Messages - The L1 to L2 messages for the block.
264
328
  * @returns Whether the block handled was produced by this same node.
265
329
  */
266
- 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.
330
+ private async handleL2Block(l2Block: L2BlockNew, l1ToL2Messages: Fr[]): Promise<WorldStateStatusFull> {
274
331
  this.log.trace(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
275
332
  blockNumber: l2Block.number,
276
333
  blockHash: await l2Block.hash().then(h => h.toString()),
@@ -286,30 +343,32 @@ export class ServerWorldStateSynchronizer
286
343
  return result;
287
344
  }
288
345
 
289
- private async handleChainFinalized(blockNumber: number) {
346
+ private async handleChainFinalized(blockNumber: BlockNumber) {
290
347
  this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
291
- const summary = await this.merkleTreeDb.setFinalised(BigInt(blockNumber));
348
+ const summary = await this.merkleTreeDb.setFinalized(blockNumber);
292
349
  if (this.historyToKeep === undefined) {
293
350
  return;
294
351
  }
295
- const newHistoricBlock = summary.finalisedBlockNumber - BigInt(this.historyToKeep) + 1n;
352
+ const newHistoricBlock = summary.finalizedBlockNumber - this.historyToKeep + 1;
296
353
  if (newHistoricBlock <= 1) {
297
354
  return;
298
355
  }
299
356
  this.log.verbose(`Pruning historic blocks to ${newHistoricBlock}`);
300
- const status = await this.merkleTreeDb.removeHistoricalBlocks(newHistoricBlock);
357
+ const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock));
301
358
  this.log.debug(`World state summary `, status.summary);
302
359
  }
303
360
 
304
- private handleChainProven(blockNumber: number) {
361
+ private handleChainProven(blockNumber: BlockNumber) {
362
+ this.provenBlockNumber = blockNumber;
305
363
  this.log.debug(`Proven chain is now at block ${blockNumber}`);
306
364
  return Promise.resolve();
307
365
  }
308
366
 
309
- private async handleChainPruned(blockNumber: number) {
367
+ private async handleChainPruned(blockNumber: BlockNumber) {
310
368
  this.log.warn(`Chain pruned to block ${blockNumber}`);
311
- const status = await this.merkleTreeDb.unwindBlocks(BigInt(blockNumber));
369
+ const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
312
370
  this.latestBlockHashQuery = undefined;
371
+ this.provenBlockNumber = undefined;
313
372
  this.instrumentation.updateWorldStateMetrics(status);
314
373
  }
315
374
 
@@ -321,24 +380,4 @@ export class ServerWorldStateSynchronizer
321
380
  this.currentState = newState;
322
381
  this.log.debug(`Moved to state ${WorldStateRunningState[this.currentState]}`);
323
382
  }
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
383
  }
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 } from '@aztec/foundation/branded-types';
7
9
  import { padArrayEnd } from '@aztec/foundation/collection';
8
- import { Fr } from '@aztec/foundation/fields';
9
- import { L2Block } from '@aztec/stdlib/block';
10
- import type { MerkleTreeReadOperations, MerkleTreeWriteOperations } from '@aztec/stdlib/interfaces/server';
10
+ import { Fr } from '@aztec/foundation/curves/bn254';
11
+ import { L2BlockNew } from '@aztec/stdlib/block';
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: L2BlockNew, 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 L2BlockNew.random(blockNum, {
80
+ indexWithinCheckpoint: isFirstBlockInCheckpoint ? 0 : 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) {
65
- const l2Block = L2Block.empty();
94
+ export async function mockEmptyBlock(blockNum: BlockNumber, fork: MerkleTreeWriteOperations) {
95
+ const l2Block = L2BlockNew.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);
package/src/testing.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { GENESIS_ARCHIVE_ROOT, GENESIS_BLOCK_HASH } from '@aztec/constants';
2
- import { Fr } from '@aztec/foundation/fields';
1
+ import { GENESIS_ARCHIVE_ROOT } from '@aztec/constants';
2
+ 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';
@@ -10,7 +10,6 @@ async function generateGenesisValues(prefilledPublicData: PublicDataTreeLeaf[])
10
10
  if (!prefilledPublicData.length) {
11
11
  return {
12
12
  genesisArchiveRoot: new Fr(GENESIS_ARCHIVE_ROOT),
13
- genesisBlockHash: new Fr(GENESIS_BLOCK_HASH),
14
13
  };
15
14
  }
16
15
 
@@ -20,14 +19,11 @@ async function generateGenesisValues(prefilledPublicData: PublicDataTreeLeaf[])
20
19
  true /* cleanupTmpDir */,
21
20
  prefilledPublicData,
22
21
  );
23
- const initialHeader = ws.getInitialHeader();
24
- const genesisBlockHash = await initialHeader.hash();
25
22
  const genesisArchiveRoot = new Fr((await ws.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
26
23
  await ws.close();
27
24
 
28
25
  return {
29
26
  genesisArchiveRoot,
30
- genesisBlockHash,
31
27
  };
32
28
  }
33
29
 
@@ -50,11 +46,11 @@ export async function getGenesisValues(
50
46
 
51
47
  prefilledPublicData.sort((a, b) => (b.slot.lt(a.slot) ? 1 : -1));
52
48
 
53
- const { genesisBlockHash, genesisArchiveRoot } = await generateGenesisValues(prefilledPublicData);
49
+ const { genesisArchiveRoot } = await generateGenesisValues(prefilledPublicData);
54
50
 
55
51
  return {
56
52
  genesisArchiveRoot,
57
- genesisBlockHash,
58
53
  prefilledPublicData,
54
+ fundingNeeded: BigInt(initialAccounts.length) * initialAccountFeeJuice.toBigInt(),
59
55
  };
60
56
  }