@aztec/archiver 0.0.1-commit.fce3e4f → 0.0.1-commit.ff7989d6c

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 (209) hide show
  1. package/README.md +156 -22
  2. package/dest/archiver.d.ts +139 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +699 -0
  5. package/dest/config.d.ts +30 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +21 -5
  8. package/dest/errors.d.ts +41 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +62 -0
  11. package/dest/factory.d.ts +9 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +97 -13
  14. package/dest/index.d.ts +11 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +9 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +148 -0
  23. package/dest/l1/calldata_retriever.d.ts +118 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +484 -0
  26. package/dest/l1/data_retrieval.d.ts +89 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +80 -153
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +157 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_trace.d.ts +32 -0
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/l1/validate_trace.js +154 -0
  44. package/dest/modules/data_source_base.d.ts +89 -0
  45. package/dest/modules/data_source_base.d.ts.map +1 -0
  46. package/dest/modules/data_source_base.js +216 -0
  47. package/dest/modules/data_store_updater.d.ts +80 -0
  48. package/dest/modules/data_store_updater.d.ts.map +1 -0
  49. package/dest/modules/data_store_updater.js +323 -0
  50. package/dest/modules/instrumentation.d.ts +39 -0
  51. package/dest/modules/instrumentation.d.ts.map +1 -0
  52. package/dest/{archiver → modules}/instrumentation.js +39 -62
  53. package/dest/modules/l1_synchronizer.d.ts +76 -0
  54. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  55. package/dest/modules/l1_synchronizer.js +1112 -0
  56. package/dest/modules/validation.d.ts +17 -0
  57. package/dest/modules/validation.d.ts.map +1 -0
  58. package/dest/{archiver → modules}/validation.js +7 -1
  59. package/dest/store/block_store.d.ts +196 -0
  60. package/dest/store/block_store.d.ts.map +1 -0
  61. package/dest/store/block_store.js +773 -0
  62. package/dest/store/contract_class_store.d.ts +18 -0
  63. package/dest/store/contract_class_store.d.ts.map +1 -0
  64. package/dest/{archiver/kv_archiver_store → store}/contract_class_store.js +13 -9
  65. package/dest/store/contract_instance_store.d.ts +24 -0
  66. package/dest/store/contract_instance_store.d.ts.map +1 -0
  67. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +1 -1
  68. package/dest/store/kv_archiver_store.d.ts +354 -0
  69. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  70. package/dest/store/kv_archiver_store.js +464 -0
  71. package/dest/store/l2_tips_cache.d.ts +19 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +89 -0
  74. package/dest/store/log_store.d.ts +54 -0
  75. package/dest/store/log_store.d.ts.map +1 -0
  76. package/dest/store/log_store.js +456 -0
  77. package/dest/store/message_store.d.ts +40 -0
  78. package/dest/store/message_store.d.ts.map +1 -0
  79. package/dest/{archiver/kv_archiver_store → store}/message_store.js +15 -14
  80. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  81. package/dest/structs/data_retrieval.d.ts.map +1 -0
  82. package/dest/structs/inbox_message.d.ts +15 -0
  83. package/dest/structs/inbox_message.d.ts.map +1 -0
  84. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  85. package/dest/structs/published.d.ts +2 -0
  86. package/dest/structs/published.d.ts.map +1 -0
  87. package/dest/test/fake_l1_state.d.ts +193 -0
  88. package/dest/test/fake_l1_state.d.ts.map +1 -0
  89. package/dest/test/fake_l1_state.js +389 -0
  90. package/dest/test/index.d.ts +2 -1
  91. package/dest/test/index.d.ts.map +1 -1
  92. package/dest/test/index.js +4 -1
  93. package/dest/test/mock_archiver.d.ts +16 -8
  94. package/dest/test/mock_archiver.d.ts.map +1 -1
  95. package/dest/test/mock_archiver.js +19 -14
  96. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  97. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  98. package/dest/test/mock_l1_to_l2_message_source.js +21 -11
  99. package/dest/test/mock_l2_block_source.d.ts +51 -18
  100. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  101. package/dest/test/mock_l2_block_source.js +245 -82
  102. package/dest/test/mock_structs.d.ts +80 -4
  103. package/dest/test/mock_structs.d.ts.map +1 -1
  104. package/dest/test/mock_structs.js +145 -11
  105. package/dest/test/noop_l1_archiver.d.ts +23 -0
  106. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  107. package/dest/test/noop_l1_archiver.js +68 -0
  108. package/package.json +20 -20
  109. package/src/archiver.ts +443 -0
  110. package/src/{archiver/config.ts → config.ts} +28 -12
  111. package/src/errors.ts +102 -0
  112. package/src/factory.ts +143 -13
  113. package/src/index.ts +11 -3
  114. package/src/interfaces.ts +9 -0
  115. package/src/l1/README.md +98 -0
  116. package/src/l1/bin/retrieve-calldata.ts +181 -0
  117. package/src/l1/calldata_retriever.ts +663 -0
  118. package/src/{archiver → l1}/data_retrieval.ts +146 -224
  119. package/src/l1/debug_tx.ts +99 -0
  120. package/src/l1/spire_proposer.ts +160 -0
  121. package/src/l1/trace_tx.ts +128 -0
  122. package/src/l1/types.ts +13 -0
  123. package/src/l1/validate_trace.ts +229 -0
  124. package/src/modules/data_source_base.ts +328 -0
  125. package/src/modules/data_store_updater.ts +448 -0
  126. package/src/{archiver → modules}/instrumentation.ts +43 -66
  127. package/src/modules/l1_synchronizer.ts +932 -0
  128. package/src/{archiver → modules}/validation.ts +11 -6
  129. package/src/store/block_store.ts +1015 -0
  130. package/src/{archiver/kv_archiver_store → store}/contract_class_store.ts +13 -9
  131. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +2 -2
  132. package/src/store/kv_archiver_store.ts +671 -0
  133. package/src/store/l2_tips_cache.ts +89 -0
  134. package/src/store/log_store.ts +637 -0
  135. package/src/{archiver/kv_archiver_store → store}/message_store.ts +21 -18
  136. package/src/{archiver/structs → structs}/inbox_message.ts +8 -8
  137. package/src/{archiver/structs → structs}/published.ts +0 -1
  138. package/src/test/fake_l1_state.ts +607 -0
  139. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  140. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  141. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  142. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  143. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  144. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  145. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  146. package/src/test/index.ts +4 -0
  147. package/src/test/mock_archiver.ts +23 -16
  148. package/src/test/mock_l1_to_l2_message_source.ts +18 -11
  149. package/src/test/mock_l2_block_source.ts +296 -90
  150. package/src/test/mock_structs.ts +275 -13
  151. package/src/test/noop_l1_archiver.ts +109 -0
  152. package/dest/archiver/archiver.d.ts +0 -287
  153. package/dest/archiver/archiver.d.ts.map +0 -1
  154. package/dest/archiver/archiver.js +0 -1408
  155. package/dest/archiver/archiver_store.d.ts +0 -255
  156. package/dest/archiver/archiver_store.d.ts.map +0 -1
  157. package/dest/archiver/archiver_store.js +0 -4
  158. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  159. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  160. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  161. package/dest/archiver/config.d.ts +0 -21
  162. package/dest/archiver/config.d.ts.map +0 -1
  163. package/dest/archiver/data_retrieval.d.ts +0 -79
  164. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  165. package/dest/archiver/errors.d.ts +0 -12
  166. package/dest/archiver/errors.d.ts.map +0 -1
  167. package/dest/archiver/errors.js +0 -17
  168. package/dest/archiver/index.d.ts +0 -7
  169. package/dest/archiver/index.d.ts.map +0 -1
  170. package/dest/archiver/index.js +0 -4
  171. package/dest/archiver/instrumentation.d.ts +0 -35
  172. package/dest/archiver/instrumentation.d.ts.map +0 -1
  173. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  174. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  175. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  176. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  177. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  178. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  179. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  180. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  181. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  182. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  183. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  184. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  185. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  186. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  187. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  188. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  189. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  190. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  191. package/dest/archiver/structs/published.d.ts +0 -3
  192. package/dest/archiver/structs/published.d.ts.map +0 -1
  193. package/dest/archiver/validation.d.ts +0 -17
  194. package/dest/archiver/validation.d.ts.map +0 -1
  195. package/dest/rpc/index.d.ts +0 -9
  196. package/dest/rpc/index.d.ts.map +0 -1
  197. package/dest/rpc/index.js +0 -15
  198. package/src/archiver/archiver.ts +0 -1858
  199. package/src/archiver/archiver_store.ts +0 -305
  200. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  201. package/src/archiver/errors.ts +0 -26
  202. package/src/archiver/index.ts +0 -6
  203. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  204. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  205. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  206. package/src/rpc/index.ts +0 -16
  207. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  208. /package/dest/{archiver/structs → structs}/published.js +0 -0
  209. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,663 @@
1
+ import { MULTI_CALL_3_ADDRESS, type ViemCommitteeAttestations, type ViemHeader } from '@aztec/ethereum/contracts';
2
+ import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
3
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
4
+ import { Fr } from '@aztec/foundation/curves/bn254';
5
+ import { EthAddress } from '@aztec/foundation/eth-address';
6
+ import type { ViemSignature } from '@aztec/foundation/eth-signature';
7
+ import type { Logger } from '@aztec/foundation/log';
8
+ import {
9
+ EmpireSlashingProposerAbi,
10
+ GovernanceProposerAbi,
11
+ RollupAbi,
12
+ SlashFactoryAbi,
13
+ TallySlashingProposerAbi,
14
+ } from '@aztec/l1-artifacts';
15
+ import { CommitteeAttestation } from '@aztec/stdlib/block';
16
+ import { ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
17
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
18
+
19
+ import {
20
+ type AbiParameter,
21
+ type Hex,
22
+ type Transaction,
23
+ decodeFunctionData,
24
+ encodeAbiParameters,
25
+ hexToBytes,
26
+ keccak256,
27
+ multicall3Abi,
28
+ toFunctionSelector,
29
+ } from 'viem';
30
+
31
+ import type { ArchiverInstrumentation } from '../modules/instrumentation.js';
32
+ import { getSuccessfulCallsFromDebug } from './debug_tx.js';
33
+ import { getCallFromSpireProposer } from './spire_proposer.js';
34
+ import { getSuccessfulCallsFromTrace } from './trace_tx.js';
35
+ import type { CallInfo } from './types.js';
36
+
37
+ /**
38
+ * Extracts calldata to the `propose` method of the rollup contract from an L1 transaction
39
+ * in order to reconstruct an L2 block header.
40
+ */
41
+ export class CalldataRetriever {
42
+ /** Tx hashes we've already logged for trace+debug failure (log once per tx per process). */
43
+ private static readonly traceFailureWarnedTxHashes = new Set<string>();
44
+
45
+ /** Clears the trace-failure warned set. For testing only. */
46
+ static resetTraceFailureWarnedForTesting(): void {
47
+ CalldataRetriever.traceFailureWarnedTxHashes.clear();
48
+ }
49
+
50
+ /** Pre-computed valid contract calls for validation */
51
+ private readonly validContractCalls: ValidContractCall[];
52
+
53
+ private readonly rollupAddress: EthAddress;
54
+
55
+ constructor(
56
+ private readonly publicClient: ViemPublicClient,
57
+ private readonly debugClient: ViemPublicDebugClient,
58
+ private readonly targetCommitteeSize: number,
59
+ private readonly instrumentation: ArchiverInstrumentation | undefined,
60
+ 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
+ }
71
+
72
+ /**
73
+ * Gets checkpoint header and metadata from the calldata of an L1 transaction.
74
+ * Tries multicall3 decoding, falls back to trace-based extraction.
75
+ * @param txHash - Hash of the tx that published it.
76
+ * @param blobHashes - Blob hashes for the checkpoint.
77
+ * @param checkpointNumber - Checkpoint number.
78
+ * @param expectedHashes - Optional expected hashes from the CheckpointProposed event for validation
79
+ * @returns Checkpoint header and metadata from the calldata, deserialized
80
+ */
81
+ async getCheckpointFromRollupTx(
82
+ txHash: `0x${string}`,
83
+ _blobHashes: Buffer[],
84
+ checkpointNumber: CheckpointNumber,
85
+ expectedHashes: {
86
+ attestationsHash?: Hex;
87
+ payloadDigest?: Hex;
88
+ },
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
+ });
102
+ 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);
105
+ }
106
+
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) {
112
+ this.logger.trace(`Decoded propose calldata from multicall3 for tx ${tx.hash}`);
113
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
114
+ return proposeCalldata;
115
+ }
116
+
117
+ // Try to decode as direct propose call
118
+ const directProposeCalldata = this.tryDecodeDirectPropose(tx);
119
+ if (directProposeCalldata) {
120
+ this.logger.trace(`Decoded propose calldata from direct call for tx ${tx.hash}`);
121
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
122
+ return directProposeCalldata;
123
+ }
124
+
125
+ // Try to decode as Spire Proposer multicall wrapper
126
+ const spireProposeCalldata = await this.tryDecodeSpireProposer(tx);
127
+ if (spireProposeCalldata) {
128
+ this.logger.trace(`Decoded propose calldata from Spire Proposer for tx ${tx.hash}`);
129
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
130
+ return spireProposeCalldata;
131
+ }
132
+
133
+ // Fall back to trace-based extraction
134
+ this.logger.warn(
135
+ `Failed to decode multicall3, direct propose, or Spire proposer for L1 tx ${tx.hash}, falling back to trace for checkpoint ${checkpointNumber}`,
136
+ );
137
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to ?? EthAddress.ZERO.toString(), true);
138
+ return await this.extractCalldataViaTrace(tx.hash);
139
+ }
140
+
141
+ /**
142
+ * 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.
144
+ * @param tx - The transaction to decode
145
+ * @returns The propose calldata if successfully decoded and validated, undefined otherwise
146
+ */
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) {
151
+ return undefined;
152
+ }
153
+
154
+ this.logger.trace(`Decoded Spire Proposer wrapping for tx ${tx.hash}, inner call to ${spireWrappedCall.to}`);
155
+
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
+
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
+ }
164
+
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;
169
+ }
170
+
171
+ this.logger.warn(
172
+ `Spire Proposer wrapped call could not be decoded as multicall3 or direct propose for tx ${tx.hash}`,
173
+ );
174
+ return undefined;
175
+ }
176
+
177
+ /**
178
+ * Attempts to decode transaction input as multicall3 and extract propose calldata.
179
+ * Returns undefined if validation fails.
180
+ * @param tx - The transaction-like object with to, input, and hash
181
+ * @returns The propose calldata if successfully validated, undefined otherwise
182
+ */
183
+ protected tryDecodeMulticall3(tx: { to: Hex | null | undefined; input: Hex; hash: Hex }): Hex | undefined {
184
+ const txHash = tx.hash;
185
+
186
+ try {
187
+ // Check if transaction is to Multicall3 address
188
+ if (!tx.to || !EthAddress.areEqual(tx.to, MULTI_CALL_3_ADDRESS)) {
189
+ this.logger.debug(`Transaction is not to Multicall3 address (to: ${tx.to})`, { txHash, to: tx.to });
190
+ return undefined;
191
+ }
192
+
193
+ // Try to decode as multicall3 aggregate3 call
194
+ const { functionName: multicall3Fn, args: multicall3Args } = decodeFunctionData({
195
+ abi: multicall3Abi,
196
+ data: tx.input,
197
+ });
198
+
199
+ // If not aggregate3, return undefined (not a multicall3 transaction)
200
+ if (multicall3Fn !== 'aggregate3') {
201
+ this.logger.warn(`Transaction is not multicall3 aggregate3 (got ${multicall3Fn})`, { txHash });
202
+ return undefined;
203
+ }
204
+
205
+ if (multicall3Args.length !== 1) {
206
+ this.logger.warn(`Unexpected number of arguments for multicall3 (got ${multicall3Args.length})`, { txHash });
207
+ return undefined;
208
+ }
209
+
210
+ const [calls] = multicall3Args;
211
+
212
+ // Validate all calls and find propose calls
213
+ const rollupAddressLower = this.rollupAddress.toString().toLowerCase();
214
+ const proposeCalls: Hex[] = [];
215
+
216
+ for (let i = 0; i < calls.length; i++) {
217
+ const addr = calls[i].target.toLowerCase();
218
+ const callData = calls[i].callData;
219
+
220
+ // Extract function selector (first 4 bytes)
221
+ 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;
225
+ }
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
+
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;
242
+ }
243
+
244
+ this.logger.trace(`Valid call found to ${addr}`, { validCall });
245
+
246
+ // Collect propose calls specifically
247
+ if (addr === rollupAddressLower && validCall.functionName === 'propose') {
248
+ proposeCalls.push(callData);
249
+ }
250
+ }
251
+
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;
256
+ }
257
+
258
+ if (proposeCalls.length > 1) {
259
+ this.logger.warn(`Multiple propose calls found in multicall3 (${proposeCalls.length})`, { txHash });
260
+ return undefined;
261
+ }
262
+
263
+ // Successfully extracted single propose call
264
+ return proposeCalls[0];
265
+ } catch (err) {
266
+ // Any decoding error triggers fallback to trace
267
+ this.logger.warn(`Failed to decode multicall3: ${err}`, { txHash });
268
+ return undefined;
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Attempts to decode transaction as a direct propose call to the rollup contract.
274
+ * Returns undefined if validation fails.
275
+ * @param tx - The transaction-like object with to, input, and hash
276
+ * @returns The propose calldata if successfully validated, undefined otherwise
277
+ */
278
+ protected tryDecodeDirectPropose(tx: { to: Hex | null | undefined; input: Hex; hash: Hex }): Hex | undefined {
279
+ const txHash = tx.hash;
280
+ try {
281
+ // Check if transaction is to the rollup address
282
+ if (!tx.to || !EthAddress.areEqual(tx.to, this.rollupAddress)) {
283
+ this.logger.debug(`Transaction is not to rollup address (to: ${tx.to})`, { txHash });
284
+ return undefined;
285
+ }
286
+
287
+ // Try to decode as propose call
288
+ const { functionName } = decodeFunctionData({ abi: RollupAbi, data: tx.input });
289
+
290
+ // If not propose, return undefined
291
+ if (functionName !== 'propose') {
292
+ this.logger.warn(`Transaction to rollup is not propose (got ${functionName})`, { txHash });
293
+ return undefined;
294
+ }
295
+
296
+ // Successfully validated direct propose call
297
+ this.logger.trace(`Validated direct propose call to rollup`, { txHash });
298
+ return tx.input;
299
+ } catch (err) {
300
+ // Any decoding error means it's not a valid propose call
301
+ this.logger.warn(`Failed to decode as direct propose: ${err}`, { txHash });
302
+ return undefined;
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Uses debug/trace RPC to extract the actual calldata from the successful propose call.
308
+ * This is the definitive fallback that works for any transaction pattern.
309
+ * Tries trace_transaction first, then falls back to debug_traceTransaction.
310
+ * @param txHash - The transaction hash to trace
311
+ * @returns The propose calldata from the successful call
312
+ */
313
+ protected async extractCalldataViaTrace(txHash: Hex): Promise<Hex> {
314
+ const rollupAddress = this.rollupAddress;
315
+ const selector = PROPOSE_SELECTOR;
316
+
317
+ let calls: CallInfo[];
318
+ try {
319
+ // Try trace_transaction first (using Parity/OpenEthereum/Erigon RPC)
320
+ this.logger.debug(`Attempting to trace transaction ${txHash} using trace_transaction`);
321
+ calls = await getSuccessfulCallsFromTrace(this.debugClient, txHash, rollupAddress, selector, this.logger);
322
+ this.logger.debug(`Successfully traced using trace_transaction, found ${calls.length} calls`);
323
+ } catch (err) {
324
+ const traceError = err instanceof Error ? err : new Error(String(err));
325
+ this.logger.verbose(`Failed trace_transaction for ${txHash}: ${traceError.message}`);
326
+ this.logger.debug(`Trace failure details for ${txHash}`, { traceError });
327
+
328
+ try {
329
+ // Fall back to debug_traceTransaction (Geth RPC)
330
+ this.logger.debug(`Attempting to trace transaction ${txHash} using debug_traceTransaction`);
331
+ calls = await getSuccessfulCallsFromDebug(this.debugClient, txHash, rollupAddress, selector, this.logger);
332
+ this.logger.debug(`Successfully traced using debug_traceTransaction, found ${calls.length} calls`);
333
+ } catch (debugErr) {
334
+ const debugError = debugErr instanceof Error ? debugErr : new Error(String(debugErr));
335
+ // Log once per tx so we don't spam on every sync cycle when sync point doesn't advance
336
+ if (!CalldataRetriever.traceFailureWarnedTxHashes.has(txHash)) {
337
+ CalldataRetriever.traceFailureWarnedTxHashes.add(txHash);
338
+ this.logger.warn(
339
+ `Cannot decode L1 tx ${txHash}: trace and debug RPC failed or unavailable. ` +
340
+ `trace_transaction: ${traceError.message}; debug_traceTransaction: ${debugError.message}`,
341
+ );
342
+ }
343
+ // Full error objects can be very long; keep at debug only
344
+ this.logger.debug(`Trace/debug failure details for tx ${txHash}`, {
345
+ traceError,
346
+ debugError,
347
+ txHash,
348
+ });
349
+ throw new Error(`Failed to trace transaction ${txHash} to extract propose calldata`);
350
+ }
351
+ }
352
+
353
+ // Validate exactly ONE successful propose call
354
+ if (calls.length === 0) {
355
+ throw new Error(`No successful propose calls found in transaction ${txHash}`);
356
+ }
357
+
358
+ if (calls.length > 1) {
359
+ throw new Error(`Multiple successful propose calls found in transaction ${txHash} (${calls.length})`);
360
+ }
361
+
362
+ // Return the calldata from the single successful propose call
363
+ return calls[0].input;
364
+ }
365
+
366
+ /**
367
+ * Extracts the CommitteeAttestations struct definition from RollupAbi.
368
+ * Finds the _attestations parameter by name in the propose function.
369
+ * Lazy-loaded to avoid issues during module initialization.
370
+ */
371
+ private getCommitteeAttestationsStructDef(): AbiParameter {
372
+ const proposeFunction = RollupAbi.find(item => item.type === 'function' && item.name === 'propose') as
373
+ | { type: 'function'; name: string; inputs: readonly AbiParameter[] }
374
+ | undefined;
375
+
376
+ if (!proposeFunction) {
377
+ throw new Error('propose function not found in RollupAbi');
378
+ }
379
+
380
+ // Find the _attestations parameter by name, not by index
381
+ const attestationsParam = proposeFunction.inputs.find(param => param.name === '_attestations');
382
+
383
+ if (!attestationsParam) {
384
+ throw new Error('_attestations parameter not found in propose function');
385
+ }
386
+
387
+ if (attestationsParam.type !== 'tuple') {
388
+ throw new Error(`Expected _attestations parameter to be a tuple, got ${attestationsParam.type}`);
389
+ }
390
+
391
+ // Extract the tuple components (struct fields)
392
+ const tupleParam = attestationsParam as unknown as {
393
+ type: 'tuple';
394
+ components?: readonly AbiParameter[];
395
+ };
396
+
397
+ return {
398
+ type: 'tuple',
399
+ components: tupleParam.components || [],
400
+ } as AbiParameter;
401
+ }
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
+ }
523
+
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)
531
+ 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
+ }