@aztec/archiver 0.0.1-commit.8f9871590 → 0.0.1-commit.9117c5f5a

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