@aztec/archiver 0.0.1-commit.9372f48 → 0.0.1-commit.949a33fd8

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 (114) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +22 -11
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +152 -145
  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 +4 -5
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +33 -27
  14. package/dest/index.d.ts +4 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +3 -1
  17. package/dest/l1/bin/retrieve-calldata.js +36 -33
  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/data_source_base.d.ts +18 -7
  31. package/dest/modules/data_source_base.d.ts.map +1 -1
  32. package/dest/modules/data_source_base.js +51 -77
  33. package/dest/modules/data_store_updater.d.ts +35 -15
  34. package/dest/modules/data_store_updater.d.ts.map +1 -1
  35. package/dest/modules/data_store_updater.js +139 -96
  36. package/dest/modules/instrumentation.d.ts +21 -3
  37. package/dest/modules/instrumentation.d.ts.map +1 -1
  38. package/dest/modules/instrumentation.js +41 -8
  39. package/dest/modules/l1_synchronizer.d.ts +11 -9
  40. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  41. package/dest/modules/l1_synchronizer.js +304 -151
  42. package/dest/modules/validation.d.ts +4 -3
  43. package/dest/modules/validation.d.ts.map +1 -1
  44. package/dest/modules/validation.js +6 -6
  45. package/dest/store/block_store.d.ts +98 -28
  46. package/dest/store/block_store.d.ts.map +1 -1
  47. package/dest/store/block_store.js +465 -138
  48. package/dest/store/contract_class_store.d.ts +2 -3
  49. package/dest/store/contract_class_store.d.ts.map +1 -1
  50. package/dest/store/contract_class_store.js +7 -67
  51. package/dest/store/contract_instance_store.d.ts +1 -1
  52. package/dest/store/contract_instance_store.d.ts.map +1 -1
  53. package/dest/store/contract_instance_store.js +6 -2
  54. package/dest/store/kv_archiver_store.d.ts +85 -24
  55. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  56. package/dest/store/kv_archiver_store.js +106 -27
  57. package/dest/store/l2_tips_cache.d.ts +20 -0
  58. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  59. package/dest/store/l2_tips_cache.js +109 -0
  60. package/dest/store/log_store.d.ts +6 -3
  61. package/dest/store/log_store.d.ts.map +1 -1
  62. package/dest/store/log_store.js +150 -55
  63. package/dest/store/message_store.d.ts +5 -1
  64. package/dest/store/message_store.d.ts.map +1 -1
  65. package/dest/store/message_store.js +21 -9
  66. package/dest/test/fake_l1_state.d.ts +25 -1
  67. package/dest/test/fake_l1_state.d.ts.map +1 -1
  68. package/dest/test/fake_l1_state.js +166 -32
  69. package/dest/test/mock_archiver.d.ts +1 -1
  70. package/dest/test/mock_archiver.d.ts.map +1 -1
  71. package/dest/test/mock_archiver.js +3 -2
  72. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  73. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  74. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  75. package/dest/test/mock_l2_block_source.d.ts +35 -5
  76. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  77. package/dest/test/mock_l2_block_source.js +182 -89
  78. package/dest/test/mock_structs.d.ts +4 -1
  79. package/dest/test/mock_structs.d.ts.map +1 -1
  80. package/dest/test/mock_structs.js +13 -1
  81. package/dest/test/noop_l1_archiver.d.ts +4 -1
  82. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  83. package/dest/test/noop_l1_archiver.js +9 -3
  84. package/package.json +13 -13
  85. package/src/archiver.ts +187 -164
  86. package/src/config.ts +23 -2
  87. package/src/errors.ts +133 -22
  88. package/src/factory.ts +47 -24
  89. package/src/index.ts +3 -1
  90. package/src/l1/README.md +25 -68
  91. package/src/l1/bin/retrieve-calldata.ts +46 -39
  92. package/src/l1/calldata_retriever.ts +261 -379
  93. package/src/l1/data_retrieval.ts +58 -69
  94. package/src/l1/spire_proposer.ts +7 -15
  95. package/src/l1/validate_historical_logs.ts +140 -0
  96. package/src/modules/data_source_base.ts +95 -98
  97. package/src/modules/data_store_updater.ts +168 -126
  98. package/src/modules/instrumentation.ts +56 -9
  99. package/src/modules/l1_synchronizer.ts +384 -188
  100. package/src/modules/validation.ts +10 -9
  101. package/src/store/block_store.ts +569 -174
  102. package/src/store/contract_class_store.ts +8 -106
  103. package/src/store/contract_instance_store.ts +8 -5
  104. package/src/store/kv_archiver_store.ts +167 -41
  105. package/src/store/l2_tips_cache.ts +134 -0
  106. package/src/store/log_store.ts +221 -63
  107. package/src/store/message_store.ts +27 -10
  108. package/src/structs/inbox_message.ts +1 -1
  109. package/src/test/fake_l1_state.ts +213 -42
  110. package/src/test/mock_archiver.ts +3 -2
  111. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  112. package/src/test/mock_l2_block_source.ts +230 -82
  113. package/src/test/mock_structs.ts +20 -6
  114. package/src/test/noop_l1_archiver.ts +10 -2
@@ -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';
4
- import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
3
+ import { InboxContract, type InboxContractState, RollupContract } from '@aztec/ethereum/contracts';
5
4
  import type { L1BlockId } from '@aztec/ethereum/l1-types';
5
+ import { getFinalizedL1Block } from '@aztec/ethereum/queries';
6
6
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
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';
12
13
  import { EthAddress } from '@aztec/foundation/eth-address';
13
14
  import { type Logger, createLogger } from '@aztec/foundation/log';
15
+ import { retryTimes } from '@aztec/foundation/retry';
14
16
  import { count } from '@aztec/foundation/string';
15
17
  import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
16
- import { isDefined } from '@aztec/foundation/types';
18
+ import { isDefined, isErrorClass } from '@aztec/foundation/types';
17
19
  import { type ArchiverEmitter, L2BlockSourceEvents, type ValidateCheckpointResult } from '@aztec/stdlib/block';
18
- import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
20
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
19
21
  import { type L1RollupConstants, getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
20
22
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
23
+ import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
21
24
  import { type Traceable, type Tracer, execInSpan, trackSpan } from '@aztec/telemetry-client';
22
25
 
23
26
  import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
24
27
  import {
25
- retrieveCheckpointsFromRollup,
28
+ type RetrievedCheckpointFromCalldata,
29
+ getCheckpointBlobDataFromBlobs,
30
+ retrieveCheckpointCalldataFromRollup,
26
31
  retrieveL1ToL2Message,
27
32
  retrieveL1ToL2Messages,
28
33
  retrievedToPublishedCheckpoint,
29
34
  } from '../l1/data_retrieval.js';
30
35
  import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
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';
@@ -60,26 +67,29 @@ export class ArchiverL1Synchronizer implements Traceable {
60
67
  private readonly debugClient: ViemPublicDebugClient,
61
68
  private readonly rollup: RollupContract,
62
69
  private readonly inbox: InboxContract,
63
- private readonly l1Addresses: Pick<
64
- L1ContractAddresses,
65
- 'registryAddress' | 'governanceProposerAddress' | 'slashFactoryAddress'
66
- > & { slashingProposerAddress: EthAddress },
67
70
  private readonly store: KVArchiverDataStore,
68
71
  private config: {
69
72
  batchSize: number;
70
73
  skipValidateCheckpointAttestations?: boolean;
74
+ skipPromoteProposedCheckpointDuringL1Sync?: boolean;
71
75
  maxAllowedEthClientDriftSeconds: number;
72
76
  },
73
77
  private readonly blobClient: BlobClientInterface,
74
78
  private readonly epochCache: EpochCache,
75
79
  private readonly dateProvider: DateProvider,
76
80
  private readonly instrumentation: ArchiverInstrumentation,
77
- private readonly l1Constants: L1RollupConstants & { l1StartBlockHash: Buffer32; genesisArchiveRoot: Fr },
81
+ private readonly l1Constants: L1RollupConstants & {
82
+ l1StartBlockHash: Buffer32;
83
+ genesisArchiveRoot: Fr;
84
+ },
78
85
  private readonly events: ArchiverEmitter,
79
86
  tracer: Tracer,
87
+ l2TipsCache?: L2TipsCache,
80
88
  private readonly log: Logger = createLogger('archiver:l1-sync'),
81
89
  ) {
82
- this.updater = new ArchiverDataStoreUpdater(this.store);
90
+ this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache, {
91
+ rollupManaLimit: l1Constants.rollupManaLimit,
92
+ });
83
93
  this.tracer = tracer;
84
94
  }
85
95
 
@@ -87,6 +97,7 @@ export class ArchiverL1Synchronizer implements Traceable {
87
97
  public setConfig(newConfig: {
88
98
  batchSize: number;
89
99
  skipValidateCheckpointAttestations?: boolean;
100
+ skipPromoteProposedCheckpointDuringL1Sync?: boolean;
90
101
  maxAllowedEthClientDriftSeconds: number;
91
102
  }) {
92
103
  this.config = newConfig;
@@ -102,6 +113,13 @@ export class ArchiverL1Synchronizer implements Traceable {
102
113
  return this.l1Timestamp;
103
114
  }
104
115
 
116
+ private getSignatureContext(): CoordinationSignatureContext {
117
+ return {
118
+ chainId: this.publicClient.chain.id,
119
+ rollupAddress: EthAddress.fromString(this.rollup.address),
120
+ };
121
+ }
122
+
105
123
  /** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */
106
124
  public async testEthereumNodeSynced(): Promise<void> {
107
125
  const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
@@ -119,10 +137,15 @@ export class ArchiverL1Synchronizer implements Traceable {
119
137
 
120
138
  @trackSpan('Archiver.syncFromL1')
121
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.
122
144
  const currentL1Block = await this.publicClient.getBlock({ includeTransactions: false });
123
145
  const currentL1BlockNumber = currentL1Block.number;
124
146
  const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
125
147
  const currentL1Timestamp = currentL1Block.timestamp;
148
+ const currentL1BlockData = { l1BlockNumber: currentL1BlockNumber, l1BlockHash: currentL1BlockHash };
126
149
 
127
150
  if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
128
151
  this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
@@ -139,45 +162,15 @@ export class ArchiverL1Synchronizer implements Traceable {
139
162
  );
140
163
  }
141
164
 
142
- // Load sync point for blocks and messages defaulting to start block
143
- const {
144
- blocksSynchedTo = this.l1Constants.l1StartBlock,
145
- messagesSynchedTo = {
146
- l1BlockNumber: this.l1Constants.l1StartBlock,
147
- l1BlockHash: this.l1Constants.l1StartBlockHash,
148
- },
149
- } = 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 });
150
168
 
151
- this.log.debug(`Starting new archiver sync iteration`, {
152
- blocksSynchedTo,
153
- messagesSynchedTo,
154
- currentL1BlockNumber,
155
- currentL1BlockHash,
156
- });
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);
157
173
 
158
- // ********** Ensuring Consistency of data pulled from L1 **********
159
-
160
- /**
161
- * There are a number of calls in this sync operation to L1 for retrieving
162
- * events and transaction data. There are a couple of things we need to bear in mind
163
- * to ensure that data is read exactly once.
164
- *
165
- * The first is the problem of eventually consistent ETH service providers like Infura.
166
- * Each L1 read operation will query data from the last L1 block that it saw emit its kind of data.
167
- * (so pending L1 to L2 messages will read from the last L1 block that emitted a message and so on)
168
- * This will mean the archiver will lag behind L1 and will only advance when there's L2-relevant activity on the chain.
169
- *
170
- * The second is that in between the various calls to L1, the block number can move meaning some
171
- * of the following calls will return data for blocks that were not present during earlier calls.
172
- * To combat this for the time being we simply ensure that all data retrieval methods only retrieve
173
- * data up to the currentBlockNumber captured at the top of this function. We might want to improve on this
174
- * in future but for the time being it should give us the guarantees that we need
175
- */
176
-
177
- // ********** Events that are processed per L1 block **********
178
- await this.handleL1ToL2Messages(messagesSynchedTo, currentL1BlockNumber);
179
-
180
- // ********** Events that are processed per checkpoint **********
181
174
  if (currentL1BlockNumber > blocksSynchedTo) {
182
175
  // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
183
176
  // pending chain validation status, proven checkpoint number, and synched L1 block number.
@@ -215,6 +208,9 @@ export class ArchiverL1Synchronizer implements Traceable {
215
208
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
216
209
  }
217
210
 
211
+ // Update the finalized L2 checkpoint based on L1 finality.
212
+ await this.updateFinalizedCheckpoint();
213
+
218
214
  // After syncing has completed, update the current l1 block number and timestamp,
219
215
  // otherwise we risk announcing to the world that we've synced to a given point,
220
216
  // but the corresponding blocks have not been processed (see #12631).
@@ -230,6 +226,34 @@ export class ArchiverL1Synchronizer implements Traceable {
230
226
  });
231
227
  }
232
228
 
229
+ /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */
230
+ private async updateFinalizedCheckpoint(): Promise<void> {
231
+ try {
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
+ }
237
+ const finalizedL1BlockNumber = finalizedL1Block.number;
238
+ const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
239
+ blockNumber: finalizedL1BlockNumber,
240
+ });
241
+ const localFinalizedCheckpointNumber = await this.store.getFinalizedCheckpointNumber();
242
+ if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
243
+ await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
244
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
245
+ finalizedCheckpointNumber,
246
+ finalizedL1BlockNumber,
247
+ });
248
+ }
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
+ }
254
+ }
255
+ }
256
+
233
257
  /** Prune all proposed local blocks that should have been checkpointed by now. */
234
258
  private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint) {
235
259
  const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
@@ -243,29 +267,33 @@ export class ArchiverL1Synchronizer implements Traceable {
243
267
  return;
244
268
  }
245
269
 
246
- // 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);
247
272
  const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
273
+
274
+ // What's the slot of the first uncheckpointed block?
248
275
  const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
249
276
  const firstUncheckpointedBlockSlot = firstUncheckpointedBlockHeader?.getSlot();
250
277
 
251
- // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
252
- const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
278
+ if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
279
+ return;
280
+ }
253
281
 
254
- // Prune provisional blocks from slots that have ended without being checkpointed
255
- if (firstUncheckpointedBlockSlot !== undefined && firstUncheckpointedBlockSlot < slotAtNextL1Block) {
256
- this.log.warn(
257
- `Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
258
- { firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(), slotAtNextL1Block },
259
- );
260
- 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
+ );
261
288
 
262
- if (prunedBlocks.length > 0) {
263
- this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
264
- type: L2BlockSourceEvents.L2PruneUncheckpointed,
265
- slotNumber: firstUncheckpointedBlockSlot,
266
- blocks: prunedBlocks,
267
- });
268
- }
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
+ });
269
297
  }
270
298
  }
271
299
 
@@ -308,17 +336,20 @@ export class ArchiverL1Synchronizer implements Traceable {
308
336
 
309
337
  const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
310
338
 
311
- const checkpointPromises = Array.from({ length: checkpointsToUnwind })
312
- .fill(0)
313
- .map((_, i) => this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
314
- const checkpoints = await Promise.all(checkpointPromises);
315
-
316
- const blockPromises = await Promise.all(
317
- checkpoints
318
- .filter(isDefined)
319
- .map(cp => this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))),
339
+ // Fetch checkpoints and blocks in bounded batches to avoid unbounded concurrent
340
+ // promises when the gap between local pending and proven checkpoint numbers is large.
341
+ const BATCH_SIZE = 10;
342
+ const indices = Array.from({ length: checkpointsToUnwind }, (_, i) => CheckpointNumber(i + pruneFrom));
343
+ const checkpoints = (await asyncPool(BATCH_SIZE, indices, idx => this.store.getCheckpointData(idx))).filter(
344
+ isDefined,
320
345
  );
321
- const newBlocks = blockPromises.filter(isDefined).flat();
346
+ const newBlocks = (
347
+ await asyncPool(BATCH_SIZE, checkpoints, cp =>
348
+ this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)),
349
+ )
350
+ )
351
+ .filter(isDefined)
352
+ .flat();
322
353
 
323
354
  // Emit an event for listening services to react to the chain prune
324
355
  this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
@@ -356,63 +387,87 @@ export class ArchiverL1Synchronizer implements Traceable {
356
387
  }
357
388
 
358
389
  @trackSpan('Archiver.handleL1ToL2Messages')
359
- private async handleL1ToL2Messages(messagesSyncPoint: L1BlockId, currentL1BlockNumber: bigint): Promise<void> {
360
- this.log.trace(`Handling L1 to L2 messages from ${messagesSyncPoint.l1BlockNumber} to ${currentL1BlockNumber}.`);
361
- if (currentL1BlockNumber <= messagesSyncPoint.l1BlockNumber) {
362
- 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;
363
403
  }
364
404
 
365
- // Load remote and local inbox states.
366
- const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
367
- const localLastMessage = await this.store.getLastL1ToL2Message();
405
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
368
406
  const remoteMessagesState = await this.inbox.getState({ blockNumber: currentL1BlockNumber });
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
+ }
369
413
 
370
- this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
371
- localMessagesInserted,
372
- localLastMessage,
373
- remoteMessagesState,
374
- });
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
+ }
375
431
 
376
- // Compare message count and rolling hash. If they match, no need to retrieve anything.
377
- if (
378
- remoteMessagesState.totalMessagesInserted === localMessagesInserted &&
379
- remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer32.ZERO)
380
- ) {
381
- this.log.trace(
382
- `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 },
383
440
  );
384
- return;
441
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
442
+ return false;
385
443
  }
386
444
 
387
- // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
388
- // Note that we need to fetch it from logs and not from inbox state at the syncpoint l1 block number, since it
389
- // could be older than 128 blocks and non-archive nodes cannot resolve it.
390
- if (localLastMessage) {
391
- const remoteLastMessage = await this.retrieveL1ToL2Message(localLastMessage.leaf);
392
- this.log.trace(`Retrieved remote message for local last`, { remoteLastMessage, localLastMessage });
393
- if (!remoteLastMessage || !remoteLastMessage.rollingHash.equals(localLastMessage.rollingHash)) {
394
- this.log.warn(`Rolling back L1 to L2 messages due to hash mismatch or msg not found.`, {
395
- remoteLastMessage,
396
- messagesSyncPoint,
397
- localLastMessage,
398
- });
445
+ // Advance the syncpoint after a successful sync
446
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
447
+ return true;
448
+ }
399
449
 
400
- messagesSyncPoint = await this.rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint);
401
- this.log.debug(`Rolled back L1 to L2 messages to L1 block ${messagesSyncPoint.l1BlockNumber}.`, {
402
- messagesSyncPoint,
403
- });
404
- }
405
- }
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 });
406
454
 
407
- // Retrieve and save messages in batches. Each batch is estimated to acommodate up to L2 'blockBatchSize' blocks,
455
+ return (
456
+ remoteState.totalMessagesInserted === localMessageCount &&
457
+ remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO)
458
+ );
459
+ }
460
+
461
+ /** Retrieves L1 to L2 messages from L1 in batches and stores them. */
462
+ private async retrieveAndStoreMessages(fromL1Block: bigint, toL1Block: bigint): Promise<void> {
408
463
  let searchStartBlock: bigint = 0n;
409
- let searchEndBlock: bigint = messagesSyncPoint.l1BlockNumber;
464
+ let searchEndBlock: bigint = fromL1Block;
410
465
 
411
466
  let lastMessage: InboxMessage | undefined;
412
467
  let messageCount = 0;
413
468
 
414
469
  do {
415
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
470
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
416
471
  this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
417
472
  const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
418
473
  const timer = new Timer();
@@ -424,81 +479,86 @@ export class ArchiverL1Synchronizer implements Traceable {
424
479
  lastMessage = msg;
425
480
  messageCount++;
426
481
  }
427
- } while (searchEndBlock < currentL1BlockNumber);
482
+ } while (searchEndBlock < toL1Block);
428
483
 
429
- // Log stats for messages retrieved (if any).
430
484
  if (messageCount > 0) {
431
485
  this.log.info(
432
486
  `Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`,
433
487
  { lastMessage, messageCount },
434
488
  );
435
489
  }
436
-
437
- // Warn if the resulting rolling hash does not match the remote state we had retrieved.
438
- if (lastMessage && !lastMessage.rollingHash.equals(remoteMessagesState.messagesRollingHash)) {
439
- this.log.warn(`Last message retrieved rolling hash does not match remote state.`, {
440
- lastMessage,
441
- remoteMessagesState,
442
- });
443
- }
444
490
  }
445
491
 
446
- private async retrieveL1ToL2Message(leaf: Fr): Promise<InboxMessage | undefined> {
447
- const currentL1BlockNumber = await this.publicClient.getBlockNumber();
448
- let searchStartBlock: bigint = 0n;
449
- 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;
450
498
 
451
- do {
452
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
453
-
454
- const message = await retrieveL1ToL2Message(this.inbox, leaf, searchStartBlock, searchEndBlock);
455
-
456
- if (message) {
457
- 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;
458
518
  }
459
- } while (searchEndBlock < currentL1BlockNumber);
460
-
461
- return undefined;
462
- }
463
519
 
464
- private async rollbackL1ToL2Messages(
465
- localLastMessage: InboxMessage,
466
- messagesSyncPoint: L1BlockId,
467
- ): Promise<L1BlockId> {
468
- // Slowly go back through our messages until we find the last common message.
469
- // We could query the logs in batch as an optimization, but the depth of the reorg should not be deep, and this
470
- // is a very rare case, so it's fine to query one log at a time.
471
- let commonMsg: undefined | InboxMessage;
472
- this.log.verbose(`Searching most recent common L1 to L2 message at or before index ${localLastMessage.index}`);
473
- for await (const msg of this.store.iterateL1ToL2Messages({ reverse: true, end: localLastMessage.index })) {
474
- const remoteMsg = await this.retrieveL1ToL2Message(msg.leaf);
475
- const logCtx = { remoteMsg, localMsg: msg };
476
- if (remoteMsg && remoteMsg.rollingHash.equals(msg.rollingHash)) {
477
- this.log.verbose(
478
- `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}`,
479
530
  logCtx,
480
531
  );
481
532
  commonMsg = remoteMsg;
482
533
  break;
483
534
  } else if (remoteMsg) {
484
- 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++;
485
537
  } else {
486
- 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++;
487
540
  }
488
541
  }
489
542
 
490
- // Delete everything after the common message we found.
491
- const lastGoodIndex = commonMsg?.index;
492
- this.log.warn(`Deleting all local L1 to L2 messages after index ${lastGoodIndex ?? 'undefined'}`);
493
- 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
+ }
494
550
 
495
551
  // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
496
552
  // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
497
553
  // after the last common message.
498
554
  const syncPointL1BlockNumber = commonMsg ? commonMsg.l1BlockNumber - 1n : this.l1Constants.l1StartBlock;
499
555
  const syncPointL1BlockHash = await this.getL1BlockHash(syncPointL1BlockNumber);
500
- messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
501
- 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
+ });
502
562
  return messagesSyncPoint;
503
563
  }
504
564
 
@@ -550,7 +610,7 @@ export class ArchiverL1Synchronizer implements Traceable {
550
610
  if (provenCheckpointNumber === 0) {
551
611
  const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
552
612
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
553
- await this.store.setProvenCheckpointNumber(provenCheckpointNumber);
613
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
554
614
  this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, { provenCheckpointNumber });
555
615
  }
556
616
  }
@@ -582,13 +642,13 @@ export class ArchiverL1Synchronizer implements Traceable {
582
642
  ) {
583
643
  const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
584
644
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
585
- await this.store.setProvenCheckpointNumber(provenCheckpointNumber);
645
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
586
646
  this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, { provenCheckpointNumber });
587
647
  const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
588
648
  const provenEpochNumber: EpochNumber = getEpochAtSlot(provenSlotNumber, this.l1Constants);
589
649
  const lastBlockNumberInCheckpoint =
590
650
  localCheckpointForDestinationProvenCheckpointNumber.startBlock +
591
- localCheckpointForDestinationProvenCheckpointNumber.numBlocks -
651
+ localCheckpointForDestinationProvenCheckpointNumber.blockCount -
592
652
  1;
593
653
 
594
654
  this.events.emit(L2BlockSourceEvents.L2BlockProven, {
@@ -597,7 +657,7 @@ export class ArchiverL1Synchronizer implements Traceable {
597
657
  slotNumber: provenSlotNumber,
598
658
  epochNumber: provenEpochNumber,
599
659
  });
600
- this.instrumentation.updateLastProvenBlock(lastBlockNumberInCheckpoint);
660
+ this.instrumentation.updateLastProvenCheckpoint(localCheckpointForDestinationProvenCheckpointNumber);
601
661
  } else {
602
662
  this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
603
663
  }
@@ -697,23 +757,20 @@ export class ArchiverL1Synchronizer implements Traceable {
697
757
 
698
758
  this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
699
759
 
700
- // TODO(md): Retrieve from blob client then from consensus client, then from peers
701
- const retrievedCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointsFromRollup', () =>
702
- 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(
703
763
  this.rollup,
704
764
  this.publicClient,
705
765
  this.debugClient,
706
- this.blobClient,
707
766
  searchStartBlock, // TODO(palla/reorg): If the L2 reorg was due to an L1 reorg, we need to start search earlier
708
767
  searchEndBlock,
709
- this.l1Addresses,
710
768
  this.instrumentation,
711
769
  this.log,
712
- !initialSyncComplete, // isHistoricalSync
713
770
  ),
714
771
  );
715
772
 
716
- if (retrievedCheckpoints.length === 0) {
773
+ if (calldataCheckpoints.length === 0) {
717
774
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
718
775
  // See further details in earlier comments.
719
776
  this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
@@ -721,21 +778,56 @@ export class ArchiverL1Synchronizer implements Traceable {
721
778
  }
722
779
 
723
780
  this.log.debug(
724
- `Retrieved ${retrievedCheckpoints.length} new checkpoints between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
781
+ `Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
725
782
  {
726
- lastProcessedCheckpoint: retrievedCheckpoints[retrievedCheckpoints.length - 1].l1,
783
+ lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
727
784
  searchStartBlock,
728
785
  searchEndBlock,
729
786
  },
730
787
  );
731
788
 
732
- 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;
733
818
  const validCheckpoints: PublishedCheckpoint[] = [];
734
819
 
820
+ // Now loop through all checkpoints and validate their attestations
735
821
  for (const published of publishedCheckpoints) {
736
822
  const validationResult = this.config.skipValidateCheckpointAttestations
737
823
  ? { valid: true as const }
738
- : 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
+ );
739
831
 
740
832
  // Only update the validation result if it has changed, so we can keep track of the first invalid checkpoint
741
833
  // in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
@@ -801,25 +893,53 @@ export class ArchiverL1Synchronizer implements Traceable {
801
893
  );
802
894
  }
803
895
 
896
+ for (const published of validCheckpoints) {
897
+ this.instrumentation.processCheckpointL1Timing({
898
+ slotNumber: published.checkpoint.header.slotNumber,
899
+ l1Timestamp: published.l1.timestamp,
900
+ l1Constants: this.l1Constants,
901
+ });
902
+ }
903
+
804
904
  try {
805
905
  const updatedValidationResult =
806
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
+
807
915
  const [processDuration, result] = await elapsed(() =>
808
916
  execInSpan(this.tracer, 'Archiver.addCheckpoints', () =>
809
- 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
+ ),
810
927
  ),
811
928
  );
812
- this.instrumentation.processNewBlocks(
813
- processDuration / validCheckpoints.length,
814
- validCheckpoints.flatMap(c => c.checkpoint.blocks),
815
- );
929
+
930
+ if (checkpointsToAdd.length > 0) {
931
+ this.instrumentation.processNewCheckpointedBlocks(
932
+ processDuration / checkpointsToAdd.length,
933
+ checkpointsToAdd.flatMap(c => c.checkpoint.blocks),
934
+ );
935
+ }
816
936
 
817
937
  // If blocks were pruned due to conflict with L1 checkpoints, emit event
818
938
  if (result.prunedBlocks && result.prunedBlocks.length > 0) {
819
939
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
820
940
  const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
821
941
 
822
- this.log.warn(
942
+ this.log.info(
823
943
  `Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`,
824
944
  { prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
825
945
  );
@@ -865,7 +985,7 @@ export class ArchiverL1Synchronizer implements Traceable {
865
985
  });
866
986
  }
867
987
  lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
868
- lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
988
+ lastL1BlockWithCheckpoint = calldataCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
869
989
  } while (searchEndBlock < currentL1BlockNumber);
870
990
 
871
991
  // Important that we update AFTER inserting the blocks.
@@ -874,6 +994,82 @@ export class ArchiverL1Synchronizer implements Traceable {
874
994
  return { ...rollupStatus, lastRetrievedCheckpoint, lastL1BlockWithCheckpoint };
875
995
  }
876
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
+
877
1073
  private async checkForNewCheckpointsBeforeL1SyncPoint(
878
1074
  status: RollupStatus,
879
1075
  blocksSynchedTo: bigint,