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

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 (80) hide show
  1. package/dest/index.d.ts +2 -1
  2. package/dest/index.d.ts.map +1 -1
  3. package/dest/index.js +1 -0
  4. package/dest/instrumentation/instrumentation.d.ts +4 -3
  5. package/dest/instrumentation/instrumentation.d.ts.map +1 -1
  6. package/dest/instrumentation/instrumentation.js +21 -50
  7. package/dest/native/bench_metrics.d.ts +1 -1
  8. package/dest/native/bench_metrics.d.ts.map +1 -1
  9. package/dest/native/fork_checkpoint.d.ts +7 -1
  10. package/dest/native/fork_checkpoint.d.ts.map +1 -1
  11. package/dest/native/fork_checkpoint.js +15 -3
  12. package/dest/native/index.d.ts +2 -1
  13. package/dest/native/index.d.ts.map +1 -1
  14. package/dest/native/index.js +1 -0
  15. package/dest/native/ipc_world_state_instance.d.ts +89 -0
  16. package/dest/native/ipc_world_state_instance.d.ts.map +1 -0
  17. package/dest/native/ipc_world_state_instance.js +661 -0
  18. package/dest/native/merkle_trees_facade.d.ts +18 -8
  19. package/dest/native/merkle_trees_facade.d.ts.map +1 -1
  20. package/dest/native/merkle_trees_facade.js +90 -111
  21. package/dest/native/message.d.ts +22 -228
  22. package/dest/native/message.d.ts.map +1 -1
  23. package/dest/native/message.js +14 -55
  24. package/dest/native/native_world_state.d.ts +30 -15
  25. package/dest/native/native_world_state.d.ts.map +1 -1
  26. package/dest/native/native_world_state.js +133 -66
  27. package/dest/native/native_world_state_instance.d.ts +56 -33
  28. package/dest/native/native_world_state_instance.d.ts.map +1 -1
  29. package/dest/native/native_world_state_instance.js +1 -182
  30. package/dest/native/world_state_operation.d.ts +7 -0
  31. package/dest/native/world_state_operation.d.ts.map +1 -0
  32. package/dest/native/world_state_operation.js +5 -0
  33. package/dest/synchronizer/config.d.ts +3 -5
  34. package/dest/synchronizer/config.d.ts.map +1 -1
  35. package/dest/synchronizer/config.js +15 -18
  36. package/dest/synchronizer/errors.d.ts +8 -1
  37. package/dest/synchronizer/errors.d.ts.map +1 -1
  38. package/dest/synchronizer/errors.js +8 -1
  39. package/dest/synchronizer/factory.d.ts +6 -5
  40. package/dest/synchronizer/factory.d.ts.map +1 -1
  41. package/dest/synchronizer/factory.js +7 -6
  42. package/dest/synchronizer/index.d.ts +2 -1
  43. package/dest/synchronizer/index.d.ts.map +1 -1
  44. package/dest/synchronizer/index.js +1 -0
  45. package/dest/synchronizer/server_world_state_synchronizer.d.ts +20 -32
  46. package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
  47. package/dest/synchronizer/server_world_state_synchronizer.js +181 -85
  48. package/dest/test/index.d.ts +1 -1
  49. package/dest/test/utils.d.ts +12 -5
  50. package/dest/test/utils.d.ts.map +1 -1
  51. package/dest/test/utils.js +59 -50
  52. package/dest/testing.d.ts +5 -4
  53. package/dest/testing.d.ts.map +1 -1
  54. package/dest/testing.js +15 -8
  55. package/dest/world-state-db/index.d.ts +1 -1
  56. package/dest/world-state-db/merkle_tree_db.d.ts +9 -19
  57. package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
  58. package/package.json +16 -13
  59. package/src/index.ts +1 -0
  60. package/src/instrumentation/instrumentation.ts +23 -59
  61. package/src/native/fork_checkpoint.ts +19 -3
  62. package/src/native/index.ts +1 -0
  63. package/src/native/ipc_world_state_instance.ts +834 -0
  64. package/src/native/merkle_trees_facade.ts +118 -104
  65. package/src/native/message.ts +33 -305
  66. package/src/native/native_world_state.ts +179 -108
  67. package/src/native/native_world_state_instance.ts +94 -251
  68. package/src/native/world_state_operation.ts +33 -0
  69. package/src/synchronizer/config.ts +16 -23
  70. package/src/synchronizer/errors.ts +8 -0
  71. package/src/synchronizer/factory.ts +18 -11
  72. package/src/synchronizer/index.ts +1 -0
  73. package/src/synchronizer/server_world_state_synchronizer.ts +219 -111
  74. package/src/test/utils.ts +96 -92
  75. package/src/testing.ts +13 -11
  76. package/src/world-state-db/merkle_tree_db.ts +12 -19
  77. package/dest/native/world_state_ops_queue.d.ts +0 -19
  78. package/dest/native/world_state_ops_queue.d.ts.map +0 -1
  79. package/dest/native/world_state_ops_queue.js +0 -146
  80. package/src/native/world_state_ops_queue.ts +0 -190
@@ -1,12 +1,11 @@
1
- import { L1_TO_L2_MSG_SUBTREE_HEIGHT } from '@aztec/constants';
2
- import { SHA256Trunc } from '@aztec/foundation/crypto';
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
3
2
  import { createLogger } from '@aztec/foundation/log';
4
3
  import { promiseWithResolvers } from '@aztec/foundation/promise';
5
4
  import { elapsed } from '@aztec/foundation/timer';
6
- import { MerkleTreeCalculator } from '@aztec/foundation/trees';
5
+ import { EventDrivenL2BlockStream } from '@aztec/stdlib/block';
7
6
  import { WorldStateRunningState } from '@aztec/stdlib/interfaces/server';
8
7
  import { MerkleTreeId } from '@aztec/stdlib/trees';
9
- import { TraceableL2BlockStream, getTelemetryClient } from '@aztec/telemetry-client';
8
+ import { getTelemetryClient } from '@aztec/telemetry-client';
10
9
  import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js';
11
10
  import { WorldStateSynchronizerError } from './errors.js';
12
11
  /**
@@ -23,7 +22,6 @@ import { WorldStateSynchronizerError } from './errors.js';
23
22
  latestBlockNumberAtStart;
24
23
  historyToKeep;
25
24
  currentState;
26
- latestBlockHashQuery;
27
25
  syncPromise;
28
26
  blockStream;
29
27
  // WorldState doesn't track the proven block number, it only tracks the latest tips of the pending chain and the finalized chain
@@ -35,12 +33,11 @@ import { WorldStateSynchronizerError } from './errors.js';
35
33
  this.config = config;
36
34
  this.instrumentation = instrumentation;
37
35
  this.log = log;
38
- this.latestBlockNumberAtStart = 0;
36
+ this.latestBlockNumberAtStart = BlockNumber.ZERO;
39
37
  this.currentState = WorldStateRunningState.IDLE;
40
- this.latestBlockHashQuery = undefined;
41
38
  this.syncPromise = promiseWithResolvers();
42
39
  this.merkleTreeCommitted = this.merkleTreeDb.getCommitted();
43
- this.historyToKeep = config.worldStateBlockHistory < 1 ? undefined : config.worldStateBlockHistory;
40
+ this.historyToKeep = config.worldStateCheckpointHistory < 1 ? undefined : config.worldStateCheckpointHistory;
44
41
  this.log.info(`Created world state synchroniser with block history of ${this.historyToKeep === undefined ? 'infinity' : this.historyToKeep}`);
45
42
  }
46
43
  getCommitted() {
@@ -49,8 +46,41 @@ import { WorldStateSynchronizerError } from './errors.js';
49
46
  getSnapshot(blockNumber) {
50
47
  return this.merkleTreeDb.getSnapshot(blockNumber);
51
48
  }
52
- fork(blockNumber) {
53
- return this.merkleTreeDb.fork(blockNumber);
49
+ async getVerifiedSnapshot(blockNumber, blockHash) {
50
+ const snapshot = this.merkleTreeDb.getSnapshot(blockNumber);
51
+ // Block 0's snapshot is the pre-genesis archive view (size 0), so archive leaf 0 is not visible from it;
52
+ // verify against the initial header hash instead. For later blocks, read archive leaf `blockNumber` from the
53
+ // snapshot's own view so the exact handle we return is validated against the requested fork.
54
+ const actualHash = blockNumber === BlockNumber.ZERO ? (await this.merkleTreeCommitted.getInitialHeader().hash()).toString() : (await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber)))?.toString();
55
+ if (actualHash === undefined) {
56
+ // A missing archive leaf means either the block's history has been pruned away (permanent: the block predates
57
+ // the oldest historical block kept by world state) or a reorg flipped the fork between the sync and this read
58
+ // (transient). Only the latter is worth retrying, so it alone surfaces as WorldStateSynchronizerError.
59
+ const { oldestHistoricalBlock } = await this.merkleTreeDb.getStatusSummary();
60
+ if (blockNumber < oldestHistoricalBlock) {
61
+ throw new Error(`Unable to find leaf for block ${blockNumber} in the archive tree: world state history has been pruned to block ${oldestHistoricalBlock}`);
62
+ }
63
+ throw new WorldStateSynchronizerError(`Unable to read block hash at block ${blockNumber} to verify snapshot`, {
64
+ cause: {
65
+ reason: 'block_not_available',
66
+ targetBlockNumber: blockNumber
67
+ }
68
+ });
69
+ }
70
+ if (actualHash !== blockHash.toString()) {
71
+ throw new WorldStateSynchronizerError(`Block hash mismatch at block ${blockNumber} (expected ${blockHash} but got ${actualHash})`, {
72
+ cause: {
73
+ reason: 'block_hash_mismatch',
74
+ targetBlockNumber: blockNumber,
75
+ expectedHash: blockHash.toString(),
76
+ actualHash
77
+ }
78
+ });
79
+ }
80
+ return snapshot;
81
+ }
82
+ fork(blockNumber, opts) {
83
+ return this.merkleTreeDb.fork(blockNumber, opts);
54
84
  }
55
85
  backupTo(dstPath, compact) {
56
86
  return this.merkleTreeDb.backupTo(dstPath, compact);
@@ -66,7 +96,7 @@ import { WorldStateSynchronizerError } from './errors.js';
66
96
  return this.syncPromise;
67
97
  }
68
98
  // Get the current latest block number
69
- this.latestBlockNumberAtStart = await (this.config.worldStateProvenBlocksOnly ? this.l2BlockSource.getProvenBlockNumber() : this.l2BlockSource.getBlockNumber());
99
+ this.latestBlockNumberAtStart = BlockNumber(await this.l2BlockSource.getBlockNumber());
70
100
  const blockToDownloadFrom = await this.getLatestBlockNumber() + 1;
71
101
  if (blockToDownloadFrom <= this.latestBlockNumberAtStart) {
72
102
  // If there are blocks to be retrieved, go to a synching state
@@ -84,12 +114,11 @@ import { WorldStateSynchronizerError } from './errors.js';
84
114
  return this.syncPromise.promise;
85
115
  }
86
116
  createBlockStream() {
87
- const tracer = this.instrumentation.telemetry.getTracer('WorldStateL2BlockStream');
88
117
  const logger = createLogger('world-state:block_stream');
89
- return new TraceableL2BlockStream(this.l2BlockSource, this, this, tracer, 'WorldStateL2BlockStream', logger, {
90
- proven: this.config.worldStateProvenBlocksOnly,
118
+ return new EventDrivenL2BlockStream(this.l2BlockSource, this, this, logger, {
91
119
  pollIntervalMS: this.config.worldStateBlockCheckIntervalMS,
92
- batchSize: this.config.worldStateBlockRequestBatchSize
120
+ batchSize: this.config.worldStateBlockRequestBatchSize,
121
+ ignoreCheckpoints: true
93
122
  });
94
123
  }
95
124
  async stop() {
@@ -103,10 +132,10 @@ import { WorldStateSynchronizerError } from './errors.js';
103
132
  async status() {
104
133
  const summary = await this.merkleTreeDb.getStatusSummary();
105
134
  const status = {
106
- latestBlockNumber: Number(summary.unfinalizedBlockNumber),
107
- latestBlockHash: await this.getL2BlockHash(Number(summary.unfinalizedBlockNumber)) ?? '',
108
- finalizedBlockNumber: Number(summary.finalizedBlockNumber),
109
- oldestHistoricBlockNumber: Number(summary.oldestHistoricalBlock),
135
+ latestBlockNumber: summary.unfinalizedBlockNumber,
136
+ latestBlockHash: await this.getL2BlockHash(summary.unfinalizedBlockNumber) ?? '',
137
+ finalizedBlockNumber: summary.finalizedBlockNumber,
138
+ oldestHistoricBlockNumber: summary.oldestHistoricalBlock,
110
139
  treesAreSynched: summary.treesAreSynched
111
140
  };
112
141
  return {
@@ -115,7 +144,7 @@ import { WorldStateSynchronizerError } from './errors.js';
115
144
  };
116
145
  }
117
146
  async getLatestBlockNumber() {
118
- return (await this.getL2Tips()).latest.number;
147
+ return (await this.getL2Tips()).proposed.number;
119
148
  }
120
149
  async stopSync() {
121
150
  this.log.debug('Stopping sync...');
@@ -133,9 +162,9 @@ import { WorldStateSynchronizerError } from './errors.js';
133
162
  /**
134
163
  * Forces an immediate sync.
135
164
  * @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
136
- * @param skipThrowIfTargetNotReached - Whether to skip throwing if the target block number is not reached.
165
+ * @param blockHash - If provided, verifies the block at targetBlockNumber matches this hash. On mismatch, triggers a resync (reorg detection).
137
166
  * @returns A promise that resolves with the block number the world state was synced to
138
- */ async syncImmediate(targetBlockNumber, skipThrowIfTargetNotReached) {
167
+ */ async syncImmediate(targetBlockNumber, blockHash) {
139
168
  if (this.currentState !== WorldStateRunningState.RUNNING) {
140
169
  throw new Error(`World State is not running. Unable to perform sync.`);
141
170
  }
@@ -145,12 +174,21 @@ import { WorldStateSynchronizerError } from './errors.js';
145
174
  // If we have been given a block number to sync to and we have reached that number then return
146
175
  const currentBlockNumber = await this.getLatestBlockNumber();
147
176
  if (targetBlockNumber !== undefined && targetBlockNumber <= currentBlockNumber) {
148
- return currentBlockNumber;
177
+ if (blockHash === undefined) {
178
+ return currentBlockNumber;
179
+ }
180
+ // If a block hash was provided, verify we're on the expected fork
181
+ const currentHash = await this.getL2BlockHash(targetBlockNumber);
182
+ if (currentHash === blockHash.toString()) {
183
+ return currentBlockNumber;
184
+ }
185
+ // Hash mismatch: a reorg may have occurred, fall through to trigger sync
186
+ this.log.debug(`World state block hash mismatch at ${targetBlockNumber} (expected ${blockHash}, got ${currentHash}). Triggering resync.`);
149
187
  }
150
188
  this.log.debug(`World State at ${currentBlockNumber} told to sync to ${targetBlockNumber ?? 'latest'}`);
151
189
  // If the archiver is behind the target block, force an archiver sync
152
190
  if (targetBlockNumber) {
153
- const archiverLatestBlock = await this.l2BlockSource.getBlockNumber();
191
+ const archiverLatestBlock = BlockNumber(await this.l2BlockSource.getBlockNumber());
154
192
  if (archiverLatestBlock < targetBlockNumber) {
155
193
  this.log.debug(`Archiver is at ${archiverLatestBlock} behind target block ${targetBlockNumber}.`);
156
194
  await this.l2BlockSource.syncImmediate();
@@ -160,7 +198,7 @@ import { WorldStateSynchronizerError } from './errors.js';
160
198
  await this.blockStream.sync();
161
199
  // If we have been given a block number to sync to and we have not reached that number then fail
162
200
  const updatedBlockNumber = await this.getLatestBlockNumber();
163
- if (!skipThrowIfTargetNotReached && targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
201
+ if (targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
164
202
  throw new WorldStateSynchronizerError(`Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`, {
165
203
  cause: {
166
204
  reason: 'block_not_available',
@@ -170,43 +208,66 @@ import { WorldStateSynchronizerError } from './errors.js';
170
208
  }
171
209
  });
172
210
  }
211
+ // If a block hash was provided, verify we're on the expected fork after syncing, throw otherwise
212
+ if (blockHash !== undefined && targetBlockNumber !== undefined) {
213
+ const updatedHash = await this.getL2BlockHash(targetBlockNumber);
214
+ if (updatedHash !== blockHash.toString()) {
215
+ throw new WorldStateSynchronizerError(`Block hash mismatch at block ${targetBlockNumber} (expected ${blockHash} but got ${updatedHash})`, {
216
+ cause: {
217
+ reason: 'block_hash_mismatch',
218
+ targetBlockNumber,
219
+ expectedHash: blockHash.toString(),
220
+ actualHash: updatedHash
221
+ }
222
+ });
223
+ }
224
+ }
173
225
  return updatedBlockNumber;
174
226
  }
175
227
  /** Returns the L2 block hash for a given number. Used by the L2BlockStream for detecting reorgs. */ async getL2BlockHash(number) {
176
- if (number === 0) {
228
+ if (number === BlockNumber.ZERO) {
177
229
  return (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
178
230
  }
179
- if (this.latestBlockHashQuery?.hash === undefined || number !== this.latestBlockHashQuery.blockNumber) {
180
- this.latestBlockHashQuery = {
181
- hash: await this.merkleTreeCommitted.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(number)).then((leaf)=>leaf?.toString()),
182
- blockNumber: number
183
- };
184
- }
185
- return this.latestBlockHashQuery.hash;
231
+ return this.merkleTreeCommitted.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(number)).then((leaf)=>leaf?.toString());
186
232
  }
187
- /** Returns the latest L2 block number for each tip of the chain (latest, proven, finalized). */ async getL2Tips() {
233
+ /**
234
+ * Returns the proposed, proven, and finalized block tips of the chain. World state drives its block stream with
235
+ * `ignoreCheckpoints`, so it does not track checkpointed blocks or checkpoints and omits `checkpointed` from the tips
236
+ * it reports.
237
+ */ async getL2Tips() {
188
238
  const status = await this.merkleTreeDb.getStatusSummary();
189
- const unfinalizedBlockHash = await this.getL2BlockHash(Number(status.unfinalizedBlockNumber));
190
- const latestBlockId = {
191
- number: Number(status.unfinalizedBlockNumber),
192
- hash: unfinalizedBlockHash
193
- };
239
+ const unfinalizedBlockHashPromise = this.getL2BlockHash(status.unfinalizedBlockNumber);
240
+ const finalizedBlockHashPromise = this.getL2BlockHash(status.finalizedBlockNumber);
241
+ const provenBlockNumber = this.provenBlockNumber ?? status.finalizedBlockNumber;
242
+ const provenBlockHashPromise = this.provenBlockNumber === undefined ? finalizedBlockHashPromise : this.getL2BlockHash(this.provenBlockNumber);
243
+ const [unfinalizedBlockHash, finalizedBlockHash, provenBlockHash] = await Promise.all([
244
+ unfinalizedBlockHashPromise,
245
+ finalizedBlockHashPromise,
246
+ provenBlockHashPromise
247
+ ]);
194
248
  return {
195
- latest: latestBlockId,
249
+ proposed: {
250
+ number: status.unfinalizedBlockNumber,
251
+ hash: unfinalizedBlockHash
252
+ },
196
253
  finalized: {
197
- number: Number(status.finalizedBlockNumber),
198
- hash: ''
254
+ block: {
255
+ number: status.finalizedBlockNumber,
256
+ hash: finalizedBlockHash
257
+ }
199
258
  },
200
259
  proven: {
201
- number: Number(this.provenBlockNumber ?? status.finalizedBlockNumber),
202
- hash: ''
260
+ block: {
261
+ number: provenBlockNumber,
262
+ hash: provenBlockHash
263
+ }
203
264
  }
204
265
  };
205
266
  }
206
267
  /** Handles an event emitted by the block stream. */ async handleBlockStreamEvent(event) {
207
268
  switch(event.type){
208
269
  case 'blocks-added':
209
- await this.handleL2Blocks(event.blocks.map((b)=>b.block));
270
+ await this.handleL2Blocks(event.blocks);
210
271
  break;
211
272
  case 'chain-pruned':
212
273
  await this.handleChainPruned(event.block.number);
@@ -217,6 +278,16 @@ import { WorldStateSynchronizerError } from './errors.js';
217
278
  case 'chain-finalized':
218
279
  await this.handleChainFinalized(event.block.number);
219
280
  break;
281
+ // World state runs in block mode with ignoreCheckpoints: it tracks tips via blocks-added/pruned/proven/finalized
282
+ // and ignores the thin tip events (it never anchors on them).
283
+ case 'chain-proposed':
284
+ case 'chain-checkpointed':
285
+ break;
286
+ default:
287
+ {
288
+ const _ = event;
289
+ break;
290
+ }
220
291
  }
221
292
  }
222
293
  /**
@@ -224,19 +295,23 @@ import { WorldStateSynchronizerError } from './errors.js';
224
295
  * @param l2Blocks - The L2 blocks to handle.
225
296
  * @returns Whether the block handled was produced by this same node.
226
297
  */ async handleL2Blocks(l2Blocks) {
227
- this.log.trace(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1).number}`);
228
- const messagePromises = l2Blocks.map((block)=>this.l2BlockSource.getL1ToL2Messages(block.number));
229
- const l1ToL2Messages = await Promise.all(messagePromises);
298
+ this.log.debug(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1).number}`);
299
+ // Fetch the L1->L2 messages for the first block in a checkpoint.
300
+ const messagesForBlocks = new Map();
301
+ await Promise.all(l2Blocks.filter((b)=>b.indexWithinCheckpoint === 0).map(async (block)=>{
302
+ const l1ToL2Messages = await this.l2BlockSource.getL1ToL2Messages(block.checkpointNumber);
303
+ messagesForBlocks.set(block.number, l1ToL2Messages);
304
+ }));
230
305
  let updateStatus = undefined;
231
- for(let i = 0; i < l2Blocks.length; i++){
232
- const [duration, result] = await elapsed(()=>this.handleL2Block(l2Blocks[i], l1ToL2Messages[i]));
233
- this.log.info(`World state updated with L2 block ${l2Blocks[i].number}`, {
306
+ for (const block of l2Blocks){
307
+ const [duration, result] = await elapsed(()=>this.handleL2Block(block, messagesForBlocks.get(block.number) ?? []));
308
+ this.log.info(`World state updated with L2 block ${block.number}`, {
234
309
  eventName: 'l2-block-handled',
235
310
  duration,
236
- unfinalizedBlockNumber: result.summary.unfinalizedBlockNumber,
237
- finalizedBlockNumber: result.summary.finalizedBlockNumber,
238
- oldestHistoricBlock: result.summary.oldestHistoricalBlock,
239
- ...l2Blocks[i].getStats()
311
+ unfinalizedBlockNumber: BigInt(result.summary.unfinalizedBlockNumber),
312
+ finalizedBlockNumber: BigInt(result.summary.finalizedBlockNumber),
313
+ oldestHistoricBlock: BigInt(result.summary.oldestHistoricalBlock),
314
+ ...block.getStats()
240
315
  });
241
316
  updateStatus = result;
242
317
  }
@@ -251,16 +326,12 @@ import { WorldStateSynchronizerError } from './errors.js';
251
326
  * @param l1ToL2Messages - The L1 to L2 messages for the block.
252
327
  * @returns Whether the block handled was produced by this same node.
253
328
  */ async handleL2Block(l2Block, l1ToL2Messages) {
254
- // First we check that the L1 to L2 messages hash to the block inHash.
255
- // Note that we cannot optimize this check by checking the root of the subtree after inserting the messages
256
- // to the real L1_TO_L2_MESSAGE_TREE (like we do in merkleTreeDb.handleL2BlockAndMessages(...)) because that
257
- // tree uses pedersen and we don't have access to the converted root.
258
- await this.verifyMessagesHashToInHash(l1ToL2Messages, l2Block.header.contentCommitment.inHash);
259
- // If the above check succeeds, we can proceed to handle the block.
260
- this.log.trace(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
329
+ this.log.debug(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
261
330
  blockNumber: l2Block.number,
262
331
  blockHash: await l2Block.hash().then((h)=>h.toString()),
263
- l1ToL2Messages: l1ToL2Messages.map((msg)=>msg.toString())
332
+ l1ToL2Messages: l1ToL2Messages.map((msg)=>msg.toString()),
333
+ blockHeader: l2Block.header.toInspect(),
334
+ blockStats: l2Block.getStats()
264
335
  });
265
336
  const result = await this.merkleTreeDb.handleL2BlockAndMessages(l2Block, l1ToL2Messages);
266
337
  if (this.currentState === WorldStateRunningState.SYNCHING && l2Block.number >= this.latestBlockNumberAtStart) {
@@ -271,28 +342,65 @@ import { WorldStateSynchronizerError } from './errors.js';
271
342
  }
272
343
  async handleChainFinalized(blockNumber) {
273
344
  this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
274
- const summary = await this.merkleTreeDb.setFinalized(BigInt(blockNumber));
345
+ // If the finalized block number is older than the oldest available block in world state,
346
+ // skip entirely. The finalized block number can jump backwards (e.g. when the finalization
347
+ // heuristic changes) and try to read block data that has already been pruned. When this
348
+ // happens, there is nothing useful to do — the native world state is already finalized
349
+ // past this point and pruning has already happened.
350
+ const currentSummary = await this.merkleTreeDb.getStatusSummary();
351
+ if (blockNumber < currentSummary.oldestHistoricalBlock || blockNumber < 1) {
352
+ this.log.trace(`Finalized block ${blockNumber} is older than the oldest available block ${currentSummary.oldestHistoricalBlock}. Skipping.`);
353
+ return;
354
+ }
355
+ const summary = await this.merkleTreeDb.setFinalized(blockNumber);
275
356
  if (this.historyToKeep === undefined) {
276
357
  return;
277
358
  }
278
- const newHistoricBlock = summary.finalizedBlockNumber - BigInt(this.historyToKeep) + 1n;
279
- if (newHistoricBlock <= 1) {
359
+ const finalisedBlockData = await this.l2BlockSource.getBlockData({
360
+ number: summary.finalizedBlockNumber
361
+ });
362
+ if (finalisedBlockData === undefined) {
363
+ this.log.warn(`Failed to retrieve checkpointed block for finalized block number: ${summary.finalizedBlockNumber}`);
364
+ return;
365
+ }
366
+ // Compute the required historic checkpoint number
367
+ const newHistoricCheckpointNumber = finalisedBlockData.checkpointNumber - this.historyToKeep + 1;
368
+ if (newHistoricCheckpointNumber <= 1) {
369
+ return;
370
+ }
371
+ // Retrieve the historic checkpoint
372
+ const historicCheckpoint = await this.l2BlockSource.getCheckpoint({
373
+ number: CheckpointNumber(newHistoricCheckpointNumber)
374
+ });
375
+ if (!historicCheckpoint) {
376
+ this.log.warn(`Failed to retrieve checkpoint number ${newHistoricCheckpointNumber} from Archiver`);
377
+ return;
378
+ }
379
+ if (historicCheckpoint.checkpoint.blocks.length === 0 || historicCheckpoint.checkpoint.blocks[0] === undefined) {
380
+ this.log.warn(`Retrieved checkpoint number ${newHistoricCheckpointNumber} has no blocks!`);
381
+ return;
382
+ }
383
+ // Find the block at the start of the checkpoint and remove blocks up to this one
384
+ const newHistoricBlock = historicCheckpoint.checkpoint.blocks[0];
385
+ if (newHistoricBlock.number <= currentSummary.oldestHistoricalBlock) {
386
+ this.log.debug(`Historic block ${newHistoricBlock.number} is not newer than oldest available ${currentSummary.oldestHistoricalBlock}. Skipping prune.`);
280
387
  return;
281
388
  }
282
- this.log.verbose(`Pruning historic blocks to ${newHistoricBlock}`);
283
- const status = await this.merkleTreeDb.removeHistoricalBlocks(newHistoricBlock);
389
+ this.log.verbose(`Pruning historic blocks to ${newHistoricBlock.number}`);
390
+ const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock.number));
284
391
  this.log.debug(`World state summary `, status.summary);
285
392
  }
286
393
  handleChainProven(blockNumber) {
287
- this.provenBlockNumber = BigInt(blockNumber);
394
+ this.provenBlockNumber = blockNumber;
288
395
  this.log.debug(`Proven chain is now at block ${blockNumber}`);
289
396
  return Promise.resolve();
290
397
  }
291
398
  async handleChainPruned(blockNumber) {
292
- this.log.warn(`Chain pruned to block ${blockNumber}`);
293
- const status = await this.merkleTreeDb.unwindBlocks(BigInt(blockNumber));
294
- this.latestBlockHashQuery = undefined;
295
- this.provenBlockNumber = undefined;
399
+ this.log.info(`Chain pruned to block ${blockNumber}`);
400
+ const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
401
+ if (this.provenBlockNumber !== undefined && this.provenBlockNumber > blockNumber) {
402
+ this.provenBlockNumber = undefined;
403
+ }
296
404
  this.instrumentation.updateWorldStateMetrics(status);
297
405
  }
298
406
  /**
@@ -302,16 +410,4 @@ import { WorldStateSynchronizerError } from './errors.js';
302
410
  this.currentState = newState;
303
411
  this.log.debug(`Moved to state ${WorldStateRunningState[this.currentState]}`);
304
412
  }
305
- /**
306
- * Verifies that the L1 to L2 messages hash to the block inHash.
307
- * @param l1ToL2Messages - The L1 to L2 messages for the block.
308
- * @param inHash - The inHash of the block.
309
- * @throws If the L1 to L2 messages do not hash to the block inHash.
310
- */ async verifyMessagesHashToInHash(l1ToL2Messages, inHash) {
311
- const treeCalculator = await MerkleTreeCalculator.create(L1_TO_L2_MSG_SUBTREE_HEIGHT, Buffer.alloc(32), (lhs, rhs)=>Promise.resolve(new SHA256Trunc().hash(lhs, rhs)));
312
- const root = await treeCalculator.computeTreeRoot(l1ToL2Messages.map((msg)=>msg.toBuffer()));
313
- if (!root.equals(inHash.toBuffer())) {
314
- throw new Error('Obtained L1 to L2 messages failed to be hashed to the block inHash');
315
- }
316
- }
317
413
  }
@@ -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, maxEffects?: number | undefined): 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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90ZXN0L3V0aWxzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQU9BLE9BQU8sRUFBRSxXQUFXLEVBQUUsS0FBSyxnQkFBZ0IsRUFBeUIsTUFBTSxpQ0FBaUMsQ0FBQztBQUU1RyxPQUFPLEVBQUUsRUFBRSxFQUFFLE1BQU0sZ0NBQWdDLENBQUM7QUFDcEQsT0FBTyxFQUFFLE9BQU8sRUFBRSxNQUFNLHFCQUFxQixDQUFDO0FBQzlDLE9BQU8sS0FBSyxFQUVWLHdCQUF3QixFQUN4Qix5QkFBeUIsRUFDMUIsTUFBTSxpQ0FBaUMsQ0FBQztBQUN6QyxPQUFPLEVBQUUseUJBQXlCLEVBQXNCLE1BQU0sdUJBQXVCLENBQUM7QUFJdEYsT0FBTyxLQUFLLEVBQUUsdUJBQXVCLEVBQUUsTUFBTSxpQ0FBaUMsQ0FBQztBQUUvRSx3QkFBc0IsZ0JBQWdCLENBQUMsS0FBSyxFQUFFLE9BQU8sRUFBRSxjQUFjLEVBQUUsRUFBRSxFQUFFLEVBQUUsSUFBSSxFQUFFLHlCQUF5QixpQkF1RDNHO0FBRUQsd0JBQXNCLFNBQVMsQ0FDN0IsUUFBUSxFQUFFLFdBQVcsRUFDckIsSUFBSSxFQUFFLE1BQU0sRUFDWixJQUFJLEVBQUUseUJBQXlCLEVBQy9CLFVBQVUsR0FBRSxNQUFNLEdBQUcsU0FBZ0IsRUFDckMsaUJBQWlCLEdBQUUsTUFBNEMsRUFDL0Qsd0JBQXdCLEdBQUUsT0FBYzs7O0dBZXpDO0FBRUQsd0JBQXNCLGNBQWMsQ0FBQyxRQUFRLEVBQUUsV0FBVyxFQUFFLElBQUksRUFBRSx5QkFBeUI7OztHQVkxRjtBQUVELHdCQUFzQixVQUFVLENBQzlCLElBQUksRUFBRSxXQUFXLEVBQ2pCLEtBQUssRUFBRSxNQUFNLEVBQ2IsTUFBTSxFQUFFLE1BQU0sRUFDZCxVQUFVLEVBQUUsdUJBQXVCOzs7R0FlcEM7QUFFRCx3QkFBc0IsY0FBYyxDQUNsQyxnQkFBZ0IsRUFBRSxnQkFBZ0IsRUFDbEMsSUFBSSxFQUFFLHlCQUF5QixFQUMvQixPQUFPLEdBQUUsT0FBTyxDQUFDLFVBQVUsQ0FBQyxPQUFPLHlCQUF5QixDQUFDLENBQUMsQ0FBQyxDQUFDLENBQU07OztHQU92RTtBQUVELHdCQUFzQixlQUFlLENBQUMsS0FBSyxFQUFFLHdCQUF3QixFQUFFLEtBQUssRUFBRSx3QkFBd0IsaUJBUXJHO0FBRUQsd0JBQXNCLGFBQWEsQ0FBQyxJQUFJLEVBQUUsd0JBQXdCLEVBQUUsS0FBSyxFQUFFLHdCQUF3QixpQkFZbEcifQ==
@@ -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,EAEV,wBAAwB,EACxB,yBAAyB,EAC1B,MAAM,iCAAiC,CAAC;AAGzC,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAE/E,wBAAsB,SAAS,CAC7B,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,yBAAyB,EAC/B,UAAU,GAAE,MAAM,GAAG,SAAqB;;;GAsD3C;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,iBAuD3G;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,37 +1,56 @@
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, maxEffects = undefined) {
7
- const l2Block = await L2Block.random(blockNum, size, maxEffects);
8
- const l1ToL2Messages = Array(NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).fill(0).map(Fr.random);
9
- {
10
- const insertData = async (treeId, data, subTreeHeight, fork)=>{
11
- for (const dataBatch of data){
12
- await fork.batchInsert(treeId, dataBatch, subTreeHeight);
13
- }
14
- };
15
- const publicDataInsert = insertData(MerkleTreeId.PUBLIC_DATA_TREE, l2Block.body.txEffects.map((txEffect)=>txEffect.publicDataWrites.map((write)=>write.toBuffer())), 0, fork);
16
- const nullifierInsert = insertData(MerkleTreeId.NULLIFIER_TREE, l2Block.body.txEffects.map((txEffect)=>padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map((nullifier)=>nullifier.toBuffer())), NULLIFIER_SUBTREE_HEIGHT, fork);
17
- const noteHashesPadded = l2Block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
18
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
19
- const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
20
- const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
21
- await Promise.all([
22
- publicDataInsert,
23
- nullifierInsert,
24
- noteHashInsert,
25
- messageInsert
26
- ]);
27
- }
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);
14
+ }
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
+ ]);
28
28
  const state = await fork.getStateReference();
29
- l2Block.header.state = state;
30
- await fork.updateArchive(l2Block.getBlockHeader());
29
+ // Capture the archive root *before* appending this block so the header's lastArchive chains off the previous block.
30
+ // sync_block now verifies lastArchive against the committed archive root, so a block carrying an unchained value
31
+ // (e.g. the random lastArchive from L2Block.random) would be rejected as a divergence from the canonical chain.
32
+ const previousArchive = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
33
+ block.header = BlockHeader.from({
34
+ ...block.header,
35
+ state,
36
+ lastArchive: new AppendOnlyTreeSnapshot(Fr.fromBuffer(previousArchive.root), Number(previousArchive.size))
37
+ });
38
+ await fork.updateArchive(block.header);
31
39
  const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
32
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
40
+ block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
41
+ }
42
+ export async function mockBlock(blockNum, size, fork, maxEffects = 1000, numL1ToL2Messages = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, isFirstBlockInCheckpoint = true) {
43
+ const block = await L2Block.random(blockNum, {
44
+ indexWithinCheckpoint: isFirstBlockInCheckpoint ? IndexWithinCheckpoint(0) : IndexWithinCheckpoint(1),
45
+ txsPerBlock: size,
46
+ txOptions: {
47
+ maxEffects
48
+ }
49
+ });
50
+ const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
51
+ await updateBlockState(block, l1ToL2Messages, fork);
33
52
  return {
34
- block: l2Block,
53
+ block,
35
54
  messages: l1ToL2Messages
36
55
  };
37
56
  }
@@ -39,38 +58,18 @@ export async function mockEmptyBlock(blockNum, fork) {
39
58
  const l2Block = L2Block.empty();
40
59
  const l1ToL2Messages = Array(16).fill(0).map(Fr.zero);
41
60
  l2Block.header.globalVariables.blockNumber = blockNum;
42
- // Sync the append only trees
43
- {
44
- const noteHashesPadded = l2Block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
45
- await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
46
- const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
47
- await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
48
- }
49
- // Sync the indexed trees
50
- {
51
- // We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
52
- for (const txEffect of l2Block.body.txEffects){
53
- await fork.batchInsert(MerkleTreeId.PUBLIC_DATA_TREE, txEffect.publicDataWrites.map((write)=>write.toBuffer()), 0);
54
- const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
55
- await fork.batchInsert(MerkleTreeId.NULLIFIER_TREE, nullifiersPadded.map((nullifier)=>nullifier.toBuffer()), NULLIFIER_SUBTREE_HEIGHT);
56
- }
57
- }
58
- const state = await fork.getStateReference();
59
- l2Block.header.state = state;
60
- await fork.updateArchive(l2Block.getBlockHeader());
61
- const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
62
- l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
61
+ await updateBlockState(l2Block, l1ToL2Messages, fork);
63
62
  return {
64
63
  block: l2Block,
65
64
  messages: l1ToL2Messages
66
65
  };
67
66
  }
68
67
  export async function mockBlocks(from, count, numTxs, worldState) {
69
- const tempFork = await worldState.fork(from - 1);
68
+ const tempFork = await worldState.fork(BlockNumber(from - 1));
70
69
  const blocks = [];
71
70
  const messagesArray = [];
72
71
  for(let blockNumber = from; blockNumber < from + count; blockNumber++){
73
- const { block, messages } = await mockBlock(blockNumber, numTxs, tempFork);
72
+ const { block, messages } = await mockBlock(BlockNumber(blockNumber), numTxs, tempFork);
74
73
  blocks.push(block);
75
74
  messagesArray.push(messages);
76
75
  }
@@ -80,6 +79,16 @@ export async function mockBlocks(from, count, numTxs, worldState) {
80
79
  messages: messagesArray
81
80
  };
82
81
  }
82
+ export async function mockCheckpoint(checkpointNumber, fork, options = {}) {
83
+ const { checkpoint, messages } = await mockCheckpointAndMessages(checkpointNumber, options);
84
+ await asyncMap(checkpoint.blocks, async (block, i)=>{
85
+ await updateBlockState(block, i === 0 ? messages : [], fork);
86
+ });
87
+ return {
88
+ checkpoint,
89
+ messages
90
+ };
91
+ }
83
92
  export async function assertSameState(forkA, forkB) {
84
93
  const nativeStateRef = await forkA.getStateReference();
85
94
  const nativeArchive = await forkA.getTreeInfo(MerkleTreeId.ARCHIVE);
package/dest/testing.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { Fr } from '@aztec/foundation/fields';
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
2
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
3
3
  import { PublicDataTreeLeaf } from '@aztec/stdlib/trees';
4
+ import type { GenesisData } from '@aztec/stdlib/world-state';
4
5
  export declare const defaultInitialAccountFeeJuice: Fr;
5
- export declare function getGenesisValues(initialAccounts: AztecAddress[], initialAccountFeeJuice?: Fr, genesisPublicData?: PublicDataTreeLeaf[]): Promise<{
6
+ export declare function getGenesisValues(initialAccounts: AztecAddress[], initialAccountFeeJuice?: Fr, genesisPublicData?: PublicDataTreeLeaf[], genesisTimestamp?: bigint): Promise<{
6
7
  genesisArchiveRoot: Fr;
7
- prefilledPublicData: PublicDataTreeLeaf[];
8
+ genesis: GenesisData;
8
9
  fundingNeeded: bigint;
9
10
  }>;
10
- //# sourceMappingURL=testing.d.ts.map
11
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdGluZy5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL3Rlc3RpbmcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQ0EsT0FBTyxFQUFFLEVBQUUsRUFBRSxNQUFNLGdDQUFnQyxDQUFDO0FBRXBELE9BQU8sS0FBSyxFQUFFLFlBQVksRUFBRSxNQUFNLDZCQUE2QixDQUFDO0FBQ2hFLE9BQU8sRUFBZ0Isa0JBQWtCLEVBQUUsTUFBTSxxQkFBcUIsQ0FBQztBQUN2RSxPQUFPLEtBQUssRUFBRSxXQUFXLEVBQUUsTUFBTSwyQkFBMkIsQ0FBQztBQXdCN0QsZUFBTyxNQUFNLDZCQUE2QixJQUFxQixDQUFDO0FBRWhFLHdCQUFzQixnQkFBZ0IsQ0FDcEMsZUFBZSxFQUFFLFlBQVksRUFBRSxFQUMvQixzQkFBc0IsS0FBZ0MsRUFDdEQsaUJBQWlCLEdBQUUsa0JBQWtCLEVBQU8sRUFDNUMsZ0JBQWdCLEdBQUUsTUFBVzs7OztHQXNCOUIifQ==