@aztec/archiver 0.0.1-commit.5de5ca79e → 0.0.1-commit.6201a7b05

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 (99) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +16 -7
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +104 -48
  5. package/dest/config.d.ts +3 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +14 -3
  8. package/dest/errors.d.ts +41 -2
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +62 -1
  11. package/dest/factory.d.ts +2 -2
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +9 -7
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -1
  17. package/dest/l1/calldata_retriever.d.ts +2 -1
  18. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  19. package/dest/l1/calldata_retriever.js +11 -5
  20. package/dest/l1/data_retrieval.d.ts +19 -10
  21. package/dest/l1/data_retrieval.d.ts.map +1 -1
  22. package/dest/l1/data_retrieval.js +25 -32
  23. package/dest/l1/validate_historical_logs.d.ts +23 -0
  24. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  25. package/dest/l1/validate_historical_logs.js +108 -0
  26. package/dest/modules/data_source_base.d.ts +8 -2
  27. package/dest/modules/data_source_base.d.ts.map +1 -1
  28. package/dest/modules/data_source_base.js +19 -1
  29. package/dest/modules/data_store_updater.d.ts +15 -10
  30. package/dest/modules/data_store_updater.d.ts.map +1 -1
  31. package/dest/modules/data_store_updater.js +71 -68
  32. package/dest/modules/instrumentation.d.ts +7 -2
  33. package/dest/modules/instrumentation.d.ts.map +1 -1
  34. package/dest/modules/instrumentation.js +22 -6
  35. package/dest/modules/l1_synchronizer.d.ts +7 -2
  36. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  37. package/dest/modules/l1_synchronizer.js +261 -143
  38. package/dest/modules/validation.d.ts +4 -3
  39. package/dest/modules/validation.d.ts.map +1 -1
  40. package/dest/modules/validation.js +6 -6
  41. package/dest/store/block_store.d.ts +72 -5
  42. package/dest/store/block_store.d.ts.map +1 -1
  43. package/dest/store/block_store.js +341 -66
  44. package/dest/store/contract_class_store.d.ts +2 -3
  45. package/dest/store/contract_class_store.d.ts.map +1 -1
  46. package/dest/store/contract_class_store.js +7 -67
  47. package/dest/store/contract_instance_store.d.ts +1 -1
  48. package/dest/store/contract_instance_store.d.ts.map +1 -1
  49. package/dest/store/contract_instance_store.js +6 -2
  50. package/dest/store/kv_archiver_store.d.ts +51 -17
  51. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  52. package/dest/store/kv_archiver_store.js +60 -16
  53. package/dest/store/l2_tips_cache.d.ts +2 -1
  54. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  55. package/dest/store/l2_tips_cache.js +27 -7
  56. package/dest/store/log_store.d.ts +1 -1
  57. package/dest/store/log_store.d.ts.map +1 -1
  58. package/dest/store/log_store.js +2 -4
  59. package/dest/store/message_store.d.ts +3 -3
  60. package/dest/store/message_store.d.ts.map +1 -1
  61. package/dest/store/message_store.js +9 -10
  62. package/dest/test/fake_l1_state.d.ts +15 -3
  63. package/dest/test/fake_l1_state.d.ts.map +1 -1
  64. package/dest/test/fake_l1_state.js +80 -18
  65. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  66. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  67. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  68. package/dest/test/mock_l2_block_source.d.ts +16 -2
  69. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  70. package/dest/test/mock_l2_block_source.js +50 -3
  71. package/dest/test/noop_l1_archiver.d.ts +1 -1
  72. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  73. package/dest/test/noop_l1_archiver.js +4 -2
  74. package/package.json +13 -13
  75. package/src/archiver.ts +126 -46
  76. package/src/config.ts +15 -1
  77. package/src/errors.ts +97 -2
  78. package/src/factory.ts +13 -7
  79. package/src/index.ts +2 -1
  80. package/src/l1/calldata_retriever.ts +17 -5
  81. package/src/l1/data_retrieval.ts +36 -45
  82. package/src/l1/validate_historical_logs.ts +140 -0
  83. package/src/modules/data_source_base.ts +32 -1
  84. package/src/modules/data_store_updater.ts +98 -97
  85. package/src/modules/instrumentation.ts +27 -7
  86. package/src/modules/l1_synchronizer.ts +328 -169
  87. package/src/modules/validation.ts +10 -9
  88. package/src/store/block_store.ts +419 -76
  89. package/src/store/contract_class_store.ts +8 -106
  90. package/src/store/contract_instance_store.ts +8 -5
  91. package/src/store/kv_archiver_store.ts +100 -32
  92. package/src/store/l2_tips_cache.ts +58 -13
  93. package/src/store/log_store.ts +2 -5
  94. package/src/store/message_store.ts +10 -12
  95. package/src/structs/inbox_message.ts +1 -1
  96. package/src/test/fake_l1_state.ts +99 -27
  97. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  98. package/src/test/mock_l2_block_source.ts +58 -2
  99. package/src/test/noop_l1_archiver.ts +3 -1
@@ -1,33 +1,40 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import { EpochCache } from '@aztec/epoch-cache';
3
- import { InboxContract, RollupContract } from '@aztec/ethereum/contracts';
3
+ import { InboxContract, type InboxContractState, RollupContract } from '@aztec/ethereum/contracts';
4
4
  import type { L1BlockId } from '@aztec/ethereum/l1-types';
5
+ import { getFinalizedL1Block } from '@aztec/ethereum/queries';
5
6
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
6
7
  import { asyncPool } from '@aztec/foundation/async-pool';
7
8
  import { maxBigint } from '@aztec/foundation/bigint';
8
9
  import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
9
- import { Buffer32 } from '@aztec/foundation/buffer';
10
- import { pick } from '@aztec/foundation/collection';
10
+ import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
11
+ import { partition, pick } from '@aztec/foundation/collection';
11
12
  import { Fr } from '@aztec/foundation/curves/bn254';
13
+ import { EthAddress } from '@aztec/foundation/eth-address';
12
14
  import { type Logger, createLogger } from '@aztec/foundation/log';
15
+ import { retryTimes } from '@aztec/foundation/retry';
13
16
  import { count } from '@aztec/foundation/string';
14
17
  import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
15
- import { isDefined } from '@aztec/foundation/types';
18
+ import { isDefined, isErrorClass } from '@aztec/foundation/types';
16
19
  import { type ArchiverEmitter, L2BlockSourceEvents, type ValidateCheckpointResult } from '@aztec/stdlib/block';
17
- import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
20
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
18
21
  import { type L1RollupConstants, getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
19
22
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
23
+ import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
20
24
  import { type Traceable, type Tracer, execInSpan, trackSpan } from '@aztec/telemetry-client';
21
25
 
22
26
  import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
23
27
  import {
24
- retrieveCheckpointsFromRollup,
28
+ type RetrievedCheckpointFromCalldata,
29
+ getCheckpointBlobDataFromBlobs,
30
+ retrieveCheckpointCalldataFromRollup,
25
31
  retrieveL1ToL2Message,
26
32
  retrieveL1ToL2Messages,
27
33
  retrievedToPublishedCheckpoint,
28
34
  } from '../l1/data_retrieval.js';
29
35
  import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
30
36
  import type { L2TipsCache } from '../store/l2_tips_cache.js';
37
+ import { MessageStoreError } from '../store/message_store.js';
31
38
  import type { InboxMessage } from '../structs/inbox_message.js';
32
39
  import { ArchiverDataStoreUpdater } from './data_store_updater.js';
33
40
  import type { ArchiverInstrumentation } from './instrumentation.js';
@@ -64,6 +71,7 @@ export class ArchiverL1Synchronizer implements Traceable {
64
71
  private config: {
65
72
  batchSize: number;
66
73
  skipValidateCheckpointAttestations?: boolean;
74
+ skipPromoteProposedCheckpointDuringL1Sync?: boolean;
67
75
  maxAllowedEthClientDriftSeconds: number;
68
76
  },
69
77
  private readonly blobClient: BlobClientInterface,
@@ -89,6 +97,7 @@ export class ArchiverL1Synchronizer implements Traceable {
89
97
  public setConfig(newConfig: {
90
98
  batchSize: number;
91
99
  skipValidateCheckpointAttestations?: boolean;
100
+ skipPromoteProposedCheckpointDuringL1Sync?: boolean;
92
101
  maxAllowedEthClientDriftSeconds: number;
93
102
  }) {
94
103
  this.config = newConfig;
@@ -104,6 +113,13 @@ export class ArchiverL1Synchronizer implements Traceable {
104
113
  return this.l1Timestamp;
105
114
  }
106
115
 
116
+ private getSignatureContext(): CoordinationSignatureContext {
117
+ return {
118
+ chainId: this.publicClient.chain.id,
119
+ rollupAddress: EthAddress.fromString(this.rollup.address),
120
+ };
121
+ }
122
+
107
123
  /** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */
108
124
  public async testEthereumNodeSynced(): Promise<void> {
109
125
  const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
@@ -121,10 +137,15 @@ export class ArchiverL1Synchronizer implements Traceable {
121
137
 
122
138
  @trackSpan('Archiver.syncFromL1')
123
139
  public async syncFromL1(initialSyncComplete: boolean): Promise<void> {
140
+ // In between the various calls to L1, the block number can move meaning some of the following
141
+ // calls will return data for blocks that were not present during earlier calls. To combat this
142
+ // we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
143
+ // captured at the top of this function.
124
144
  const currentL1Block = await this.publicClient.getBlock({ includeTransactions: false });
125
145
  const currentL1BlockNumber = currentL1Block.number;
126
146
  const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
127
147
  const currentL1Timestamp = currentL1Block.timestamp;
148
+ const currentL1BlockData = { l1BlockNumber: currentL1BlockNumber, l1BlockHash: currentL1BlockHash };
128
149
 
129
150
  if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
130
151
  this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
@@ -141,45 +162,15 @@ export class ArchiverL1Synchronizer implements Traceable {
141
162
  );
142
163
  }
143
164
 
144
- // Load sync point for blocks and messages defaulting to start block
145
- const {
146
- blocksSynchedTo = this.l1Constants.l1StartBlock,
147
- messagesSynchedTo = {
148
- l1BlockNumber: this.l1Constants.l1StartBlock,
149
- l1BlockHash: this.l1Constants.l1StartBlockHash,
150
- },
151
- } = await this.store.getSynchPoint();
165
+ // Load sync point for blocks defaulting to start block
166
+ const { blocksSynchedTo = this.l1Constants.l1StartBlock } = await this.store.getSynchPoint();
167
+ this.log.debug(`Starting new archiver sync iteration`, { blocksSynchedTo, currentL1BlockData });
152
168
 
153
- this.log.debug(`Starting new archiver sync iteration`, {
154
- blocksSynchedTo,
155
- messagesSynchedTo,
156
- currentL1BlockNumber,
157
- currentL1BlockHash,
158
- });
169
+ // Sync L1 to L2 messages. We retry this a few times since there are error conditions that reset the sync point, requiring a new iteration.
170
+ // Note that we cannot just wait for the l1 synchronizer to loop again, since the synchronizer would report as synced up to the current L1
171
+ // block, when that wouldn't be the case, since L1 to L2 messages would need another iteration.
172
+ await retryTimes(() => this.handleL1ToL2Messages(currentL1BlockData), 'Handling L1 to L2 messages', 3, 0.1);
159
173
 
160
- // ********** Ensuring Consistency of data pulled from L1 **********
161
-
162
- /**
163
- * There are a number of calls in this sync operation to L1 for retrieving
164
- * events and transaction data. There are a couple of things we need to bear in mind
165
- * to ensure that data is read exactly once.
166
- *
167
- * The first is the problem of eventually consistent ETH service providers like Infura.
168
- * Each L1 read operation will query data from the last L1 block that it saw emit its kind of data.
169
- * (so pending L1 to L2 messages will read from the last L1 block that emitted a message and so on)
170
- * This will mean the archiver will lag behind L1 and will only advance when there's L2-relevant activity on the chain.
171
- *
172
- * The second is that in between the various calls to L1, the block number can move meaning some
173
- * of the following calls will return data for blocks that were not present during earlier calls.
174
- * To combat this for the time being we simply ensure that all data retrieval methods only retrieve
175
- * data up to the currentBlockNumber captured at the top of this function. We might want to improve on this
176
- * in future but for the time being it should give us the guarantees that we need
177
- */
178
-
179
- // ********** Events that are processed per L1 block **********
180
- await this.handleL1ToL2Messages(messagesSynchedTo, currentL1BlockNumber);
181
-
182
- // ********** Events that are processed per checkpoint **********
183
174
  if (currentL1BlockNumber > blocksSynchedTo) {
184
175
  // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
185
176
  // pending chain validation status, proven checkpoint number, and synched L1 block number.
@@ -238,7 +229,11 @@ export class ArchiverL1Synchronizer implements Traceable {
238
229
  /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */
239
230
  private async updateFinalizedCheckpoint(): Promise<void> {
240
231
  try {
241
- const finalizedL1Block = await this.publicClient.getBlock({ blockTag: 'finalized', includeTransactions: false });
232
+ const finalizedL1Block = await getFinalizedL1Block(this.publicClient);
233
+ if (!finalizedL1Block) {
234
+ this.log.trace(`Skipping finalized checkpoint update: L1 has no finalized block yet.`);
235
+ return;
236
+ }
242
237
  const finalizedL1BlockNumber = finalizedL1Block.number;
243
238
  const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
244
239
  blockNumber: finalizedL1BlockNumber,
@@ -251,8 +246,11 @@ export class ArchiverL1Synchronizer implements Traceable {
251
246
  finalizedL1BlockNumber,
252
247
  });
253
248
  }
254
- } catch (err) {
255
- this.log.warn(`Failed to update finalized checkpoint: ${err}`);
249
+ } catch (err: any) {
250
+ // The rollup contract may not exist at the finalized L1 block right after deployment.
251
+ if (!err?.message?.includes('returned no data')) {
252
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
253
+ }
256
254
  }
257
255
  }
258
256
 
@@ -269,29 +267,33 @@ export class ArchiverL1Synchronizer implements Traceable {
269
267
  return;
270
268
  }
271
269
 
272
- // What's the slot of the first uncheckpointed block?
270
+ // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
271
+ const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
273
272
  const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
273
+
274
+ // What's the slot of the first uncheckpointed block?
274
275
  const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
275
276
  const firstUncheckpointedBlockSlot = firstUncheckpointedBlockHeader?.getSlot();
276
277
 
277
- // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
278
- const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
278
+ if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
279
+ return;
280
+ }
279
281
 
280
- // Prune provisional blocks from slots that have ended without being checkpointed
281
- if (firstUncheckpointedBlockSlot !== undefined && firstUncheckpointedBlockSlot < slotAtNextL1Block) {
282
- this.log.warn(
283
- `Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
284
- { firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(), slotAtNextL1Block },
285
- );
286
- const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
282
+ // Prune provisional blocks from slots that have ended without being checkpointed.
283
+ // This also clears any proposed checkpoint whose blocks are being pruned.
284
+ this.log.warn(
285
+ `Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
286
+ { firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(), slotAtNextL1Block },
287
+ );
287
288
 
288
- if (prunedBlocks.length > 0) {
289
- this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
290
- type: L2BlockSourceEvents.L2PruneUncheckpointed,
291
- slotNumber: firstUncheckpointedBlockSlot,
292
- blocks: prunedBlocks,
293
- });
294
- }
289
+ const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
290
+
291
+ if (prunedBlocks.length > 0) {
292
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
293
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
294
+ slotNumber: firstUncheckpointedBlockSlot,
295
+ blocks: prunedBlocks,
296
+ });
295
297
  }
296
298
  }
297
299
 
@@ -385,64 +387,87 @@ export class ArchiverL1Synchronizer implements Traceable {
385
387
  }
386
388
 
387
389
  @trackSpan('Archiver.handleL1ToL2Messages')
388
- private async handleL1ToL2Messages(messagesSyncPoint: L1BlockId, currentL1BlockNumber: bigint): Promise<void> {
389
- this.log.trace(`Handling L1 to L2 messages from ${messagesSyncPoint.l1BlockNumber} to ${currentL1BlockNumber}.`);
390
- if (currentL1BlockNumber <= messagesSyncPoint.l1BlockNumber) {
391
- return;
390
+ private async handleL1ToL2Messages(currentL1Block: L1BlockId): Promise<boolean> {
391
+ // Load the syncpoint, which may have been updated in a previous iteration
392
+ const {
393
+ messagesSynchedTo = {
394
+ l1BlockNumber: this.l1Constants.l1StartBlock,
395
+ l1BlockHash: this.l1Constants.l1StartBlockHash,
396
+ },
397
+ } = await this.store.getSynchPoint();
398
+
399
+ // Nothing to do if L1 block number has not moved forward
400
+ const currentL1BlockNumber = currentL1Block.l1BlockNumber;
401
+ if (currentL1BlockNumber <= messagesSynchedTo.l1BlockNumber) {
402
+ return true;
392
403
  }
393
404
 
394
- // Load remote and local inbox states.
395
- const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
396
- const localLastMessage = await this.store.getLastL1ToL2Message();
405
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
397
406
  const remoteMessagesState = await this.inbox.getState({ blockNumber: currentL1BlockNumber });
398
- await this.store.setInboxTreeInProgress(remoteMessagesState.treeInProgress);
407
+ const localLastMessage = await this.store.getLastL1ToL2Message();
408
+ if (await this.localStateMatches(localLastMessage, remoteMessagesState)) {
409
+ this.log.trace(`Local L1 to L2 messages are already in sync with remote at L1 block ${currentL1BlockNumber}`);
410
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
411
+ return true;
412
+ }
399
413
 
400
- this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
401
- localMessagesInserted,
402
- localLastMessage,
403
- remoteMessagesState,
404
- });
414
+ // If not, then we are out of sync. Most likely there are new messages on the inbox, so we try retrieving them.
415
+ // However, it could also be the case that there was an L1 reorg and our syncpoint is no longer valid.
416
+ // If that's the case, we'd get an exception out of the message store since the rolling hash of the first message
417
+ // we try to insert would not match the one in the db, in which case we rollback to the last common message with L1.
418
+ try {
419
+ await this.retrieveAndStoreMessages(messagesSynchedTo.l1BlockNumber, currentL1BlockNumber);
420
+ } catch (error) {
421
+ if (isErrorClass(error, MessageStoreError)) {
422
+ this.log.warn(
423
+ `Failed to store L1 to L2 messages retrieved from L1: ${error.message}. Rolling back syncpoint to retry.`,
424
+ { inboxMessage: error.inboxMessage },
425
+ );
426
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
427
+ return false;
428
+ }
429
+ throw error;
430
+ }
405
431
 
406
- // Compare message count and rolling hash. If they match, no need to retrieve anything.
407
- if (
408
- remoteMessagesState.totalMessagesInserted === localMessagesInserted &&
409
- remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer32.ZERO)
410
- ) {
411
- this.log.trace(
412
- `No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`,
432
+ // Note that, if there are no new messages to insert, but there was an L1 reorg that pruned out last messages,
433
+ // we'd notice by comparing our local state with the remote one again, and seeing they don't match even after
434
+ // our sync attempt. In this case, we also rollback our syncpoint, and trigger a retry.
435
+ const localLastMessageAfterSync = await this.store.getLastL1ToL2Message();
436
+ if (!(await this.localStateMatches(localLastMessageAfterSync, remoteMessagesState))) {
437
+ this.log.warn(
438
+ `Local L1 to L2 messages state does not match remote after sync attempt. Rolling back syncpoint to retry.`,
439
+ { localLastMessageAfterSync, remoteMessagesState },
413
440
  );
414
- return;
441
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
442
+ return false;
415
443
  }
416
444
 
417
- // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
418
- // Note that we need to fetch it from logs and not from inbox state at the syncpoint l1 block number, since it
419
- // could be older than 128 blocks and non-archive nodes cannot resolve it.
420
- if (localLastMessage) {
421
- const remoteLastMessage = await this.retrieveL1ToL2Message(localLastMessage.leaf);
422
- this.log.trace(`Retrieved remote message for local last`, { remoteLastMessage, localLastMessage });
423
- if (!remoteLastMessage || !remoteLastMessage.rollingHash.equals(localLastMessage.rollingHash)) {
424
- this.log.warn(`Rolling back L1 to L2 messages due to hash mismatch or msg not found.`, {
425
- remoteLastMessage,
426
- messagesSyncPoint,
427
- localLastMessage,
428
- });
445
+ // Advance the syncpoint after a successful sync
446
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
447
+ return true;
448
+ }
429
449
 
430
- messagesSyncPoint = await this.rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint);
431
- this.log.debug(`Rolled back L1 to L2 messages to L1 block ${messagesSyncPoint.l1BlockNumber}.`, {
432
- messagesSyncPoint,
433
- });
434
- }
435
- }
450
+ /** Checks if the local rolling hash and message count matches the remote state */
451
+ private async localStateMatches(localLastMessage: InboxMessage | undefined, remoteState: InboxContractState) {
452
+ const localMessageCount = await this.store.getTotalL1ToL2MessageCount();
453
+ this.log.trace(`Comparing local and remote inbox state`, { localMessageCount, localLastMessage, remoteState });
454
+
455
+ return (
456
+ remoteState.totalMessagesInserted === localMessageCount &&
457
+ remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO)
458
+ );
459
+ }
436
460
 
437
- // Retrieve and save messages in batches. Each batch is estimated to acommodate up to L2 'blockBatchSize' blocks,
461
+ /** Retrieves L1 to L2 messages from L1 in batches and stores them. */
462
+ private async retrieveAndStoreMessages(fromL1Block: bigint, toL1Block: bigint): Promise<void> {
438
463
  let searchStartBlock: bigint = 0n;
439
- let searchEndBlock: bigint = messagesSyncPoint.l1BlockNumber;
464
+ let searchEndBlock: bigint = fromL1Block;
440
465
 
441
466
  let lastMessage: InboxMessage | undefined;
442
467
  let messageCount = 0;
443
468
 
444
469
  do {
445
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
470
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
446
471
  this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
447
472
  const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
448
473
  const timer = new Timer();
@@ -454,81 +479,86 @@ export class ArchiverL1Synchronizer implements Traceable {
454
479
  lastMessage = msg;
455
480
  messageCount++;
456
481
  }
457
- } while (searchEndBlock < currentL1BlockNumber);
482
+ } while (searchEndBlock < toL1Block);
458
483
 
459
- // Log stats for messages retrieved (if any).
460
484
  if (messageCount > 0) {
461
485
  this.log.info(
462
486
  `Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`,
463
487
  { lastMessage, messageCount },
464
488
  );
465
489
  }
466
-
467
- // Warn if the resulting rolling hash does not match the remote state we had retrieved.
468
- if (lastMessage && !lastMessage.rollingHash.equals(remoteMessagesState.messagesRollingHash)) {
469
- this.log.warn(`Last message retrieved rolling hash does not match remote state.`, {
470
- lastMessage,
471
- remoteMessagesState,
472
- });
473
- }
474
490
  }
475
491
 
476
- private async retrieveL1ToL2Message(leaf: Fr): Promise<InboxMessage | undefined> {
477
- const currentL1BlockNumber = await this.publicClient.getBlockNumber();
478
- let searchStartBlock: bigint = 0n;
479
- let searchEndBlock: bigint = this.l1Constants.l1StartBlock - 1n;
492
+ /**
493
+ * Rolls back local L1 to L2 messages to the last common message with L1, and updates the syncpoint to the L1 block of that message.
494
+ * If no common message is found, rolls back all messages and sets the syncpoint to the start block.
495
+ */
496
+ private async rollbackL1ToL2Messages(remoteMessagesState: InboxContractState): Promise<L1BlockId> {
497
+ const { treeInProgress: remoteTreeInProgress, messagesRollingHash: remoteRollingHash } = remoteMessagesState;
480
498
 
481
- do {
482
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
483
-
484
- const message = await retrieveL1ToL2Message(this.inbox, leaf, searchStartBlock, searchEndBlock);
485
-
486
- if (message) {
487
- return message;
499
+ // Slowly go back through our messages until we find the last common message. We could query the logs in
500
+ // batch as an optimization, but the depth of the reorg should not be deep, and this is a very rare case,
501
+ // so it's fine to query one log at a time.
502
+ let commonMsg: undefined | InboxMessage;
503
+ let messagesToDelete = 0;
504
+ this.log.verbose(`Searching most recent common L1 to L2 message`);
505
+ for await (const localMsg of this.store.iterateL1ToL2Messages({ reverse: true })) {
506
+ const logCtx = { remoteMsg: undefined as InboxMessage | undefined, localMsg, remoteMessagesState };
507
+
508
+ // First check if the local message rolling hash matches the current rolling hash of the inbox contract,
509
+ // which means we just need to rollback some local messages and we should be back in sync. This means there
510
+ // was an L1 reorg that removed some of the messages we had, but no new messages were added compared.
511
+ if (localMsg.rollingHash.equals(remoteRollingHash)) {
512
+ this.log.info(
513
+ `Found common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber} matching current remote state`,
514
+ logCtx,
515
+ );
516
+ commonMsg = localMsg;
517
+ break;
488
518
  }
489
- } while (searchEndBlock < currentL1BlockNumber);
490
-
491
- return undefined;
492
- }
493
519
 
494
- private async rollbackL1ToL2Messages(
495
- localLastMessage: InboxMessage,
496
- messagesSyncPoint: L1BlockId,
497
- ): Promise<L1BlockId> {
498
- // Slowly go back through our messages until we find the last common message.
499
- // We could query the logs in batch as an optimization, but the depth of the reorg should not be deep, and this
500
- // is a very rare case, so it's fine to query one log at a time.
501
- let commonMsg: undefined | InboxMessage;
502
- this.log.verbose(`Searching most recent common L1 to L2 message at or before index ${localLastMessage.index}`);
503
- for await (const msg of this.store.iterateL1ToL2Messages({ reverse: true, end: localLastMessage.index })) {
504
- const remoteMsg = await this.retrieveL1ToL2Message(msg.leaf);
505
- const logCtx = { remoteMsg, localMsg: msg };
506
- if (remoteMsg && remoteMsg.rollingHash.equals(msg.rollingHash)) {
507
- this.log.verbose(
508
- `Found most recent common L1 to L2 message at index ${msg.index} on L1 block ${msg.l1BlockNumber}`,
520
+ // If there's no match with the current remote state, check if the message exists on the inbox contract at all
521
+ // by looking at the inbox events. If the L1 reorg *added* new messages in addition to deleting existing ones,
522
+ // then the current remote state's rolling hash will not match anything we have locally, so we need to check existence
523
+ // of individual messages via logs. Note we use logs and not historical queries so we don't have to depend on
524
+ // an archival rpc node, since the message could be from a long time ago if we're catching up with syncing.
525
+ const remoteMsg = await retrieveL1ToL2Message(this.inbox, localMsg);
526
+ logCtx.remoteMsg = remoteMsg;
527
+ if (remoteMsg && remoteMsg.rollingHash.equals(localMsg.rollingHash)) {
528
+ this.log.info(
529
+ `Found most recent common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber}`,
509
530
  logCtx,
510
531
  );
511
532
  commonMsg = remoteMsg;
512
533
  break;
513
534
  } else if (remoteMsg) {
514
- this.log.debug(`Local L1 to L2 message with index ${msg.index} has different rolling hash`, logCtx);
535
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} has different rolling hash`, logCtx);
536
+ messagesToDelete++;
515
537
  } else {
516
- this.log.debug(`Local L1 to L2 message with index ${msg.index} not found on L1`, logCtx);
538
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} not found on L1`, logCtx);
539
+ messagesToDelete++;
517
540
  }
518
541
  }
519
542
 
520
- // Delete everything after the common message we found.
521
- const lastGoodIndex = commonMsg?.index;
522
- this.log.warn(`Deleting all local L1 to L2 messages after index ${lastGoodIndex ?? 'undefined'}`);
523
- await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
543
+ // Delete everything after the common message we found, if anything needs to be deleted.
544
+ // Do not exit early if there are no messages to delete, we still want to update the syncpoint.
545
+ if (messagesToDelete > 0) {
546
+ const lastGoodIndex = commonMsg?.index;
547
+ this.log.warn(`Rolling back all local L1 to L2 messages after index ${lastGoodIndex ?? 'initial'}`);
548
+ await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
549
+ }
524
550
 
525
551
  // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
526
552
  // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
527
553
  // after the last common message.
528
554
  const syncPointL1BlockNumber = commonMsg ? commonMsg.l1BlockNumber - 1n : this.l1Constants.l1StartBlock;
529
555
  const syncPointL1BlockHash = await this.getL1BlockHash(syncPointL1BlockNumber);
530
- messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
531
- await this.store.setMessageSynchedL1Block(messagesSyncPoint);
556
+ const messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
557
+ await this.store.setMessageSyncState(messagesSyncPoint, remoteTreeInProgress);
558
+ this.log.verbose(`Updated messages syncpoint to L1 block ${syncPointL1BlockNumber}`, {
559
+ ...messagesSyncPoint,
560
+ remoteTreeInProgress,
561
+ });
532
562
  return messagesSyncPoint;
533
563
  }
534
564
 
@@ -727,22 +757,20 @@ export class ArchiverL1Synchronizer implements Traceable {
727
757
 
728
758
  this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
729
759
 
730
- // TODO(md): Retrieve from blob client then from consensus client, then from peers
731
- const retrievedCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointsFromRollup', () =>
732
- retrieveCheckpointsFromRollup(
760
+ // First fetch calldata only, no blobs yet, since we may be able to just get that data out of the proposed chain
761
+ const calldataCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', () =>
762
+ retrieveCheckpointCalldataFromRollup(
733
763
  this.rollup,
734
764
  this.publicClient,
735
765
  this.debugClient,
736
- this.blobClient,
737
766
  searchStartBlock, // TODO(palla/reorg): If the L2 reorg was due to an L1 reorg, we need to start search earlier
738
767
  searchEndBlock,
739
768
  this.instrumentation,
740
769
  this.log,
741
- !initialSyncComplete, // isHistoricalSync
742
770
  ),
743
771
  );
744
772
 
745
- if (retrievedCheckpoints.length === 0) {
773
+ if (calldataCheckpoints.length === 0) {
746
774
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
747
775
  // See further details in earlier comments.
748
776
  this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
@@ -750,21 +778,56 @@ export class ArchiverL1Synchronizer implements Traceable {
750
778
  }
751
779
 
752
780
  this.log.debug(
753
- `Retrieved ${retrievedCheckpoints.length} new checkpoints between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
781
+ `Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
754
782
  {
755
- lastProcessedCheckpoint: retrievedCheckpoints[retrievedCheckpoints.length - 1].l1,
783
+ lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
756
784
  searchStartBlock,
757
785
  searchEndBlock,
758
786
  },
759
787
  );
760
788
 
761
- const publishedCheckpoints = await Promise.all(retrievedCheckpoints.map(b => retrievedToPublishedCheckpoint(b)));
789
+ // Check if the last checkpoint matches a local pending entry (so we can skip blob fetch).
790
+ // We only check the last one; if it matches, the blob fetch is skipped for that entry.
791
+ // TODO(palla/pipelining): We may have more than a single checkpoint to promote
792
+ const lastCalldataCheckpoint = calldataCheckpoints[calldataCheckpoints.length - 1];
793
+ const promoteResult = await this.tryBuildPublishedCheckpointFromProposed(lastCalldataCheckpoint);
794
+ const checkpointToPromote = promoteResult && !('diverged' in promoteResult) ? promoteResult : undefined;
795
+ const evictProposedFrom =
796
+ promoteResult && 'diverged' in promoteResult ? promoteResult.fromCheckpointNumber : undefined;
797
+
798
+ // Then fetch blobs in parallel and build the full published checkpoints
799
+ const toFetchBlobs = checkpointToPromote ? calldataCheckpoints.slice(0, -1) : calldataCheckpoints;
800
+ const blobFetched = await asyncPool(10, toFetchBlobs, async checkpoint =>
801
+ retrievedToPublishedCheckpoint({
802
+ ...checkpoint,
803
+ checkpointBlobData: await getCheckpointBlobDataFromBlobs(
804
+ this.blobClient,
805
+ checkpoint.l1.blockHash,
806
+ checkpoint.blobHashes,
807
+ checkpoint.checkpointNumber,
808
+ this.log,
809
+ !initialSyncComplete,
810
+ checkpoint.parentBeaconBlockRoot,
811
+ checkpoint.l1.timestamp,
812
+ ),
813
+ }),
814
+ );
815
+
816
+ // And add the promoted checkpoint to the list of all checkpoints
817
+ const publishedCheckpoints = checkpointToPromote ? [...blobFetched, checkpointToPromote] : blobFetched;
762
818
  const validCheckpoints: PublishedCheckpoint[] = [];
763
819
 
820
+ // Now loop through all checkpoints and validate their attestations
764
821
  for (const published of publishedCheckpoints) {
765
822
  const validationResult = this.config.skipValidateCheckpointAttestations
766
823
  ? { valid: true as const }
767
- : await validateCheckpointAttestations(published, this.epochCache, this.l1Constants, this.log);
824
+ : await validateCheckpointAttestations(
825
+ published,
826
+ this.epochCache,
827
+ this.l1Constants,
828
+ this.getSignatureContext(),
829
+ this.log,
830
+ );
768
831
 
769
832
  // Only update the validation result if it has changed, so we can keep track of the first invalid checkpoint
770
833
  // in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
@@ -841,15 +904,35 @@ export class ArchiverL1Synchronizer implements Traceable {
841
904
  try {
842
905
  const updatedValidationResult =
843
906
  rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
907
+
908
+ // Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
909
+ // the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
910
+ const [[maybeValidCheckpointToPromote], checkpointsToAdd] = partition(
911
+ validCheckpoints,
912
+ c => c.checkpoint.number === checkpointToPromote?.checkpoint.number,
913
+ );
914
+
844
915
  const [processDuration, result] = await elapsed(() =>
845
916
  execInSpan(this.tracer, 'Archiver.addCheckpoints', () =>
846
- this.updater.addCheckpoints(validCheckpoints, updatedValidationResult),
917
+ this.updater.addCheckpoints(
918
+ checkpointsToAdd,
919
+ updatedValidationResult,
920
+ maybeValidCheckpointToPromote && {
921
+ l1: lastCalldataCheckpoint.l1,
922
+ attestations: lastCalldataCheckpoint.attestations,
923
+ checkpoint: maybeValidCheckpointToPromote,
924
+ },
925
+ evictProposedFrom,
926
+ ),
847
927
  ),
848
928
  );
849
- this.instrumentation.processNewBlocks(
850
- processDuration / validCheckpoints.length,
851
- validCheckpoints.flatMap(c => c.checkpoint.blocks),
852
- );
929
+
930
+ if (checkpointsToAdd.length > 0) {
931
+ this.instrumentation.processNewCheckpointedBlocks(
932
+ processDuration / checkpointsToAdd.length,
933
+ checkpointsToAdd.flatMap(c => c.checkpoint.blocks),
934
+ );
935
+ }
853
936
 
854
937
  // If blocks were pruned due to conflict with L1 checkpoints, emit event
855
938
  if (result.prunedBlocks && result.prunedBlocks.length > 0) {
@@ -902,7 +985,7 @@ export class ArchiverL1Synchronizer implements Traceable {
902
985
  });
903
986
  }
904
987
  lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
905
- lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
988
+ lastL1BlockWithCheckpoint = calldataCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
906
989
  } while (searchEndBlock < currentL1BlockNumber);
907
990
 
908
991
  // Important that we update AFTER inserting the blocks.
@@ -911,6 +994,82 @@ export class ArchiverL1Synchronizer implements Traceable {
911
994
  return { ...rollupStatus, lastRetrievedCheckpoint, lastL1BlockWithCheckpoint };
912
995
  }
913
996
 
997
+ /**
998
+ * Checks if a specific checkpoint matches a local pending entry, and if so, loads local data to build
999
+ * a synthetic published checkpoint (skipping blob fetch).
1000
+ *
1001
+ * Returns { diverged: true, fromCheckpointNumber } when the L1 checkpoint does NOT match local pending
1002
+ * data for that number, so the caller can evict the entire pending suffix >= fromCheckpointNumber
1003
+ * (those entries chain off the now-invalid local state) within the same addCheckpoints transaction.
1004
+ */
1005
+ private async tryBuildPublishedCheckpointFromProposed(
1006
+ calldataCheckpoint: RetrievedCheckpointFromCalldata | undefined,
1007
+ ): Promise<PublishedCheckpoint | { diverged: true; fromCheckpointNumber: CheckpointNumber } | undefined> {
1008
+ if (this.config.skipPromoteProposedCheckpointDuringL1Sync || !calldataCheckpoint) {
1009
+ return undefined;
1010
+ }
1011
+
1012
+ // Look up the specific pending entry for the checkpoint being mined, not just the tip
1013
+ const proposed = await this.store.getProposedCheckpointByNumber(calldataCheckpoint.checkpointNumber);
1014
+ if (!proposed) {
1015
+ return undefined;
1016
+ }
1017
+
1018
+ if (
1019
+ !proposed.header.equals(calldataCheckpoint.header) ||
1020
+ !proposed.archive.root.equals(calldataCheckpoint.archiveRoot)
1021
+ ) {
1022
+ this.log.warn(
1023
+ `Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`,
1024
+ {
1025
+ proposedCheckpointNumber: proposed.checkpointNumber,
1026
+ proposedHeader: proposed.header.toInspect(),
1027
+ proposedArchiveRoot: proposed.archive.root.toString(),
1028
+ calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
1029
+ calldataHeader: calldataCheckpoint.header.toInspect(),
1030
+ calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString(),
1031
+ },
1032
+ );
1033
+ // Return a divergence signal so the caller can evict pending >= this number
1034
+ return { diverged: true, fromCheckpointNumber: proposed.checkpointNumber };
1035
+ }
1036
+
1037
+ this.log.debug(
1038
+ `Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`,
1039
+ { proposedHeader: proposed.header.toInspect(), proposedArchiveRoot: proposed.archive.root.toString() },
1040
+ );
1041
+
1042
+ const blocks = await this.store.getBlocks(BlockNumber(proposed.startBlock), proposed.blockCount);
1043
+ if (blocks.length !== proposed.blockCount) {
1044
+ this.log.warn(
1045
+ `Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`,
1046
+ {
1047
+ proposedCheckpointNumber: proposed.checkpointNumber,
1048
+ proposedStartBlock: proposed.startBlock,
1049
+ proposedBlockCount: proposed.blockCount,
1050
+ retrievedBlocks: blocks.map(b => b.number),
1051
+ },
1052
+ );
1053
+ return undefined;
1054
+ }
1055
+
1056
+ const checkpoint = Checkpoint.from({
1057
+ archive: proposed.archive,
1058
+ header: proposed.header,
1059
+ blocks,
1060
+ number: proposed.checkpointNumber,
1061
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier,
1062
+ });
1063
+ const promotedCheckpoint = PublishedCheckpoint.from({
1064
+ checkpoint,
1065
+ l1: calldataCheckpoint.l1,
1066
+ attestations: calldataCheckpoint.attestations,
1067
+ });
1068
+ this.instrumentation.processCheckpointPromoted();
1069
+
1070
+ return promotedCheckpoint;
1071
+ }
1072
+
914
1073
  private async checkForNewCheckpointsBeforeL1SyncPoint(
915
1074
  status: RollupStatus,
916
1075
  blocksSynchedTo: bigint,