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