@aztec/archiver 0.0.1-commit.d1f2d6c → 0.0.1-commit.d20b825a7

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 (120) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +16 -10
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +110 -122
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +15 -3
  8. package/dest/errors.d.ts +55 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +74 -15
  11. package/dest/factory.d.ts +5 -4
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +34 -29
  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 +73 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +191 -259
  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 +43 -48
  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/l1/validate_trace.d.ts +6 -3
  31. package/dest/l1/validate_trace.d.ts.map +1 -1
  32. package/dest/l1/validate_trace.js +13 -9
  33. package/dest/modules/data_source_base.d.ts +17 -10
  34. package/dest/modules/data_source_base.d.ts.map +1 -1
  35. package/dest/modules/data_source_base.js +39 -77
  36. package/dest/modules/data_store_updater.d.ts +50 -26
  37. package/dest/modules/data_store_updater.d.ts.map +1 -1
  38. package/dest/modules/data_store_updater.js +169 -130
  39. package/dest/modules/instrumentation.d.ts +21 -3
  40. package/dest/modules/instrumentation.d.ts.map +1 -1
  41. package/dest/modules/instrumentation.js +58 -18
  42. package/dest/modules/l1_synchronizer.d.ts +10 -9
  43. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  44. package/dest/modules/l1_synchronizer.js +285 -157
  45. package/dest/modules/validation.d.ts +1 -1
  46. package/dest/modules/validation.d.ts.map +1 -1
  47. package/dest/modules/validation.js +2 -2
  48. package/dest/store/block_store.d.ts +85 -36
  49. package/dest/store/block_store.d.ts.map +1 -1
  50. package/dest/store/block_store.js +433 -162
  51. package/dest/store/contract_class_store.d.ts +2 -3
  52. package/dest/store/contract_class_store.d.ts.map +1 -1
  53. package/dest/store/contract_class_store.js +16 -72
  54. package/dest/store/contract_instance_store.d.ts +1 -1
  55. package/dest/store/contract_instance_store.d.ts.map +1 -1
  56. package/dest/store/contract_instance_store.js +6 -2
  57. package/dest/store/kv_archiver_store.d.ts +76 -32
  58. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  59. package/dest/store/kv_archiver_store.js +92 -37
  60. package/dest/store/l2_tips_cache.d.ts +20 -0
  61. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  62. package/dest/store/l2_tips_cache.js +109 -0
  63. package/dest/store/log_store.d.ts +6 -3
  64. package/dest/store/log_store.d.ts.map +1 -1
  65. package/dest/store/log_store.js +151 -56
  66. package/dest/store/message_store.d.ts +5 -1
  67. package/dest/store/message_store.d.ts.map +1 -1
  68. package/dest/store/message_store.js +21 -9
  69. package/dest/test/fake_l1_state.d.ts +24 -1
  70. package/dest/test/fake_l1_state.d.ts.map +1 -1
  71. package/dest/test/fake_l1_state.js +145 -28
  72. package/dest/test/index.js +3 -1
  73. package/dest/test/mock_archiver.d.ts +1 -1
  74. package/dest/test/mock_archiver.d.ts.map +1 -1
  75. package/dest/test/mock_archiver.js +3 -2
  76. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  77. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  78. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  79. package/dest/test/mock_l2_block_source.d.ts +31 -10
  80. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  81. package/dest/test/mock_l2_block_source.js +163 -92
  82. package/dest/test/mock_structs.d.ts +6 -2
  83. package/dest/test/mock_structs.d.ts.map +1 -1
  84. package/dest/test/mock_structs.js +20 -6
  85. package/dest/test/noop_l1_archiver.d.ts +26 -0
  86. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  87. package/dest/test/noop_l1_archiver.js +74 -0
  88. package/package.json +14 -13
  89. package/src/archiver.ts +150 -146
  90. package/src/config.ts +22 -2
  91. package/src/errors.ts +116 -26
  92. package/src/factory.ts +49 -26
  93. package/src/index.ts +3 -1
  94. package/src/l1/README.md +25 -68
  95. package/src/l1/bin/retrieve-calldata.ts +46 -39
  96. package/src/l1/calldata_retriever.ts +250 -379
  97. package/src/l1/data_retrieval.ts +59 -70
  98. package/src/l1/spire_proposer.ts +7 -15
  99. package/src/l1/validate_historical_logs.ts +140 -0
  100. package/src/l1/validate_trace.ts +24 -6
  101. package/src/modules/data_source_base.ts +81 -101
  102. package/src/modules/data_store_updater.ts +202 -160
  103. package/src/modules/instrumentation.ts +71 -19
  104. package/src/modules/l1_synchronizer.ts +365 -197
  105. package/src/modules/validation.ts +2 -2
  106. package/src/store/block_store.ts +546 -206
  107. package/src/store/contract_class_store.ts +16 -110
  108. package/src/store/contract_instance_store.ts +8 -5
  109. package/src/store/kv_archiver_store.ts +143 -53
  110. package/src/store/l2_tips_cache.ts +134 -0
  111. package/src/store/log_store.ts +225 -67
  112. package/src/store/message_store.ts +27 -10
  113. package/src/structs/inbox_message.ts +1 -1
  114. package/src/test/fake_l1_state.ts +193 -32
  115. package/src/test/index.ts +3 -0
  116. package/src/test/mock_archiver.ts +3 -2
  117. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  118. package/src/test/mock_l2_block_source.ts +217 -90
  119. package/src/test/mock_structs.ts +42 -12
  120. package/src/test/noop_l1_archiver.ts +117 -0
@@ -1,33 +1,38 @@
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
- import { EthAddress } from '@aztec/foundation/eth-address';
13
13
  import { type Logger, createLogger } from '@aztec/foundation/log';
14
+ import { retryTimes } from '@aztec/foundation/retry';
14
15
  import { count } from '@aztec/foundation/string';
15
16
  import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
16
- import { isDefined } from '@aztec/foundation/types';
17
+ import { isDefined, isErrorClass } from '@aztec/foundation/types';
17
18
  import { type ArchiverEmitter, L2BlockSourceEvents, type ValidateCheckpointResult } from '@aztec/stdlib/block';
18
- import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
19
- import { type L1RollupConstants, getEpochAtSlot, getSlotAtTimestamp } from '@aztec/stdlib/epoch-helpers';
19
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
20
+ import { type L1RollupConstants, getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
20
21
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
21
22
  import { type Traceable, type Tracer, execInSpan, trackSpan } from '@aztec/telemetry-client';
22
23
 
23
24
  import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
24
25
  import {
25
- retrieveCheckpointsFromRollup,
26
+ type RetrievedCheckpointFromCalldata,
27
+ getCheckpointBlobDataFromBlobs,
28
+ retrieveCheckpointCalldataFromRollup,
26
29
  retrieveL1ToL2Message,
27
30
  retrieveL1ToL2Messages,
28
31
  retrievedToPublishedCheckpoint,
29
32
  } from '../l1/data_retrieval.js';
30
33
  import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
34
+ import type { L2TipsCache } from '../store/l2_tips_cache.js';
35
+ import { MessageStoreError } from '../store/message_store.js';
31
36
  import type { InboxMessage } from '../structs/inbox_message.js';
32
37
  import { ArchiverDataStoreUpdater } from './data_store_updater.js';
33
38
  import type { ArchiverInstrumentation } from './instrumentation.js';
@@ -60,26 +65,29 @@ export class ArchiverL1Synchronizer implements Traceable {
60
65
  private readonly debugClient: ViemPublicDebugClient,
61
66
  private readonly rollup: RollupContract,
62
67
  private readonly inbox: InboxContract,
63
- private readonly l1Addresses: Pick<
64
- L1ContractAddresses,
65
- 'registryAddress' | 'governanceProposerAddress' | 'slashFactoryAddress'
66
- > & { slashingProposerAddress: EthAddress },
67
68
  private readonly store: KVArchiverDataStore,
68
69
  private config: {
69
70
  batchSize: number;
70
71
  skipValidateCheckpointAttestations?: boolean;
72
+ skipPromoteProposedCheckpointDuringL1Sync?: boolean;
71
73
  maxAllowedEthClientDriftSeconds: number;
72
74
  },
73
75
  private readonly blobClient: BlobClientInterface,
74
76
  private readonly epochCache: EpochCache,
75
77
  private readonly dateProvider: DateProvider,
76
78
  private readonly instrumentation: ArchiverInstrumentation,
77
- private readonly l1Constants: L1RollupConstants & { l1StartBlockHash: Buffer32; genesisArchiveRoot: Fr },
79
+ private readonly l1Constants: L1RollupConstants & {
80
+ l1StartBlockHash: Buffer32;
81
+ genesisArchiveRoot: Fr;
82
+ },
78
83
  private readonly events: ArchiverEmitter,
79
84
  tracer: Tracer,
85
+ l2TipsCache?: L2TipsCache,
80
86
  private readonly log: Logger = createLogger('archiver:l1-sync'),
81
87
  ) {
82
- this.updater = new ArchiverDataStoreUpdater(this.store);
88
+ this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache, {
89
+ rollupManaLimit: l1Constants.rollupManaLimit,
90
+ });
83
91
  this.tracer = tracer;
84
92
  }
85
93
 
@@ -87,6 +95,7 @@ export class ArchiverL1Synchronizer implements Traceable {
87
95
  public setConfig(newConfig: {
88
96
  batchSize: number;
89
97
  skipValidateCheckpointAttestations?: boolean;
98
+ skipPromoteProposedCheckpointDuringL1Sync?: boolean;
90
99
  maxAllowedEthClientDriftSeconds: number;
91
100
  }) {
92
101
  this.config = newConfig;
@@ -119,10 +128,15 @@ export class ArchiverL1Synchronizer implements Traceable {
119
128
 
120
129
  @trackSpan('Archiver.syncFromL1')
121
130
  public async syncFromL1(initialSyncComplete: boolean): Promise<void> {
131
+ // In between the various calls to L1, the block number can move meaning some of the following
132
+ // calls will return data for blocks that were not present during earlier calls. To combat this
133
+ // we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
134
+ // captured at the top of this function.
122
135
  const currentL1Block = await this.publicClient.getBlock({ includeTransactions: false });
123
136
  const currentL1BlockNumber = currentL1Block.number;
124
137
  const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
125
138
  const currentL1Timestamp = currentL1Block.timestamp;
139
+ const currentL1BlockData = { l1BlockNumber: currentL1BlockNumber, l1BlockHash: currentL1BlockHash };
126
140
 
127
141
  if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
128
142
  this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
@@ -139,45 +153,15 @@ export class ArchiverL1Synchronizer implements Traceable {
139
153
  );
140
154
  }
141
155
 
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();
156
+ // Load sync point for blocks defaulting to start block
157
+ const { blocksSynchedTo = this.l1Constants.l1StartBlock } = await this.store.getSynchPoint();
158
+ this.log.debug(`Starting new archiver sync iteration`, { blocksSynchedTo, currentL1BlockData });
150
159
 
151
- this.log.debug(`Starting new archiver sync iteration`, {
152
- blocksSynchedTo,
153
- messagesSynchedTo,
154
- currentL1BlockNumber,
155
- currentL1BlockHash,
156
- });
160
+ // 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.
161
+ // 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
162
+ // block, when that wouldn't be the case, since L1 to L2 messages would need another iteration.
163
+ await retryTimes(() => this.handleL1ToL2Messages(currentL1BlockData), 'Handling L1 to L2 messages', 3, 0.1);
157
164
 
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
165
  if (currentL1BlockNumber > blocksSynchedTo) {
182
166
  // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
183
167
  // pending chain validation status, proven checkpoint number, and synched L1 block number.
@@ -215,6 +199,9 @@ export class ArchiverL1Synchronizer implements Traceable {
215
199
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
216
200
  }
217
201
 
202
+ // Update the finalized L2 checkpoint based on L1 finality.
203
+ await this.updateFinalizedCheckpoint();
204
+
218
205
  // After syncing has completed, update the current l1 block number and timestamp,
219
206
  // otherwise we risk announcing to the world that we've synced to a given point,
220
207
  // but the corresponding blocks have not been processed (see #12631).
@@ -230,6 +217,34 @@ export class ArchiverL1Synchronizer implements Traceable {
230
217
  });
231
218
  }
232
219
 
220
+ /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */
221
+ private async updateFinalizedCheckpoint(): Promise<void> {
222
+ try {
223
+ const finalizedL1Block = await getFinalizedL1Block(this.publicClient);
224
+ if (!finalizedL1Block) {
225
+ this.log.trace(`Skipping finalized checkpoint update: L1 has no finalized block yet.`);
226
+ return;
227
+ }
228
+ const finalizedL1BlockNumber = finalizedL1Block.number;
229
+ const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
230
+ blockNumber: finalizedL1BlockNumber,
231
+ });
232
+ const localFinalizedCheckpointNumber = await this.store.getFinalizedCheckpointNumber();
233
+ if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
234
+ await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
235
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
236
+ finalizedCheckpointNumber,
237
+ finalizedL1BlockNumber,
238
+ });
239
+ }
240
+ } catch (err: any) {
241
+ // The rollup contract may not exist at the finalized L1 block right after deployment.
242
+ if (!err?.message?.includes('returned no data')) {
243
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
244
+ }
245
+ }
246
+ }
247
+
233
248
  /** Prune all proposed local blocks that should have been checkpointed by now. */
234
249
  private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint) {
235
250
  const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
@@ -243,30 +258,33 @@ export class ArchiverL1Synchronizer implements Traceable {
243
258
  return;
244
259
  }
245
260
 
246
- // What's the slot of the first uncheckpointed block?
261
+ // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
262
+ const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
247
263
  const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
264
+
265
+ // What's the slot of the first uncheckpointed block?
248
266
  const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
249
267
  const firstUncheckpointedBlockSlot = firstUncheckpointedBlockHeader?.getSlot();
250
268
 
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 nextL1BlockTimestamp = currentL1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration);
253
- const slotAtNextL1Block = getSlotAtTimestamp(nextL1BlockTimestamp, this.l1Constants);
269
+ if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
270
+ return;
271
+ }
254
272
 
255
- // Prune provisional blocks from slots that have ended without being checkpointed
256
- if (firstUncheckpointedBlockSlot !== undefined && firstUncheckpointedBlockSlot < slotAtNextL1Block) {
257
- this.log.warn(
258
- `Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
259
- { firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(), slotAtNextL1Block },
260
- );
261
- const prunedBlocks = await this.updater.removeBlocksAfter(lastCheckpointedBlockNumber);
273
+ // Prune provisional blocks from slots that have ended without being checkpointed.
274
+ // This also clears any proposed checkpoint whose blocks are being pruned.
275
+ this.log.warn(
276
+ `Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
277
+ { firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(), slotAtNextL1Block },
278
+ );
262
279
 
263
- if (prunedBlocks.length > 0) {
264
- this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
265
- type: L2BlockSourceEvents.L2PruneUncheckpointed,
266
- slotNumber: firstUncheckpointedBlockSlot,
267
- blocks: prunedBlocks,
268
- });
269
- }
280
+ const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
281
+
282
+ if (prunedBlocks.length > 0) {
283
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
284
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
285
+ slotNumber: firstUncheckpointedBlockSlot,
286
+ blocks: prunedBlocks,
287
+ });
270
288
  }
271
289
  }
272
290
 
@@ -309,17 +327,20 @@ export class ArchiverL1Synchronizer implements Traceable {
309
327
 
310
328
  const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
311
329
 
312
- const checkpointPromises = Array.from({ length: checkpointsToUnwind })
313
- .fill(0)
314
- .map((_, i) => this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
315
- const checkpoints = await Promise.all(checkpointPromises);
316
-
317
- const blockPromises = await Promise.all(
318
- checkpoints
319
- .filter(isDefined)
320
- .map(cp => this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))),
330
+ // Fetch checkpoints and blocks in bounded batches to avoid unbounded concurrent
331
+ // promises when the gap between local pending and proven checkpoint numbers is large.
332
+ const BATCH_SIZE = 10;
333
+ const indices = Array.from({ length: checkpointsToUnwind }, (_, i) => CheckpointNumber(i + pruneFrom));
334
+ const checkpoints = (await asyncPool(BATCH_SIZE, indices, idx => this.store.getCheckpointData(idx))).filter(
335
+ isDefined,
321
336
  );
322
- const newBlocks = blockPromises.filter(isDefined).flat();
337
+ const newBlocks = (
338
+ await asyncPool(BATCH_SIZE, checkpoints, cp =>
339
+ this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)),
340
+ )
341
+ )
342
+ .filter(isDefined)
343
+ .flat();
323
344
 
324
345
  // Emit an event for listening services to react to the chain prune
325
346
  this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
@@ -331,10 +352,10 @@ export class ArchiverL1Synchronizer implements Traceable {
331
352
  this.log.debug(
332
353
  `L2 prune from ${provenCheckpointNumber + 1} to ${localPendingCheckpointNumber} will occur on next checkpoint submission.`,
333
354
  );
334
- await this.updater.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
355
+ await this.updater.removeCheckpointsAfter(provenCheckpointNumber);
335
356
  this.log.warn(
336
- `Unwound ${count(checkpointsToUnwind, 'checkpoint')} from checkpoint ${localPendingCheckpointNumber} ` +
337
- `to ${provenCheckpointNumber} due to predicted reorg at L1 block ${currentL1BlockNumber}. ` +
357
+ `Removed ${count(checkpointsToUnwind, 'checkpoint')} after checkpoint ${provenCheckpointNumber} ` +
358
+ `due to predicted reorg at L1 block ${currentL1BlockNumber}. ` +
338
359
  `Updated latest checkpoint is ${await this.store.getSynchedCheckpointNumber()}.`,
339
360
  );
340
361
  this.instrumentation.processPrune(timer.ms());
@@ -357,63 +378,87 @@ export class ArchiverL1Synchronizer implements Traceable {
357
378
  }
358
379
 
359
380
  @trackSpan('Archiver.handleL1ToL2Messages')
360
- private async handleL1ToL2Messages(messagesSyncPoint: L1BlockId, currentL1BlockNumber: bigint): Promise<void> {
361
- this.log.trace(`Handling L1 to L2 messages from ${messagesSyncPoint.l1BlockNumber} to ${currentL1BlockNumber}.`);
362
- if (currentL1BlockNumber <= messagesSyncPoint.l1BlockNumber) {
363
- return;
381
+ private async handleL1ToL2Messages(currentL1Block: L1BlockId): Promise<boolean> {
382
+ // Load the syncpoint, which may have been updated in a previous iteration
383
+ const {
384
+ messagesSynchedTo = {
385
+ l1BlockNumber: this.l1Constants.l1StartBlock,
386
+ l1BlockHash: this.l1Constants.l1StartBlockHash,
387
+ },
388
+ } = await this.store.getSynchPoint();
389
+
390
+ // Nothing to do if L1 block number has not moved forward
391
+ const currentL1BlockNumber = currentL1Block.l1BlockNumber;
392
+ if (currentL1BlockNumber <= messagesSynchedTo.l1BlockNumber) {
393
+ return true;
364
394
  }
365
395
 
366
- // Load remote and local inbox states.
367
- const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
368
- const localLastMessage = await this.store.getLastL1ToL2Message();
396
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
369
397
  const remoteMessagesState = await this.inbox.getState({ blockNumber: currentL1BlockNumber });
398
+ const localLastMessage = await this.store.getLastL1ToL2Message();
399
+ if (await this.localStateMatches(localLastMessage, remoteMessagesState)) {
400
+ this.log.trace(`Local L1 to L2 messages are already in sync with remote at L1 block ${currentL1BlockNumber}`);
401
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
402
+ return true;
403
+ }
370
404
 
371
- this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
372
- localMessagesInserted,
373
- localLastMessage,
374
- remoteMessagesState,
375
- });
405
+ // If not, then we are out of sync. Most likely there are new messages on the inbox, so we try retrieving them.
406
+ // However, it could also be the case that there was an L1 reorg and our syncpoint is no longer valid.
407
+ // If that's the case, we'd get an exception out of the message store since the rolling hash of the first message
408
+ // we try to insert would not match the one in the db, in which case we rollback to the last common message with L1.
409
+ try {
410
+ await this.retrieveAndStoreMessages(messagesSynchedTo.l1BlockNumber, currentL1BlockNumber);
411
+ } catch (error) {
412
+ if (isErrorClass(error, MessageStoreError)) {
413
+ this.log.warn(
414
+ `Failed to store L1 to L2 messages retrieved from L1: ${error.message}. Rolling back syncpoint to retry.`,
415
+ { inboxMessage: error.inboxMessage },
416
+ );
417
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
418
+ return false;
419
+ }
420
+ throw error;
421
+ }
376
422
 
377
- // Compare message count and rolling hash. If they match, no need to retrieve anything.
378
- if (
379
- remoteMessagesState.totalMessagesInserted === localMessagesInserted &&
380
- remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer32.ZERO)
381
- ) {
382
- this.log.trace(
383
- `No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`,
423
+ // Note that, if there are no new messages to insert, but there was an L1 reorg that pruned out last messages,
424
+ // we'd notice by comparing our local state with the remote one again, and seeing they don't match even after
425
+ // our sync attempt. In this case, we also rollback our syncpoint, and trigger a retry.
426
+ const localLastMessageAfterSync = await this.store.getLastL1ToL2Message();
427
+ if (!(await this.localStateMatches(localLastMessageAfterSync, remoteMessagesState))) {
428
+ this.log.warn(
429
+ `Local L1 to L2 messages state does not match remote after sync attempt. Rolling back syncpoint to retry.`,
430
+ { localLastMessageAfterSync, remoteMessagesState },
384
431
  );
385
- return;
432
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
433
+ return false;
386
434
  }
387
435
 
388
- // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
389
- // Note that we need to fetch it from logs and not from inbox state at the syncpoint l1 block number, since it
390
- // could be older than 128 blocks and non-archive nodes cannot resolve it.
391
- if (localLastMessage) {
392
- const remoteLastMessage = await this.retrieveL1ToL2Message(localLastMessage.leaf);
393
- this.log.trace(`Retrieved remote message for local last`, { remoteLastMessage, localLastMessage });
394
- if (!remoteLastMessage || !remoteLastMessage.rollingHash.equals(localLastMessage.rollingHash)) {
395
- this.log.warn(`Rolling back L1 to L2 messages due to hash mismatch or msg not found.`, {
396
- remoteLastMessage,
397
- messagesSyncPoint,
398
- localLastMessage,
399
- });
436
+ // Advance the syncpoint after a successful sync
437
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
438
+ return true;
439
+ }
400
440
 
401
- messagesSyncPoint = await this.rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint);
402
- this.log.debug(`Rolled back L1 to L2 messages to L1 block ${messagesSyncPoint.l1BlockNumber}.`, {
403
- messagesSyncPoint,
404
- });
405
- }
406
- }
441
+ /** Checks if the local rolling hash and message count matches the remote state */
442
+ private async localStateMatches(localLastMessage: InboxMessage | undefined, remoteState: InboxContractState) {
443
+ const localMessageCount = await this.store.getTotalL1ToL2MessageCount();
444
+ this.log.trace(`Comparing local and remote inbox state`, { localMessageCount, localLastMessage, remoteState });
445
+
446
+ return (
447
+ remoteState.totalMessagesInserted === localMessageCount &&
448
+ remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO)
449
+ );
450
+ }
407
451
 
408
- // Retrieve and save messages in batches. Each batch is estimated to acommodate up to L2 'blockBatchSize' blocks,
452
+ /** Retrieves L1 to L2 messages from L1 in batches and stores them. */
453
+ private async retrieveAndStoreMessages(fromL1Block: bigint, toL1Block: bigint): Promise<void> {
409
454
  let searchStartBlock: bigint = 0n;
410
- let searchEndBlock: bigint = messagesSyncPoint.l1BlockNumber;
455
+ let searchEndBlock: bigint = fromL1Block;
411
456
 
412
457
  let lastMessage: InboxMessage | undefined;
413
458
  let messageCount = 0;
414
459
 
415
460
  do {
416
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
461
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
417
462
  this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
418
463
  const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
419
464
  const timer = new Timer();
@@ -425,81 +470,86 @@ export class ArchiverL1Synchronizer implements Traceable {
425
470
  lastMessage = msg;
426
471
  messageCount++;
427
472
  }
428
- } while (searchEndBlock < currentL1BlockNumber);
473
+ } while (searchEndBlock < toL1Block);
429
474
 
430
- // Log stats for messages retrieved (if any).
431
475
  if (messageCount > 0) {
432
476
  this.log.info(
433
477
  `Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`,
434
478
  { lastMessage, messageCount },
435
479
  );
436
480
  }
437
-
438
- // Warn if the resulting rolling hash does not match the remote state we had retrieved.
439
- if (lastMessage && !lastMessage.rollingHash.equals(remoteMessagesState.messagesRollingHash)) {
440
- this.log.warn(`Last message retrieved rolling hash does not match remote state.`, {
441
- lastMessage,
442
- remoteMessagesState,
443
- });
444
- }
445
481
  }
446
482
 
447
- private async retrieveL1ToL2Message(leaf: Fr): Promise<InboxMessage | undefined> {
448
- const currentL1BlockNumber = await this.publicClient.getBlockNumber();
449
- let searchStartBlock: bigint = 0n;
450
- let searchEndBlock: bigint = this.l1Constants.l1StartBlock - 1n;
451
-
452
- do {
453
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
483
+ /**
484
+ * 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.
485
+ * If no common message is found, rolls back all messages and sets the syncpoint to the start block.
486
+ */
487
+ private async rollbackL1ToL2Messages(remoteMessagesState: InboxContractState): Promise<L1BlockId> {
488
+ const { treeInProgress: remoteTreeInProgress, messagesRollingHash: remoteRollingHash } = remoteMessagesState;
454
489
 
455
- const message = await retrieveL1ToL2Message(this.inbox, leaf, searchStartBlock, searchEndBlock);
456
-
457
- if (message) {
458
- return message;
490
+ // Slowly go back through our messages until we find the last common message. We could query the logs in
491
+ // batch as an optimization, but the depth of the reorg should not be deep, and this is a very rare case,
492
+ // so it's fine to query one log at a time.
493
+ let commonMsg: undefined | InboxMessage;
494
+ let messagesToDelete = 0;
495
+ this.log.verbose(`Searching most recent common L1 to L2 message`);
496
+ for await (const localMsg of this.store.iterateL1ToL2Messages({ reverse: true })) {
497
+ const logCtx = { remoteMsg: undefined as InboxMessage | undefined, localMsg, remoteMessagesState };
498
+
499
+ // First check if the local message rolling hash matches the current rolling hash of the inbox contract,
500
+ // which means we just need to rollback some local messages and we should be back in sync. This means there
501
+ // was an L1 reorg that removed some of the messages we had, but no new messages were added compared.
502
+ if (localMsg.rollingHash.equals(remoteRollingHash)) {
503
+ this.log.info(
504
+ `Found common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber} matching current remote state`,
505
+ logCtx,
506
+ );
507
+ commonMsg = localMsg;
508
+ break;
459
509
  }
460
- } while (searchEndBlock < currentL1BlockNumber);
461
510
 
462
- return undefined;
463
- }
464
-
465
- private async rollbackL1ToL2Messages(
466
- localLastMessage: InboxMessage,
467
- messagesSyncPoint: L1BlockId,
468
- ): Promise<L1BlockId> {
469
- // Slowly go back through our messages until we find the last common message.
470
- // We could query the logs in batch as an optimization, but the depth of the reorg should not be deep, and this
471
- // is a very rare case, so it's fine to query one log at a time.
472
- let commonMsg: undefined | InboxMessage;
473
- this.log.verbose(`Searching most recent common L1 to L2 message at or before index ${localLastMessage.index}`);
474
- for await (const msg of this.store.iterateL1ToL2Messages({ reverse: true, end: localLastMessage.index })) {
475
- const remoteMsg = await this.retrieveL1ToL2Message(msg.leaf);
476
- const logCtx = { remoteMsg, localMsg: msg };
477
- if (remoteMsg && remoteMsg.rollingHash.equals(msg.rollingHash)) {
478
- this.log.verbose(
479
- `Found most recent common L1 to L2 message at index ${msg.index} on L1 block ${msg.l1BlockNumber}`,
511
+ // If there's no match with the current remote state, check if the message exists on the inbox contract at all
512
+ // by looking at the inbox events. If the L1 reorg *added* new messages in addition to deleting existing ones,
513
+ // then the current remote state's rolling hash will not match anything we have locally, so we need to check existence
514
+ // of individual messages via logs. Note we use logs and not historical queries so we don't have to depend on
515
+ // an archival rpc node, since the message could be from a long time ago if we're catching up with syncing.
516
+ const remoteMsg = await retrieveL1ToL2Message(this.inbox, localMsg);
517
+ logCtx.remoteMsg = remoteMsg;
518
+ if (remoteMsg && remoteMsg.rollingHash.equals(localMsg.rollingHash)) {
519
+ this.log.info(
520
+ `Found most recent common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber}`,
480
521
  logCtx,
481
522
  );
482
523
  commonMsg = remoteMsg;
483
524
  break;
484
525
  } else if (remoteMsg) {
485
- this.log.debug(`Local L1 to L2 message with index ${msg.index} has different rolling hash`, logCtx);
526
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} has different rolling hash`, logCtx);
527
+ messagesToDelete++;
486
528
  } else {
487
- this.log.debug(`Local L1 to L2 message with index ${msg.index} not found on L1`, logCtx);
529
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} not found on L1`, logCtx);
530
+ messagesToDelete++;
488
531
  }
489
532
  }
490
533
 
491
- // Delete everything after the common message we found.
492
- const lastGoodIndex = commonMsg?.index;
493
- this.log.warn(`Deleting all local L1 to L2 messages after index ${lastGoodIndex ?? 'undefined'}`);
494
- await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
534
+ // Delete everything after the common message we found, if anything needs to be deleted.
535
+ // Do not exit early if there are no messages to delete, we still want to update the syncpoint.
536
+ if (messagesToDelete > 0) {
537
+ const lastGoodIndex = commonMsg?.index;
538
+ this.log.warn(`Rolling back all local L1 to L2 messages after index ${lastGoodIndex ?? 'initial'}`);
539
+ await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
540
+ }
495
541
 
496
542
  // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
497
543
  // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
498
544
  // after the last common message.
499
545
  const syncPointL1BlockNumber = commonMsg ? commonMsg.l1BlockNumber - 1n : this.l1Constants.l1StartBlock;
500
546
  const syncPointL1BlockHash = await this.getL1BlockHash(syncPointL1BlockNumber);
501
- messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
502
- await this.store.setMessageSynchedL1Block(messagesSyncPoint);
547
+ const messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
548
+ await this.store.setMessageSyncState(messagesSyncPoint, remoteTreeInProgress);
549
+ this.log.verbose(`Updated messages syncpoint to L1 block ${syncPointL1BlockNumber}`, {
550
+ ...messagesSyncPoint,
551
+ remoteTreeInProgress,
552
+ });
503
553
  return messagesSyncPoint;
504
554
  }
505
555
 
@@ -551,7 +601,7 @@ export class ArchiverL1Synchronizer implements Traceable {
551
601
  if (provenCheckpointNumber === 0) {
552
602
  const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
553
603
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
554
- await this.store.setProvenCheckpointNumber(provenCheckpointNumber);
604
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
555
605
  this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, { provenCheckpointNumber });
556
606
  }
557
607
  }
@@ -583,13 +633,13 @@ export class ArchiverL1Synchronizer implements Traceable {
583
633
  ) {
584
634
  const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
585
635
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
586
- await this.store.setProvenCheckpointNumber(provenCheckpointNumber);
636
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
587
637
  this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, { provenCheckpointNumber });
588
638
  const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
589
639
  const provenEpochNumber: EpochNumber = getEpochAtSlot(provenSlotNumber, this.l1Constants);
590
640
  const lastBlockNumberInCheckpoint =
591
641
  localCheckpointForDestinationProvenCheckpointNumber.startBlock +
592
- localCheckpointForDestinationProvenCheckpointNumber.numBlocks -
642
+ localCheckpointForDestinationProvenCheckpointNumber.blockCount -
593
643
  1;
594
644
 
595
645
  this.events.emit(L2BlockSourceEvents.L2BlockProven, {
@@ -598,7 +648,7 @@ export class ArchiverL1Synchronizer implements Traceable {
598
648
  slotNumber: provenSlotNumber,
599
649
  epochNumber: provenEpochNumber,
600
650
  });
601
- this.instrumentation.updateLastProvenBlock(lastBlockNumberInCheckpoint);
651
+ this.instrumentation.updateLastProvenCheckpoint(localCheckpointForDestinationProvenCheckpointNumber);
602
652
  } else {
603
653
  this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
604
654
  }
@@ -675,11 +725,11 @@ export class ArchiverL1Synchronizer implements Traceable {
675
725
  tipAfterUnwind--;
676
726
  }
677
727
 
678
- const checkpointsToUnwind = localPendingCheckpointNumber - tipAfterUnwind;
679
- await this.updater.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
728
+ const checkpointsToRemove = localPendingCheckpointNumber - tipAfterUnwind;
729
+ await this.updater.removeCheckpointsAfter(CheckpointNumber(tipAfterUnwind));
680
730
 
681
731
  this.log.warn(
682
- `Unwound ${count(checkpointsToUnwind, 'checkpoint')} from checkpoint ${localPendingCheckpointNumber} ` +
732
+ `Removed ${count(checkpointsToRemove, 'checkpoint')} after checkpoint ${tipAfterUnwind} ` +
683
733
  `due to mismatched checkpoint hashes at L1 block ${currentL1BlockNumber}. ` +
684
734
  `Updated L2 latest checkpoint is ${await this.store.getSynchedCheckpointNumber()}.`,
685
735
  );
@@ -698,23 +748,20 @@ export class ArchiverL1Synchronizer implements Traceable {
698
748
 
699
749
  this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
700
750
 
701
- // TODO(md): Retrieve from blob client then from consensus client, then from peers
702
- const retrievedCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointsFromRollup', () =>
703
- retrieveCheckpointsFromRollup(
751
+ // First fetch calldata only, no blobs yet, since we may be able to just get that data out of the proposed chain
752
+ const calldataCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', () =>
753
+ retrieveCheckpointCalldataFromRollup(
704
754
  this.rollup,
705
755
  this.publicClient,
706
756
  this.debugClient,
707
- this.blobClient,
708
757
  searchStartBlock, // TODO(palla/reorg): If the L2 reorg was due to an L1 reorg, we need to start search earlier
709
758
  searchEndBlock,
710
- this.l1Addresses,
711
759
  this.instrumentation,
712
760
  this.log,
713
- !initialSyncComplete, // isHistoricalSync
714
761
  ),
715
762
  );
716
763
 
717
- if (retrievedCheckpoints.length === 0) {
764
+ if (calldataCheckpoints.length === 0) {
718
765
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
719
766
  // See further details in earlier comments.
720
767
  this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
@@ -722,17 +769,43 @@ export class ArchiverL1Synchronizer implements Traceable {
722
769
  }
723
770
 
724
771
  this.log.debug(
725
- `Retrieved ${retrievedCheckpoints.length} new checkpoints between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
772
+ `Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
726
773
  {
727
- lastProcessedCheckpoint: retrievedCheckpoints[retrievedCheckpoints.length - 1].l1,
774
+ lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
728
775
  searchStartBlock,
729
776
  searchEndBlock,
730
777
  },
731
778
  );
732
779
 
733
- const publishedCheckpoints = await Promise.all(retrievedCheckpoints.map(b => retrievedToPublishedCheckpoint(b)));
780
+ // Check if the last checkpoint matches the proposed one (so we can skip blob fetch).
781
+ // We only check the last one because the proposed checkpoint is always the most recent one,
782
+ // and if it's in a multi-checkpoint batch it will always be last (sorted by L1 block number).
783
+ const lastCalldataCheckpoint = calldataCheckpoints[calldataCheckpoints.length - 1];
784
+ const checkpointToPromote = await this.tryBuildPublishedCheckpointFromProposed(lastCalldataCheckpoint);
785
+
786
+ // Then fetch blobs in parallel and build the full published checkpoints
787
+ const toFetchBlobs = checkpointToPromote ? calldataCheckpoints.slice(0, -1) : calldataCheckpoints;
788
+ const blobFetched = await asyncPool(10, toFetchBlobs, async checkpoint =>
789
+ retrievedToPublishedCheckpoint({
790
+ ...checkpoint,
791
+ checkpointBlobData: await getCheckpointBlobDataFromBlobs(
792
+ this.blobClient,
793
+ checkpoint.l1.blockHash,
794
+ checkpoint.blobHashes,
795
+ checkpoint.checkpointNumber,
796
+ this.log,
797
+ !initialSyncComplete,
798
+ checkpoint.parentBeaconBlockRoot,
799
+ checkpoint.l1.timestamp,
800
+ ),
801
+ }),
802
+ );
803
+
804
+ // And add the promoted checkpoint to the list of all checkpoints
805
+ const publishedCheckpoints = checkpointToPromote ? [...blobFetched, checkpointToPromote] : blobFetched;
734
806
  const validCheckpoints: PublishedCheckpoint[] = [];
735
807
 
808
+ // Now loop through all checkpoints and validate their attestations
736
809
  for (const published of publishedCheckpoints) {
737
810
  const validationResult = this.config.skipValidateCheckpointAttestations
738
811
  ? { valid: true as const }
@@ -802,25 +875,52 @@ export class ArchiverL1Synchronizer implements Traceable {
802
875
  );
803
876
  }
804
877
 
878
+ for (const published of validCheckpoints) {
879
+ this.instrumentation.processCheckpointL1Timing({
880
+ slotNumber: published.checkpoint.header.slotNumber,
881
+ l1Timestamp: published.l1.timestamp,
882
+ l1Constants: this.l1Constants,
883
+ });
884
+ }
885
+
805
886
  try {
806
887
  const updatedValidationResult =
807
888
  rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
889
+
890
+ // Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
891
+ // the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
892
+ const [[maybeValidCheckpointToPromote], checkpointsToAdd] = partition(
893
+ validCheckpoints,
894
+ c => c.checkpoint.number === checkpointToPromote?.checkpoint.number,
895
+ );
896
+
808
897
  const [processDuration, result] = await elapsed(() =>
809
- execInSpan(this.tracer, 'Archiver.setCheckpointData', () =>
810
- this.updater.setNewCheckpointData(validCheckpoints, updatedValidationResult),
898
+ execInSpan(this.tracer, 'Archiver.addCheckpoints', () =>
899
+ this.updater.addCheckpoints(
900
+ checkpointsToAdd,
901
+ updatedValidationResult,
902
+ maybeValidCheckpointToPromote && {
903
+ l1: lastCalldataCheckpoint.l1,
904
+ attestations: lastCalldataCheckpoint.attestations,
905
+ checkpoint: maybeValidCheckpointToPromote,
906
+ },
907
+ ),
811
908
  ),
812
909
  );
813
- this.instrumentation.processNewBlocks(
814
- processDuration / validCheckpoints.length,
815
- validCheckpoints.flatMap(c => c.checkpoint.blocks),
816
- );
910
+
911
+ if (checkpointsToAdd.length > 0) {
912
+ this.instrumentation.processNewCheckpointedBlocks(
913
+ processDuration / checkpointsToAdd.length,
914
+ checkpointsToAdd.flatMap(c => c.checkpoint.blocks),
915
+ );
916
+ }
817
917
 
818
918
  // If blocks were pruned due to conflict with L1 checkpoints, emit event
819
919
  if (result.prunedBlocks && result.prunedBlocks.length > 0) {
820
920
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
821
921
  const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
822
922
 
823
- this.log.warn(
923
+ this.log.info(
824
924
  `Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`,
825
925
  { prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
826
926
  );
@@ -866,7 +966,7 @@ export class ArchiverL1Synchronizer implements Traceable {
866
966
  });
867
967
  }
868
968
  lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
869
- lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
969
+ lastL1BlockWithCheckpoint = calldataCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
870
970
  } while (searchEndBlock < currentL1BlockNumber);
871
971
 
872
972
  // Important that we update AFTER inserting the blocks.
@@ -875,6 +975,74 @@ export class ArchiverL1Synchronizer implements Traceable {
875
975
  return { ...rollupStatus, lastRetrievedCheckpoint, lastL1BlockWithCheckpoint };
876
976
  }
877
977
 
978
+ /** Checks if this checkpoint matches the local proposed one, and if so, loads local data to build a synthetic published checkpoint. */
979
+ private async tryBuildPublishedCheckpointFromProposed(
980
+ calldataCheckpoint: RetrievedCheckpointFromCalldata | undefined,
981
+ ): Promise<PublishedCheckpoint | undefined> {
982
+ const proposed = await this.store.getProposedCheckpointOnly();
983
+ if (
984
+ this.config.skipPromoteProposedCheckpointDuringL1Sync ||
985
+ !proposed ||
986
+ !calldataCheckpoint ||
987
+ proposed.checkpointNumber !== calldataCheckpoint.checkpointNumber
988
+ ) {
989
+ return undefined;
990
+ }
991
+
992
+ if (
993
+ !proposed.header.equals(calldataCheckpoint.header) ||
994
+ !proposed.archive.root.equals(calldataCheckpoint.archiveRoot)
995
+ ) {
996
+ this.log.warn(
997
+ `Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`,
998
+ {
999
+ proposedCheckpointNumber: proposed.checkpointNumber,
1000
+ proposedHeader: proposed.header.toInspect(),
1001
+ proposedArchiveRoot: proposed.archive.root.toString(),
1002
+ calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
1003
+ calldataHeader: calldataCheckpoint.header.toInspect(),
1004
+ calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString(),
1005
+ },
1006
+ );
1007
+ return undefined;
1008
+ }
1009
+
1010
+ this.log.debug(
1011
+ `Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`,
1012
+ { proposedHeader: proposed.header.toInspect(), proposedArchiveRoot: proposed.archive.root.toString() },
1013
+ );
1014
+
1015
+ const blocks = await this.store.getBlocks(BlockNumber(proposed.startBlock), proposed.blockCount);
1016
+ if (blocks.length !== proposed.blockCount) {
1017
+ this.log.warn(
1018
+ `Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`,
1019
+ {
1020
+ proposedCheckpointNumber: proposed.checkpointNumber,
1021
+ proposedStartBlock: proposed.startBlock,
1022
+ proposedBlockCount: proposed.blockCount,
1023
+ retrievedBlocks: blocks.map(b => b.number),
1024
+ },
1025
+ );
1026
+ return undefined;
1027
+ }
1028
+
1029
+ const checkpoint = Checkpoint.from({
1030
+ archive: proposed.archive,
1031
+ header: proposed.header,
1032
+ blocks,
1033
+ number: proposed.checkpointNumber,
1034
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier,
1035
+ });
1036
+ const promotedCheckpoint = PublishedCheckpoint.from({
1037
+ checkpoint,
1038
+ l1: calldataCheckpoint.l1,
1039
+ attestations: calldataCheckpoint.attestations,
1040
+ });
1041
+ this.instrumentation.processCheckpointPromoted();
1042
+
1043
+ return promotedCheckpoint;
1044
+ }
1045
+
878
1046
  private async checkForNewCheckpointsBeforeL1SyncPoint(
879
1047
  status: RollupStatus,
880
1048
  blocksSynchedTo: bigint,