@aztec/archiver 0.0.1-commit.e558bd1c → 0.0.1-commit.e5a3663dd

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 (126) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +26 -15
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +161 -153
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +16 -4
  8. package/dest/errors.d.ts +61 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +88 -14
  11. package/dest/factory.d.ts +6 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +40 -32
  14. package/dest/index.d.ts +11 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +10 -2
  17. package/dest/l1/bin/retrieve-calldata.js +32 -28
  18. package/dest/l1/calldata_retriever.d.ts +74 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +197 -260
  21. package/dest/l1/data_retrieval.d.ts +26 -17
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +42 -47
  24. package/dest/l1/spire_proposer.d.ts +5 -5
  25. package/dest/l1/spire_proposer.d.ts.map +1 -1
  26. package/dest/l1/spire_proposer.js +9 -17
  27. package/dest/l1/validate_historical_logs.d.ts +23 -0
  28. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  29. package/dest/l1/validate_historical_logs.js +108 -0
  30. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  31. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  32. package/dest/modules/contract_data_source_adapter.js +42 -0
  33. package/dest/modules/data_source_base.d.ts +27 -14
  34. package/dest/modules/data_source_base.d.ts.map +1 -1
  35. package/dest/modules/data_source_base.js +98 -125
  36. package/dest/modules/data_store_updater.d.ts +37 -17
  37. package/dest/modules/data_store_updater.d.ts.map +1 -1
  38. package/dest/modules/data_store_updater.js +155 -112
  39. package/dest/modules/instrumentation.d.ts +21 -3
  40. package/dest/modules/instrumentation.d.ts.map +1 -1
  41. package/dest/modules/instrumentation.js +41 -8
  42. package/dest/modules/l1_synchronizer.d.ts +13 -11
  43. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  44. package/dest/modules/l1_synchronizer.js +355 -182
  45. package/dest/modules/validation.d.ts +4 -3
  46. package/dest/modules/validation.d.ts.map +1 -1
  47. package/dest/modules/validation.js +6 -6
  48. package/dest/store/block_store.d.ts +107 -31
  49. package/dest/store/block_store.d.ts.map +1 -1
  50. package/dest/store/block_store.js +477 -141
  51. package/dest/store/contract_class_store.d.ts +17 -4
  52. package/dest/store/contract_class_store.d.ts.map +1 -1
  53. package/dest/store/contract_class_store.js +24 -68
  54. package/dest/store/contract_instance_store.d.ts +28 -1
  55. package/dest/store/contract_instance_store.d.ts.map +1 -1
  56. package/dest/store/contract_instance_store.js +37 -2
  57. package/dest/store/data_stores.d.ts +68 -0
  58. package/dest/store/data_stores.d.ts.map +1 -0
  59. package/dest/store/data_stores.js +50 -0
  60. package/dest/store/function_names_cache.d.ts +17 -0
  61. package/dest/store/function_names_cache.d.ts.map +1 -0
  62. package/dest/store/function_names_cache.js +30 -0
  63. package/dest/store/l2_tips_cache.d.ts +20 -0
  64. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  65. package/dest/store/l2_tips_cache.js +109 -0
  66. package/dest/store/log_store.d.ts +6 -3
  67. package/dest/store/log_store.d.ts.map +1 -1
  68. package/dest/store/log_store.js +95 -20
  69. package/dest/store/message_store.d.ts +11 -1
  70. package/dest/store/message_store.d.ts.map +1 -1
  71. package/dest/store/message_store.js +51 -9
  72. package/dest/test/fake_l1_state.d.ts +25 -1
  73. package/dest/test/fake_l1_state.d.ts.map +1 -1
  74. package/dest/test/fake_l1_state.js +166 -32
  75. package/dest/test/mock_archiver.d.ts +1 -1
  76. package/dest/test/mock_archiver.d.ts.map +1 -1
  77. package/dest/test/mock_archiver.js +3 -2
  78. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  79. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  80. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  81. package/dest/test/mock_l2_block_source.d.ts +35 -5
  82. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  83. package/dest/test/mock_l2_block_source.js +182 -89
  84. package/dest/test/mock_structs.d.ts +4 -1
  85. package/dest/test/mock_structs.d.ts.map +1 -1
  86. package/dest/test/mock_structs.js +13 -1
  87. package/dest/test/noop_l1_archiver.d.ts +7 -4
  88. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  89. package/dest/test/noop_l1_archiver.js +14 -8
  90. package/package.json +13 -13
  91. package/src/archiver.ts +199 -174
  92. package/src/config.ts +23 -2
  93. package/src/errors.ts +133 -22
  94. package/src/factory.ts +53 -30
  95. package/src/index.ts +18 -2
  96. package/src/l1/README.md +25 -68
  97. package/src/l1/bin/retrieve-calldata.ts +40 -27
  98. package/src/l1/calldata_retriever.ts +261 -379
  99. package/src/l1/data_retrieval.ts +58 -69
  100. package/src/l1/spire_proposer.ts +7 -15
  101. package/src/l1/validate_historical_logs.ts +140 -0
  102. package/src/modules/contract_data_source_adapter.ts +59 -0
  103. package/src/modules/data_source_base.ts +142 -144
  104. package/src/modules/data_store_updater.ts +187 -141
  105. package/src/modules/instrumentation.ts +56 -9
  106. package/src/modules/l1_synchronizer.ts +463 -218
  107. package/src/modules/validation.ts +10 -9
  108. package/src/store/block_store.ts +587 -177
  109. package/src/store/contract_class_store.ts +31 -103
  110. package/src/store/contract_instance_store.ts +51 -5
  111. package/src/store/data_stores.ts +108 -0
  112. package/src/store/function_names_cache.ts +37 -0
  113. package/src/store/l2_tips_cache.ts +134 -0
  114. package/src/store/log_store.ts +128 -32
  115. package/src/store/message_store.ts +60 -10
  116. package/src/structs/inbox_message.ts +1 -1
  117. package/src/test/fake_l1_state.ts +213 -42
  118. package/src/test/mock_archiver.ts +3 -2
  119. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  120. package/src/test/mock_l2_block_source.ts +230 -82
  121. package/src/test/mock_structs.ts +20 -6
  122. package/src/test/noop_l1_archiver.ts +16 -8
  123. package/dest/store/kv_archiver_store.d.ts +0 -340
  124. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  125. package/dest/store/kv_archiver_store.js +0 -446
  126. package/src/store/kv_archiver_store.ts +0 -639
@@ -35,20 +35,32 @@ import type { DataRetrieval } from '../structs/data_retrieval.js';
35
35
  import type { InboxMessage } from '../structs/inbox_message.js';
36
36
  import { CalldataRetriever } from './calldata_retriever.js';
37
37
 
38
- export type RetrievedCheckpoint = {
38
+ type RetrievedCheckpointBase = {
39
39
  checkpointNumber: CheckpointNumber;
40
40
  archiveRoot: Fr;
41
+ feeAssetPriceModifier: bigint;
41
42
  header: CheckpointHeader;
42
- checkpointBlobData: CheckpointBlobData;
43
43
  l1: L1PublishedData;
44
44
  chainId: Fr;
45
45
  version: Fr;
46
46
  attestations: CommitteeAttestation[];
47
47
  };
48
48
 
49
+ /** Checkpoint data as retrieved from L1 calldata and blob data. */
50
+ export type RetrievedCheckpoint = RetrievedCheckpointBase & { checkpointBlobData: CheckpointBlobData };
51
+
52
+ /** Checkpoint data retrieved from L1 calldata only, without blob data. */
53
+ export type RetrievedCheckpointFromCalldata = RetrievedCheckpointBase & {
54
+ /** Versioned blob hashes from the checkpoint proposed event. */
55
+ blobHashes: Buffer[];
56
+ /** Parent beacon block root from the L1 block, used for blob fetching. */
57
+ parentBeaconBlockRoot: string | undefined;
58
+ };
59
+
49
60
  export async function retrievedToPublishedCheckpoint({
50
61
  checkpointNumber,
51
62
  archiveRoot,
63
+ feeAssetPriceModifier,
52
64
  header: checkpointHeader,
53
65
  checkpointBlobData,
54
66
  l1,
@@ -128,42 +140,34 @@ export async function retrievedToPublishedCheckpoint({
128
140
  header: checkpointHeader,
129
141
  blocks: l2Blocks,
130
142
  number: checkpointNumber,
143
+ feeAssetPriceModifier: feeAssetPriceModifier,
131
144
  });
132
145
 
133
146
  return PublishedCheckpoint.from({ checkpoint, l1, attestations });
134
147
  }
135
148
 
136
149
  /**
137
- * Fetches new checkpoints.
150
+ * Fetches checkpoint calldata from the rollup contract without fetching blob data.
151
+ * Returns RetrievedCheckpointFromCalldata objects that preserve the information needed for deferred blob fetching.
138
152
  * @param rollup - The rollup contract wrapper.
139
153
  * @param publicClient - The viem public client to use for transaction retrieval.
140
154
  * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
141
- * @param blobClient - The blob client client for fetching blob data.
142
155
  * @param searchStartBlock - The block number to use for starting the search.
143
156
  * @param searchEndBlock - The highest block number that we should search up to.
144
- * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
145
157
  * @param instrumentation - The archiver instrumentation instance.
146
158
  * @param logger - The logger instance.
147
- * @param isHistoricalSync - Whether this is a historical sync.
148
- * @returns An array of retrieved checkpoints.
159
+ * @returns An array of calldata-only checkpoints.
149
160
  */
150
- export async function retrieveCheckpointsFromRollup(
161
+ export async function retrieveCheckpointCalldataFromRollup(
151
162
  rollup: RollupContract,
152
163
  publicClient: ViemPublicClient,
153
164
  debugClient: ViemPublicDebugClient,
154
- blobClient: BlobClientInterface,
155
165
  searchStartBlock: bigint,
156
166
  searchEndBlock: bigint,
157
- contractAddresses: {
158
- governanceProposerAddress: EthAddress;
159
- slashFactoryAddress?: EthAddress;
160
- slashingProposerAddress: EthAddress;
161
- },
162
167
  instrumentation: ArchiverInstrumentation,
163
168
  logger: Logger = createLogger('archiver'),
164
- isHistoricalSync: boolean = false,
165
- ): Promise<RetrievedCheckpoint[]> {
166
- const retrievedCheckpoints: RetrievedCheckpoint[] = [];
169
+ ): Promise<RetrievedCheckpointFromCalldata[]> {
170
+ const retrievedCheckpoints: RetrievedCheckpointFromCalldata[] = [];
167
171
 
168
172
  let rollupConstants: { chainId: Fr; version: Fr; targetCommitteeSize: number } | undefined;
169
173
 
@@ -199,60 +203,46 @@ export async function retrieveCheckpointsFromRollup(
199
203
  rollup,
200
204
  publicClient,
201
205
  debugClient,
202
- blobClient,
203
206
  checkpointProposedLogs,
204
207
  rollupConstants,
205
- contractAddresses,
206
208
  instrumentation,
207
209
  logger,
208
- isHistoricalSync,
209
210
  );
210
211
  retrievedCheckpoints.push(...newCheckpoints);
211
212
  searchStartBlock = lastLog.l1BlockNumber + 1n;
212
213
  } while (searchStartBlock <= searchEndBlock);
213
214
 
214
- // The asyncPool from processCheckpointProposedLogs will not necessarily return the checkpoints in order, so we sort them before returning.
215
215
  return retrievedCheckpoints.sort((a, b) => Number(a.l1.blockNumber - b.l1.blockNumber));
216
216
  }
217
217
 
218
218
  /**
219
- * Processes newly received CheckpointProposed logs.
219
+ * Processes CheckpointProposed logs, fetching only calldata (no blobs).
220
220
  * @param rollup - The rollup contract wrapper.
221
221
  * @param publicClient - The viem public client to use for transaction retrieval.
222
222
  * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
223
- * @param blobClient - The blob client client for fetching blob data.
224
223
  * @param logs - CheckpointProposed logs.
225
224
  * @param rollupConstants - The rollup constants (chainId, version, targetCommitteeSize).
226
- * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
227
225
  * @param instrumentation - The archiver instrumentation instance.
228
226
  * @param logger - The logger instance.
229
- * @param isHistoricalSync - Whether this is a historical sync.
230
- * @returns An array of retrieved checkpoints.
227
+ * @returns An array of calldata-only checkpoints.
231
228
  */
232
229
  async function processCheckpointProposedLogs(
233
230
  rollup: RollupContract,
234
231
  publicClient: ViemPublicClient,
235
232
  debugClient: ViemPublicDebugClient,
236
- blobClient: BlobClientInterface,
237
233
  logs: CheckpointProposedLog[],
238
234
  { chainId, version, targetCommitteeSize }: { chainId: Fr; version: Fr; targetCommitteeSize: number },
239
- contractAddresses: {
240
- governanceProposerAddress: EthAddress;
241
- slashFactoryAddress?: EthAddress;
242
- slashingProposerAddress: EthAddress;
243
- },
244
235
  instrumentation: ArchiverInstrumentation,
245
236
  logger: Logger,
246
- isHistoricalSync: boolean,
247
- ): Promise<RetrievedCheckpoint[]> {
248
- const retrievedCheckpoints: RetrievedCheckpoint[] = [];
237
+ ): Promise<RetrievedCheckpointFromCalldata[]> {
238
+ const retrievedCheckpoints: RetrievedCheckpointFromCalldata[] = [];
249
239
  const calldataRetriever = new CalldataRetriever(
250
240
  publicClient,
251
241
  debugClient,
252
242
  targetCommitteeSize,
253
243
  instrumentation,
254
244
  logger,
255
- { ...contractAddresses, rollupAddress: EthAddress.fromString(rollup.address) },
245
+ EthAddress.fromString(rollup.address),
256
246
  );
257
247
 
258
248
  await asyncPool(10, logs, async log => {
@@ -261,12 +251,10 @@ async function processCheckpointProposedLogs(
261
251
  const archiveFromChain = await rollup.archiveAt(checkpointNumber);
262
252
  const blobHashes = log.args.versionedBlobHashes;
263
253
 
264
- // The value from the event and contract will match only if the checkpoint is in the chain.
265
254
  if (archive.equals(archiveFromChain)) {
266
- // Build expected hashes object (fields may be undefined for backwards compatibility with older events)
267
255
  const expectedHashes = {
268
- attestationsHash: log.args.attestationsHash?.toString(),
269
- payloadDigest: log.args.payloadDigest?.toString(),
256
+ attestationsHash: log.args.attestationsHash.toString() as Hex,
257
+ payloadDigest: log.args.payloadDigest.toString() as Hex,
270
258
  };
271
259
 
272
260
  const checkpoint = await calldataRetriever.getCheckpointFromRollupTx(
@@ -275,23 +263,19 @@ async function processCheckpointProposedLogs(
275
263
  checkpointNumber,
276
264
  expectedHashes,
277
265
  );
278
- const checkpointBlobData = await getCheckpointBlobDataFromBlobs(
279
- blobClient,
280
- checkpoint.blockHash,
266
+ const { timestamp, parentBeaconBlockRoot } = await getL1Block(publicClient, log.l1BlockNumber);
267
+ const l1 = new L1PublishedData(log.l1BlockNumber, timestamp, log.l1BlockHash.toString());
268
+
269
+ retrievedCheckpoints.push({
270
+ ...checkpoint,
271
+ l1,
272
+ chainId,
273
+ version,
281
274
  blobHashes,
282
- checkpointNumber,
283
- logger,
284
- isHistoricalSync,
285
- );
286
-
287
- const l1 = new L1PublishedData(
288
- log.l1BlockNumber,
289
- await getL1BlockTime(publicClient, log.l1BlockNumber),
290
- log.l1BlockHash.toString(),
291
- );
275
+ parentBeaconBlockRoot,
276
+ });
292
277
 
293
- retrievedCheckpoints.push({ ...checkpoint, checkpointBlobData, l1, chainId, version });
294
- logger.trace(`Retrieved checkpoint ${checkpointNumber} from L1 tx ${log.l1TransactionHash}`, {
278
+ logger.trace(`Retrieved checkpoint calldata ${checkpointNumber} from L1 tx ${log.l1TransactionHash}`, {
295
279
  l1BlockNumber: log.l1BlockNumber,
296
280
  checkpointNumber,
297
281
  archive: archive.toString(),
@@ -308,9 +292,12 @@ async function processCheckpointProposedLogs(
308
292
  return retrievedCheckpoints;
309
293
  }
310
294
 
311
- export async function getL1BlockTime(publicClient: ViemPublicClient, blockNumber: bigint): Promise<bigint> {
295
+ export async function getL1Block(
296
+ publicClient: ViemPublicClient,
297
+ blockNumber: bigint,
298
+ ): Promise<{ timestamp: bigint; parentBeaconBlockRoot: string | undefined }> {
312
299
  const block = await publicClient.getBlock({ blockNumber, includeTransactions: false });
313
- return block.timestamp;
300
+ return { timestamp: block.timestamp, parentBeaconBlockRoot: block.parentBeaconBlockRoot };
314
301
  }
315
302
 
316
303
  export async function getCheckpointBlobDataFromBlobs(
@@ -320,8 +307,14 @@ export async function getCheckpointBlobDataFromBlobs(
320
307
  checkpointNumber: CheckpointNumber,
321
308
  logger: Logger,
322
309
  isHistoricalSync: boolean,
310
+ parentBeaconBlockRoot?: string,
311
+ l1BlockTimestamp?: bigint,
323
312
  ): Promise<CheckpointBlobData> {
324
- const blobBodies = await blobClient.getBlobSidecar(blockHash, blobHashes, { isHistoricalSync });
313
+ const blobBodies = await blobClient.getBlobSidecar(blockHash, blobHashes, {
314
+ isHistoricalSync,
315
+ parentBeaconBlockRoot,
316
+ l1BlockTimestamp,
317
+ });
325
318
  if (blobBodies.length === 0) {
326
319
  throw new NoBlobBodiesFoundError(checkpointNumber);
327
320
  }
@@ -346,14 +339,10 @@ export async function getCheckpointBlobDataFromBlobs(
346
339
  /** Given an L1 to L2 message, retrieves its corresponding event from the Inbox within a specific block range. */
347
340
  export async function retrieveL1ToL2Message(
348
341
  inbox: InboxContract,
349
- leaf: Fr,
350
- fromBlock: bigint,
351
- toBlock: bigint,
342
+ message: InboxMessage,
352
343
  ): Promise<InboxMessage | undefined> {
353
- const logs = await inbox.getMessageSentEventByHash(leaf.toString(), fromBlock, toBlock);
354
-
355
- const messages = mapLogsInboxMessage(logs);
356
- return messages.length > 0 ? messages[0] : undefined;
344
+ const log = await inbox.getMessageSentEventByHash(message.leaf.toString(), message.l1BlockNumber);
345
+ return log && mapLogInboxMessage(log);
357
346
  }
358
347
 
359
348
  /**
@@ -376,22 +365,22 @@ export async function retrieveL1ToL2Messages(
376
365
  break;
377
366
  }
378
367
 
379
- retrievedL1ToL2Messages.push(...mapLogsInboxMessage(messageSentLogs));
368
+ retrievedL1ToL2Messages.push(...messageSentLogs.map(mapLogInboxMessage));
380
369
  searchStartBlock = messageSentLogs.at(-1)!.l1BlockNumber + 1n;
381
370
  }
382
371
 
383
372
  return retrievedL1ToL2Messages;
384
373
  }
385
374
 
386
- function mapLogsInboxMessage(logs: MessageSentLog[]): InboxMessage[] {
387
- return logs.map(log => ({
375
+ function mapLogInboxMessage(log: MessageSentLog): InboxMessage {
376
+ return {
388
377
  index: log.args.index,
389
378
  leaf: log.args.leaf,
390
379
  l1BlockNumber: log.l1BlockNumber,
391
380
  l1BlockHash: log.l1BlockHash,
392
381
  checkpointNumber: log.args.checkpointNumber,
393
382
  rollingHash: log.args.rollingHash,
394
- }));
383
+ };
395
384
  }
396
385
 
397
386
  /** Retrieves L2ProofVerified events from the rollup contract. */
@@ -87,17 +87,17 @@ export async function verifyProxyImplementation(
87
87
  /**
88
88
  * Attempts to decode transaction as a Spire Proposer Multicall.
89
89
  * Spire Proposer is a proxy contract that wraps multiple calls.
90
- * Returns the target address and calldata of the wrapped call if validation succeeds and there is a single call.
90
+ * Returns all wrapped calls if validation succeeds (caller handles hash matching to find the propose call).
91
91
  * @param tx - The transaction to decode
92
92
  * @param publicClient - The viem public client for proxy verification
93
93
  * @param logger - Logger instance
94
- * @returns Object with 'to' and 'data' of the wrapped call, or undefined if validation fails
94
+ * @returns Array of wrapped calls with 'to' and 'data', or undefined if not a valid Spire Proposer tx
95
95
  */
96
- export async function getCallFromSpireProposer(
96
+ export async function getCallsFromSpireProposer(
97
97
  tx: Transaction,
98
98
  publicClient: { getStorageAt: (params: { address: Hex; slot: Hex }) => Promise<Hex | undefined> },
99
99
  logger: Logger,
100
- ): Promise<{ to: Hex; data: Hex } | undefined> {
100
+ ): Promise<{ to: Hex; data: Hex }[] | undefined> {
101
101
  const txHash = tx.hash;
102
102
 
103
103
  try {
@@ -141,17 +141,9 @@ export async function getCallFromSpireProposer(
141
141
 
142
142
  const [calls] = spireArgs;
143
143
 
144
- // Validate exactly ONE call (see ./README.md for rationale)
145
- if (calls.length !== 1) {
146
- logger.warn(`Spire Proposer multicall must contain exactly one call (got ${calls.length})`, { txHash });
147
- return undefined;
148
- }
149
-
150
- const call = calls[0];
151
-
152
- // Successfully extracted the single wrapped call
153
- logger.trace(`Decoded Spire Proposer with single call to ${call.target}`, { txHash });
154
- return { to: call.target, data: call.data };
144
+ // Return all wrapped calls (hash matching in the caller determines which is the propose call)
145
+ logger.trace(`Decoded Spire Proposer with ${calls.length} call(s)`, { txHash });
146
+ return calls.map(call => ({ to: call.target, data: call.data }));
155
147
  } catch (err) {
156
148
  // Any decoding error triggers fallback to trace
157
149
  logger.warn(`Failed to decode Spire Proposer: ${err}`, { txHash });
@@ -0,0 +1,140 @@
1
+ import { getPublicClient, getRpcUrlsFromClient } from '@aztec/ethereum/client';
2
+ import { RollupContract } from '@aztec/ethereum/contracts';
3
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
4
+ import type { ViemPublicClient } from '@aztec/ethereum/types';
5
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
6
+
7
+ /** Subset of L1 contract addresses whose historical logs the Aztec node relies on. */
8
+ export type HistoricalLogsContractAddresses = Pick<
9
+ L1ContractAddresses,
10
+ 'rollupAddress' | 'inboxAddress' | 'registryAddress' | 'governanceProposerAddress'
11
+ >;
12
+
13
+ /** Result of probing a single RPC URL. */
14
+ type ProbeResult = { ok: true } | { ok: false; reason: string; clientVersion: string | undefined };
15
+
16
+ /**
17
+ * Validates that every configured L1 RPC URL returns historical logs for the Rollup contract.
18
+ *
19
+ * Some RPC providers prune old logs, which would cause L1 syncing to silently fail. To detect this,
20
+ * we query for the `OwnershipTransferred` event which every Rollup emits in its constructor (via
21
+ * Ownable) on the block it was deployed (`l1StartBlock`). The `client` is typically a viem fallback
22
+ * transport over several user-configured RPC URLs — checking only the first URL would miss a bad
23
+ * secondary, so we probe each URL independently. The first URL that fails aborts startup, unless
24
+ * the operator has explicitly opted out.
25
+ *
26
+ * @param client - The L1 public client built from the user-configured RPC URLs.
27
+ * @param addresses - The subset of L1 contract addresses we rely on for historical log retrieval.
28
+ * @param skipCheck - If true, log warnings instead of throwing.
29
+ * @param bindings - Optional logger bindings for context.
30
+ * @throws Error if any URL fails the probe and skipCheck is false.
31
+ */
32
+ export async function validateAndLogHistoricalLogsAvailability(
33
+ client: ViemPublicClient,
34
+ addresses: HistoricalLogsContractAddresses,
35
+ skipCheck: boolean,
36
+ bindings?: LoggerBindings,
37
+ ): Promise<void> {
38
+ const logger = createLogger('archiver:validate_historical_logs', bindings);
39
+ logger.debug('Validating historical log availability on L1 RPCs');
40
+
41
+ const urls = getRpcUrlsFromClient(client);
42
+ if (urls.length === 0) {
43
+ logger.warn('Could not determine L1 RPC URLs from the public client; skipping historical logs check.');
44
+ return;
45
+ }
46
+
47
+ const chainId = client.chain?.id;
48
+ if (chainId === undefined) {
49
+ logger.warn('Could not determine L1 chain ID from the public client; skipping historical logs check.');
50
+ return;
51
+ }
52
+
53
+ for (const url of urls) {
54
+ const probeClient = getPublicClient({ l1RpcUrls: [url], l1ChainId: chainId });
55
+ const rollup = new RollupContract(probeClient, addresses.rollupAddress.toString());
56
+ const result = await probeRpcUrl(rollup, probeClient, logger);
57
+
58
+ if (result.ok) {
59
+ logger.debug(`L1 RPC ${url} returned historical OwnershipTransferred log for the Rollup contract.`);
60
+ continue;
61
+ }
62
+
63
+ const errorMessage = buildErrorMessage(url, result, addresses);
64
+ if (skipCheck) {
65
+ logger.warn(`${errorMessage}\nContinuing because ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK is true.`);
66
+ continue;
67
+ }
68
+
69
+ logger.error(errorMessage);
70
+ throw new Error(errorMessage);
71
+ }
72
+ }
73
+
74
+ /** Runs the OwnershipTransferred probe against a single RPC and queries its client version. */
75
+ async function probeRpcUrl(rollup: RollupContract, client: ViemPublicClient, logger: Logger): Promise<ProbeResult> {
76
+ let queryError: unknown;
77
+ try {
78
+ const logs = await rollup.getOwnershipTransferredEventsAtDeploy();
79
+ if (logs.length > 0) {
80
+ return { ok: true };
81
+ }
82
+ } catch (err) {
83
+ queryError = err;
84
+ }
85
+
86
+ const clientVersion = await getClientVersion(client, logger);
87
+
88
+ let reason: string;
89
+ if (queryError instanceof Error) {
90
+ reason = `Query for historical logs failed: ${queryError.message}`;
91
+ } else if (queryError !== undefined) {
92
+ reason = 'Query for historical logs failed with a non-Error value.';
93
+ } else {
94
+ reason = 'No OwnershipTransferred event was returned by the L1 RPC for the Rollup deploy block.';
95
+ }
96
+ return { ok: false, reason, clientVersion };
97
+ }
98
+
99
+ /** Builds the operator-facing error message for a failing RPC URL. */
100
+ function buildErrorMessage(
101
+ url: string,
102
+ result: Extract<ProbeResult, { ok: false }>,
103
+ addresses: HistoricalLogsContractAddresses,
104
+ ): string {
105
+ return [
106
+ `L1 RPC at ${url} does not return historical logs for the Rollup contract. ${result.reason}`,
107
+ `This likely means this Ethereum RPC node prunes old logs, which would cause the archiver ` +
108
+ `to silently miss data during L1 sync.`,
109
+ result.clientVersion
110
+ ? `Detected L1 client version for ${url}: ${result.clientVersion}.`
111
+ : `Could not determine L1 client version for ${url}.`,
112
+ `The following L1 contract addresses must have their historical logs retained by the RPC node:`,
113
+ ` - Rollup: ${addresses.rollupAddress.toString()}`,
114
+ ` - Inbox: ${addresses.inboxAddress.toString()}`,
115
+ ` - Registry: ${addresses.registryAddress.toString()}`,
116
+ ` - GovernanceProposer: ${addresses.governanceProposerAddress.toString()}`,
117
+ isReth(result.clientVersion)
118
+ ? `To retain logs for these contracts, configure reth with a ` +
119
+ `prune.segments.receipts_log_filter entry for each address above ` +
120
+ `so reth does not prune their receipts/logs. See https://reth.rs/run/pruning.html for details.`
121
+ : `Point this RPC endpoint at a node that retains full log history for the addresses above.`,
122
+ `Set ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK=true to bypass this check at your own risk.`,
123
+ ].join('\n');
124
+ }
125
+
126
+ /** Queries `web3_clientVersion` on the L1 RPC. Returns undefined if the call fails or returns a non-string. */
127
+ async function getClientVersion(client: ViemPublicClient, logger: Logger): Promise<string | undefined> {
128
+ try {
129
+ const result = await client.request({ method: 'web3_clientVersion' });
130
+ return typeof result === 'string' ? result : undefined;
131
+ } catch (err) {
132
+ logger.debug(`Failed to query web3_clientVersion: ${err instanceof Error ? err.message : err}`);
133
+ return undefined;
134
+ }
135
+ }
136
+
137
+ /** Heuristic check for reth based on the web3_clientVersion string (reth returns e.g. "reth/v1.0.0-..."). */
138
+ function isReth(clientVersion: string | undefined): boolean {
139
+ return !!clientVersion && /reth/i.test(clientVersion);
140
+ }
@@ -0,0 +1,59 @@
1
+ import type { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import type { Fr } from '@aztec/foundation/curves/bn254';
3
+ import type { FunctionSelector } from '@aztec/stdlib/abi';
4
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
5
+ import type { ContractClassPublic, ContractDataSource, ContractInstanceWithAddress } from '@aztec/stdlib/contract';
6
+ import type { UInt64 } from '@aztec/stdlib/types';
7
+
8
+ import type { ArchiverDataStores } from '../store/data_stores.js';
9
+
10
+ /**
11
+ * Thin {@link ContractDataSource} adapter over {@link ArchiverDataStores}.
12
+ *
13
+ * Used by contexts (e.g. offline epoch re-prover tools) that need a ContractDataSource
14
+ * but do not need a full archiver instance.
15
+ */
16
+ export class ArchiverContractDataSourceAdapter implements ContractDataSource {
17
+ constructor(private readonly stores: ArchiverDataStores) {}
18
+
19
+ public getBlockNumber(): Promise<BlockNumber> {
20
+ return this.stores.blocks.getLatestL2BlockNumber();
21
+ }
22
+
23
+ public getContractClass(id: Fr): Promise<ContractClassPublic | undefined> {
24
+ return this.stores.contractClasses.getContractClass(id);
25
+ }
26
+
27
+ public getBytecodeCommitment(id: Fr): Promise<Fr | undefined> {
28
+ return this.stores.contractClasses.getBytecodeCommitment(id);
29
+ }
30
+
31
+ public async getContract(
32
+ address: AztecAddress,
33
+ maybeTimestamp?: UInt64,
34
+ ): Promise<ContractInstanceWithAddress | undefined> {
35
+ let timestamp = maybeTimestamp;
36
+ if (timestamp === undefined) {
37
+ const latest = await this.stores.blocks.getLatestL2BlockNumber();
38
+ if ((latest as BlockNumber) === 0) {
39
+ timestamp = 0n;
40
+ } else {
41
+ const [header] = await this.stores.blocks.getBlockHeaders(latest, 1);
42
+ timestamp = header ? header.globalVariables.timestamp : 0n;
43
+ }
44
+ }
45
+ return this.stores.contractInstances.getContractInstance(address, timestamp);
46
+ }
47
+
48
+ public getContractClassIds(): Promise<Fr[]> {
49
+ return this.stores.contractClasses.getContractClassIds();
50
+ }
51
+
52
+ public getDebugFunctionName(_address: AztecAddress, selector: FunctionSelector): Promise<string | undefined> {
53
+ return Promise.resolve(this.stores.functionNames.get(selector));
54
+ }
55
+
56
+ public registerContractFunctionSignatures(signatures: string[]): Promise<void> {
57
+ return this.stores.functionNames.register(signatures);
58
+ }
59
+ }