@aztec/world-state 0.0.0-test.1 → 0.0.1-commit.017a351

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 (69) 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 +7 -1
  9. package/dest/native/fork_checkpoint.d.ts.map +1 -1
  10. package/dest/native/fork_checkpoint.js +15 -3
  11. package/dest/native/index.d.ts +1 -1
  12. package/dest/native/ipc_world_state_instance.d.ts +45 -0
  13. package/dest/native/ipc_world_state_instance.d.ts.map +1 -0
  14. package/dest/native/ipc_world_state_instance.js +750 -0
  15. package/dest/native/merkle_trees_facade.d.ts +25 -9
  16. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  17. package/dest/native/merkle_trees_facade.js +109 -25
  18. package/dest/native/message.d.ts +87 -58
  19. package/dest/native/message.d.ts.map +1 -1
  20. package/dest/native/message.js +61 -61
  21. package/dest/native/native_world_state.d.ts +41 -21
  22. package/dest/native/native_world_state.d.ts.map +1 -1
  23. package/dest/native/native_world_state.js +177 -50
  24. package/dest/native/native_world_state_instance.d.ts +23 -25
  25. package/dest/native/native_world_state_instance.d.ts.map +1 -1
  26. package/dest/native/native_world_state_instance.js +8 -163
  27. package/dest/native/world_state_ops_queue.d.ts +1 -1
  28. package/dest/native/world_state_ops_queue.d.ts.map +1 -1
  29. package/dest/native/world_state_ops_queue.js +6 -6
  30. package/dest/synchronizer/config.d.ts +14 -6
  31. package/dest/synchronizer/config.d.ts.map +1 -1
  32. package/dest/synchronizer/config.js +36 -14
  33. package/dest/synchronizer/errors.d.ts +4 -0
  34. package/dest/synchronizer/errors.d.ts.map +1 -0
  35. package/dest/synchronizer/errors.js +5 -0
  36. package/dest/synchronizer/factory.d.ts +13 -5
  37. package/dest/synchronizer/factory.d.ts.map +1 -1
  38. package/dest/synchronizer/factory.js +15 -9
  39. package/dest/synchronizer/index.d.ts +1 -1
  40. package/dest/synchronizer/server_world_state_synchronizer.d.ts +21 -31
  41. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  42. package/dest/synchronizer/server_world_state_synchronizer.js +220 -96
  43. package/dest/test/index.d.ts +1 -1
  44. package/dest/test/utils.d.ts +12 -5
  45. package/dest/test/utils.d.ts.map +1 -1
  46. package/dest/test/utils.js +54 -47
  47. package/dest/testing.d.ts +6 -5
  48. package/dest/testing.d.ts.map +1 -1
  49. package/dest/testing.js +15 -15
  50. package/dest/world-state-db/index.d.ts +1 -1
  51. package/dest/world-state-db/merkle_tree_db.d.ts +12 -18
  52. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  53. package/package.json +27 -25
  54. package/src/instrumentation/instrumentation.ts +31 -43
  55. package/src/native/bench_metrics.ts +91 -0
  56. package/src/native/fork_checkpoint.ts +19 -3
  57. package/src/native/ipc_world_state_instance.ts +863 -0
  58. package/src/native/merkle_trees_facade.ts +127 -33
  59. package/src/native/message.ts +109 -80
  60. package/src/native/native_world_state.ts +207 -64
  61. package/src/native/native_world_state_instance.ts +28 -223
  62. package/src/native/world_state_ops_queue.ts +6 -6
  63. package/src/synchronizer/config.ts +58 -20
  64. package/src/synchronizer/errors.ts +5 -0
  65. package/src/synchronizer/factory.ts +48 -18
  66. package/src/synchronizer/server_world_state_synchronizer.ts +249 -121
  67. package/src/test/utils.ts +92 -82
  68. package/src/testing.ts +11 -16
  69. package/src/world-state-db/merkle_tree_db.ts +16 -18
@@ -1,13 +1,14 @@
1
- import { L1_TO_L2_MSG_SUBTREE_HEIGHT } from '@aztec/constants';
1
+ import { INITIAL_CHECKPOINT_NUMBER } from '@aztec/constants';
2
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
3
  import { createLogger } from '@aztec/foundation/log';
3
4
  import { promiseWithResolvers } from '@aztec/foundation/promise';
4
5
  import { elapsed } from '@aztec/foundation/timer';
5
- import { MerkleTreeCalculator } from '@aztec/foundation/trees';
6
- import { SHA256Trunc } from '@aztec/merkle-tree';
6
+ import { GENESIS_CHECKPOINT_HEADER_HASH, L2BlockStream } from '@aztec/stdlib/block';
7
7
  import { WorldStateRunningState } from '@aztec/stdlib/interfaces/server';
8
8
  import { MerkleTreeId } from '@aztec/stdlib/trees';
9
- import { TraceableL2BlockStream, getTelemetryClient } from '@aztec/telemetry-client';
9
+ import { getTelemetryClient } from '@aztec/telemetry-client';
10
10
  import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js';
11
+ import { WorldStateSynchronizerError } from './errors.js';
11
12
  /**
12
13
  * Synchronizes the world state with the L2 blocks from a L2BlockSource via a block stream.
13
14
  * The synchronizer will download the L2 blocks from the L2BlockSource and update the merkle trees.
@@ -22,21 +23,22 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
22
23
  latestBlockNumberAtStart;
23
24
  historyToKeep;
24
25
  currentState;
25
- latestBlockHashQuery;
26
26
  syncPromise;
27
27
  blockStream;
28
+ // WorldState doesn't track the proven block number, it only tracks the latest tips of the pending chain and the finalized chain
29
+ // store the proven block number here, in the synchronizer, so that we don't end up spamming the logs with 'chain-proved' events
30
+ provenBlockNumber;
28
31
  constructor(merkleTreeDb, l2BlockSource, config, instrumentation = new WorldStateInstrumentation(getTelemetryClient()), log = createLogger('world_state')){
29
32
  this.merkleTreeDb = merkleTreeDb;
30
33
  this.l2BlockSource = l2BlockSource;
31
34
  this.config = config;
32
35
  this.instrumentation = instrumentation;
33
36
  this.log = log;
34
- this.latestBlockNumberAtStart = 0;
37
+ this.latestBlockNumberAtStart = BlockNumber.ZERO;
35
38
  this.currentState = WorldStateRunningState.IDLE;
36
- this.latestBlockHashQuery = undefined;
37
39
  this.syncPromise = promiseWithResolvers();
38
40
  this.merkleTreeCommitted = this.merkleTreeDb.getCommitted();
39
- this.historyToKeep = config.worldStateBlockHistory < 1 ? undefined : config.worldStateBlockHistory;
41
+ this.historyToKeep = config.worldStateCheckpointHistory < 1 ? undefined : config.worldStateCheckpointHistory;
40
42
  this.log.info(`Created world state synchroniser with block history of ${this.historyToKeep === undefined ? 'infinity' : this.historyToKeep}`);
41
43
  }
42
44
  getCommitted() {
@@ -45,8 +47,14 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
45
47
  getSnapshot(blockNumber) {
46
48
  return this.merkleTreeDb.getSnapshot(blockNumber);
47
49
  }
48
- fork(blockNumber) {
49
- return this.merkleTreeDb.fork(blockNumber);
50
+ fork(blockNumber, opts) {
51
+ return this.merkleTreeDb.fork(blockNumber, opts);
52
+ }
53
+ backupTo(dstPath, compact) {
54
+ return this.merkleTreeDb.backupTo(dstPath, compact);
55
+ }
56
+ clear() {
57
+ return this.merkleTreeDb.clear();
50
58
  }
51
59
  async start() {
52
60
  if (this.currentState === WorldStateRunningState.STOPPED) {
@@ -56,7 +64,7 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
56
64
  return this.syncPromise;
57
65
  }
58
66
  // Get the current latest block number
59
- this.latestBlockNumberAtStart = await (this.config.worldStateProvenBlocksOnly ? this.l2BlockSource.getProvenBlockNumber() : this.l2BlockSource.getBlockNumber());
67
+ this.latestBlockNumberAtStart = BlockNumber(await this.l2BlockSource.getBlockNumber());
60
68
  const blockToDownloadFrom = await this.getLatestBlockNumber() + 1;
61
69
  if (blockToDownloadFrom <= this.latestBlockNumberAtStart) {
62
70
  // If there are blocks to be retrieved, go to a synching state
@@ -74,12 +82,11 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
74
82
  return this.syncPromise.promise;
75
83
  }
76
84
  createBlockStream() {
77
- const tracer = this.instrumentation.telemetry.getTracer('WorldStateL2BlockStream');
78
85
  const logger = createLogger('world-state:block_stream');
79
- return new TraceableL2BlockStream(this.l2BlockSource, this, this, tracer, 'WorldStateL2BlockStream', logger, {
80
- proven: this.config.worldStateProvenBlocksOnly,
86
+ return new L2BlockStream(this.l2BlockSource, this, this, logger, {
81
87
  pollIntervalMS: this.config.worldStateBlockCheckIntervalMS,
82
- batchSize: this.config.worldStateBlockRequestBatchSize
88
+ batchSize: this.config.worldStateBlockRequestBatchSize,
89
+ ignoreCheckpoints: true
83
90
  });
84
91
  }
85
92
  async stop() {
@@ -93,10 +100,10 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
93
100
  async status() {
94
101
  const summary = await this.merkleTreeDb.getStatusSummary();
95
102
  const status = {
96
- latestBlockNumber: Number(summary.unfinalisedBlockNumber),
97
- latestBlockHash: await this.getL2BlockHash(Number(summary.unfinalisedBlockNumber)) ?? '',
98
- finalisedBlockNumber: Number(summary.finalisedBlockNumber),
99
- oldestHistoricBlockNumber: Number(summary.oldestHistoricalBlock),
103
+ latestBlockNumber: summary.unfinalizedBlockNumber,
104
+ latestBlockHash: await this.getL2BlockHash(summary.unfinalizedBlockNumber) ?? '',
105
+ finalizedBlockNumber: summary.finalizedBlockNumber,
106
+ oldestHistoricBlockNumber: summary.oldestHistoricalBlock,
100
107
  treesAreSynched: summary.treesAreSynched
101
108
  };
102
109
  return {
@@ -105,80 +112,170 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
105
112
  };
106
113
  }
107
114
  async getLatestBlockNumber() {
108
- return (await this.getL2Tips()).latest.number;
115
+ return (await this.getL2Tips()).proposed.number;
116
+ }
117
+ async stopSync() {
118
+ this.log.debug('Stopping sync...');
119
+ await this.blockStream?.stop();
120
+ this.log.info('Stopped sync');
121
+ }
122
+ resumeSync() {
123
+ if (!this.blockStream) {
124
+ throw new Error('Cannot resume sync as block stream is not initialized');
125
+ }
126
+ this.log.debug('Resuming sync...');
127
+ this.blockStream.start();
128
+ this.log.info('Resumed sync');
109
129
  }
110
130
  /**
111
131
  * Forces an immediate sync.
112
- * @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.
132
+ * @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
133
+ * @param blockHash - If provided, verifies the block at targetBlockNumber matches this hash. On mismatch, triggers a resync (reorg detection).
113
134
  * @returns A promise that resolves with the block number the world state was synced to
114
- */ async syncImmediate(targetBlockNumber) {
115
- if (this.currentState !== WorldStateRunningState.RUNNING || this.blockStream === undefined) {
135
+ */ async syncImmediate(targetBlockNumber, blockHash) {
136
+ if (this.currentState !== WorldStateRunningState.RUNNING) {
116
137
  throw new Error(`World State is not running. Unable to perform sync.`);
117
138
  }
139
+ if (this.blockStream === undefined) {
140
+ throw new Error('Block stream is not initialized. Unable to perform sync.');
141
+ }
118
142
  // If we have been given a block number to sync to and we have reached that number then return
119
143
  const currentBlockNumber = await this.getLatestBlockNumber();
120
144
  if (targetBlockNumber !== undefined && targetBlockNumber <= currentBlockNumber) {
121
- return currentBlockNumber;
145
+ if (blockHash === undefined) {
146
+ return currentBlockNumber;
147
+ }
148
+ // If a block hash was provided, verify we're on the expected fork
149
+ const currentHash = await this.getL2BlockHash(targetBlockNumber);
150
+ if (currentHash === blockHash.toString()) {
151
+ return currentBlockNumber;
152
+ }
153
+ // Hash mismatch: a reorg may have occurred, fall through to trigger sync
154
+ this.log.debug(`World state block hash mismatch at ${targetBlockNumber} (expected ${blockHash}, got ${currentHash}). Triggering resync.`);
122
155
  }
123
156
  this.log.debug(`World State at ${currentBlockNumber} told to sync to ${targetBlockNumber ?? 'latest'}`);
157
+ // If the archiver is behind the target block, force an archiver sync
158
+ if (targetBlockNumber) {
159
+ const archiverLatestBlock = BlockNumber(await this.l2BlockSource.getBlockNumber());
160
+ if (archiverLatestBlock < targetBlockNumber) {
161
+ this.log.debug(`Archiver is at ${archiverLatestBlock} behind target block ${targetBlockNumber}.`);
162
+ await this.l2BlockSource.syncImmediate();
163
+ }
164
+ }
124
165
  // Force the block stream to sync against the archiver now
125
166
  await this.blockStream.sync();
126
167
  // If we have been given a block number to sync to and we have not reached that number then fail
127
168
  const updatedBlockNumber = await this.getLatestBlockNumber();
128
169
  if (targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
129
- throw new Error(`Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`);
170
+ throw new WorldStateSynchronizerError(`Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`, {
171
+ cause: {
172
+ reason: 'block_not_available',
173
+ previousBlockNumber: currentBlockNumber,
174
+ updatedBlockNumber,
175
+ targetBlockNumber
176
+ }
177
+ });
178
+ }
179
+ // If a block hash was provided, verify we're on the expected fork after syncing, throw otherwise
180
+ if (blockHash !== undefined && targetBlockNumber !== undefined) {
181
+ const updatedHash = await this.getL2BlockHash(targetBlockNumber);
182
+ if (updatedHash !== blockHash.toString()) {
183
+ throw new WorldStateSynchronizerError(`Block hash mismatch at block ${targetBlockNumber} (expected ${blockHash} but got ${updatedHash})`, {
184
+ cause: {
185
+ reason: 'block_hash_mismatch',
186
+ targetBlockNumber,
187
+ expectedHash: blockHash.toString(),
188
+ actualHash: updatedHash
189
+ }
190
+ });
191
+ }
130
192
  }
131
193
  return updatedBlockNumber;
132
194
  }
133
195
  /** Returns the L2 block hash for a given number. Used by the L2BlockStream for detecting reorgs. */ async getL2BlockHash(number) {
134
- if (number === 0) {
196
+ if (number === BlockNumber.ZERO) {
135
197
  return (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
136
198
  }
137
- if (this.latestBlockHashQuery?.hash === undefined || number !== this.latestBlockHashQuery.blockNumber) {
138
- this.latestBlockHashQuery = {
139
- hash: await this.merkleTreeCommitted.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(number)).then((leaf)=>leaf?.toString()),
140
- blockNumber: number
141
- };
142
- }
143
- return this.latestBlockHashQuery.hash;
199
+ return this.merkleTreeCommitted.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(number)).then((leaf)=>leaf?.toString());
144
200
  }
145
201
  /** Returns the latest L2 block number for each tip of the chain (latest, proven, finalized). */ async getL2Tips() {
146
202
  const status = await this.merkleTreeDb.getStatusSummary();
147
- const unfinalisedBlockHash = await this.getL2BlockHash(Number(status.unfinalisedBlockNumber));
203
+ const unfinalizedBlockHashPromise = this.getL2BlockHash(status.unfinalizedBlockNumber);
204
+ const finalizedBlockHashPromise = this.getL2BlockHash(status.finalizedBlockNumber);
205
+ const provenBlockNumber = this.provenBlockNumber ?? status.finalizedBlockNumber;
206
+ const provenBlockHashPromise = this.provenBlockNumber === undefined ? finalizedBlockHashPromise : this.getL2BlockHash(this.provenBlockNumber);
207
+ const [unfinalizedBlockHash, finalizedBlockHash, provenBlockHash] = await Promise.all([
208
+ unfinalizedBlockHashPromise,
209
+ finalizedBlockHashPromise,
210
+ provenBlockHashPromise
211
+ ]);
148
212
  const latestBlockId = {
149
- number: Number(status.unfinalisedBlockNumber),
150
- hash: unfinalisedBlockHash
213
+ number: status.unfinalizedBlockNumber,
214
+ hash: unfinalizedBlockHash
151
215
  };
216
+ // World state doesn't track checkpointed blocks or checkpoints themselves.
217
+ // but we use a block stream so we need to provide 'local' L2Tips.
218
+ // We configure the block stream to ignore checkpoints and set checkpoint values to genesis here.
219
+ const genesisCheckpointHeaderHash = GENESIS_CHECKPOINT_HEADER_HASH.toString();
220
+ const initialBlockHash = (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
152
221
  return {
153
- latest: latestBlockId,
222
+ proposed: latestBlockId,
223
+ checkpointed: {
224
+ block: {
225
+ number: BlockNumber.ZERO,
226
+ hash: initialBlockHash
227
+ },
228
+ checkpoint: {
229
+ number: INITIAL_CHECKPOINT_NUMBER,
230
+ hash: genesisCheckpointHeaderHash
231
+ }
232
+ },
233
+ proposedCheckpoint: {
234
+ block: {
235
+ number: BlockNumber.ZERO,
236
+ hash: initialBlockHash
237
+ },
238
+ checkpoint: {
239
+ number: INITIAL_CHECKPOINT_NUMBER,
240
+ hash: genesisCheckpointHeaderHash
241
+ }
242
+ },
154
243
  finalized: {
155
- number: Number(status.finalisedBlockNumber),
156
- hash: ''
244
+ block: {
245
+ number: status.finalizedBlockNumber,
246
+ hash: finalizedBlockHash ?? ''
247
+ },
248
+ checkpoint: {
249
+ number: INITIAL_CHECKPOINT_NUMBER,
250
+ hash: genesisCheckpointHeaderHash
251
+ }
157
252
  },
158
253
  proven: {
159
- number: Number(status.finalisedBlockNumber),
160
- hash: ''
254
+ block: {
255
+ number: provenBlockNumber,
256
+ hash: provenBlockHash ?? ''
257
+ },
258
+ checkpoint: {
259
+ number: INITIAL_CHECKPOINT_NUMBER,
260
+ hash: genesisCheckpointHeaderHash
261
+ }
161
262
  }
162
263
  };
163
264
  }
164
265
  /** Handles an event emitted by the block stream. */ async handleBlockStreamEvent(event) {
165
- try {
166
- switch(event.type){
167
- case 'blocks-added':
168
- await this.handleL2Blocks(event.blocks);
169
- break;
170
- case 'chain-pruned':
171
- await this.handleChainPruned(event.blockNumber);
172
- break;
173
- case 'chain-proven':
174
- await this.handleChainProven(event.blockNumber);
175
- break;
176
- case 'chain-finalized':
177
- await this.handleChainFinalized(event.blockNumber);
178
- break;
179
- }
180
- } catch (err) {
181
- this.log.error('Error processing block stream', err);
266
+ switch(event.type){
267
+ case 'blocks-added':
268
+ await this.handleL2Blocks(event.blocks);
269
+ break;
270
+ case 'chain-pruned':
271
+ await this.handleChainPruned(event.block.number);
272
+ break;
273
+ case 'chain-proven':
274
+ await this.handleChainProven(event.block.number);
275
+ break;
276
+ case 'chain-finalized':
277
+ await this.handleChainFinalized(event.block.number);
278
+ break;
182
279
  }
183
280
  }
184
281
  /**
@@ -186,19 +283,23 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
186
283
  * @param l2Blocks - The L2 blocks to handle.
187
284
  * @returns Whether the block handled was produced by this same node.
188
285
  */ async handleL2Blocks(l2Blocks) {
189
- this.log.trace(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1).number}`);
190
- const messagePromises = l2Blocks.map((block)=>this.l2BlockSource.getL1ToL2Messages(BigInt(block.number)));
191
- const l1ToL2Messages = await Promise.all(messagePromises);
286
+ this.log.debug(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1).number}`);
287
+ // Fetch the L1->L2 messages for the first block in a checkpoint.
288
+ const messagesForBlocks = new Map();
289
+ await Promise.all(l2Blocks.filter((b)=>b.indexWithinCheckpoint === 0).map(async (block)=>{
290
+ const l1ToL2Messages = await this.l2BlockSource.getL1ToL2Messages(block.checkpointNumber);
291
+ messagesForBlocks.set(block.number, l1ToL2Messages);
292
+ }));
192
293
  let updateStatus = undefined;
193
- for(let i = 0; i < l2Blocks.length; i++){
194
- const [duration, result] = await elapsed(()=>this.handleL2Block(l2Blocks[i], l1ToL2Messages[i]));
195
- this.log.verbose(`World state updated with L2 block ${l2Blocks[i].number}`, {
294
+ for (const block of l2Blocks){
295
+ const [duration, result] = await elapsed(()=>this.handleL2Block(block, messagesForBlocks.get(block.number) ?? []));
296
+ this.log.info(`World state updated with L2 block ${block.number}`, {
196
297
  eventName: 'l2-block-handled',
197
298
  duration,
198
- unfinalisedBlockNumber: result.summary.unfinalisedBlockNumber,
199
- finalisedBlockNumber: result.summary.finalisedBlockNumber,
200
- oldestHistoricBlock: result.summary.oldestHistoricalBlock,
201
- ...l2Blocks[i].getStats()
299
+ unfinalizedBlockNumber: BigInt(result.summary.unfinalizedBlockNumber),
300
+ finalizedBlockNumber: BigInt(result.summary.finalizedBlockNumber),
301
+ oldestHistoricBlock: BigInt(result.summary.oldestHistoricalBlock),
302
+ ...block.getStats()
202
303
  });
203
304
  updateStatus = result;
204
305
  }
@@ -213,16 +314,12 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
213
314
  * @param l1ToL2Messages - The L1 to L2 messages for the block.
214
315
  * @returns Whether the block handled was produced by this same node.
215
316
  */ async handleL2Block(l2Block, l1ToL2Messages) {
216
- // First we check that the L1 to L2 messages hash to the block inHash.
217
- // Note that we cannot optimize this check by checking the root of the subtree after inserting the messages
218
- // to the real L1_TO_L2_MESSAGE_TREE (like we do in merkleTreeDb.handleL2BlockAndMessages(...)) because that
219
- // tree uses pedersen and we don't have access to the converted root.
220
- await this.verifyMessagesHashToInHash(l1ToL2Messages, l2Block.header.contentCommitment.inHash);
221
- // If the above check succeeds, we can proceed to handle the block.
222
- this.log.trace(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
317
+ this.log.debug(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
223
318
  blockNumber: l2Block.number,
224
319
  blockHash: await l2Block.hash().then((h)=>h.toString()),
225
- l1ToL2Messages: l1ToL2Messages.map((msg)=>msg.toString())
320
+ l1ToL2Messages: l1ToL2Messages.map((msg)=>msg.toString()),
321
+ blockHeader: l2Block.header.toInspect(),
322
+ blockStats: l2Block.getStats()
226
323
  });
227
324
  const result = await this.merkleTreeDb.handleL2BlockAndMessages(l2Block, l1ToL2Messages);
228
325
  if (this.currentState === WorldStateRunningState.SYNCHING && l2Block.number >= this.latestBlockNumberAtStart) {
@@ -233,26 +330,65 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
233
330
  }
234
331
  async handleChainFinalized(blockNumber) {
235
332
  this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
236
- const summary = await this.merkleTreeDb.setFinalised(BigInt(blockNumber));
333
+ // If the finalized block number is older than the oldest available block in world state,
334
+ // skip entirely. The finalized block number can jump backwards (e.g. when the finalization
335
+ // heuristic changes) and try to read block data that has already been pruned. When this
336
+ // happens, there is nothing useful to do — the native world state is already finalized
337
+ // past this point and pruning has already happened.
338
+ const currentSummary = await this.merkleTreeDb.getStatusSummary();
339
+ if (blockNumber < currentSummary.oldestHistoricalBlock || blockNumber < 1) {
340
+ this.log.trace(`Finalized block ${blockNumber} is older than the oldest available block ${currentSummary.oldestHistoricalBlock}. Skipping.`);
341
+ return;
342
+ }
343
+ const summary = await this.merkleTreeDb.setFinalized(blockNumber);
237
344
  if (this.historyToKeep === undefined) {
238
345
  return;
239
346
  }
240
- const newHistoricBlock = summary.finalisedBlockNumber - BigInt(this.historyToKeep) + 1n;
241
- if (newHistoricBlock <= 1) {
347
+ const finalisedBlockData = await this.l2BlockSource.getBlockData({
348
+ number: summary.finalizedBlockNumber
349
+ });
350
+ if (finalisedBlockData === undefined) {
351
+ this.log.warn(`Failed to retrieve checkpointed block for finalized block number: ${summary.finalizedBlockNumber}`);
352
+ return;
353
+ }
354
+ // Compute the required historic checkpoint number
355
+ const newHistoricCheckpointNumber = finalisedBlockData.checkpointNumber - this.historyToKeep + 1;
356
+ if (newHistoricCheckpointNumber <= 1) {
357
+ return;
358
+ }
359
+ // Retrieve the historic checkpoint
360
+ const historicCheckpoint = await this.l2BlockSource.getCheckpoint({
361
+ number: CheckpointNumber(newHistoricCheckpointNumber)
362
+ });
363
+ if (!historicCheckpoint) {
364
+ this.log.warn(`Failed to retrieve checkpoint number ${newHistoricCheckpointNumber} from Archiver`);
365
+ return;
366
+ }
367
+ if (historicCheckpoint.checkpoint.blocks.length === 0 || historicCheckpoint.checkpoint.blocks[0] === undefined) {
368
+ this.log.warn(`Retrieved checkpoint number ${newHistoricCheckpointNumber} has no blocks!`);
242
369
  return;
243
370
  }
244
- this.log.verbose(`Pruning historic blocks to ${newHistoricBlock}`);
245
- const status = await this.merkleTreeDb.removeHistoricalBlocks(newHistoricBlock);
371
+ // Find the block at the start of the checkpoint and remove blocks up to this one
372
+ const newHistoricBlock = historicCheckpoint.checkpoint.blocks[0];
373
+ if (newHistoricBlock.number <= currentSummary.oldestHistoricalBlock) {
374
+ this.log.debug(`Historic block ${newHistoricBlock.number} is not newer than oldest available ${currentSummary.oldestHistoricalBlock}. Skipping prune.`);
375
+ return;
376
+ }
377
+ this.log.verbose(`Pruning historic blocks to ${newHistoricBlock.number}`);
378
+ const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock.number));
246
379
  this.log.debug(`World state summary `, status.summary);
247
380
  }
248
381
  handleChainProven(blockNumber) {
382
+ this.provenBlockNumber = blockNumber;
249
383
  this.log.debug(`Proven chain is now at block ${blockNumber}`);
250
384
  return Promise.resolve();
251
385
  }
252
386
  async handleChainPruned(blockNumber) {
253
- this.log.warn(`Chain pruned to block ${blockNumber}`);
254
- const status = await this.merkleTreeDb.unwindBlocks(BigInt(blockNumber));
255
- this.latestBlockHashQuery = undefined;
387
+ this.log.info(`Chain pruned to block ${blockNumber}`);
388
+ const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
389
+ if (this.provenBlockNumber !== undefined && this.provenBlockNumber > blockNumber) {
390
+ this.provenBlockNumber = undefined;
391
+ }
256
392
  this.instrumentation.updateWorldStateMetrics(status);
257
393
  }
258
394
  /**
@@ -262,16 +398,4 @@ import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js
262
398
  this.currentState = newState;
263
399
  this.log.debug(`Moved to state ${WorldStateRunningState[this.currentState]}`);
264
400
  }
265
- /**
266
- * Verifies that the L1 to L2 messages hash to the block inHash.
267
- * @param l1ToL2Messages - The L1 to L2 messages for the block.
268
- * @param inHash - The inHash of the block.
269
- * @throws If the L1 to L2 messages do not hash to the block inHash.
270
- */ async verifyMessagesHashToInHash(l1ToL2Messages, inHash) {
271
- const treeCalculator = await MerkleTreeCalculator.create(L1_TO_L2_MSG_SUBTREE_HEIGHT, Buffer.alloc(32), (lhs, rhs)=>Promise.resolve(new SHA256Trunc().hash(lhs, rhs)));
272
- const root = await treeCalculator.computeTreeRoot(l1ToL2Messages.map((msg)=>msg.toBuffer()));
273
- if (!root.equals(inHash)) {
274
- throw new Error('Obtained L1 to L2 messages failed to be hashed to the block inHash');
275
- }
276
- }
277
401
  }
@@ -1,2 +1,2 @@
1
1
  export * from './utils.js';
2
- //# sourceMappingURL=index.d.ts.map
2
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90ZXN0L2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWMsWUFBWSxDQUFDIn0=
@@ -1,19 +1,26 @@
1
- import { Fr } from '@aztec/foundation/fields';
1
+ import { BlockNumber, type CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
3
  import { L2Block } from '@aztec/stdlib/block';
3
4
  import type { MerkleTreeReadOperations, MerkleTreeWriteOperations } from '@aztec/stdlib/interfaces/server';
5
+ import { mockCheckpointAndMessages } from '@aztec/stdlib/testing';
4
6
  import type { NativeWorldStateService } from '../native/native_world_state.js';
5
- export declare function mockBlock(blockNum: number, size: number, fork: MerkleTreeWriteOperations): Promise<{
7
+ export declare function updateBlockState(block: L2Block, l1ToL2Messages: Fr[], fork: MerkleTreeWriteOperations): Promise<void>;
8
+ export declare function mockBlock(blockNum: BlockNumber, size: number, fork: MerkleTreeWriteOperations, maxEffects?: number | undefined, numL1ToL2Messages?: number, isFirstBlockInCheckpoint?: boolean): Promise<{
6
9
  block: L2Block;
7
10
  messages: Fr[];
8
11
  }>;
9
- export declare function mockEmptyBlock(blockNum: number, fork: MerkleTreeWriteOperations): Promise<{
12
+ export declare function mockEmptyBlock(blockNum: BlockNumber, fork: MerkleTreeWriteOperations): Promise<{
10
13
  block: L2Block;
11
14
  messages: Fr[];
12
15
  }>;
13
- export declare function mockBlocks(from: number, count: number, numTxs: number, worldState: NativeWorldStateService): Promise<{
16
+ export declare function mockBlocks(from: BlockNumber, count: number, numTxs: number, worldState: NativeWorldStateService): Promise<{
14
17
  blocks: L2Block[];
15
18
  messages: Fr[][];
16
19
  }>;
20
+ export declare function mockCheckpoint(checkpointNumber: CheckpointNumber, fork: MerkleTreeWriteOperations, options?: Partial<Parameters<typeof mockCheckpointAndMessages>[1]>): Promise<{
21
+ checkpoint: import("@aztec/stdlib/checkpoint").Checkpoint;
22
+ messages: Fr[];
23
+ }>;
17
24
  export declare function assertSameState(forkA: MerkleTreeReadOperations, forkB: MerkleTreeReadOperations): Promise<void>;
18
25
  export declare function compareChains(left: MerkleTreeReadOperations, right: MerkleTreeReadOperations): Promise<void>;
19
- //# sourceMappingURL=utils.d.ts.map
26
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90ZXN0L3V0aWxzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQU9BLE9BQU8sRUFBRSxXQUFXLEVBQUUsS0FBSyxnQkFBZ0IsRUFBeUIsTUFBTSxpQ0FBaUMsQ0FBQztBQUU1RyxPQUFPLEVBQUUsRUFBRSxFQUFFLE1BQU0sZ0NBQWdDLENBQUM7QUFDcEQsT0FBTyxFQUFFLE9BQU8sRUFBRSxNQUFNLHFCQUFxQixDQUFDO0FBQzlDLE9BQU8sS0FBSyxFQUVWLHdCQUF3QixFQUN4Qix5QkFBeUIsRUFDMUIsTUFBTSxpQ0FBaUMsQ0FBQztBQUN6QyxPQUFPLEVBQUUseUJBQXlCLEVBQXNCLE1BQU0sdUJBQXVCLENBQUM7QUFJdEYsT0FBTyxLQUFLLEVBQUUsdUJBQXVCLEVBQUUsTUFBTSxpQ0FBaUMsQ0FBQztBQUUvRSx3QkFBc0IsZ0JBQWdCLENBQUMsS0FBSyxFQUFFLE9BQU8sRUFBRSxjQUFjLEVBQUUsRUFBRSxFQUFFLEVBQUUsSUFBSSxFQUFFLHlCQUF5QixpQkE4QzNHO0FBRUQsd0JBQXNCLFNBQVMsQ0FDN0IsUUFBUSxFQUFFLFdBQVcsRUFDckIsSUFBSSxFQUFFLE1BQU0sRUFDWixJQUFJLEVBQUUseUJBQXlCLEVBQy9CLFVBQVUsR0FBRSxNQUFNLEdBQUcsU0FBZ0IsRUFDckMsaUJBQWlCLEdBQUUsTUFBNEMsRUFDL0Qsd0JBQXdCLEdBQUUsT0FBYzs7O0dBZXpDO0FBRUQsd0JBQXNCLGNBQWMsQ0FBQyxRQUFRLEVBQUUsV0FBVyxFQUFFLElBQUksRUFBRSx5QkFBeUI7OztHQVkxRjtBQUVELHdCQUFzQixVQUFVLENBQzlCLElBQUksRUFBRSxXQUFXLEVBQ2pCLEtBQUssRUFBRSxNQUFNLEVBQ2IsTUFBTSxFQUFFLE1BQU0sRUFDZCxVQUFVLEVBQUUsdUJBQXVCOzs7R0FlcEM7QUFFRCx3QkFBc0IsY0FBYyxDQUNsQyxnQkFBZ0IsRUFBRSxnQkFBZ0IsRUFDbEMsSUFBSSxFQUFFLHlCQUF5QixFQUMvQixPQUFPLEdBQUUsT0FBTyxDQUFDLFVBQVUsQ0FBQyxPQUFPLHlCQUF5QixDQUFDLENBQUMsQ0FBQyxDQUFDLENBQU07OztHQU92RTtBQUVELHdCQUFzQixlQUFlLENBQUMsS0FBSyxFQUFFLHdCQUF3QixFQUFFLEtBQUssRUFBRSx3QkFBd0IsaUJBUXJHO0FBRUQsd0JBQXNCLGFBQWEsQ0FBQyxJQUFJLEVBQUUsd0JBQXdCLEVBQUUsS0FBSyxFQUFFLHdCQUF3QixpQkFZbEcifQ==
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/test/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,EAAE,EAAE,MAAM,0BAA0B,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,KAAK,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,iCAAiC,CAAC;AAG3G,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAE/E,wBAAsB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB;;;GA+C9F;AAED,wBAAsB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB;;;GAiDrF;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,uBAAuB;;;GAchH;AAED,wBAAsB,eAAe,CAAC,KAAK,EAAE,wBAAwB,EAAE,KAAK,EAAE,wBAAwB,iBAQrG;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,wBAAwB,EAAE,KAAK,EAAE,wBAAwB,iBAYlG"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/test/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAyB,MAAM,iCAAiC,CAAC;AAE5G,OAAO,EAAE,EAAE,EAAE,MAAM,gCAAgC,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,KAAK,EAEV,wBAAwB,EACxB,yBAAyB,EAC1B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,yBAAyB,EAAsB,MAAM,uBAAuB,CAAC;AAItF,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAE/E,wBAAsB,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,yBAAyB,iBA8C3G;AAED,wBAAsB,SAAS,CAC7B,QAAQ,EAAE,WAAW,EACrB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,yBAAyB,EAC/B,UAAU,GAAE,MAAM,GAAG,SAAgB,EACrC,iBAAiB,GAAE,MAA4C,EAC/D,wBAAwB,GAAE,OAAc;;;GAezC;AAED,wBAAsB,cAAc,CAAC,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,yBAAyB;;;GAY1F;AAED,wBAAsB,UAAU,CAC9B,IAAI,EAAE,WAAW,EACjB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,uBAAuB;;;GAepC;AAED,wBAAsB,cAAc,CAClC,gBAAgB,EAAE,gBAAgB,EAClC,IAAI,EAAE,yBAAyB,EAC/B,OAAO,GAAE,OAAO,CAAC,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAAC,CAAC,CAAC,CAAM;;;GAOvE;AAED,wBAAsB,eAAe,CAAC,KAAK,EAAE,wBAAwB,EAAE,KAAK,EAAE,wBAAwB,iBAQrG;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,wBAAwB,EAAE,KAAK,EAAE,wBAAwB,iBAYlG"}
@@ -1,73 +1,70 @@
1
1
  import { MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, NULLIFIER_SUBTREE_HEIGHT, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/constants';
2
+ import { asyncMap } from '@aztec/foundation/async-map';
3
+ import { BlockNumber, IndexWithinCheckpoint } from '@aztec/foundation/branded-types';
2
4
  import { padArrayEnd } from '@aztec/foundation/collection';
3
- import { Fr } from '@aztec/foundation/fields';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
6
  import { L2Block } from '@aztec/stdlib/block';
7
+ import { mockCheckpointAndMessages, mockL1ToL2Messages } from '@aztec/stdlib/testing';
5
8
  import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
6
- export async function mockBlock(blockNum, size, fork) {
7
- const l2Block = await L2Block.random(blockNum, size);
8
- const l1ToL2Messages = Array(16).fill(0).map(Fr.random);
9
- // Sync the append only trees
10
- {
11
- const noteHashesPadded = l2Block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
12
- await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
13
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
14
- await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
15
- }
16
- // Sync the indexed trees
17
- {
18
- // We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
19
- for (const txEffect of l2Block.body.txEffects){
20
- await fork.batchInsert(MerkleTreeId.PUBLIC_DATA_TREE, txEffect.publicDataWrites.map((write)=>write.toBuffer()), 0);
21
- const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
22
- await fork.batchInsert(MerkleTreeId.NULLIFIER_TREE, nullifiersPadded.map((nullifier)=>nullifier.toBuffer()), NULLIFIER_SUBTREE_HEIGHT);
9
+ import { BlockHeader } from '@aztec/stdlib/tx';
10
+ export async function updateBlockState(block, l1ToL2Messages, fork) {
11
+ const insertData = async (treeId, data, subTreeHeight, fork)=>{
12
+ for (const dataBatch of data){
13
+ await fork.batchInsert(treeId, dataBatch, subTreeHeight);
23
14
  }
24
- }
15
+ };
16
+ const publicDataInsert = insertData(MerkleTreeId.PUBLIC_DATA_TREE, block.body.txEffects.map((txEffect)=>txEffect.publicDataWrites.map((write)=>write.toBuffer())), 0, fork);
17
+ const nullifierInsert = insertData(MerkleTreeId.NULLIFIER_TREE, block.body.txEffects.map((txEffect)=>padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map((nullifier)=>nullifier.toBuffer())), NULLIFIER_SUBTREE_HEIGHT, fork);
18
+ const noteHashesPadded = block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
19
+ const l1ToL2MessagesPadded = block.indexWithinCheckpoint === 0 ? padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP) : l1ToL2Messages;
20
+ const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
21
+ const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
22
+ await Promise.all([
23
+ publicDataInsert,
24
+ nullifierInsert,
25
+ noteHashInsert,
26
+ messageInsert
27
+ ]);
25
28
  const state = await fork.getStateReference();
26
- l2Block.header.state = state;
27
- await fork.updateArchive(l2Block.header);
29
+ block.header = BlockHeader.from({
30
+ ...block.header,
31
+ state
32
+ });
33
+ await fork.updateArchive(block.header);
28
34
  const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
29
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
35
+ block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
36
+ }
37
+ export async function mockBlock(blockNum, size, fork, maxEffects = 1000, numL1ToL2Messages = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, isFirstBlockInCheckpoint = true) {
38
+ const block = await L2Block.random(blockNum, {
39
+ indexWithinCheckpoint: isFirstBlockInCheckpoint ? IndexWithinCheckpoint(0) : IndexWithinCheckpoint(1),
40
+ txsPerBlock: size,
41
+ txOptions: {
42
+ maxEffects
43
+ }
44
+ });
45
+ const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
46
+ await updateBlockState(block, l1ToL2Messages, fork);
30
47
  return {
31
- block: l2Block,
48
+ block,
32
49
  messages: l1ToL2Messages
33
50
  };
34
51
  }
35
52
  export async function mockEmptyBlock(blockNum, fork) {
36
53
  const l2Block = L2Block.empty();
37
54
  const l1ToL2Messages = Array(16).fill(0).map(Fr.zero);
38
- l2Block.header.globalVariables.blockNumber = new Fr(blockNum);
39
- // Sync the append only trees
40
- {
41
- const noteHashesPadded = l2Block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
42
- await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
43
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
44
- await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
45
- }
46
- // Sync the indexed trees
47
- {
48
- // We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
49
- for (const txEffect of l2Block.body.txEffects){
50
- await fork.batchInsert(MerkleTreeId.PUBLIC_DATA_TREE, txEffect.publicDataWrites.map((write)=>write.toBuffer()), 0);
51
- const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
52
- await fork.batchInsert(MerkleTreeId.NULLIFIER_TREE, nullifiersPadded.map((nullifier)=>nullifier.toBuffer()), NULLIFIER_SUBTREE_HEIGHT);
53
- }
54
- }
55
- const state = await fork.getStateReference();
56
- l2Block.header.state = state;
57
- await fork.updateArchive(l2Block.header);
58
- const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
59
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
55
+ l2Block.header.globalVariables.blockNumber = blockNum;
56
+ await updateBlockState(l2Block, l1ToL2Messages, fork);
60
57
  return {
61
58
  block: l2Block,
62
59
  messages: l1ToL2Messages
63
60
  };
64
61
  }
65
62
  export async function mockBlocks(from, count, numTxs, worldState) {
66
- const tempFork = await worldState.fork(from - 1);
63
+ const tempFork = await worldState.fork(BlockNumber(from - 1));
67
64
  const blocks = [];
68
65
  const messagesArray = [];
69
66
  for(let blockNumber = from; blockNumber < from + count; blockNumber++){
70
- const { block, messages } = await mockBlock(blockNumber, numTxs, tempFork);
67
+ const { block, messages } = await mockBlock(BlockNumber(blockNumber), numTxs, tempFork);
71
68
  blocks.push(block);
72
69
  messagesArray.push(messages);
73
70
  }
@@ -77,6 +74,16 @@ export async function mockBlocks(from, count, numTxs, worldState) {
77
74
  messages: messagesArray
78
75
  };
79
76
  }
77
+ export async function mockCheckpoint(checkpointNumber, fork, options = {}) {
78
+ const { checkpoint, messages } = await mockCheckpointAndMessages(checkpointNumber, options);
79
+ await asyncMap(checkpoint.blocks, async (block, i)=>{
80
+ await updateBlockState(block, i === 0 ? messages : [], fork);
81
+ });
82
+ return {
83
+ checkpoint,
84
+ messages
85
+ };
86
+ }
80
87
  export async function assertSameState(forkA, forkB) {
81
88
  const nativeStateRef = await forkA.getStateReference();
82
89
  const nativeArchive = await forkA.getTreeInfo(MerkleTreeId.ARCHIVE);