@aztec/archiver 0.0.1-commit.7ac86ea28 → 0.0.1-commit.7b86788

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.
@@ -3,15 +3,8 @@ import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/ty
3
3
  import { CheckpointNumber } from '@aztec/foundation/branded-types';
4
4
  import { Fr } from '@aztec/foundation/curves/bn254';
5
5
  import { EthAddress } from '@aztec/foundation/eth-address';
6
- import type { ViemSignature } from '@aztec/foundation/eth-signature';
7
6
  import type { Logger } from '@aztec/foundation/log';
8
- import {
9
- EmpireSlashingProposerAbi,
10
- GovernanceProposerAbi,
11
- RollupAbi,
12
- SlashFactoryAbi,
13
- TallySlashingProposerAbi,
14
- } from '@aztec/l1-artifacts';
7
+ import { RollupAbi } from '@aztec/l1-artifacts';
15
8
  import { CommitteeAttestation } from '@aztec/stdlib/block';
16
9
  import { ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
17
10
  import { CheckpointHeader } from '@aztec/stdlib/rollup';
@@ -30,13 +23,24 @@ import {
30
23
 
31
24
  import type { ArchiverInstrumentation } from '../modules/instrumentation.js';
32
25
  import { getSuccessfulCallsFromDebug } from './debug_tx.js';
33
- import { getCallFromSpireProposer } from './spire_proposer.js';
26
+ import { getCallsFromSpireProposer } from './spire_proposer.js';
34
27
  import { getSuccessfulCallsFromTrace } from './trace_tx.js';
35
28
  import type { CallInfo } from './types.js';
36
29
 
30
+ /** Decoded checkpoint data from a propose calldata. */
31
+ type CheckpointData = {
32
+ checkpointNumber: CheckpointNumber;
33
+ archiveRoot: Fr;
34
+ header: CheckpointHeader;
35
+ attestations: CommitteeAttestation[];
36
+ blockHash: string;
37
+ feeAssetPriceModifier: bigint;
38
+ };
39
+
37
40
  /**
38
41
  * Extracts calldata to the `propose` method of the rollup contract from an L1 transaction
39
- * in order to reconstruct an L2 block header.
42
+ * in order to reconstruct an L2 block header. Uses hash matching against expected hashes
43
+ * from the CheckpointProposed event to verify the correct propose calldata.
40
44
  */
41
45
  export class CalldataRetriever {
42
46
  /** Tx hashes we've already logged for trace+debug failure (log once per tx per process). */
@@ -47,27 +51,14 @@ export class CalldataRetriever {
47
51
  CalldataRetriever.traceFailureWarnedTxHashes.clear();
48
52
  }
49
53
 
50
- /** Pre-computed valid contract calls for validation */
51
- private readonly validContractCalls: ValidContractCall[];
52
-
53
- private readonly rollupAddress: EthAddress;
54
-
55
54
  constructor(
56
55
  private readonly publicClient: ViemPublicClient,
57
56
  private readonly debugClient: ViemPublicDebugClient,
58
57
  private readonly targetCommitteeSize: number,
59
58
  private readonly instrumentation: ArchiverInstrumentation | undefined,
60
59
  private readonly logger: Logger,
61
- contractAddresses: {
62
- rollupAddress: EthAddress;
63
- governanceProposerAddress: EthAddress;
64
- slashingProposerAddress: EthAddress;
65
- slashFactoryAddress?: EthAddress;
66
- },
67
- ) {
68
- this.rollupAddress = contractAddresses.rollupAddress;
69
- this.validContractCalls = computeValidContractCalls(contractAddresses);
70
- }
60
+ private readonly rollupAddress: EthAddress,
61
+ ) {}
71
62
 
72
63
  /**
73
64
  * Gets checkpoint header and metadata from the calldata of an L1 transaction.
@@ -75,7 +66,7 @@ export class CalldataRetriever {
75
66
  * @param txHash - Hash of the tx that published it.
76
67
  * @param blobHashes - Blob hashes for the checkpoint.
77
68
  * @param checkpointNumber - Checkpoint number.
78
- * @param expectedHashes - Optional expected hashes from the CheckpointProposed event for validation
69
+ * @param expectedHashes - Expected hashes from the CheckpointProposed event for validation
79
70
  * @returns Checkpoint header and metadata from the calldata, deserialized
80
71
  */
81
72
  async getCheckpointFromRollupTx(
@@ -83,51 +74,43 @@ export class CalldataRetriever {
83
74
  _blobHashes: Buffer[],
84
75
  checkpointNumber: CheckpointNumber,
85
76
  expectedHashes: {
86
- attestationsHash?: Hex;
87
- payloadDigest?: Hex;
77
+ attestationsHash: Hex;
78
+ payloadDigest: Hex;
88
79
  },
89
- ): Promise<{
90
- checkpointNumber: CheckpointNumber;
91
- archiveRoot: Fr;
92
- header: CheckpointHeader;
93
- attestations: CommitteeAttestation[];
94
- blockHash: string;
95
- feeAssetPriceModifier: bigint;
96
- }> {
97
- this.logger.trace(`Fetching checkpoint ${checkpointNumber} from rollup tx ${txHash}`, {
98
- willValidateHashes: !!expectedHashes.attestationsHash || !!expectedHashes.payloadDigest,
99
- hasAttestationsHash: !!expectedHashes.attestationsHash,
100
- hasPayloadDigest: !!expectedHashes.payloadDigest,
101
- });
80
+ ): Promise<CheckpointData> {
81
+ this.logger.trace(`Fetching checkpoint ${checkpointNumber} from rollup tx ${txHash}`);
102
82
  const tx = await this.publicClient.getTransaction({ hash: txHash });
103
- const proposeCalldata = await this.getProposeCallData(tx, checkpointNumber);
104
- return this.decodeAndBuildCheckpoint(proposeCalldata, tx.blockHash!, checkpointNumber, expectedHashes);
83
+ return this.getCheckpointFromTx(tx, checkpointNumber, expectedHashes);
105
84
  }
106
85
 
107
- /** Gets rollup propose calldata from a transaction */
108
- protected async getProposeCallData(tx: Transaction, checkpointNumber: CheckpointNumber): Promise<Hex> {
109
- // Try to decode as multicall3 with validation
110
- const proposeCalldata = this.tryDecodeMulticall3(tx);
111
- if (proposeCalldata) {
86
+ /** Gets checkpoint data from a transaction by trying decode strategies then falling back to trace. */
87
+ protected async getCheckpointFromTx(
88
+ tx: Transaction,
89
+ checkpointNumber: CheckpointNumber,
90
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
91
+ ): Promise<CheckpointData> {
92
+ // Try to decode as multicall3 with hash-verified matching
93
+ const multicall3Result = this.tryDecodeMulticall3(tx, expectedHashes, checkpointNumber, tx.blockHash!);
94
+ if (multicall3Result) {
112
95
  this.logger.trace(`Decoded propose calldata from multicall3 for tx ${tx.hash}`);
113
96
  this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
114
- return proposeCalldata;
97
+ return multicall3Result;
115
98
  }
116
99
 
117
100
  // Try to decode as direct propose call
118
- const directProposeCalldata = this.tryDecodeDirectPropose(tx);
119
- if (directProposeCalldata) {
101
+ const directResult = this.tryDecodeDirectPropose(tx, expectedHashes, checkpointNumber, tx.blockHash!);
102
+ if (directResult) {
120
103
  this.logger.trace(`Decoded propose calldata from direct call for tx ${tx.hash}`);
121
104
  this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
122
- return directProposeCalldata;
105
+ return directResult;
123
106
  }
124
107
 
125
108
  // Try to decode as Spire Proposer multicall wrapper
126
- const spireProposeCalldata = await this.tryDecodeSpireProposer(tx);
127
- if (spireProposeCalldata) {
109
+ const spireResult = await this.tryDecodeSpireProposer(tx, expectedHashes, checkpointNumber, tx.blockHash!);
110
+ if (spireResult) {
128
111
  this.logger.trace(`Decoded propose calldata from Spire Proposer for tx ${tx.hash}`);
129
112
  this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
130
- return spireProposeCalldata;
113
+ return spireResult;
131
114
  }
132
115
 
133
116
  // Fall back to trace-based extraction
@@ -135,52 +118,82 @@ export class CalldataRetriever {
135
118
  `Failed to decode multicall3, direct propose, or Spire proposer for L1 tx ${tx.hash}, falling back to trace for checkpoint ${checkpointNumber}`,
136
119
  );
137
120
  this.instrumentation?.recordBlockProposalTxTarget(tx.to ?? EthAddress.ZERO.toString(), true);
138
- return await this.extractCalldataViaTrace(tx.hash);
121
+ const tracedCalldata = await this.extractCalldataViaTrace(tx.hash);
122
+ const tracedResult = this.tryDecodeAndVerifyPropose(
123
+ tracedCalldata,
124
+ expectedHashes,
125
+ checkpointNumber,
126
+ tx.blockHash!,
127
+ );
128
+ if (!tracedResult) {
129
+ throw new Error(`Hash mismatch for traced propose calldata in tx ${tx.hash} for checkpoint ${checkpointNumber}`);
130
+ }
131
+ return tracedResult;
139
132
  }
140
133
 
141
134
  /**
142
135
  * Attempts to decode a transaction as a Spire Proposer multicall wrapper.
143
- * If successful, extracts the wrapped call and validates it as either multicall3 or direct propose.
136
+ * If successful, iterates all wrapped calls and validates each as either multicall3
137
+ * or direct propose, verifying against expected hashes.
144
138
  * @param tx - The transaction to decode
145
- * @returns The propose calldata if successfully decoded and validated, undefined otherwise
139
+ * @param expectedHashes - Expected hashes for hash-verified matching
140
+ * @param checkpointNumber - The checkpoint number
141
+ * @param blockHash - The L1 block hash
142
+ * @returns The checkpoint data if successfully decoded and validated, undefined otherwise
146
143
  */
147
- protected async tryDecodeSpireProposer(tx: Transaction): Promise<Hex | undefined> {
148
- // Try to decode as Spire Proposer multicall (extracts the wrapped call)
149
- const spireWrappedCall = await getCallFromSpireProposer(tx, this.publicClient, this.logger);
150
- if (!spireWrappedCall) {
144
+ protected async tryDecodeSpireProposer(
145
+ tx: Transaction,
146
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
147
+ checkpointNumber: CheckpointNumber,
148
+ blockHash: Hex,
149
+ ): Promise<CheckpointData | undefined> {
150
+ // Try to decode as Spire Proposer multicall (extracts all wrapped calls)
151
+ const spireWrappedCalls = await getCallsFromSpireProposer(tx, this.publicClient, this.logger);
152
+ if (!spireWrappedCalls) {
151
153
  return undefined;
152
154
  }
153
155
 
154
- this.logger.trace(`Decoded Spire Proposer wrapping for tx ${tx.hash}, inner call to ${spireWrappedCall.to}`);
156
+ this.logger.trace(`Decoded Spire Proposer wrapping for tx ${tx.hash}, ${spireWrappedCalls.length} inner call(s)`);
155
157
 
156
- // Now try to decode the wrapped call as either multicall3 or direct propose
157
- const wrappedTx = { to: spireWrappedCall.to, input: spireWrappedCall.data, hash: tx.hash };
158
+ // Try each wrapped call as either multicall3 or direct propose
159
+ for (const spireWrappedCall of spireWrappedCalls) {
160
+ const wrappedTx = { to: spireWrappedCall.to, input: spireWrappedCall.data, hash: tx.hash };
158
161
 
159
- const multicall3Calldata = this.tryDecodeMulticall3(wrappedTx);
160
- if (multicall3Calldata) {
161
- this.logger.trace(`Decoded propose calldata from Spire Proposer to multicall3 for tx ${tx.hash}`);
162
- return multicall3Calldata;
163
- }
162
+ const multicall3Result = this.tryDecodeMulticall3(wrappedTx, expectedHashes, checkpointNumber, blockHash);
163
+ if (multicall3Result) {
164
+ this.logger.trace(`Decoded propose calldata from Spire Proposer to multicall3 for tx ${tx.hash}`);
165
+ return multicall3Result;
166
+ }
164
167
 
165
- const directProposeCalldata = this.tryDecodeDirectPropose(wrappedTx);
166
- if (directProposeCalldata) {
167
- this.logger.trace(`Decoded propose calldata from Spire Proposer to direct propose for tx ${tx.hash}`);
168
- return directProposeCalldata;
168
+ const directResult = this.tryDecodeDirectPropose(wrappedTx, expectedHashes, checkpointNumber, blockHash);
169
+ if (directResult) {
170
+ this.logger.trace(`Decoded propose calldata from Spire Proposer to direct propose for tx ${tx.hash}`);
171
+ return directResult;
172
+ }
169
173
  }
170
174
 
171
175
  this.logger.warn(
172
- `Spire Proposer wrapped call could not be decoded as multicall3 or direct propose for tx ${tx.hash}`,
176
+ `Spire Proposer wrapped calls could not be decoded as multicall3 or direct propose for tx ${tx.hash}`,
173
177
  );
174
178
  return undefined;
175
179
  }
176
180
 
177
181
  /**
178
182
  * Attempts to decode transaction input as multicall3 and extract propose calldata.
179
- * Returns undefined if validation fails.
183
+ * Finds all calls matching the rollup address and propose selector, then decodes
184
+ * and verifies each candidate against expected hashes from the CheckpointProposed event.
180
185
  * @param tx - The transaction-like object with to, input, and hash
181
- * @returns The propose calldata if successfully validated, undefined otherwise
186
+ * @param expectedHashes - Expected hashes from CheckpointProposed event
187
+ * @param checkpointNumber - The checkpoint number
188
+ * @param blockHash - The L1 block hash
189
+ * @returns The checkpoint data if successfully validated, undefined otherwise
182
190
  */
183
- protected tryDecodeMulticall3(tx: { to: Hex | null | undefined; input: Hex; hash: Hex }): Hex | undefined {
191
+ protected tryDecodeMulticall3(
192
+ tx: { to: Hex | null | undefined; input: Hex; hash: Hex },
193
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
194
+ checkpointNumber: CheckpointNumber,
195
+ blockHash: Hex,
196
+ ): CheckpointData | undefined {
184
197
  const txHash = tx.hash;
185
198
 
186
199
  try {
@@ -209,59 +222,54 @@ export class CalldataRetriever {
209
222
 
210
223
  const [calls] = multicall3Args;
211
224
 
212
- // Validate all calls and find propose calls
225
+ // Find all calls matching rollup address + propose selector
213
226
  const rollupAddressLower = this.rollupAddress.toString().toLowerCase();
214
- const proposeCalls: Hex[] = [];
227
+ const proposeSelectorLower = PROPOSE_SELECTOR.toLowerCase();
228
+ const candidates: Hex[] = [];
215
229
 
216
- for (let i = 0; i < calls.length; i++) {
217
- const addr = calls[i].target.toLowerCase();
218
- const callData = calls[i].callData;
230
+ for (const call of calls) {
231
+ const addr = call.target.toLowerCase();
232
+ const callData = call.callData;
219
233
 
220
- // Extract function selector (first 4 bytes)
221
234
  if (callData.length < 10) {
222
- // "0x" + 8 hex chars = 10 chars minimum for a valid function call
223
- this.logger.warn(`Invalid calldata length at index ${i} (${callData.length})`, { txHash });
224
- return undefined;
235
+ continue;
225
236
  }
226
- const functionSelector = callData.slice(0, 10) as Hex;
227
-
228
- // Validate this call is allowed by searching through valid calls
229
- const validCall = this.validContractCalls.find(
230
- vc => vc.address === addr && vc.functionSelector === functionSelector,
231
- );
232
237
 
233
- if (!validCall) {
234
- this.logger.warn(`Invalid contract call detected in multicall3`, {
235
- index: i,
236
- targetAddress: addr,
237
- functionSelector,
238
- validCalls: this.validContractCalls.map(c => ({ address: c.address, selector: c.functionSelector })),
239
- txHash,
240
- });
241
- return undefined;
238
+ const selector = callData.slice(0, 10).toLowerCase();
239
+ if (addr === rollupAddressLower && selector === proposeSelectorLower) {
240
+ candidates.push(callData);
242
241
  }
242
+ }
243
243
 
244
- this.logger.trace(`Valid call found to ${addr}`, { validCall });
244
+ if (candidates.length === 0) {
245
+ this.logger.debug(`No propose candidates found in multicall3`, { txHash });
246
+ return undefined;
247
+ }
245
248
 
246
- // Collect propose calls specifically
247
- if (addr === rollupAddressLower && validCall.functionName === 'propose') {
248
- proposeCalls.push(callData);
249
+ // Decode, verify, and build for each candidate
250
+ const verified: CheckpointData[] = [];
251
+ for (const candidate of candidates) {
252
+ const result = this.tryDecodeAndVerifyPropose(candidate, expectedHashes, checkpointNumber, blockHash);
253
+ if (result) {
254
+ verified.push(result);
249
255
  }
250
256
  }
251
257
 
252
- // Validate exactly ONE propose call
253
- if (proposeCalls.length === 0) {
254
- this.logger.warn(`No propose calls found in multicall3`, { txHash });
255
- return undefined;
258
+ if (verified.length === 1) {
259
+ this.logger.trace(`Verified single propose candidate via hash matching`, { txHash });
260
+ return verified[0];
256
261
  }
257
262
 
258
- if (proposeCalls.length > 1) {
259
- this.logger.warn(`Multiple propose calls found in multicall3 (${proposeCalls.length})`, { txHash });
260
- return undefined;
263
+ if (verified.length > 1) {
264
+ this.logger.warn(
265
+ `Multiple propose candidates verified (${verified.length}), returning first (identical data)`,
266
+ { txHash },
267
+ );
268
+ return verified[0];
261
269
  }
262
270
 
263
- // Successfully extracted single propose call
264
- return proposeCalls[0];
271
+ this.logger.debug(`No candidates verified against expected hashes`, { txHash });
272
+ return undefined;
265
273
  } catch (err) {
266
274
  // Any decoding error triggers fallback to trace
267
275
  this.logger.warn(`Failed to decode multicall3: ${err}`, { txHash });
@@ -271,11 +279,19 @@ export class CalldataRetriever {
271
279
 
272
280
  /**
273
281
  * Attempts to decode transaction as a direct propose call to the rollup contract.
274
- * Returns undefined if validation fails.
282
+ * Decodes, verifies hashes, and builds checkpoint data in a single pass.
275
283
  * @param tx - The transaction-like object with to, input, and hash
276
- * @returns The propose calldata if successfully validated, undefined otherwise
284
+ * @param expectedHashes - Expected hashes from CheckpointProposed event
285
+ * @param checkpointNumber - The checkpoint number
286
+ * @param blockHash - The L1 block hash
287
+ * @returns The checkpoint data if successfully validated, undefined otherwise
277
288
  */
278
- protected tryDecodeDirectPropose(tx: { to: Hex | null | undefined; input: Hex; hash: Hex }): Hex | undefined {
289
+ protected tryDecodeDirectPropose(
290
+ tx: { to: Hex | null | undefined; input: Hex; hash: Hex },
291
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
292
+ checkpointNumber: CheckpointNumber,
293
+ blockHash: Hex,
294
+ ): CheckpointData | undefined {
279
295
  const txHash = tx.hash;
280
296
  try {
281
297
  // Check if transaction is to the rollup address
@@ -284,18 +300,16 @@ export class CalldataRetriever {
284
300
  return undefined;
285
301
  }
286
302
 
287
- // Try to decode as propose call
303
+ // Validate it's a propose call before full decode+verify
288
304
  const { functionName } = decodeFunctionData({ abi: RollupAbi, data: tx.input });
289
-
290
- // If not propose, return undefined
291
305
  if (functionName !== 'propose') {
292
306
  this.logger.warn(`Transaction to rollup is not propose (got ${functionName})`, { txHash });
293
307
  return undefined;
294
308
  }
295
309
 
296
- // Successfully validated direct propose call
310
+ // Decode, verify hashes, and build checkpoint data
297
311
  this.logger.trace(`Validated direct propose call to rollup`, { txHash });
298
- return tx.input;
312
+ return this.tryDecodeAndVerifyPropose(tx.input, expectedHashes, checkpointNumber, blockHash);
299
313
  } catch (err) {
300
314
  // Any decoding error means it's not a valid propose call
301
315
  this.logger.warn(`Failed to decode as direct propose: ${err}`, { txHash });
@@ -363,10 +377,102 @@ export class CalldataRetriever {
363
377
  return calls[0].input;
364
378
  }
365
379
 
380
+ /**
381
+ * Decodes propose calldata, verifies against expected hashes, and builds checkpoint data.
382
+ * Returns undefined on decode errors or hash mismatches (soft failure for try-based callers).
383
+ * @param proposeCalldata - The propose function calldata
384
+ * @param expectedHashes - Expected hashes from the CheckpointProposed event
385
+ * @param checkpointNumber - The checkpoint number
386
+ * @param blockHash - The L1 block hash
387
+ * @returns The decoded checkpoint data, or undefined on failure
388
+ */
389
+ protected tryDecodeAndVerifyPropose(
390
+ proposeCalldata: Hex,
391
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
392
+ checkpointNumber: CheckpointNumber,
393
+ blockHash: Hex,
394
+ ): CheckpointData | undefined {
395
+ try {
396
+ const { functionName, args } = decodeFunctionData({ abi: RollupAbi, data: proposeCalldata });
397
+ if (functionName !== 'propose') {
398
+ return undefined;
399
+ }
400
+
401
+ const [decodedArgs, packedAttestations] = args! as readonly [
402
+ { archive: Hex; oracleInput: { feeAssetPriceModifier: bigint }; header: ViemHeader },
403
+ ViemCommitteeAttestations,
404
+ ...unknown[],
405
+ ];
406
+
407
+ // Verify attestationsHash
408
+ const computedAttestationsHash = this.computeAttestationsHash(packedAttestations);
409
+ if (
410
+ !Buffer.from(hexToBytes(computedAttestationsHash)).equals(
411
+ Buffer.from(hexToBytes(expectedHashes.attestationsHash)),
412
+ )
413
+ ) {
414
+ this.logger.warn(`Attestations hash mismatch during verification`, {
415
+ computed: computedAttestationsHash,
416
+ expected: expectedHashes.attestationsHash,
417
+ });
418
+ return undefined;
419
+ }
420
+
421
+ // Verify payloadDigest
422
+ const header = CheckpointHeader.fromViem(decodedArgs.header);
423
+ const archiveRoot = new Fr(Buffer.from(hexToBytes(decodedArgs.archive)));
424
+ const feeAssetPriceModifier = decodedArgs.oracleInput.feeAssetPriceModifier;
425
+ const computedPayloadDigest = this.computePayloadDigest(header, archiveRoot, feeAssetPriceModifier);
426
+ if (
427
+ !Buffer.from(hexToBytes(computedPayloadDigest)).equals(Buffer.from(hexToBytes(expectedHashes.payloadDigest)))
428
+ ) {
429
+ this.logger.warn(`Payload digest mismatch during verification`, {
430
+ computed: computedPayloadDigest,
431
+ expected: expectedHashes.payloadDigest,
432
+ });
433
+ return undefined;
434
+ }
435
+
436
+ const attestations = CommitteeAttestation.fromPacked(packedAttestations, this.targetCommitteeSize);
437
+
438
+ this.logger.trace(`Validated and decoded propose calldata for checkpoint ${checkpointNumber}`, {
439
+ checkpointNumber,
440
+ archive: decodedArgs.archive,
441
+ header: decodedArgs.header,
442
+ l1BlockHash: blockHash,
443
+ attestations,
444
+ packedAttestations,
445
+ targetCommitteeSize: this.targetCommitteeSize,
446
+ });
447
+
448
+ return {
449
+ checkpointNumber,
450
+ archiveRoot,
451
+ header,
452
+ attestations,
453
+ blockHash,
454
+ feeAssetPriceModifier,
455
+ };
456
+ } catch {
457
+ return undefined;
458
+ }
459
+ }
460
+
461
+ /** Computes the keccak256 hash of ABI-encoded CommitteeAttestations. */
462
+ private computeAttestationsHash(packedAttestations: ViemCommitteeAttestations): Hex {
463
+ return keccak256(encodeAbiParameters([this.getCommitteeAttestationsStructDef()], [packedAttestations]));
464
+ }
465
+
466
+ /** Computes the keccak256 payload digest from the checkpoint header, archive root, and fee asset price modifier. */
467
+ private computePayloadDigest(header: CheckpointHeader, archiveRoot: Fr, feeAssetPriceModifier: bigint): Hex {
468
+ const consensusPayload = new ConsensusPayload(header, archiveRoot, feeAssetPriceModifier);
469
+ const payloadToSign = consensusPayload.getPayloadToSign(SignatureDomainSeparator.checkpointAttestation);
470
+ return keccak256(payloadToSign);
471
+ }
472
+
366
473
  /**
367
474
  * Extracts the CommitteeAttestations struct definition from RollupAbi.
368
475
  * Finds the _attestations parameter by name in the propose function.
369
- * Lazy-loaded to avoid issues during module initialization.
370
476
  */
371
477
  private getCommitteeAttestationsStructDef(): AbiParameter {
372
478
  const proposeFunction = RollupAbi.find(item => item.type === 'function' && item.name === 'propose') as
@@ -399,265 +505,7 @@ export class CalldataRetriever {
399
505
  components: tupleParam.components || [],
400
506
  } as AbiParameter;
401
507
  }
402
-
403
- /**
404
- * Decodes propose calldata and builds the checkpoint header structure.
405
- * @param proposeCalldata - The propose function calldata
406
- * @param blockHash - The L1 block hash containing this transaction
407
- * @param checkpointNumber - The checkpoint number
408
- * @param expectedHashes - Optional expected hashes from the CheckpointProposed event for validation
409
- * @returns The decoded checkpoint header and metadata
410
- */
411
- protected decodeAndBuildCheckpoint(
412
- proposeCalldata: Hex,
413
- blockHash: Hex,
414
- checkpointNumber: CheckpointNumber,
415
- expectedHashes: {
416
- attestationsHash?: Hex;
417
- payloadDigest?: Hex;
418
- },
419
- ): {
420
- checkpointNumber: CheckpointNumber;
421
- archiveRoot: Fr;
422
- header: CheckpointHeader;
423
- attestations: CommitteeAttestation[];
424
- blockHash: string;
425
- feeAssetPriceModifier: bigint;
426
- } {
427
- const { functionName: rollupFunctionName, args: rollupArgs } = decodeFunctionData({
428
- abi: RollupAbi,
429
- data: proposeCalldata,
430
- });
431
-
432
- if (rollupFunctionName !== 'propose') {
433
- throw new Error(`Unexpected rollup method called ${rollupFunctionName}`);
434
- }
435
-
436
- const [decodedArgs, packedAttestations, _signers, _attestationsAndSignersSignature, _blobInput] =
437
- rollupArgs! as readonly [
438
- {
439
- archive: Hex;
440
- oracleInput: { feeAssetPriceModifier: bigint };
441
- header: ViemHeader;
442
- },
443
- ViemCommitteeAttestations,
444
- Hex[],
445
- ViemSignature,
446
- Hex,
447
- ];
448
-
449
- const attestations = CommitteeAttestation.fromPacked(packedAttestations, this.targetCommitteeSize);
450
- const header = CheckpointHeader.fromViem(decodedArgs.header);
451
- const archiveRoot = new Fr(Buffer.from(hexToBytes(decodedArgs.archive)));
452
-
453
- // Validate attestationsHash if provided (skip for backwards compatibility with older events)
454
- if (expectedHashes.attestationsHash) {
455
- // Compute attestationsHash: keccak256(abi.encode(CommitteeAttestations))
456
- const computedAttestationsHash = keccak256(
457
- encodeAbiParameters([this.getCommitteeAttestationsStructDef()], [packedAttestations]),
458
- );
459
-
460
- // Compare as buffers to avoid case-sensitivity and string comparison issues
461
- const computedBuffer = Buffer.from(hexToBytes(computedAttestationsHash));
462
- const expectedBuffer = Buffer.from(hexToBytes(expectedHashes.attestationsHash));
463
-
464
- if (!computedBuffer.equals(expectedBuffer)) {
465
- throw new Error(
466
- `Attestations hash mismatch for checkpoint ${checkpointNumber}: ` +
467
- `computed=${computedAttestationsHash}, expected=${expectedHashes.attestationsHash}`,
468
- );
469
- }
470
-
471
- this.logger.trace(`Validated attestationsHash for checkpoint ${checkpointNumber}`, {
472
- computedAttestationsHash,
473
- expectedAttestationsHash: expectedHashes.attestationsHash,
474
- });
475
- }
476
-
477
- // Validate payloadDigest if provided (skip for backwards compatibility with older events)
478
- if (expectedHashes.payloadDigest) {
479
- // Use ConsensusPayload to compute the digest - this ensures we match the exact logic
480
- // used by the network for signing and verification
481
- const feeAssetPriceModifier = decodedArgs.oracleInput.feeAssetPriceModifier;
482
- const consensusPayload = new ConsensusPayload(header, archiveRoot, feeAssetPriceModifier);
483
- const payloadToSign = consensusPayload.getPayloadToSign(SignatureDomainSeparator.checkpointAttestation);
484
- const computedPayloadDigest = keccak256(payloadToSign);
485
-
486
- // Compare as buffers to avoid case-sensitivity and string comparison issues
487
- const computedBuffer = Buffer.from(hexToBytes(computedPayloadDigest));
488
- const expectedBuffer = Buffer.from(hexToBytes(expectedHashes.payloadDigest));
489
-
490
- if (!computedBuffer.equals(expectedBuffer)) {
491
- throw new Error(
492
- `Payload digest mismatch for checkpoint ${checkpointNumber}: ` +
493
- `computed=${computedPayloadDigest}, expected=${expectedHashes.payloadDigest}`,
494
- );
495
- }
496
-
497
- this.logger.trace(`Validated payloadDigest for checkpoint ${checkpointNumber}`, {
498
- computedPayloadDigest,
499
- expectedPayloadDigest: expectedHashes.payloadDigest,
500
- });
501
- }
502
-
503
- this.logger.trace(`Decoded propose calldata`, {
504
- checkpointNumber,
505
- archive: decodedArgs.archive,
506
- header: decodedArgs.header,
507
- l1BlockHash: blockHash,
508
- attestations,
509
- packedAttestations,
510
- targetCommitteeSize: this.targetCommitteeSize,
511
- });
512
-
513
- return {
514
- checkpointNumber,
515
- archiveRoot,
516
- header,
517
- attestations,
518
- blockHash,
519
- feeAssetPriceModifier: decodedArgs.oracleInput.feeAssetPriceModifier,
520
- };
521
- }
522
508
  }
523
509
 
524
- /**
525
- * Pre-computed function selectors for all valid contract calls.
526
- * These are computed once at module load time from the ABIs.
527
- * Based on analysis of sequencer-client/src/publisher/sequencer-publisher.ts
528
- */
529
-
530
- // Rollup contract function selectors (always valid)
510
+ /** Function selector for the `propose` method of the rollup contract. */
531
511
  const PROPOSE_SELECTOR = toFunctionSelector(RollupAbi.find(x => x.type === 'function' && x.name === 'propose')!);
532
- const INVALIDATE_BAD_ATTESTATION_SELECTOR = toFunctionSelector(
533
- RollupAbi.find(x => x.type === 'function' && x.name === 'invalidateBadAttestation')!,
534
- );
535
- const INVALIDATE_INSUFFICIENT_ATTESTATIONS_SELECTOR = toFunctionSelector(
536
- RollupAbi.find(x => x.type === 'function' && x.name === 'invalidateInsufficientAttestations')!,
537
- );
538
-
539
- // Governance proposer function selectors
540
- const GOVERNANCE_SIGNAL_WITH_SIG_SELECTOR = toFunctionSelector(
541
- GovernanceProposerAbi.find(x => x.type === 'function' && x.name === 'signalWithSig')!,
542
- );
543
-
544
- // Slash factory function selectors
545
- const CREATE_SLASH_PAYLOAD_SELECTOR = toFunctionSelector(
546
- SlashFactoryAbi.find(x => x.type === 'function' && x.name === 'createSlashPayload')!,
547
- );
548
-
549
- // Empire slashing proposer function selectors
550
- const EMPIRE_SIGNAL_WITH_SIG_SELECTOR = toFunctionSelector(
551
- EmpireSlashingProposerAbi.find(x => x.type === 'function' && x.name === 'signalWithSig')!,
552
- );
553
- const EMPIRE_SUBMIT_ROUND_WINNER_SELECTOR = toFunctionSelector(
554
- EmpireSlashingProposerAbi.find(x => x.type === 'function' && x.name === 'submitRoundWinner')!,
555
- );
556
-
557
- // Tally slashing proposer function selectors
558
- const TALLY_VOTE_SELECTOR = toFunctionSelector(
559
- TallySlashingProposerAbi.find(x => x.type === 'function' && x.name === 'vote')!,
560
- );
561
- const TALLY_EXECUTE_ROUND_SELECTOR = toFunctionSelector(
562
- TallySlashingProposerAbi.find(x => x.type === 'function' && x.name === 'executeRound')!,
563
- );
564
-
565
- /**
566
- * Defines a valid contract call that can appear in a sequencer publisher transaction
567
- */
568
- interface ValidContractCall {
569
- /** Contract address (lowercase for comparison) */
570
- address: string;
571
- /** Function selector (4 bytes) */
572
- functionSelector: Hex;
573
- /** Human-readable function name for logging */
574
- functionName: string;
575
- }
576
-
577
- /**
578
- * All valid contract calls that the sequencer publisher can make.
579
- * Builds the list of valid (address, selector) pairs for validation.
580
- *
581
- * Alternatively, if we are absolutely sure that no code path from any of these
582
- * contracts can eventually land on another call to `propose`, we can remove the
583
- * function selectors.
584
- */
585
- function computeValidContractCalls(addresses: {
586
- rollupAddress: EthAddress;
587
- governanceProposerAddress?: EthAddress;
588
- slashFactoryAddress?: EthAddress;
589
- slashingProposerAddress?: EthAddress;
590
- }): ValidContractCall[] {
591
- const { rollupAddress, governanceProposerAddress, slashFactoryAddress, slashingProposerAddress } = addresses;
592
- const calls: ValidContractCall[] = [];
593
-
594
- // Rollup contract calls (always present)
595
- calls.push(
596
- {
597
- address: rollupAddress.toString().toLowerCase(),
598
- functionSelector: PROPOSE_SELECTOR,
599
- functionName: 'propose',
600
- },
601
- {
602
- address: rollupAddress.toString().toLowerCase(),
603
- functionSelector: INVALIDATE_BAD_ATTESTATION_SELECTOR,
604
- functionName: 'invalidateBadAttestation',
605
- },
606
- {
607
- address: rollupAddress.toString().toLowerCase(),
608
- functionSelector: INVALIDATE_INSUFFICIENT_ATTESTATIONS_SELECTOR,
609
- functionName: 'invalidateInsufficientAttestations',
610
- },
611
- );
612
-
613
- // Governance proposer calls (optional)
614
- if (governanceProposerAddress && !governanceProposerAddress.isZero()) {
615
- calls.push({
616
- address: governanceProposerAddress.toString().toLowerCase(),
617
- functionSelector: GOVERNANCE_SIGNAL_WITH_SIG_SELECTOR,
618
- functionName: 'signalWithSig',
619
- });
620
- }
621
-
622
- // Slash factory calls (optional)
623
- if (slashFactoryAddress && !slashFactoryAddress.isZero()) {
624
- calls.push({
625
- address: slashFactoryAddress.toString().toLowerCase(),
626
- functionSelector: CREATE_SLASH_PAYLOAD_SELECTOR,
627
- functionName: 'createSlashPayload',
628
- });
629
- }
630
-
631
- // Slashing proposer calls (optional, can be either Empire or Tally)
632
- if (slashingProposerAddress && !slashingProposerAddress.isZero()) {
633
- // Empire calls
634
- calls.push(
635
- {
636
- address: slashingProposerAddress.toString().toLowerCase(),
637
- functionSelector: EMPIRE_SIGNAL_WITH_SIG_SELECTOR,
638
- functionName: 'signalWithSig (empire)',
639
- },
640
- {
641
- address: slashingProposerAddress.toString().toLowerCase(),
642
- functionSelector: EMPIRE_SUBMIT_ROUND_WINNER_SELECTOR,
643
- functionName: 'submitRoundWinner',
644
- },
645
- );
646
-
647
- // Tally calls
648
- calls.push(
649
- {
650
- address: slashingProposerAddress.toString().toLowerCase(),
651
- functionSelector: TALLY_VOTE_SELECTOR,
652
- functionName: 'vote',
653
- },
654
- {
655
- address: slashingProposerAddress.toString().toLowerCase(),
656
- functionSelector: TALLY_EXECUTE_ROUND_SELECTOR,
657
- functionName: 'executeRound',
658
- },
659
- );
660
- }
661
-
662
- return calls;
663
- }