@aztec/archiver 0.0.1-commit.d6f2b3f94 → 0.0.1-commit.dbf9cec

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 (68) hide show
  1. package/dest/archiver.d.ts +5 -2
  2. package/dest/archiver.d.ts.map +1 -1
  3. package/dest/archiver.js +9 -91
  4. package/dest/factory.d.ts +1 -1
  5. package/dest/factory.d.ts.map +1 -1
  6. package/dest/factory.js +5 -5
  7. package/dest/index.d.ts +2 -1
  8. package/dest/index.d.ts.map +1 -1
  9. package/dest/index.js +1 -0
  10. package/dest/l1/bin/retrieve-calldata.js +32 -28
  11. package/dest/l1/calldata_retriever.d.ts +73 -50
  12. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  13. package/dest/l1/calldata_retriever.js +190 -259
  14. package/dest/l1/data_retrieval.d.ts +9 -9
  15. package/dest/l1/data_retrieval.d.ts.map +1 -1
  16. package/dest/l1/data_retrieval.js +21 -19
  17. package/dest/l1/spire_proposer.d.ts +5 -5
  18. package/dest/l1/spire_proposer.d.ts.map +1 -1
  19. package/dest/l1/spire_proposer.js +9 -17
  20. package/dest/modules/data_source_base.d.ts +8 -3
  21. package/dest/modules/data_source_base.d.ts.map +1 -1
  22. package/dest/modules/data_source_base.js +28 -72
  23. package/dest/modules/data_store_updater.d.ts +9 -2
  24. package/dest/modules/data_store_updater.d.ts.map +1 -1
  25. package/dest/modules/data_store_updater.js +40 -19
  26. package/dest/modules/instrumentation.d.ts +15 -2
  27. package/dest/modules/instrumentation.d.ts.map +1 -1
  28. package/dest/modules/instrumentation.js +19 -2
  29. package/dest/modules/l1_synchronizer.d.ts +4 -8
  30. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  31. package/dest/modules/l1_synchronizer.js +14 -9
  32. package/dest/store/block_store.d.ts +18 -14
  33. package/dest/store/block_store.d.ts.map +1 -1
  34. package/dest/store/block_store.js +69 -17
  35. package/dest/store/kv_archiver_store.d.ts +18 -4
  36. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  37. package/dest/store/kv_archiver_store.js +18 -0
  38. package/dest/store/l2_tips_cache.d.ts +19 -0
  39. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  40. package/dest/store/l2_tips_cache.js +89 -0
  41. package/dest/test/fake_l1_state.d.ts +6 -1
  42. package/dest/test/fake_l1_state.d.ts.map +1 -1
  43. package/dest/test/fake_l1_state.js +56 -18
  44. package/dest/test/mock_archiver.d.ts +1 -1
  45. package/dest/test/mock_archiver.d.ts.map +1 -1
  46. package/dest/test/mock_archiver.js +3 -2
  47. package/dest/test/mock_l2_block_source.d.ts +18 -3
  48. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  49. package/dest/test/mock_l2_block_source.js +125 -82
  50. package/package.json +13 -13
  51. package/src/archiver.ts +10 -110
  52. package/src/factory.ts +7 -1
  53. package/src/index.ts +1 -0
  54. package/src/l1/README.md +25 -68
  55. package/src/l1/bin/retrieve-calldata.ts +40 -27
  56. package/src/l1/calldata_retriever.ts +249 -379
  57. package/src/l1/data_retrieval.ts +23 -25
  58. package/src/l1/spire_proposer.ts +7 -15
  59. package/src/modules/data_source_base.ts +53 -92
  60. package/src/modules/data_store_updater.ts +43 -18
  61. package/src/modules/instrumentation.ts +29 -2
  62. package/src/modules/l1_synchronizer.ts +15 -12
  63. package/src/store/block_store.ts +85 -36
  64. package/src/store/kv_archiver_store.ts +35 -3
  65. package/src/store/l2_tips_cache.ts +89 -0
  66. package/src/test/fake_l1_state.ts +75 -17
  67. package/src/test/mock_archiver.ts +3 -2
  68. package/src/test/mock_l2_block_source.ts +158 -78
@@ -14,6 +14,7 @@ import { CommitteeAttestation, CommitteeAttestationsAndSigners, L2Block } from '
14
14
  import { Checkpoint } from '@aztec/stdlib/checkpoint';
15
15
  import { getSlotAtTimestamp } from '@aztec/stdlib/epoch-helpers';
16
16
  import { InboxLeaf } from '@aztec/stdlib/messaging';
17
+ import { ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
17
18
  import {
18
19
  makeAndSignCommitteeAttestationsAndSigners,
19
20
  makeCheckpointAttestationFromCheckpoint,
@@ -22,7 +23,16 @@ import {
22
23
  import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
23
24
 
24
25
  import { type MockProxy, mock } from 'jest-mock-extended';
25
- import { type FormattedBlock, type Transaction, encodeFunctionData, multicall3Abi, toHex } from 'viem';
26
+ import {
27
+ type AbiParameter,
28
+ type FormattedBlock,
29
+ type Transaction,
30
+ encodeAbiParameters,
31
+ encodeFunctionData,
32
+ keccak256,
33
+ multicall3Abi,
34
+ toHex,
35
+ } from 'viem';
26
36
 
27
37
  import { updateRollingHash } from '../structs/inbox_message.js';
28
38
 
@@ -87,6 +97,10 @@ type CheckpointData = {
87
97
  blobHashes: `0x${string}`[];
88
98
  blobs: Blob[];
89
99
  signers: Secp256k1Signer[];
100
+ /** Hash of the packed attestations, matching what the L1 event emits. */
101
+ attestationsHash: Buffer32;
102
+ /** Payload digest, matching what the L1 event emits. */
103
+ payloadDigest: Buffer32;
90
104
  /** If true, archiveAt will ignore it */
91
105
  pruned?: boolean;
92
106
  };
@@ -131,6 +145,7 @@ export class FakeL1State {
131
145
  private provenCheckpointNumber: CheckpointNumber = CheckpointNumber(0);
132
146
  private targetCommitteeSize: number = 0;
133
147
  private version: bigint = 1n;
148
+ private canPruneResult: boolean = false;
134
149
 
135
150
  // Computed from checkpoints based on L1 block visibility
136
151
  private pendingCheckpointNumber: CheckpointNumber = CheckpointNumber(0);
@@ -193,10 +208,10 @@ export class FakeL1State {
193
208
  // Store the messages internally so they match the checkpoint's inHash
194
209
  this.addMessages(checkpointNumber, messagesL1BlockNumber, messages);
195
210
 
196
- // Create the transaction and blobs
197
- const tx = this.makeRollupTx(checkpoint, signers);
198
- const blobHashes = this.makeVersionedBlobHashes(checkpoint);
199
- const blobs = this.makeBlobsFromCheckpoint(checkpoint);
211
+ // Create the transaction, blobs, and event hashes
212
+ const { tx, attestationsHash, payloadDigest } = await this.makeRollupTx(checkpoint, signers);
213
+ const blobHashes = await this.makeVersionedBlobHashes(checkpoint);
214
+ const blobs = await this.makeBlobsFromCheckpoint(checkpoint);
200
215
 
201
216
  // Store the checkpoint data
202
217
  this.checkpoints.push({
@@ -207,6 +222,8 @@ export class FakeL1State {
207
222
  blobHashes,
208
223
  blobs,
209
224
  signers,
225
+ attestationsHash,
226
+ payloadDigest,
210
227
  });
211
228
 
212
229
  // Update last archive for auto-chaining
@@ -276,6 +293,11 @@ export class FakeL1State {
276
293
  this.targetCommitteeSize = size;
277
294
  }
278
295
 
296
+ /** Sets whether the rollup contract would allow pruning at the next block. */
297
+ setCanPrune(value: boolean): void {
298
+ this.canPruneResult = value;
299
+ }
300
+
279
301
  /**
280
302
  * Removes all entries for a checkpoint number (simulates L1 reorg or prune).
281
303
  * Note: Does NOT remove messages for this checkpoint (use numL1ToL2Messages: 0 when re-adding).
@@ -384,6 +406,8 @@ export class FakeL1State {
384
406
  });
385
407
  });
386
408
 
409
+ mockRollup.canPruneAtTime.mockImplementation(() => Promise.resolve(this.canPruneResult));
410
+
387
411
  // Mock the wrapper method for fetching checkpoint events
388
412
  mockRollup.getCheckpointProposedEvents.mockImplementation((fromBlock: bigint, toBlock: bigint) =>
389
413
  Promise.resolve(this.getCheckpointProposedLogs(fromBlock, toBlock)),
@@ -502,10 +526,8 @@ export class FakeL1State {
502
526
  checkpointNumber: cpData.checkpointNumber,
503
527
  archive: cpData.checkpoint.archive.root,
504
528
  versionedBlobHashes: cpData.blobHashes.map(h => Buffer.from(h.slice(2), 'hex')),
505
- // These are intentionally undefined to skip hash validation in the archiver
506
- // (validation is skipped when these fields are falsy)
507
- payloadDigest: undefined,
508
- attestationsHash: undefined,
529
+ attestationsHash: cpData.attestationsHash,
530
+ payloadDigest: cpData.payloadDigest,
509
531
  },
510
532
  }));
511
533
  }
@@ -531,14 +553,17 @@ export class FakeL1State {
531
553
  }));
532
554
  }
533
555
 
534
- private makeRollupTx(checkpoint: Checkpoint, signers: Secp256k1Signer[]): Transaction {
556
+ private async makeRollupTx(
557
+ checkpoint: Checkpoint,
558
+ signers: Secp256k1Signer[],
559
+ ): Promise<{ tx: Transaction; attestationsHash: Buffer32; payloadDigest: Buffer32 }> {
535
560
  const attestations = signers
536
561
  .map(signer => makeCheckpointAttestationFromCheckpoint(checkpoint, signer))
537
562
  .map(attestation => CommitteeAttestation.fromSignature(attestation.signature))
538
563
  .map(committeeAttestation => committeeAttestation.toViem());
539
564
 
540
565
  const header = checkpoint.header.toViem();
541
- const blobInput = getPrefixedEthBlobCommitments(getBlobsPerL1Block(checkpoint.toBlobFields()));
566
+ const blobInput = getPrefixedEthBlobCommitments(await getBlobsPerL1Block(checkpoint.toBlobFields()));
542
567
  const archive = toHex(checkpoint.archive.root.toBuffer());
543
568
  const attestationsAndSigners = new CommitteeAttestationsAndSigners(
544
569
  attestations.map(attestation => CommitteeAttestation.fromViem(attestation)),
@@ -549,6 +574,8 @@ export class FakeL1State {
549
574
  signers[0],
550
575
  );
551
576
 
577
+ const packedAttestations = attestationsAndSigners.getPackedAttestations();
578
+
552
579
  const rollupInput = encodeFunctionData({
553
580
  abi: RollupAbi,
554
581
  functionName: 'propose',
@@ -558,7 +585,7 @@ export class FakeL1State {
558
585
  archive,
559
586
  oracleInput: { feeAssetPriceModifier: 0n },
560
587
  },
561
- attestationsAndSigners.getPackedAttestations(),
588
+ packedAttestations,
562
589
  attestationsAndSigners.getSigners().map(signer => signer.toString()),
563
590
  attestationsAndSignersSignature.toViemSignature(),
564
591
  blobInput,
@@ -579,21 +606,52 @@ export class FakeL1State {
579
606
  ],
580
607
  });
581
608
 
582
- return {
609
+ // Compute attestationsHash (same logic as CalldataRetriever)
610
+ const attestationsHash = Buffer32.fromString(
611
+ keccak256(encodeAbiParameters([this.getCommitteeAttestationsStructDef()], [packedAttestations])),
612
+ );
613
+
614
+ // 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));
618
+
619
+ const tx = {
583
620
  input: multiCallInput,
584
621
  hash: archive,
585
622
  blockHash: archive,
586
623
  to: MULTI_CALL_3_ADDRESS as `0x${string}`,
587
624
  } as Transaction<bigint, number>;
625
+
626
+ return { tx, attestationsHash, payloadDigest };
627
+ }
628
+
629
+ /** Extracts the CommitteeAttestations struct definition from RollupAbi for hash computation. */
630
+ private getCommitteeAttestationsStructDef(): AbiParameter {
631
+ const proposeFunction = RollupAbi.find(item => item.type === 'function' && item.name === 'propose') as
632
+ | { type: 'function'; name: string; inputs: readonly AbiParameter[] }
633
+ | undefined;
634
+
635
+ if (!proposeFunction) {
636
+ throw new Error('propose function not found in RollupAbi');
637
+ }
638
+
639
+ const attestationsParam = proposeFunction.inputs.find(param => param.name === '_attestations');
640
+ if (!attestationsParam) {
641
+ throw new Error('_attestations parameter not found in propose function');
642
+ }
643
+
644
+ const tupleParam = attestationsParam as unknown as { type: 'tuple'; components?: readonly AbiParameter[] };
645
+ return { type: 'tuple', components: tupleParam.components || [] } as AbiParameter;
588
646
  }
589
647
 
590
- private makeVersionedBlobHashes(checkpoint: Checkpoint): `0x${string}`[] {
591
- return getBlobsPerL1Block(checkpoint.toBlobFields()).map(
648
+ private async makeVersionedBlobHashes(checkpoint: Checkpoint): Promise<`0x${string}`[]> {
649
+ return (await getBlobsPerL1Block(checkpoint.toBlobFields())).map(
592
650
  b => `0x${b.getEthVersionedBlobHash().toString('hex')}` as `0x${string}`,
593
651
  );
594
652
  }
595
653
 
596
- private makeBlobsFromCheckpoint(checkpoint: Checkpoint): Blob[] {
597
- return getBlobsPerL1Block(checkpoint.toBlobFields());
654
+ private async makeBlobsFromCheckpoint(checkpoint: Checkpoint): Promise<Blob[]> {
655
+ return await getBlobsPerL1Block(checkpoint.toBlobFields());
598
656
  }
599
657
  }
@@ -56,8 +56,9 @@ export class MockPrefilledArchiver extends MockArchiver {
56
56
  }
57
57
 
58
58
  const fromBlock = this.l2Blocks.length;
59
- // TODO: Add L2 blocks and checkpoints separately once archiver has the apis for that.
60
- this.addProposedBlocks(this.prefilled.slice(fromBlock, fromBlock + numBlocks).flatMap(c => c.blocks));
59
+ const checkpointsToAdd = this.prefilled.slice(fromBlock, fromBlock + numBlocks);
60
+ this.addProposedBlocks(checkpointsToAdd.flatMap(c => c.blocks));
61
+ this.checkpointList.push(...checkpointsToAdd);
61
62
  return Promise.resolve();
62
63
  }
63
64
  }
@@ -8,6 +8,7 @@ import { createLogger } from '@aztec/foundation/log';
8
8
  import type { FunctionSelector } from '@aztec/stdlib/abi';
9
9
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
10
10
  import {
11
+ type BlockData,
11
12
  BlockHash,
12
13
  CheckpointedL2Block,
13
14
  L2Block,
@@ -15,9 +16,11 @@ import {
15
16
  type L2Tips,
16
17
  type ValidateCheckpointResult,
17
18
  } from '@aztec/stdlib/block';
18
- import { Checkpoint, L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
19
+ import { Checkpoint, type CheckpointData, L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
19
20
  import type { ContractClassPublic, ContractDataSource, ContractInstanceWithAddress } from '@aztec/stdlib/contract';
20
21
  import { EmptyL1RollupConstants, type L1RollupConstants, getSlotRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
22
+ import { computeCheckpointOutHash } from '@aztec/stdlib/messaging';
23
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
21
24
  import { type BlockHeader, TxExecutionResult, TxHash, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
22
25
  import type { UInt64 } from '@aztec/stdlib/types';
23
26
 
@@ -26,6 +29,7 @@ import type { UInt64 } from '@aztec/stdlib/types';
26
29
  */
27
30
  export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
28
31
  protected l2Blocks: L2Block[] = [];
32
+ protected checkpointList: Checkpoint[] = [];
29
33
 
30
34
  private provenBlockNumber: number = 0;
31
35
  private finalizedBlockNumber: number = 0;
@@ -33,14 +37,30 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
33
37
 
34
38
  private log = createLogger('archiver:mock_l2_block_source');
35
39
 
40
+ /** Creates blocks grouped into single-block checkpoints. */
36
41
  public async createBlocks(numBlocks: number) {
37
- for (let i = 0; i < numBlocks; i++) {
38
- const blockNum = this.l2Blocks.length + 1;
39
- const block = await L2Block.random(BlockNumber(blockNum), { slotNumber: SlotNumber(blockNum) });
40
- this.l2Blocks.push(block);
42
+ await this.createCheckpoints(numBlocks, 1);
43
+ }
44
+
45
+ /** Creates checkpoints, each containing `blocksPerCheckpoint` blocks. */
46
+ public async createCheckpoints(numCheckpoints: number, blocksPerCheckpoint: number = 1) {
47
+ for (let c = 0; c < numCheckpoints; c++) {
48
+ const checkpointNum = CheckpointNumber(this.checkpointList.length + 1);
49
+ const startBlockNum = this.l2Blocks.length + 1;
50
+ const slotNumber = SlotNumber(Number(checkpointNum));
51
+ const checkpoint = await Checkpoint.random(checkpointNum, {
52
+ numBlocks: blocksPerCheckpoint,
53
+ startBlockNumber: startBlockNum,
54
+ slotNumber,
55
+ checkpointNumber: checkpointNum,
56
+ });
57
+ this.checkpointList.push(checkpoint);
58
+ this.l2Blocks.push(...checkpoint.blocks);
41
59
  }
42
60
 
43
- this.log.verbose(`Created ${numBlocks} blocks in the mock L2 block source`);
61
+ this.log.verbose(
62
+ `Created ${numCheckpoints} checkpoints with ${blocksPerCheckpoint} blocks each in the mock L2 block source`,
63
+ );
44
64
  }
45
65
 
46
66
  public addProposedBlocks(blocks: L2Block[]) {
@@ -50,6 +70,16 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
50
70
 
51
71
  public removeBlocks(numBlocks: number) {
52
72
  this.l2Blocks = this.l2Blocks.slice(0, -numBlocks);
73
+ const maxBlockNum = this.l2Blocks.length;
74
+ // Remove any checkpoint whose last block is beyond the remaining blocks.
75
+ this.checkpointList = this.checkpointList.filter(c => {
76
+ const lastBlockNum = c.blocks[0].number + c.blocks.length - 1;
77
+ return lastBlockNum <= maxBlockNum;
78
+ });
79
+ // Keep tip numbers consistent with remaining blocks.
80
+ this.checkpointedBlockNumber = Math.min(this.checkpointedBlockNumber, maxBlockNum);
81
+ this.provenBlockNumber = Math.min(this.provenBlockNumber, maxBlockNum);
82
+ this.finalizedBlockNumber = Math.min(this.finalizedBlockNumber, maxBlockNum);
53
83
  this.log.verbose(`Removed ${numBlocks} blocks from the mock L2 block source`);
54
84
  }
55
85
 
@@ -65,7 +95,33 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
65
95
  }
66
96
 
67
97
  public setCheckpointedBlockNumber(checkpointedBlockNumber: number) {
98
+ const prevCheckpointed = this.checkpointedBlockNumber;
68
99
  this.checkpointedBlockNumber = checkpointedBlockNumber;
100
+ // Auto-create single-block checkpoints for newly checkpointed blocks that don't have one yet.
101
+ // This handles blocks added via addProposedBlocks that are now being marked as checkpointed.
102
+ const newCheckpoints: Checkpoint[] = [];
103
+ for (let blockNum = prevCheckpointed + 1; blockNum <= checkpointedBlockNumber; blockNum++) {
104
+ const block = this.l2Blocks[blockNum - 1];
105
+ if (!block) {
106
+ continue;
107
+ }
108
+ if (this.checkpointList.some(c => c.blocks.some(b => b.number === block.number))) {
109
+ continue;
110
+ }
111
+ const checkpointNum = CheckpointNumber(this.checkpointList.length + newCheckpoints.length + 1);
112
+ const checkpoint = new Checkpoint(
113
+ block.archive,
114
+ CheckpointHeader.random({ slotNumber: block.header.globalVariables.slotNumber }),
115
+ [block],
116
+ checkpointNum,
117
+ );
118
+ newCheckpoints.push(checkpoint);
119
+ }
120
+ // Insert new checkpoints in order by number.
121
+ if (newCheckpoints.length > 0) {
122
+ this.checkpointList.push(...newCheckpoints);
123
+ this.checkpointList.sort((a, b) => a.number - b.number);
124
+ }
69
125
  }
70
126
 
71
127
  /**
@@ -112,13 +168,7 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
112
168
  if (!block) {
113
169
  return Promise.resolve(undefined);
114
170
  }
115
- const checkpointedBlock = new CheckpointedL2Block(
116
- CheckpointNumber.fromBlockNumber(number),
117
- block,
118
- new L1PublishedData(BigInt(number), BigInt(number), `0x${number.toString(16).padStart(64, '0')}`),
119
- [],
120
- );
121
- return Promise.resolve(checkpointedBlock);
171
+ return Promise.resolve(this.toCheckpointedBlock(block));
122
172
  }
123
173
 
124
174
  public async getCheckpointedBlocks(from: BlockNumber, limit: number): Promise<CheckpointedL2Block[]> {
@@ -167,44 +217,22 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
167
217
  }
168
218
 
169
219
  public getCheckpoints(from: CheckpointNumber, limit: number) {
170
- // TODO(mbps): Implement this properly. This only works when we have one block per checkpoint.
171
- const blocks = this.l2Blocks.slice(from - 1, from - 1 + limit);
172
- return Promise.all(
173
- blocks.map(async block => {
174
- // Create a checkpoint from the block - manually construct since L2Block doesn't have toCheckpoint()
175
- const checkpoint = await Checkpoint.random(block.checkpointNumber, { numBlocks: 1 });
176
- checkpoint.blocks = [block];
177
- return new PublishedCheckpoint(
178
- checkpoint,
179
- new L1PublishedData(BigInt(block.number), BigInt(block.number), Buffer32.random().toString()),
180
- [],
181
- );
182
- }),
220
+ const checkpoints = this.checkpointList.slice(from - 1, from - 1 + limit);
221
+ return Promise.resolve(
222
+ checkpoints.map(checkpoint => new PublishedCheckpoint(checkpoint, this.mockL1DataForCheckpoint(checkpoint), [])),
183
223
  );
184
224
  }
185
225
 
186
- public async getCheckpointByArchive(archive: Fr): Promise<Checkpoint | undefined> {
187
- // TODO(mbps): Implement this properly. This only works when we have one block per checkpoint.
188
- const block = this.l2Blocks.find(b => b.archive.root.equals(archive));
189
- if (!block) {
190
- return undefined;
191
- }
192
- // Create a checkpoint from the block - manually construct since L2Block doesn't have toCheckpoint()
193
- const checkpoint = await Checkpoint.random(block.checkpointNumber, { numBlocks: 1 });
194
- checkpoint.blocks = [block];
195
- return checkpoint;
226
+ public getCheckpointByArchive(archive: Fr): Promise<Checkpoint | undefined> {
227
+ const checkpoint = this.checkpointList.find(c => c.archive.root.equals(archive));
228
+ return Promise.resolve(checkpoint);
196
229
  }
197
230
 
198
231
  public async getCheckpointedBlockByHash(blockHash: BlockHash): Promise<CheckpointedL2Block | undefined> {
199
232
  for (const block of this.l2Blocks) {
200
233
  const hash = await block.hash();
201
234
  if (hash.equals(blockHash)) {
202
- return CheckpointedL2Block.fromFields({
203
- checkpointNumber: CheckpointNumber.fromBlockNumber(block.number),
204
- block,
205
- l1: new L1PublishedData(BigInt(block.number), BigInt(block.number), Buffer32.random().toString()),
206
- attestations: [],
207
- });
235
+ return this.toCheckpointedBlock(block);
208
236
  }
209
237
  }
210
238
  return undefined;
@@ -215,14 +243,7 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
215
243
  if (!block) {
216
244
  return Promise.resolve(undefined);
217
245
  }
218
- return Promise.resolve(
219
- CheckpointedL2Block.fromFields({
220
- checkpointNumber: CheckpointNumber.fromBlockNumber(block.number),
221
- block,
222
- l1: new L1PublishedData(BigInt(block.number), BigInt(block.number), Buffer32.random().toString()),
223
- attestations: [],
224
- }),
225
- );
246
+ return Promise.resolve(this.toCheckpointedBlock(block));
226
247
  }
227
248
 
228
249
  public async getL2BlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
@@ -255,47 +276,69 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
255
276
  return Promise.resolve(block?.header);
256
277
  }
257
278
 
279
+ public async getBlockData(number: BlockNumber): Promise<BlockData | undefined> {
280
+ const block = this.l2Blocks[number - 1];
281
+ if (!block) {
282
+ return undefined;
283
+ }
284
+ return {
285
+ header: block.header,
286
+ archive: block.archive,
287
+ blockHash: await block.hash(),
288
+ checkpointNumber: block.checkpointNumber,
289
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
290
+ };
291
+ }
292
+
293
+ public async getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
294
+ const block = this.l2Blocks.find(b => b.archive.root.equals(archive));
295
+ if (!block) {
296
+ return undefined;
297
+ }
298
+ return {
299
+ header: block.header,
300
+ archive: block.archive,
301
+ blockHash: await block.hash(),
302
+ checkpointNumber: block.checkpointNumber,
303
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
304
+ };
305
+ }
306
+
258
307
  getBlockHeader(number: number | 'latest'): Promise<BlockHeader | undefined> {
259
308
  return Promise.resolve(this.l2Blocks.at(typeof number === 'number' ? number - 1 : -1)?.header);
260
309
  }
261
310
 
262
311
  getCheckpointsForEpoch(epochNumber: EpochNumber): Promise<Checkpoint[]> {
263
- // TODO(mbps): Implement this properly. This only works when we have one block per checkpoint.
264
- const epochDuration = DefaultL1ContractsConfig.aztecEpochDuration;
265
- const [start, end] = getSlotRangeForEpoch(epochNumber, { epochDuration });
266
- const blocks = this.l2Blocks.filter(b => {
267
- const slot = b.header.globalVariables.slotNumber;
268
- return slot >= start && slot <= end;
269
- });
270
- // Create checkpoints from blocks - manually construct since L2Block doesn't have toCheckpoint()
271
- return Promise.all(
272
- blocks.map(async block => {
273
- const checkpoint = await Checkpoint.random(block.checkpointNumber, { numBlocks: 1 });
274
- checkpoint.blocks = [block];
275
- return checkpoint;
276
- }),
277
- );
312
+ return Promise.resolve(this.getCheckpointsInEpoch(epochNumber));
278
313
  }
279
314
 
280
- getCheckpointedBlocksForEpoch(epochNumber: EpochNumber): Promise<CheckpointedL2Block[]> {
281
- const epochDuration = DefaultL1ContractsConfig.aztecEpochDuration;
282
- const [start, end] = getSlotRangeForEpoch(epochNumber, { epochDuration });
283
- const blocks = this.l2Blocks.filter(b => {
284
- const slot = b.header.globalVariables.slotNumber;
285
- return slot >= start && slot <= end;
286
- });
315
+ getCheckpointsDataForEpoch(epochNumber: EpochNumber): Promise<CheckpointData[]> {
316
+ const checkpoints = this.getCheckpointsInEpoch(epochNumber);
287
317
  return Promise.resolve(
288
- blocks.map(block =>
289
- CheckpointedL2Block.fromFields({
290
- checkpointNumber: CheckpointNumber.fromBlockNumber(block.number),
291
- block,
292
- l1: new L1PublishedData(BigInt(block.number), BigInt(block.number), Buffer32.random().toString()),
318
+ checkpoints.map(
319
+ (checkpoint): CheckpointData => ({
320
+ checkpointNumber: checkpoint.number,
321
+ header: checkpoint.header,
322
+ archive: checkpoint.archive,
323
+ checkpointOutHash: computeCheckpointOutHash(
324
+ checkpoint.blocks.map(b => b.body.txEffects.map(tx => tx.l2ToL1Msgs)),
325
+ ),
326
+ startBlock: checkpoint.blocks[0].number,
327
+ blockCount: checkpoint.blocks.length,
293
328
  attestations: [],
329
+ l1: this.mockL1DataForCheckpoint(checkpoint),
294
330
  }),
295
331
  ),
296
332
  );
297
333
  }
298
334
 
335
+ getCheckpointedBlocksForEpoch(epochNumber: EpochNumber): Promise<CheckpointedL2Block[]> {
336
+ const checkpoints = this.getCheckpointsInEpoch(epochNumber);
337
+ return Promise.resolve(
338
+ checkpoints.flatMap(checkpoint => checkpoint.blocks.map(block => this.toCheckpointedBlock(block))),
339
+ );
340
+ }
341
+
299
342
  getBlocksForSlot(slotNumber: SlotNumber): Promise<L2Block[]> {
300
343
  const blocks = this.l2Blocks.filter(b => b.header.globalVariables.slotNumber === slotNumber);
301
344
  return Promise.resolve(blocks);
@@ -384,7 +427,10 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
384
427
 
385
428
  const makeTipId = (blockId: typeof latestBlockId) => ({
386
429
  block: blockId,
387
- checkpoint: { number: CheckpointNumber.fromBlockNumber(blockId.number), hash: blockId.hash },
430
+ checkpoint: {
431
+ number: this.findCheckpointNumberForBlock(blockId.number) ?? CheckpointNumber(0),
432
+ hash: blockId.hash,
433
+ },
388
434
  });
389
435
 
390
436
  return {
@@ -472,4 +518,38 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
472
518
  getPendingChainValidationStatus(): Promise<ValidateCheckpointResult> {
473
519
  return Promise.resolve({ valid: true });
474
520
  }
521
+
522
+ /** Returns checkpoints whose slot falls within the given epoch. */
523
+ private getCheckpointsInEpoch(epochNumber: EpochNumber): Checkpoint[] {
524
+ const epochDuration = DefaultL1ContractsConfig.aztecEpochDuration;
525
+ const [start, end] = getSlotRangeForEpoch(epochNumber, { epochDuration });
526
+ return this.checkpointList.filter(c => c.header.slotNumber >= start && c.header.slotNumber <= end);
527
+ }
528
+
529
+ /** Creates a mock L1PublishedData for a checkpoint. */
530
+ private mockL1DataForCheckpoint(checkpoint: Checkpoint): L1PublishedData {
531
+ return new L1PublishedData(BigInt(checkpoint.number), BigInt(checkpoint.number), Buffer32.random().toString());
532
+ }
533
+
534
+ /** Creates a CheckpointedL2Block from a block using stored checkpoint info. */
535
+ private toCheckpointedBlock(block: L2Block): CheckpointedL2Block {
536
+ const checkpoint = this.checkpointList.find(c => c.blocks.some(b => b.number === block.number));
537
+ const checkpointNumber = checkpoint?.number ?? block.checkpointNumber;
538
+ return new CheckpointedL2Block(
539
+ checkpointNumber,
540
+ block,
541
+ new L1PublishedData(
542
+ BigInt(block.number),
543
+ BigInt(block.number),
544
+ `0x${block.number.toString(16).padStart(64, '0')}`,
545
+ ),
546
+ [],
547
+ );
548
+ }
549
+
550
+ /** Finds the checkpoint number for a block, or undefined if the block is not in any checkpoint. */
551
+ private findCheckpointNumberForBlock(blockNumber: BlockNumber): CheckpointNumber | undefined {
552
+ const checkpoint = this.checkpointList.find(c => c.blocks.some(b => b.number === blockNumber));
553
+ return checkpoint?.number;
554
+ }
475
555
  }