@aztec/archiver 0.0.1-commit.934299a21 → 0.0.1-commit.949a33fd8

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 (103) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +18 -10
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +146 -57
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +16 -4
  8. package/dest/errors.d.ts +61 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +88 -14
  11. package/dest/factory.d.ts +4 -5
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +26 -22
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -1
  17. package/dest/l1/calldata_retriever.d.ts +2 -1
  18. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  19. package/dest/l1/calldata_retriever.js +11 -5
  20. package/dest/l1/data_retrieval.d.ts +24 -12
  21. package/dest/l1/data_retrieval.d.ts.map +1 -1
  22. package/dest/l1/data_retrieval.js +36 -37
  23. package/dest/l1/validate_historical_logs.d.ts +23 -0
  24. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  25. package/dest/l1/validate_historical_logs.js +108 -0
  26. package/dest/modules/data_source_base.d.ts +12 -6
  27. package/dest/modules/data_source_base.d.ts.map +1 -1
  28. package/dest/modules/data_source_base.js +24 -6
  29. package/dest/modules/data_store_updater.d.ts +28 -15
  30. package/dest/modules/data_store_updater.d.ts.map +1 -1
  31. package/dest/modules/data_store_updater.js +102 -80
  32. package/dest/modules/instrumentation.d.ts +7 -2
  33. package/dest/modules/instrumentation.d.ts.map +1 -1
  34. package/dest/modules/instrumentation.js +22 -6
  35. package/dest/modules/l1_synchronizer.d.ts +8 -2
  36. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  37. package/dest/modules/l1_synchronizer.js +292 -144
  38. package/dest/modules/validation.d.ts +4 -3
  39. package/dest/modules/validation.d.ts.map +1 -1
  40. package/dest/modules/validation.js +6 -6
  41. package/dest/store/block_store.d.ts +83 -17
  42. package/dest/store/block_store.d.ts.map +1 -1
  43. package/dest/store/block_store.js +399 -124
  44. package/dest/store/contract_class_store.d.ts +2 -3
  45. package/dest/store/contract_class_store.d.ts.map +1 -1
  46. package/dest/store/contract_class_store.js +7 -67
  47. package/dest/store/contract_instance_store.d.ts +1 -1
  48. package/dest/store/contract_instance_store.d.ts.map +1 -1
  49. package/dest/store/contract_instance_store.js +6 -2
  50. package/dest/store/kv_archiver_store.d.ts +70 -23
  51. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  52. package/dest/store/kv_archiver_store.js +88 -27
  53. package/dest/store/l2_tips_cache.d.ts +2 -1
  54. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  55. package/dest/store/l2_tips_cache.js +27 -7
  56. package/dest/store/log_store.d.ts +6 -3
  57. package/dest/store/log_store.d.ts.map +1 -1
  58. package/dest/store/log_store.js +95 -20
  59. package/dest/store/message_store.d.ts +5 -1
  60. package/dest/store/message_store.d.ts.map +1 -1
  61. package/dest/store/message_store.js +21 -9
  62. package/dest/test/fake_l1_state.d.ts +20 -1
  63. package/dest/test/fake_l1_state.d.ts.map +1 -1
  64. package/dest/test/fake_l1_state.js +114 -18
  65. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  66. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  67. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  68. package/dest/test/mock_l2_block_source.d.ts +19 -4
  69. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  70. package/dest/test/mock_l2_block_source.js +57 -7
  71. package/dest/test/mock_structs.d.ts +4 -1
  72. package/dest/test/mock_structs.d.ts.map +1 -1
  73. package/dest/test/mock_structs.js +13 -1
  74. package/dest/test/noop_l1_archiver.d.ts +4 -1
  75. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  76. package/dest/test/noop_l1_archiver.js +9 -3
  77. package/package.json +13 -13
  78. package/src/archiver.ts +179 -56
  79. package/src/config.ts +23 -2
  80. package/src/errors.ts +133 -22
  81. package/src/factory.ts +24 -15
  82. package/src/index.ts +2 -1
  83. package/src/l1/calldata_retriever.ts +17 -5
  84. package/src/l1/data_retrieval.ts +52 -53
  85. package/src/l1/validate_historical_logs.ts +140 -0
  86. package/src/modules/data_source_base.ts +43 -7
  87. package/src/modules/data_store_updater.ts +126 -109
  88. package/src/modules/instrumentation.ts +27 -7
  89. package/src/modules/l1_synchronizer.ts +371 -178
  90. package/src/modules/validation.ts +10 -9
  91. package/src/store/block_store.ts +489 -143
  92. package/src/store/contract_class_store.ts +8 -106
  93. package/src/store/contract_instance_store.ts +8 -5
  94. package/src/store/kv_archiver_store.ts +133 -39
  95. package/src/store/l2_tips_cache.ts +58 -13
  96. package/src/store/log_store.ts +128 -32
  97. package/src/store/message_store.ts +27 -10
  98. package/src/structs/inbox_message.ts +1 -1
  99. package/src/test/fake_l1_state.ts +142 -29
  100. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  101. package/src/test/mock_l2_block_source.ts +73 -5
  102. package/src/test/mock_structs.ts +20 -6
  103. package/src/test/noop_l1_archiver.ts +10 -2
@@ -1,7 +1,6 @@
1
1
  import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
2
  import { BlockNumber } from '@aztec/foundation/branded-types';
3
- import { filterAsync } from '@aztec/foundation/collection';
4
- import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { compactArray, filterAsync } from '@aztec/foundation/collection';
5
4
  import { createLogger } from '@aztec/foundation/log';
6
5
  import { BufferReader, numToUInt32BE } from '@aztec/foundation/serialize';
7
6
  import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
@@ -22,6 +21,7 @@ import {
22
21
  } from '@aztec/stdlib/logs';
23
22
  import { TxHash } from '@aztec/stdlib/tx';
24
23
 
24
+ import { OutOfOrderLogInsertionError } from '../errors.js';
25
25
  import type { BlockStore } from './block_store.js';
26
26
 
27
27
  /**
@@ -165,10 +165,21 @@ export class LogStore {
165
165
 
166
166
  for (const taggedLogBuffer of currentPrivateTaggedLogs) {
167
167
  if (taggedLogBuffer.logBuffers && taggedLogBuffer.logBuffers.length > 0) {
168
- privateTaggedLogs.set(
169
- taggedLogBuffer.tag,
170
- taggedLogBuffer.logBuffers!.concat(privateTaggedLogs.get(taggedLogBuffer.tag)!),
171
- );
168
+ const newLogs = privateTaggedLogs.get(taggedLogBuffer.tag)!;
169
+ if (newLogs.length === 0) {
170
+ continue;
171
+ }
172
+ const lastExisting = TxScopedL2Log.fromBuffer(taggedLogBuffer.logBuffers.at(-1)!);
173
+ const firstNew = TxScopedL2Log.fromBuffer(newLogs[0]);
174
+ if (lastExisting.blockNumber > firstNew.blockNumber) {
175
+ throw new OutOfOrderLogInsertionError(
176
+ 'private',
177
+ taggedLogBuffer.tag,
178
+ lastExisting.blockNumber,
179
+ firstNew.blockNumber,
180
+ );
181
+ }
182
+ privateTaggedLogs.set(taggedLogBuffer.tag, taggedLogBuffer.logBuffers.concat(newLogs));
172
183
  }
173
184
  }
174
185
 
@@ -200,10 +211,21 @@ export class LogStore {
200
211
 
201
212
  for (const taggedLogBuffer of currentPublicTaggedLogs) {
202
213
  if (taggedLogBuffer.logBuffers && taggedLogBuffer.logBuffers.length > 0) {
203
- publicTaggedLogs.set(
204
- taggedLogBuffer.tag,
205
- taggedLogBuffer.logBuffers!.concat(publicTaggedLogs.get(taggedLogBuffer.tag)!),
206
- );
214
+ const newLogs = publicTaggedLogs.get(taggedLogBuffer.tag)!;
215
+ if (newLogs.length === 0) {
216
+ continue;
217
+ }
218
+ const lastExisting = TxScopedL2Log.fromBuffer(taggedLogBuffer.logBuffers.at(-1)!);
219
+ const firstNew = TxScopedL2Log.fromBuffer(newLogs[0]);
220
+ if (lastExisting.blockNumber > firstNew.blockNumber) {
221
+ throw new OutOfOrderLogInsertionError(
222
+ 'public',
223
+ taggedLogBuffer.tag,
224
+ lastExisting.blockNumber,
225
+ firstNew.blockNumber,
226
+ );
227
+ }
228
+ publicTaggedLogs.set(taggedLogBuffer.tag, taggedLogBuffer.logBuffers.concat(newLogs));
207
229
  }
208
230
  }
209
231
 
@@ -279,29 +301,58 @@ export class LogStore {
279
301
  }
280
302
 
281
303
  #unpackBlockHash(reader: BufferReader): BlockHash {
282
- const blockHash = reader.remainingBytes() > 0 ? reader.readObject(Fr) : undefined;
283
-
284
- if (!blockHash) {
304
+ if (reader.remainingBytes() === 0) {
285
305
  throw new Error('Failed to read block hash from log entry buffer');
286
306
  }
287
307
 
288
- return new BlockHash(blockHash);
308
+ return BlockHash.fromBuffer(reader);
289
309
  }
290
310
 
291
311
  deleteLogs(blocks: L2Block[]): Promise<boolean> {
292
312
  return this.db.transactionAsync(async () => {
293
- await Promise.all(
294
- blocks.map(async block => {
295
- // Delete private logs
296
- const privateKeys = (await this.#privateLogKeysByBlock.getAsync(block.number)) ?? [];
297
- await Promise.all(privateKeys.map(tag => this.#privateLogsByTag.delete(tag)));
298
-
299
- // Delete public logs
300
- const publicKeys = (await this.#publicLogKeysByBlock.getAsync(block.number)) ?? [];
301
- await Promise.all(publicKeys.map(key => this.#publicLogsByContractAndTag.delete(key)));
302
- }),
313
+ const blockNumbers = new Set(blocks.map(block => block.number));
314
+ const firstBlockToDelete = Math.min(...blockNumbers);
315
+
316
+ // Collect all unique private tags across all blocks being deleted
317
+ const allPrivateTags = new Set(
318
+ compactArray(await Promise.all(blocks.map(block => this.#privateLogKeysByBlock.getAsync(block.number)))).flat(),
319
+ );
320
+
321
+ // Trim private logs: for each tag, delete all instances including and after the first block being deleted.
322
+ // This hinges on the invariant that logs for a given tag are always inserted in order of block number, which is enforced in #addPrivateLogs.
323
+ for (const tag of allPrivateTags) {
324
+ const existing = await this.#privateLogsByTag.getAsync(tag);
325
+ if (existing === undefined || existing.length === 0) {
326
+ continue;
327
+ }
328
+ const lastIndexToKeep = existing.findLastIndex(
329
+ buf => TxScopedL2Log.getBlockNumberFromBuffer(buf) < firstBlockToDelete,
330
+ );
331
+ const remaining = existing.slice(0, lastIndexToKeep + 1);
332
+ await (remaining.length > 0 ? this.#privateLogsByTag.set(tag, remaining) : this.#privateLogsByTag.delete(tag));
333
+ }
334
+
335
+ // Collect all unique public keys across all blocks being deleted
336
+ const allPublicKeys = new Set(
337
+ compactArray(await Promise.all(blocks.map(block => this.#publicLogKeysByBlock.getAsync(block.number)))).flat(),
303
338
  );
304
339
 
340
+ // And do the same as we did with private logs
341
+ for (const key of allPublicKeys) {
342
+ const existing = await this.#publicLogsByContractAndTag.getAsync(key);
343
+ if (existing === undefined || existing.length === 0) {
344
+ continue;
345
+ }
346
+ const lastIndexToKeep = existing.findLastIndex(
347
+ buf => TxScopedL2Log.getBlockNumberFromBuffer(buf) < firstBlockToDelete,
348
+ );
349
+ const remaining = existing.slice(0, lastIndexToKeep + 1);
350
+ await (remaining.length > 0
351
+ ? this.#publicLogsByContractAndTag.set(key, remaining)
352
+ : this.#publicLogsByContractAndTag.delete(key));
353
+ }
354
+
355
+ // After trimming the tagged logs, we can delete the block-level keys that track which tags are in which blocks.
305
356
  await Promise.all(
306
357
  blocks.map(block =>
307
358
  Promise.all([
@@ -322,17 +373,30 @@ export class LogStore {
322
373
  * array implies no logs match that tag.
323
374
  * @param tags - The tags to search for.
324
375
  * @param page - The page number (0-indexed) for pagination.
376
+ * @param upToBlockNumber - If set, only return logs from blocks up to and including this block number.
325
377
  * @returns An array of log arrays, one per tag. Returns at most MAX_LOGS_PER_TAG logs per tag per page. If
326
378
  * MAX_LOGS_PER_TAG logs are returned for a tag, the caller should fetch the next page to check for more logs.
327
379
  */
328
- async getPrivateLogsByTags(tags: SiloedTag[], page: number = 0): Promise<TxScopedL2Log[][]> {
380
+ async getPrivateLogsByTags(
381
+ tags: SiloedTag[],
382
+ page: number = 0,
383
+ upToBlockNumber?: BlockNumber,
384
+ ): Promise<TxScopedL2Log[][]> {
329
385
  const logs = await Promise.all(tags.map(tag => this.#privateLogsByTag.getAsync(tag.toString())));
386
+
330
387
  const start = page * MAX_LOGS_PER_TAG;
331
388
  const end = start + MAX_LOGS_PER_TAG;
332
389
 
333
- return logs.map(
334
- logBuffers => logBuffers?.slice(start, end).map(logBuffer => TxScopedL2Log.fromBuffer(logBuffer)) ?? [],
335
- );
390
+ return logs.map(logBuffers => {
391
+ const deserialized = logBuffers?.slice(start, end).map(buf => TxScopedL2Log.fromBuffer(buf)) ?? [];
392
+ if (upToBlockNumber !== undefined) {
393
+ const cutoff = deserialized.findIndex(log => log.blockNumber > upToBlockNumber);
394
+ if (cutoff !== -1) {
395
+ return deserialized.slice(0, cutoff);
396
+ }
397
+ }
398
+ return deserialized;
399
+ });
336
400
  }
337
401
 
338
402
  /**
@@ -341,6 +405,7 @@ export class LogStore {
341
405
  * @param contractAddress - The contract address to search logs for.
342
406
  * @param tags - The tags to search for.
343
407
  * @param page - The page number (0-indexed) for pagination.
408
+ * @param upToBlockNumber - If set, only return logs from blocks up to and including this block number.
344
409
  * @returns An array of log arrays, one per tag. Returns at most MAX_LOGS_PER_TAG logs per tag per page. If
345
410
  * MAX_LOGS_PER_TAG logs are returned for a tag, the caller should fetch the next page to check for more logs.
346
411
  */
@@ -348,6 +413,7 @@ export class LogStore {
348
413
  contractAddress: AztecAddress,
349
414
  tags: Tag[],
350
415
  page: number = 0,
416
+ upToBlockNumber?: BlockNumber,
351
417
  ): Promise<TxScopedL2Log[][]> {
352
418
  const logs = await Promise.all(
353
419
  tags.map(tag => {
@@ -358,9 +424,16 @@ export class LogStore {
358
424
  const start = page * MAX_LOGS_PER_TAG;
359
425
  const end = start + MAX_LOGS_PER_TAG;
360
426
 
361
- return logs.map(
362
- logBuffers => logBuffers?.slice(start, end).map(logBuffer => TxScopedL2Log.fromBuffer(logBuffer)) ?? [],
363
- );
427
+ return logs.map(logBuffers => {
428
+ const deserialized = logBuffers?.slice(start, end).map(buf => TxScopedL2Log.fromBuffer(buf)) ?? [];
429
+ if (upToBlockNumber !== undefined) {
430
+ const cutoff = deserialized.findIndex(log => log.blockNumber > upToBlockNumber);
431
+ if (cutoff !== -1) {
432
+ return deserialized.slice(0, cutoff);
433
+ }
434
+ }
435
+ return deserialized;
436
+ });
364
437
  }
365
438
 
366
439
  /**
@@ -588,11 +661,24 @@ export class LogStore {
588
661
  txLogs: PublicLog[],
589
662
  filter: LogFilter = {},
590
663
  ): boolean {
664
+ if (filter.fromBlock && blockNumber < filter.fromBlock) {
665
+ return false;
666
+ }
667
+ if (filter.toBlock && blockNumber >= filter.toBlock) {
668
+ return false;
669
+ }
670
+ if (filter.txHash && !txHash.equals(filter.txHash)) {
671
+ return false;
672
+ }
673
+
591
674
  let maxLogsHit = false;
592
675
  let logIndex = typeof filter.afterLog?.logIndex === 'number' ? filter.afterLog.logIndex + 1 : 0;
593
676
  for (; logIndex < txLogs.length; logIndex++) {
594
677
  const log = txLogs[logIndex];
595
- if (!filter.contractAddress || log.contractAddress.equals(filter.contractAddress)) {
678
+ if (
679
+ (!filter.contractAddress || log.contractAddress.equals(filter.contractAddress)) &&
680
+ (!filter.tag || log.fields[0]?.equals(filter.tag))
681
+ ) {
596
682
  results.push(
597
683
  new ExtendedPublicLog(new LogId(BlockNumber(blockNumber), blockHash, txHash, txIndex, logIndex), log),
598
684
  );
@@ -616,6 +702,16 @@ export class LogStore {
616
702
  txLogs: ContractClassLog[],
617
703
  filter: LogFilter = {},
618
704
  ): boolean {
705
+ if (filter.fromBlock && blockNumber < filter.fromBlock) {
706
+ return false;
707
+ }
708
+ if (filter.toBlock && blockNumber >= filter.toBlock) {
709
+ return false;
710
+ }
711
+ if (filter.txHash && !txHash.equals(filter.txHash)) {
712
+ return false;
713
+ }
714
+
619
715
  let maxLogsHit = false;
620
716
  let logIndex = typeof filter.afterLog?.logIndex === 'number' ? filter.afterLog.logIndex + 1 : 0;
621
717
  for (; logIndex < txLogs.length; logIndex++) {
@@ -14,6 +14,7 @@ import {
14
14
  } from '@aztec/kv-store';
15
15
  import { InboxLeaf } from '@aztec/stdlib/messaging';
16
16
 
17
+ import { L1ToL2MessagesNotReadyError } from '../errors.js';
17
18
  import {
18
19
  type InboxMessage,
19
20
  deserializeInboxMessage,
@@ -40,6 +41,8 @@ export class MessageStore {
40
41
  #lastSynchedL1Block: AztecAsyncSingleton<Buffer>;
41
42
  /** Stores total messages stored */
42
43
  #totalMessageCount: AztecAsyncSingleton<bigint>;
44
+ /** Stores the checkpoint number whose message tree is currently being filled on L1. */
45
+ #inboxTreeInProgress: AztecAsyncSingleton<bigint>;
43
46
 
44
47
  #log = createLogger('archiver:message_store');
45
48
 
@@ -48,6 +51,7 @@ export class MessageStore {
48
51
  this.#l1ToL2MessageIndices = db.openMap('archiver_l1_to_l2_message_indices');
49
52
  this.#lastSynchedL1Block = db.openSingleton('archiver_last_l1_block_id');
50
53
  this.#totalMessageCount = db.openSingleton('archiver_l1_to_l2_message_count');
54
+ this.#inboxTreeInProgress = db.openSingleton('archiver_inbox_tree_in_progress');
51
55
  }
52
56
 
53
57
  public async getTotalL1ToL2MessageCount(): Promise<bigint> {
@@ -137,7 +141,7 @@ export class MessageStore {
137
141
  );
138
142
  }
139
143
 
140
- // Check the first message in a block has the correct index.
144
+ // Check the first message in a checkpoint has the correct index.
141
145
  if (
142
146
  (!lastMessage || message.checkpointNumber > lastMessage.checkpointNumber) &&
143
147
  message.index !== expectedStart
@@ -157,15 +161,6 @@ export class MessageStore {
157
161
  lastMessage = message;
158
162
  }
159
163
 
160
- // Update the L1 sync point to that of the last message added.
161
- const currentSyncPoint = await this.getSynchedL1Block();
162
- if (!currentSyncPoint || currentSyncPoint.l1BlockNumber < lastMessage!.l1BlockNumber) {
163
- await this.setSynchedL1Block({
164
- l1BlockNumber: lastMessage!.l1BlockNumber,
165
- l1BlockHash: lastMessage!.l1BlockHash,
166
- });
167
- }
168
-
169
164
  // Update total message count with the number of inserted messages.
170
165
  await this.increaseTotalMessageCount(messageCount);
171
166
  });
@@ -185,7 +180,29 @@ export class MessageStore {
185
180
  return msg ? deserializeInboxMessage(msg) : undefined;
186
181
  }
187
182
 
183
+ /** Returns the inbox tree-in-progress checkpoint number from L1, or undefined if not yet set. */
184
+ public getInboxTreeInProgress(): Promise<bigint | undefined> {
185
+ return this.#inboxTreeInProgress.getAsync();
186
+ }
187
+
188
+ /** Atomically updates the message sync state: the L1 sync point and the inbox tree-in-progress marker. */
189
+ public setMessageSyncState(l1Block: L1BlockId, treeInProgress: bigint | undefined): Promise<void> {
190
+ return this.db.transactionAsync(async () => {
191
+ await this.setSynchedL1Block(l1Block);
192
+ if (treeInProgress !== undefined) {
193
+ await this.#inboxTreeInProgress.set(treeInProgress);
194
+ } else {
195
+ await this.#inboxTreeInProgress.delete();
196
+ }
197
+ });
198
+ }
199
+
188
200
  public async getL1ToL2Messages(checkpointNumber: CheckpointNumber): Promise<Fr[]> {
201
+ const treeInProgress = await this.#inboxTreeInProgress.getAsync();
202
+ if (treeInProgress !== undefined && BigInt(checkpointNumber) >= treeInProgress) {
203
+ throw new L1ToL2MessagesNotReadyError(checkpointNumber, treeInProgress);
204
+ }
205
+
189
206
  const messages: Fr[] = [];
190
207
 
191
208
  const [startIndex, endIndex] = InboxLeaf.indexRangeForCheckpoint(checkpointNumber);
@@ -8,7 +8,7 @@ export type InboxMessage = {
8
8
  index: bigint;
9
9
  leaf: Fr;
10
10
  checkpointNumber: CheckpointNumber;
11
- l1BlockNumber: bigint; // L1 block number - NOT Aztec L2
11
+ l1BlockNumber: bigint;
12
12
  l1BlockHash: Buffer32;
13
13
  rollingHash: Buffer16;
14
14
  };
@@ -1,5 +1,6 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import { type Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec/blob-lib';
3
+ import { INITIAL_CHECKPOINT_NUMBER } from '@aztec/constants';
3
4
  import type { CheckpointProposedLog, InboxContract, MessageSentLog, RollupContract } from '@aztec/ethereum/contracts';
4
5
  import { MULTI_CALL_3_ADDRESS } from '@aztec/ethereum/contracts';
5
6
  import type { ViemPublicClient } from '@aztec/ethereum/types';
@@ -14,12 +15,8 @@ import { CommitteeAttestation, CommitteeAttestationsAndSigners, L2Block } from '
14
15
  import { Checkpoint } from '@aztec/stdlib/checkpoint';
15
16
  import { getSlotAtTimestamp } from '@aztec/stdlib/epoch-helpers';
16
17
  import { InboxLeaf } from '@aztec/stdlib/messaging';
17
- import { ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
18
- import {
19
- makeAndSignCommitteeAttestationsAndSigners,
20
- makeCheckpointAttestationFromCheckpoint,
21
- mockCheckpointAndMessages,
22
- } from '@aztec/stdlib/testing';
18
+ import { ConsensusPayload, getHashedSignaturePayloadTypedData } from '@aztec/stdlib/p2p';
19
+ import { mockCheckpointAndMessages } from '@aztec/stdlib/testing';
23
20
  import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
24
21
 
25
22
  import { type MockProxy, mock } from 'jest-mock-extended';
@@ -150,8 +147,14 @@ export class FakeL1State {
150
147
  // Computed from checkpoints based on L1 block visibility
151
148
  private pendingCheckpointNumber: CheckpointNumber = CheckpointNumber(0);
152
149
 
150
+ // The L1 block number reported as "finalized" (defaults to the start block).
151
+ // `undefined` simulates the startup window on a fresh devnet where
152
+ // `getBlock({ blockTag: 'finalized' })` fails with "finalized block not found".
153
+ private finalizedL1BlockNumber: bigint | undefined;
154
+
153
155
  constructor(private readonly config: FakeL1StateConfig) {
154
156
  this.l1BlockNumber = config.l1StartBlock;
157
+ this.finalizedL1BlockNumber = config.l1StartBlock;
155
158
  this.lastArchive = new AppendOnlyTreeSnapshot(config.genesisArchiveRoot, 1);
156
159
  }
157
160
 
@@ -283,11 +286,33 @@ export class FakeL1State {
283
286
  this.updatePendingCheckpointNumber();
284
287
  }
285
288
 
289
+ /**
290
+ * Sets the L1 block number that will be reported as "finalized". Pass `undefined` to
291
+ * simulate a chain that does not yet have a finalized block (devnet startup).
292
+ */
293
+ setFinalizedL1BlockNumber(blockNumber: bigint | undefined): void {
294
+ this.finalizedL1BlockNumber = blockNumber;
295
+ }
296
+
286
297
  /** Marks a checkpoint as proven. Updates provenCheckpointNumber. */
287
298
  markCheckpointAsProven(checkpointNumber: CheckpointNumber): void {
288
299
  this.provenCheckpointNumber = checkpointNumber;
289
300
  }
290
301
 
302
+ /**
303
+ * Simulates what `rollup.getProvenCheckpointNumber({ blockNumber: atL1Block })` would return.
304
+ */
305
+ getProvenCheckpointNumberAtL1Block(atL1Block: bigint): CheckpointNumber {
306
+ if (this.provenCheckpointNumber === 0) {
307
+ return CheckpointNumber(0);
308
+ }
309
+ const checkpoint = this.checkpoints.find(cp => cp.checkpointNumber === this.provenCheckpointNumber);
310
+ if (checkpoint && checkpoint.l1BlockNumber <= atL1Block) {
311
+ return this.provenCheckpointNumber;
312
+ }
313
+ return CheckpointNumber(0);
314
+ }
315
+
291
316
  /** Sets the target committee size for attestation validation. */
292
317
  setTargetCommitteeSize(size: number): void {
293
318
  this.targetCommitteeSize = size;
@@ -308,6 +333,21 @@ export class FakeL1State {
308
333
  this.updatePendingCheckpointNumber();
309
334
  }
310
335
 
336
+ /**
337
+ * Moves a checkpoint to a different L1 block number (simulates L1 reorg that
338
+ * re-includes the same checkpoint transaction in a different block).
339
+ * The checkpoint content stays the same — only the L1 metadata changes.
340
+ * Auto-updates pending status.
341
+ */
342
+ moveCheckpointToL1Block(checkpointNumber: CheckpointNumber, newL1BlockNumber: bigint): void {
343
+ for (const cpData of this.checkpoints) {
344
+ if (cpData.checkpointNumber === checkpointNumber) {
345
+ cpData.l1BlockNumber = newL1BlockNumber;
346
+ }
347
+ }
348
+ this.updatePendingCheckpointNumber();
349
+ }
350
+
311
351
  /**
312
352
  * Removes messages after a given total index (simulates L1 reorg).
313
353
  * Auto-updates rolling hash.
@@ -406,6 +446,11 @@ export class FakeL1State {
406
446
  });
407
447
  });
408
448
 
449
+ mockRollup.getProvenCheckpointNumber.mockImplementation((options?: { blockNumber?: bigint }) => {
450
+ const atBlock = options?.blockNumber ?? this.l1BlockNumber;
451
+ return Promise.resolve(this.getProvenCheckpointNumberAtL1Block(atBlock));
452
+ });
453
+
409
454
  mockRollup.canPruneAtTime.mockImplementation(() => Promise.resolve(this.canPruneResult));
410
455
 
411
456
  // Mock the wrapper method for fetching checkpoint events
@@ -422,21 +467,44 @@ export class FakeL1State {
422
467
  createMockInboxContract(_publicClient: MockProxy<ViemPublicClient>): MockProxy<InboxContract> {
423
468
  const mockInbox = mock<InboxContract>();
424
469
 
425
- mockInbox.getState.mockImplementation(() =>
426
- Promise.resolve({
427
- messagesRollingHash: this.messagesRollingHash,
428
- totalMessagesInserted: BigInt(this.messages.length),
429
- treeInProgress: 0n,
430
- }),
431
- );
470
+ mockInbox.getState.mockImplementation((opts: { blockTag?: string; blockNumber?: bigint } = {}) => {
471
+ // Filter messages visible at the given block number (or all if not specified)
472
+ const blockNumber = opts.blockNumber ?? this.l1BlockNumber;
473
+ const visibleMessages = this.messages.filter(m => m.l1BlockNumber <= blockNumber);
474
+
475
+ // treeInProgress must be > any sealed checkpoint. On L1, a checkpoint can only be proposed
476
+ // after its messages are sealed, so treeInProgress > checkpointNumber for all published checkpoints.
477
+ const maxFromMessages =
478
+ visibleMessages.length > 0 ? Math.max(...visibleMessages.map(m => Number(m.checkpointNumber))) + 1 : 0;
479
+ const maxFromCheckpoints =
480
+ this.checkpoints.length > 0
481
+ ? Math.max(
482
+ ...this.checkpoints
483
+ .filter(cp => !cp.pruned && cp.l1BlockNumber <= blockNumber)
484
+ .map(cp => Number(cp.checkpointNumber)),
485
+ 0,
486
+ ) + 1
487
+ : 0;
488
+ const treeInProgress = Math.max(maxFromMessages, maxFromCheckpoints, INITIAL_CHECKPOINT_NUMBER);
489
+
490
+ // Compute rolling hash only for visible messages
491
+ const rollingHash =
492
+ visibleMessages.length > 0 ? visibleMessages[visibleMessages.length - 1].rollingHash : Buffer16.ZERO;
493
+
494
+ return Promise.resolve({
495
+ messagesRollingHash: rollingHash,
496
+ totalMessagesInserted: BigInt(visibleMessages.length),
497
+ treeInProgress: BigInt(treeInProgress),
498
+ });
499
+ });
432
500
 
433
501
  // Mock the wrapper methods for fetching message events
434
502
  mockInbox.getMessageSentEvents.mockImplementation((fromBlock: bigint, toBlock: bigint) =>
435
503
  Promise.resolve(this.getMessageSentLogs(fromBlock, toBlock)),
436
504
  );
437
505
 
438
- mockInbox.getMessageSentEventByHash.mockImplementation((hash: string, fromBlock: bigint, toBlock: bigint) =>
439
- Promise.resolve(this.getMessageSentLogs(fromBlock, toBlock, hash)),
506
+ mockInbox.getMessageSentEventByHash.mockImplementation((msgHash: string, aroundL1BlockNumber: bigint) =>
507
+ Promise.resolve(this.getMessageSentLogByHash(msgHash, aroundL1BlockNumber) as MessageSentLog),
440
508
  );
441
509
 
442
510
  return mockInbox;
@@ -447,12 +515,23 @@ export class FakeL1State {
447
515
  const publicClient = mock<ViemPublicClient>();
448
516
 
449
517
  publicClient.getChainId.mockResolvedValue(1);
518
+ // Several consumers (CalldataRetriever, ArchiverL1Synchronizer) derive the EIP-712 signing
519
+ // context from `publicClient.chain.id`. Pin it so it matches `getSignatureContext()` below.
520
+ (publicClient as unknown as { chain: { id: number } }).chain = { id: 1 };
450
521
  publicClient.getBlockNumber.mockImplementation(() => Promise.resolve(this.l1BlockNumber));
451
522
 
452
- // Use async function pattern that existing test uses for getBlock
453
-
454
- publicClient.getBlock.mockImplementation((async (args: { blockNumber?: bigint } = {}) => {
455
- const blockNum = args.blockNumber ?? (await publicClient.getBlockNumber());
523
+ publicClient.getBlock.mockImplementation((async (args: { blockNumber?: bigint; blockTag?: string } = {}) => {
524
+ let blockNum: bigint;
525
+ if (args.blockTag === 'finalized') {
526
+ if (this.finalizedL1BlockNumber === undefined) {
527
+ throw Object.assign(new Error('finalized block not found'), {
528
+ details: 'finalized block not found',
529
+ });
530
+ }
531
+ blockNum = this.finalizedL1BlockNumber;
532
+ } else {
533
+ blockNum = args.blockNumber ?? (await publicClient.getBlockNumber());
534
+ }
456
535
  return {
457
536
  number: blockNum,
458
537
  timestamp: BigInt(blockNum) * BigInt(this.config.ethereumSlotDuration) + this.config.l1GenesisTime,
@@ -474,10 +553,10 @@ export class FakeL1State {
474
553
  createMockBlobClient(): MockProxy<BlobClientInterface> {
475
554
  const blobClient = mock<BlobClientInterface>();
476
555
 
477
- // The blockId is the transaction's blockHash, which we set to the checkpoint's archive root
556
+ // The blockId is the L1 block hash, which we derive from the L1 block number
478
557
  blobClient.getBlobSidecar.mockImplementation((blockId: `0x${string}`) =>
479
558
  Promise.resolve(
480
- this.checkpoints.find(cpData => cpData.checkpoint.archive.root.toString() === blockId)?.blobs ?? [],
559
+ this.checkpoints.find(cpData => Buffer32.fromBigInt(cpData.l1BlockNumber).toString() === blockId)?.blobs ?? [],
481
560
  ),
482
561
  );
483
562
 
@@ -553,13 +632,38 @@ export class FakeL1State {
553
632
  }));
554
633
  }
555
634
 
635
+ private getMessageSentLogByHash(msgHash: string, aroundL1BlockNumber: bigint): MessageSentLog | undefined {
636
+ const msg = this.messages.find(
637
+ msg =>
638
+ msg.leaf.toString() === msgHash &&
639
+ msg.l1BlockNumber >= aroundL1BlockNumber - 5n &&
640
+ msg.l1BlockNumber <= aroundL1BlockNumber + 5n,
641
+ );
642
+ if (!msg) {
643
+ return undefined;
644
+ }
645
+ return {
646
+ l1BlockNumber: msg.l1BlockNumber,
647
+ l1BlockHash: Buffer32.fromBigInt(msg.l1BlockNumber),
648
+ l1TransactionHash: `0x${msg.l1BlockNumber.toString(16)}` as `0x${string}`,
649
+ args: {
650
+ checkpointNumber: msg.checkpointNumber,
651
+ index: msg.index,
652
+ leaf: msg.leaf,
653
+ rollingHash: msg.rollingHash,
654
+ },
655
+ };
656
+ }
657
+
556
658
  private async makeRollupTx(
557
659
  checkpoint: Checkpoint,
558
660
  signers: Secp256k1Signer[],
559
661
  ): Promise<{ tx: Transaction; attestationsHash: Buffer32; payloadDigest: Buffer32 }> {
662
+ const signatureContext = this.getSignatureContext();
663
+ const consensusPayload = ConsensusPayload.fromCheckpoint(checkpoint, signatureContext);
664
+ const attestationDigest = getHashedSignaturePayloadTypedData(consensusPayload);
560
665
  const attestations = signers
561
- .map(signer => makeCheckpointAttestationFromCheckpoint(checkpoint, signer))
562
- .map(attestation => CommitteeAttestation.fromSignature(attestation.signature))
666
+ .map(signer => CommitteeAttestation.fromSignature(signer.sign(attestationDigest)))
563
667
  .map(committeeAttestation => committeeAttestation.toViem());
564
668
 
565
669
  const header = checkpoint.header.toViem();
@@ -567,11 +671,15 @@ export class FakeL1State {
567
671
  const archive = toHex(checkpoint.archive.root.toBuffer());
568
672
  const attestationsAndSigners = new CommitteeAttestationsAndSigners(
569
673
  attestations.map(attestation => CommitteeAttestation.fromViem(attestation)),
674
+ signatureContext,
570
675
  );
571
676
 
572
- const attestationsAndSignersSignature = makeAndSignCommitteeAttestationsAndSigners(
573
- attestationsAndSigners,
574
- signers[0],
677
+ // Fall back to a random signer when no attesters are provided, so tests that
678
+ // don't care about the proposer identity (e.g. sync tests) still produce a
679
+ // valid-looking signature for the attestationsAndSigners struct.
680
+ const proposerSigner = signers[0] ?? Secp256k1Signer.random();
681
+ const attestationsAndSignersSignature = proposerSigner.sign(
682
+ getHashedSignaturePayloadTypedData(attestationsAndSigners),
575
683
  );
576
684
 
577
685
  const packedAttestations = attestationsAndSigners.getPackedAttestations();
@@ -612,9 +720,7 @@ export class FakeL1State {
612
720
  );
613
721
 
614
722
  // Compute payloadDigest (same logic as CalldataRetriever)
615
- const consensusPayload = ConsensusPayload.fromCheckpoint(checkpoint);
616
- const payloadToSign = consensusPayload.getPayloadToSign(SignatureDomainSeparator.checkpointAttestation);
617
- const payloadDigest = Buffer32.fromString(keccak256(payloadToSign));
723
+ const payloadDigest = getHashedSignaturePayloadTypedData(consensusPayload);
618
724
 
619
725
  const tx = {
620
726
  input: multiCallInput,
@@ -626,6 +732,13 @@ export class FakeL1State {
626
732
  return { tx, attestationsHash, payloadDigest };
627
733
  }
628
734
 
735
+ private getSignatureContext() {
736
+ return {
737
+ chainId: 1,
738
+ rollupAddress: this.config.rollupAddress,
739
+ };
740
+ }
741
+
629
742
  /** Extracts the CommitteeAttestations struct definition from RollupAbi for hash computation. */
630
743
  private getCommitteeAttestationsStructDef(): AbiParameter {
631
744
  const proposeFunction = RollupAbi.find(item => item.type === 'function' && item.name === 'propose') as
@@ -44,6 +44,7 @@ export class MockL1ToL2MessageSource implements L1ToL2MessageSource {
44
44
  checkpointed: tip,
45
45
  proven: tip,
46
46
  finalized: tip,
47
+ proposedCheckpoint: tip,
47
48
  });
48
49
  }
49
50
  }