@aztec/archiver 0.0.1-commit.cf93bcc56 → 0.0.1-commit.d0fcfb7f

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 (66) hide show
  1. package/dest/archiver.d.ts +3 -3
  2. package/dest/archiver.d.ts.map +1 -1
  3. package/dest/archiver.js +46 -14
  4. package/dest/factory.d.ts +1 -1
  5. package/dest/factory.d.ts.map +1 -1
  6. package/dest/factory.js +6 -7
  7. package/dest/l1/bin/retrieve-calldata.js +32 -28
  8. package/dest/l1/calldata_retriever.d.ts +70 -53
  9. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  10. package/dest/l1/calldata_retriever.js +178 -260
  11. package/dest/l1/data_retrieval.d.ts +2 -6
  12. package/dest/l1/data_retrieval.d.ts.map +1 -1
  13. package/dest/l1/data_retrieval.js +6 -11
  14. package/dest/l1/spire_proposer.d.ts +5 -5
  15. package/dest/l1/spire_proposer.d.ts.map +1 -1
  16. package/dest/l1/spire_proposer.js +9 -17
  17. package/dest/modules/data_source_base.d.ts +3 -3
  18. package/dest/modules/data_source_base.d.ts.map +1 -1
  19. package/dest/modules/data_source_base.js +1 -1
  20. package/dest/modules/data_store_updater.d.ts +6 -3
  21. package/dest/modules/data_store_updater.d.ts.map +1 -1
  22. package/dest/modules/data_store_updater.js +10 -2
  23. package/dest/modules/l1_synchronizer.d.ts +2 -7
  24. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  25. package/dest/modules/l1_synchronizer.js +6 -6
  26. package/dest/store/block_store.d.ts +5 -5
  27. package/dest/store/block_store.d.ts.map +1 -1
  28. package/dest/store/block_store.js +10 -7
  29. package/dest/store/kv_archiver_store.d.ts +2 -2
  30. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  31. package/dest/store/kv_archiver_store.js +2 -2
  32. package/dest/store/log_store.d.ts +1 -1
  33. package/dest/store/log_store.d.ts.map +1 -1
  34. package/dest/store/log_store.js +19 -1
  35. package/dest/store/message_store.js +1 -1
  36. package/dest/test/fake_l1_state.d.ts +3 -1
  37. package/dest/test/fake_l1_state.d.ts.map +1 -1
  38. package/dest/test/fake_l1_state.js +42 -10
  39. package/dest/test/mock_l2_block_source.d.ts +4 -3
  40. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  41. package/dest/test/mock_l2_block_source.js +7 -4
  42. package/dest/test/mock_structs.d.ts +4 -1
  43. package/dest/test/mock_structs.d.ts.map +1 -1
  44. package/dest/test/mock_structs.js +13 -1
  45. package/dest/test/noop_l1_archiver.d.ts +4 -1
  46. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  47. package/dest/test/noop_l1_archiver.js +5 -1
  48. package/package.json +13 -13
  49. package/src/archiver.ts +57 -17
  50. package/src/factory.ts +3 -1
  51. package/src/l1/README.md +25 -68
  52. package/src/l1/bin/retrieve-calldata.ts +40 -27
  53. package/src/l1/calldata_retriever.ts +231 -383
  54. package/src/l1/data_retrieval.ts +3 -16
  55. package/src/l1/spire_proposer.ts +7 -15
  56. package/src/modules/data_source_base.ts +3 -3
  57. package/src/modules/data_store_updater.ts +7 -2
  58. package/src/modules/l1_synchronizer.ts +8 -10
  59. package/src/store/block_store.ts +14 -6
  60. package/src/store/kv_archiver_store.ts +5 -2
  61. package/src/store/log_store.ts +24 -1
  62. package/src/store/message_store.ts +1 -1
  63. package/src/test/fake_l1_state.ts +60 -10
  64. package/src/test/mock_l2_block_source.ts +15 -3
  65. package/src/test/mock_structs.ts +20 -6
  66. package/src/test/noop_l1_archiver.ts +7 -1
@@ -157,11 +157,6 @@ export async function retrieveCheckpointsFromRollup(
157
157
  blobClient: BlobClientInterface,
158
158
  searchStartBlock: bigint,
159
159
  searchEndBlock: bigint,
160
- contractAddresses: {
161
- governanceProposerAddress: EthAddress;
162
- slashFactoryAddress?: EthAddress;
163
- slashingProposerAddress: EthAddress;
164
- },
165
160
  instrumentation: ArchiverInstrumentation,
166
161
  logger: Logger = createLogger('archiver'),
167
162
  isHistoricalSync: boolean = false,
@@ -205,7 +200,6 @@ export async function retrieveCheckpointsFromRollup(
205
200
  blobClient,
206
201
  checkpointProposedLogs,
207
202
  rollupConstants,
208
- contractAddresses,
209
203
  instrumentation,
210
204
  logger,
211
205
  isHistoricalSync,
@@ -226,7 +220,6 @@ export async function retrieveCheckpointsFromRollup(
226
220
  * @param blobClient - The blob client client for fetching blob data.
227
221
  * @param logs - CheckpointProposed logs.
228
222
  * @param rollupConstants - The rollup constants (chainId, version, targetCommitteeSize).
229
- * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
230
223
  * @param instrumentation - The archiver instrumentation instance.
231
224
  * @param logger - The logger instance.
232
225
  * @param isHistoricalSync - Whether this is a historical sync.
@@ -239,11 +232,6 @@ async function processCheckpointProposedLogs(
239
232
  blobClient: BlobClientInterface,
240
233
  logs: CheckpointProposedLog[],
241
234
  { chainId, version, targetCommitteeSize }: { chainId: Fr; version: Fr; targetCommitteeSize: number },
242
- contractAddresses: {
243
- governanceProposerAddress: EthAddress;
244
- slashFactoryAddress?: EthAddress;
245
- slashingProposerAddress: EthAddress;
246
- },
247
235
  instrumentation: ArchiverInstrumentation,
248
236
  logger: Logger,
249
237
  isHistoricalSync: boolean,
@@ -255,7 +243,7 @@ async function processCheckpointProposedLogs(
255
243
  targetCommitteeSize,
256
244
  instrumentation,
257
245
  logger,
258
- { ...contractAddresses, rollupAddress: EthAddress.fromString(rollup.address) },
246
+ EthAddress.fromString(rollup.address),
259
247
  );
260
248
 
261
249
  await asyncPool(10, logs, async log => {
@@ -266,10 +254,9 @@ async function processCheckpointProposedLogs(
266
254
 
267
255
  // The value from the event and contract will match only if the checkpoint is in the chain.
268
256
  if (archive.equals(archiveFromChain)) {
269
- // Build expected hashes object (fields may be undefined for backwards compatibility with older events)
270
257
  const expectedHashes = {
271
- attestationsHash: log.args.attestationsHash?.toString(),
272
- payloadDigest: log.args.payloadDigest?.toString(),
258
+ attestationsHash: log.args.attestationsHash.toString() as Hex,
259
+ payloadDigest: log.args.payloadDigest.toString() as Hex,
273
260
  };
274
261
 
275
262
  const checkpoint = await calldataRetriever.getCheckpointFromRollupTx(
@@ -87,17 +87,17 @@ export async function verifyProxyImplementation(
87
87
  /**
88
88
  * Attempts to decode transaction as a Spire Proposer Multicall.
89
89
  * Spire Proposer is a proxy contract that wraps multiple calls.
90
- * Returns the target address and calldata of the wrapped call if validation succeeds and there is a single call.
90
+ * Returns all wrapped calls if validation succeeds (caller handles hash matching to find the propose call).
91
91
  * @param tx - The transaction to decode
92
92
  * @param publicClient - The viem public client for proxy verification
93
93
  * @param logger - Logger instance
94
- * @returns Object with 'to' and 'data' of the wrapped call, or undefined if validation fails
94
+ * @returns Array of wrapped calls with 'to' and 'data', or undefined if not a valid Spire Proposer tx
95
95
  */
96
- export async function getCallFromSpireProposer(
96
+ export async function getCallsFromSpireProposer(
97
97
  tx: Transaction,
98
98
  publicClient: { getStorageAt: (params: { address: Hex; slot: Hex }) => Promise<Hex | undefined> },
99
99
  logger: Logger,
100
- ): Promise<{ to: Hex; data: Hex } | undefined> {
100
+ ): Promise<{ to: Hex; data: Hex }[] | undefined> {
101
101
  const txHash = tx.hash;
102
102
 
103
103
  try {
@@ -141,17 +141,9 @@ export async function getCallFromSpireProposer(
141
141
 
142
142
  const [calls] = spireArgs;
143
143
 
144
- // Validate exactly ONE call (see ./README.md for rationale)
145
- if (calls.length !== 1) {
146
- logger.warn(`Spire Proposer multicall must contain exactly one call (got ${calls.length})`, { txHash });
147
- return undefined;
148
- }
149
-
150
- const call = calls[0];
151
-
152
- // Successfully extracted the single wrapped call
153
- logger.trace(`Decoded Spire Proposer with single call to ${call.target}`, { txHash });
154
- return { to: call.target, data: call.data };
144
+ // Return all wrapped calls (hash matching in the caller determines which is the propose call)
145
+ logger.trace(`Decoded Spire Proposer with ${calls.length} call(s)`, { txHash });
146
+ return calls.map(call => ({ to: call.target, data: call.data }));
155
147
  } catch (err) {
156
148
  // Any decoding error triggers fallback to trace
157
149
  logger.warn(`Failed to decode Spire Proposer: ${err}`, { txHash });
@@ -46,9 +46,9 @@ export abstract class ArchiverDataSourceBase
46
46
 
47
47
  abstract getL2Tips(): Promise<L2Tips>;
48
48
 
49
- abstract getL2SlotNumber(): Promise<SlotNumber | undefined>;
49
+ abstract getSyncedL2SlotNumber(): Promise<SlotNumber | undefined>;
50
50
 
51
- abstract getL2EpochNumber(): Promise<EpochNumber | undefined>;
51
+ abstract getSyncedL2EpochNumber(): Promise<EpochNumber | undefined>;
52
52
 
53
53
  abstract isEpochComplete(epochNumber: EpochNumber): Promise<boolean>;
54
54
 
@@ -154,7 +154,7 @@ export abstract class ArchiverDataSourceBase
154
154
  }
155
155
 
156
156
  public getSettledTxReceipt(txHash: TxHash): Promise<TxReceipt | undefined> {
157
- return this.store.getSettledTxReceipt(txHash);
157
+ return this.store.getSettledTxReceipt(txHash, this.l1Constants);
158
158
  }
159
159
 
160
160
  public isPendingChainInvalid(): Promise<boolean> {
@@ -11,7 +11,7 @@ import {
11
11
  ContractInstanceUpdatedEvent,
12
12
  } from '@aztec/protocol-contracts/instance-registry';
13
13
  import type { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
14
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
14
+ import { type PublishedCheckpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
15
15
  import {
16
16
  type ExecutablePrivateFunctionWithMembershipProof,
17
17
  type UtilityFunctionWithMembershipProof,
@@ -48,6 +48,7 @@ export class ArchiverDataStoreUpdater {
48
48
  constructor(
49
49
  private store: KVArchiverDataStore,
50
50
  private l2TipsCache?: L2TipsCache,
51
+ private opts: { rollupManaLimit?: number } = {},
51
52
  ) {}
52
53
 
53
54
  /**
@@ -97,6 +98,10 @@ export class ArchiverDataStoreUpdater {
97
98
  checkpoints: PublishedCheckpoint[],
98
99
  pendingChainValidationStatus?: ValidateCheckpointResult,
99
100
  ): Promise<ReconcileCheckpointsResult> {
101
+ for (const checkpoint of checkpoints) {
102
+ validateCheckpoint(checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
103
+ }
104
+
100
105
  const result = await this.store.transactionAsync(async () => {
101
106
  // Before adding checkpoints, check for conflicts with local blocks if any
102
107
  const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
@@ -173,7 +178,7 @@ export class ArchiverDataStoreUpdater {
173
178
  this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
174
179
  lastAlreadyInsertedBlockNumber = blockNumber;
175
180
  } else {
176
- this.log.warn(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
181
+ this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
177
182
  const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
178
183
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
179
184
  }
@@ -1,7 +1,6 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import { EpochCache } from '@aztec/epoch-cache';
3
3
  import { InboxContract, RollupContract } from '@aztec/ethereum/contracts';
4
- import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
5
4
  import type { L1BlockId } from '@aztec/ethereum/l1-types';
6
5
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
7
6
  import { maxBigint } from '@aztec/foundation/bigint';
@@ -9,7 +8,6 @@ import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/br
9
8
  import { Buffer32 } from '@aztec/foundation/buffer';
10
9
  import { pick } from '@aztec/foundation/collection';
11
10
  import { Fr } from '@aztec/foundation/curves/bn254';
12
- import { EthAddress } from '@aztec/foundation/eth-address';
13
11
  import { type Logger, createLogger } from '@aztec/foundation/log';
14
12
  import { count } from '@aztec/foundation/string';
15
13
  import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
@@ -61,10 +59,6 @@ export class ArchiverL1Synchronizer implements Traceable {
61
59
  private readonly debugClient: ViemPublicDebugClient,
62
60
  private readonly rollup: RollupContract,
63
61
  private readonly inbox: InboxContract,
64
- private readonly l1Addresses: Pick<
65
- L1ContractAddresses,
66
- 'registryAddress' | 'governanceProposerAddress' | 'slashFactoryAddress'
67
- > & { slashingProposerAddress: EthAddress },
68
62
  private readonly store: KVArchiverDataStore,
69
63
  private config: {
70
64
  batchSize: number;
@@ -75,13 +69,18 @@ export class ArchiverL1Synchronizer implements Traceable {
75
69
  private readonly epochCache: EpochCache,
76
70
  private readonly dateProvider: DateProvider,
77
71
  private readonly instrumentation: ArchiverInstrumentation,
78
- private readonly l1Constants: L1RollupConstants & { l1StartBlockHash: Buffer32; genesisArchiveRoot: Fr },
72
+ private readonly l1Constants: L1RollupConstants & {
73
+ l1StartBlockHash: Buffer32;
74
+ genesisArchiveRoot: Fr;
75
+ },
79
76
  private readonly events: ArchiverEmitter,
80
77
  tracer: Tracer,
81
78
  l2TipsCache?: L2TipsCache,
82
79
  private readonly log: Logger = createLogger('archiver:l1-sync'),
83
80
  ) {
84
- this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache);
81
+ this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache, {
82
+ rollupManaLimit: l1Constants.rollupManaLimit,
83
+ });
85
84
  this.tracer = tracer;
86
85
  }
87
86
 
@@ -708,7 +707,6 @@ export class ArchiverL1Synchronizer implements Traceable {
708
707
  this.blobClient,
709
708
  searchStartBlock, // TODO(palla/reorg): If the L2 reorg was due to an L1 reorg, we need to start search earlier
710
709
  searchEndBlock,
711
- this.l1Addresses,
712
710
  this.instrumentation,
713
711
  this.log,
714
712
  !initialSyncComplete, // isHistoricalSync
@@ -821,7 +819,7 @@ export class ArchiverL1Synchronizer implements Traceable {
821
819
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
822
820
  const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
823
821
 
824
- this.log.warn(
822
+ this.log.info(
825
823
  `Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`,
826
824
  { prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
827
825
  );
@@ -20,7 +20,7 @@ import {
20
20
  serializeValidateCheckpointResult,
21
21
  } from '@aztec/stdlib/block';
22
22
  import { type CheckpointData, L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
23
- import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
23
+ import { type L1RollupConstants, getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
24
24
  import { CheckpointHeader } from '@aztec/stdlib/rollup';
25
25
  import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
26
26
  import {
@@ -130,14 +130,14 @@ export class BlockStore {
130
130
 
131
131
  /**
132
132
  * Computes the finalized block number based on the proven block number.
133
- * A block is considered finalized when it's 2 epochs behind the proven block.
133
+ * We approximate finalization as 2 epochs worth of checkpoints behind the proven block.
134
+ * Each checkpoint is assumed to contain 4 blocks, so the lookback is epochDuration * 2 * 4 blocks.
134
135
  * TODO(#13569): Compute proper finalized block number based on L1 finalized block.
135
- * TODO(palla/mbps): Even the provisional computation is wrong, since it should subtract checkpoints, not blocks
136
136
  * @returns The finalized block number.
137
137
  */
138
138
  async getFinalizedL2BlockNumber(): Promise<BlockNumber> {
139
139
  const provenBlockNumber = await this.getProvenBlockNumber();
140
- return BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2, 0));
140
+ return BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2 * 4, 0));
141
141
  }
142
142
 
143
143
  /**
@@ -871,7 +871,10 @@ export class BlockStore {
871
871
  * @param txHash - The hash of a tx we try to get the receipt for.
872
872
  * @returns The requested tx receipt (or undefined if not found).
873
873
  */
874
- async getSettledTxReceipt(txHash: TxHash): Promise<TxReceipt | undefined> {
874
+ async getSettledTxReceipt(
875
+ txHash: TxHash,
876
+ l1Constants?: Pick<L1RollupConstants, 'epochDuration'>,
877
+ ): Promise<TxReceipt | undefined> {
875
878
  const txEffect = await this.getTxEffect(txHash);
876
879
  if (!txEffect) {
877
880
  return undefined;
@@ -880,10 +883,11 @@ export class BlockStore {
880
883
  const blockNumber = BlockNumber(txEffect.l2BlockNumber);
881
884
 
882
885
  // Use existing archiver methods to determine finalization level
883
- const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber] = await Promise.all([
886
+ const [provenBlockNumber, checkpointedBlockNumber, finalizedBlockNumber, blockData] = await Promise.all([
884
887
  this.getProvenBlockNumber(),
885
888
  this.getCheckpointedL2BlockNumber(),
886
889
  this.getFinalizedL2BlockNumber(),
890
+ this.getBlockData(blockNumber),
887
891
  ]);
888
892
 
889
893
  let status: TxStatus;
@@ -897,6 +901,9 @@ export class BlockStore {
897
901
  status = TxStatus.PROPOSED;
898
902
  }
899
903
 
904
+ const epochNumber =
905
+ blockData && l1Constants ? getEpochAtSlot(blockData.header.globalVariables.slotNumber, l1Constants) : undefined;
906
+
900
907
  return new TxReceipt(
901
908
  txHash,
902
909
  status,
@@ -905,6 +912,7 @@ export class BlockStore {
905
912
  txEffect.data.transactionFee.toBigInt(),
906
913
  txEffect.l2BlockHash,
907
914
  blockNumber,
915
+ epochNumber,
908
916
  );
909
917
  }
910
918
 
@@ -410,8 +410,11 @@ export class KVArchiverDataStore implements ContractDataSource {
410
410
  * @param txHash - The hash of a tx we try to get the receipt for.
411
411
  * @returns The requested tx receipt (or undefined if not found).
412
412
  */
413
- getSettledTxReceipt(txHash: TxHash): Promise<TxReceipt | undefined> {
414
- return this.#blockStore.getSettledTxReceipt(txHash);
413
+ getSettledTxReceipt(
414
+ txHash: TxHash,
415
+ l1Constants?: Pick<L1RollupConstants, 'epochDuration'>,
416
+ ): Promise<TxReceipt | undefined> {
417
+ return this.#blockStore.getSettledTxReceipt(txHash, l1Constants);
415
418
  }
416
419
 
417
420
  /**
@@ -588,11 +588,24 @@ export class LogStore {
588
588
  txLogs: PublicLog[],
589
589
  filter: LogFilter = {},
590
590
  ): boolean {
591
+ if (filter.fromBlock && blockNumber < filter.fromBlock) {
592
+ return false;
593
+ }
594
+ if (filter.toBlock && blockNumber >= filter.toBlock) {
595
+ return false;
596
+ }
597
+ if (filter.txHash && !txHash.equals(filter.txHash)) {
598
+ return false;
599
+ }
600
+
591
601
  let maxLogsHit = false;
592
602
  let logIndex = typeof filter.afterLog?.logIndex === 'number' ? filter.afterLog.logIndex + 1 : 0;
593
603
  for (; logIndex < txLogs.length; logIndex++) {
594
604
  const log = txLogs[logIndex];
595
- if (!filter.contractAddress || log.contractAddress.equals(filter.contractAddress)) {
605
+ if (
606
+ (!filter.contractAddress || log.contractAddress.equals(filter.contractAddress)) &&
607
+ (!filter.tag || log.fields[0]?.equals(filter.tag))
608
+ ) {
596
609
  results.push(
597
610
  new ExtendedPublicLog(new LogId(BlockNumber(blockNumber), blockHash, txHash, txIndex, logIndex), log),
598
611
  );
@@ -616,6 +629,16 @@ export class LogStore {
616
629
  txLogs: ContractClassLog[],
617
630
  filter: LogFilter = {},
618
631
  ): boolean {
632
+ if (filter.fromBlock && blockNumber < filter.fromBlock) {
633
+ return false;
634
+ }
635
+ if (filter.toBlock && blockNumber >= filter.toBlock) {
636
+ return false;
637
+ }
638
+ if (filter.txHash && !txHash.equals(filter.txHash)) {
639
+ return false;
640
+ }
641
+
619
642
  let maxLogsHit = false;
620
643
  let logIndex = typeof filter.afterLog?.logIndex === 'number' ? filter.afterLog.logIndex + 1 : 0;
621
644
  for (; logIndex < txLogs.length; logIndex++) {
@@ -137,7 +137,7 @@ export class MessageStore {
137
137
  );
138
138
  }
139
139
 
140
- // Check the first message in a block has the correct index.
140
+ // Check the first message in a checkpoint has the correct index.
141
141
  if (
142
142
  (!lastMessage || message.checkpointNumber > lastMessage.checkpointNumber) &&
143
143
  message.index !== expectedStart
@@ -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
  };
@@ -194,8 +208,8 @@ export class FakeL1State {
194
208
  // Store the messages internally so they match the checkpoint's inHash
195
209
  this.addMessages(checkpointNumber, messagesL1BlockNumber, messages);
196
210
 
197
- // Create the transaction and blobs
198
- const tx = await this.makeRollupTx(checkpoint, signers);
211
+ // Create the transaction, blobs, and event hashes
212
+ const { tx, attestationsHash, payloadDigest } = await this.makeRollupTx(checkpoint, signers);
199
213
  const blobHashes = await this.makeVersionedBlobHashes(checkpoint);
200
214
  const blobs = await this.makeBlobsFromCheckpoint(checkpoint);
201
215
 
@@ -208,6 +222,8 @@ export class FakeL1State {
208
222
  blobHashes,
209
223
  blobs,
210
224
  signers,
225
+ attestationsHash,
226
+ payloadDigest,
211
227
  });
212
228
 
213
229
  // Update last archive for auto-chaining
@@ -510,10 +526,8 @@ export class FakeL1State {
510
526
  checkpointNumber: cpData.checkpointNumber,
511
527
  archive: cpData.checkpoint.archive.root,
512
528
  versionedBlobHashes: cpData.blobHashes.map(h => Buffer.from(h.slice(2), 'hex')),
513
- // These are intentionally undefined to skip hash validation in the archiver
514
- // (validation is skipped when these fields are falsy)
515
- payloadDigest: undefined,
516
- attestationsHash: undefined,
529
+ attestationsHash: cpData.attestationsHash,
530
+ payloadDigest: cpData.payloadDigest,
517
531
  },
518
532
  }));
519
533
  }
@@ -539,7 +553,10 @@ export class FakeL1State {
539
553
  }));
540
554
  }
541
555
 
542
- private async makeRollupTx(checkpoint: Checkpoint, signers: Secp256k1Signer[]): Promise<Transaction> {
556
+ private async makeRollupTx(
557
+ checkpoint: Checkpoint,
558
+ signers: Secp256k1Signer[],
559
+ ): Promise<{ tx: Transaction; attestationsHash: Buffer32; payloadDigest: Buffer32 }> {
543
560
  const attestations = signers
544
561
  .map(signer => makeCheckpointAttestationFromCheckpoint(checkpoint, signer))
545
562
  .map(attestation => CommitteeAttestation.fromSignature(attestation.signature))
@@ -557,6 +574,8 @@ export class FakeL1State {
557
574
  signers[0],
558
575
  );
559
576
 
577
+ const packedAttestations = attestationsAndSigners.getPackedAttestations();
578
+
560
579
  const rollupInput = encodeFunctionData({
561
580
  abi: RollupAbi,
562
581
  functionName: 'propose',
@@ -566,7 +585,7 @@ export class FakeL1State {
566
585
  archive,
567
586
  oracleInput: { feeAssetPriceModifier: 0n },
568
587
  },
569
- attestationsAndSigners.getPackedAttestations(),
588
+ packedAttestations,
570
589
  attestationsAndSigners.getSigners().map(signer => signer.toString()),
571
590
  attestationsAndSignersSignature.toViemSignature(),
572
591
  blobInput,
@@ -587,12 +606,43 @@ export class FakeL1State {
587
606
  ],
588
607
  });
589
608
 
590
- 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 = {
591
620
  input: multiCallInput,
592
621
  hash: archive,
593
622
  blockHash: archive,
594
623
  to: MULTI_CALL_3_ADDRESS as `0x${string}`,
595
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;
596
646
  }
597
647
 
598
648
  private async makeVersionedBlobHashes(checkpoint: Checkpoint): Promise<`0x${string}`[]> {
@@ -18,7 +18,12 @@ import {
18
18
  } from '@aztec/stdlib/block';
19
19
  import { Checkpoint, type CheckpointData, L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
20
20
  import type { ContractClassPublic, ContractDataSource, ContractInstanceWithAddress } from '@aztec/stdlib/contract';
21
- import { EmptyL1RollupConstants, type L1RollupConstants, getSlotRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
21
+ import {
22
+ EmptyL1RollupConstants,
23
+ type L1RollupConstants,
24
+ getEpochAtSlot,
25
+ getSlotRangeForEpoch,
26
+ } from '@aztec/stdlib/epoch-helpers';
22
27
  import { computeCheckpointOutHash } from '@aztec/stdlib/messaging';
23
28
  import { CheckpointHeader } from '@aztec/stdlib/rollup';
24
29
  import { type BlockHeader, TxExecutionResult, TxHash, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
@@ -42,6 +47,12 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
42
47
  await this.createCheckpoints(numBlocks, 1);
43
48
  }
44
49
 
50
+ public getCheckpointNumber(): Promise<CheckpointNumber> {
51
+ return Promise.resolve(
52
+ this.checkpointList.length === 0 ? CheckpointNumber.ZERO : CheckpointNumber(this.checkpointList.length),
53
+ );
54
+ }
55
+
45
56
  /** Creates checkpoints, each containing `blocksPerCheckpoint` blocks. */
46
57
  public async createCheckpoints(numCheckpoints: number, blocksPerCheckpoint: number = 1) {
47
58
  for (let c = 0; c < numCheckpoints; c++) {
@@ -388,6 +399,7 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
388
399
  txEffect.transactionFee.toBigInt(),
389
400
  await block.hash(),
390
401
  block.number,
402
+ getEpochAtSlot(block.slot, EmptyL1RollupConstants),
391
403
  );
392
404
  }
393
405
  }
@@ -441,11 +453,11 @@ export class MockL2BlockSource implements L2BlockSource, ContractDataSource {
441
453
  };
442
454
  }
443
455
 
444
- getL2EpochNumber(): Promise<EpochNumber> {
456
+ getSyncedL2EpochNumber(): Promise<EpochNumber> {
445
457
  throw new Error('Method not implemented.');
446
458
  }
447
459
 
448
- getL2SlotNumber(): Promise<SlotNumber> {
460
+ getSyncedL2SlotNumber(): Promise<SlotNumber> {
449
461
  throw new Error('Method not implemented.');
450
462
  }
451
463
 
@@ -127,6 +127,25 @@ export function makeL1PublishedData(l1BlockNumber: number): L1PublishedData {
127
127
  return new L1PublishedData(BigInt(l1BlockNumber), BigInt(l1BlockNumber * 1000), makeBlockHash(l1BlockNumber));
128
128
  }
129
129
 
130
+ /** Creates a Checkpoint from a list of blocks with a header that matches the blocks' structure. */
131
+ export function makeCheckpoint(blocks: L2Block[], checkpointNumber = CheckpointNumber(1)): Checkpoint {
132
+ const firstBlock = blocks[0];
133
+ const { slotNumber, timestamp, coinbase, feeRecipient, gasFees } = firstBlock.header.globalVariables;
134
+ return new Checkpoint(
135
+ blocks.at(-1)!.archive,
136
+ CheckpointHeader.random({
137
+ lastArchiveRoot: firstBlock.header.lastArchive.root,
138
+ slotNumber,
139
+ timestamp,
140
+ coinbase,
141
+ feeRecipient,
142
+ gasFees,
143
+ }),
144
+ blocks,
145
+ checkpointNumber,
146
+ );
147
+ }
148
+
130
149
  /** Wraps a Checkpoint with L1 published data and random attestations. */
131
150
  export function makePublishedCheckpoint(
132
151
  checkpoint: Checkpoint,
@@ -301,11 +320,6 @@ export async function makeCheckpointWithLogs(
301
320
  return txEffect;
302
321
  });
303
322
 
304
- const checkpoint = new Checkpoint(
305
- AppendOnlyTreeSnapshot.random(),
306
- CheckpointHeader.random(),
307
- [block],
308
- CheckpointNumber.fromBlockNumber(BlockNumber(blockNumber)),
309
- );
323
+ const checkpoint = makeCheckpoint([block], CheckpointNumber.fromBlockNumber(BlockNumber(blockNumber)));
310
324
  return makePublishedCheckpoint(checkpoint, blockNumber);
311
325
  }
@@ -1,6 +1,7 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import type { RollupContract } from '@aztec/ethereum/contracts';
3
3
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
4
+ import { SlotNumber } from '@aztec/foundation/branded-types';
4
5
  import { Buffer32 } from '@aztec/foundation/buffer';
5
6
  import { Fr } from '@aztec/foundation/curves/bn254';
6
7
  import { EthAddress } from '@aztec/foundation/eth-address';
@@ -30,7 +31,7 @@ class NoopL1Synchronizer implements FunctionsOf<ArchiverL1Synchronizer> {
30
31
  return 0n;
31
32
  }
32
33
  getL1Timestamp(): bigint | undefined {
33
- return 0n;
34
+ return undefined;
34
35
  }
35
36
  testEthereumNodeSynced(): Promise<void> {
36
37
  return Promise.resolve();
@@ -96,6 +97,11 @@ export class NoopL1Archiver extends Archiver {
96
97
  this.runningPromise.start();
97
98
  return Promise.resolve();
98
99
  }
100
+
101
+ /** Always reports as fully synced since there is no real L1 to sync from. */
102
+ public override getSyncedL2SlotNumber(): Promise<SlotNumber | undefined> {
103
+ return Promise.resolve(SlotNumber(Number.MAX_SAFE_INTEGER));
104
+ }
99
105
  }
100
106
 
101
107
  /** Creates an archiver with mocked L1 connectivity for testing. */