@aztec-labs/archiver 6.0.0-rc.2 → 6.0.0-rc.4

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 (62) hide show
  1. package/dest/archiver.d.ts +11 -2
  2. package/dest/archiver.d.ts.map +1 -1
  3. package/dest/archiver.js +94 -2
  4. package/dest/config.js +1 -1
  5. package/dest/errors.d.ts +12 -1
  6. package/dest/errors.d.ts.map +1 -1
  7. package/dest/errors.js +12 -0
  8. package/dest/l1/bin/retrieve-calldata.js +7 -5
  9. package/dest/l1/calldata_retriever.d.ts +5 -2
  10. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  11. package/dest/l1/calldata_retriever.js +8 -3
  12. package/dest/l1/data_retrieval.d.ts +2 -1
  13. package/dest/l1/data_retrieval.d.ts.map +1 -1
  14. package/dest/l1/data_retrieval.js +14 -9
  15. package/dest/l1/validate_trace.d.ts +3 -1
  16. package/dest/l1/validate_trace.d.ts.map +1 -1
  17. package/dest/l1/validate_trace.js +8 -3
  18. package/dest/modules/checkpoint_ingestor.d.ts +71 -0
  19. package/dest/modules/checkpoint_ingestor.d.ts.map +1 -0
  20. package/dest/modules/checkpoint_ingestor.js +516 -0
  21. package/dest/modules/data_store_updater.d.ts +6 -11
  22. package/dest/modules/data_store_updater.d.ts.map +1 -1
  23. package/dest/modules/data_store_updater.js +4 -3
  24. package/dest/modules/instrumentation.d.ts +8 -4
  25. package/dest/modules/instrumentation.d.ts.map +1 -1
  26. package/dest/modules/instrumentation.js +8 -2
  27. package/dest/modules/l1_synchronizer.d.ts +3 -7
  28. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  29. package/dest/modules/l1_synchronizer.js +84 -420
  30. package/dest/modules/pending_chain_validation_tracker.d.ts +21 -0
  31. package/dest/modules/pending_chain_validation_tracker.d.ts.map +1 -0
  32. package/dest/modules/pending_chain_validation_tracker.js +32 -0
  33. package/dest/modules/validation.d.ts +2 -2
  34. package/dest/modules/validation.d.ts.map +1 -1
  35. package/dest/modules/validation.js +17 -11
  36. package/dest/store/block_store.d.ts +1 -1
  37. package/dest/store/block_store.d.ts.map +1 -1
  38. package/dest/store/block_store.js +8 -2
  39. package/dest/store/log_store_codec.d.ts +2 -1
  40. package/dest/store/log_store_codec.d.ts.map +1 -1
  41. package/dest/store/log_store_codec.js +1 -0
  42. package/dest/test/fake_l1_state.d.ts +21 -1
  43. package/dest/test/fake_l1_state.d.ts.map +1 -1
  44. package/dest/test/fake_l1_state.js +82 -30
  45. package/package.json +15 -15
  46. package/src/archiver.ts +112 -3
  47. package/src/config.ts +1 -1
  48. package/src/errors.ts +21 -0
  49. package/src/l1/README.md +5 -0
  50. package/src/l1/bin/retrieve-calldata.ts +5 -3
  51. package/src/l1/calldata_retriever.ts +8 -3
  52. package/src/l1/data_retrieval.ts +13 -11
  53. package/src/l1/validate_trace.ts +11 -2
  54. package/src/modules/checkpoint_ingestor.ts +742 -0
  55. package/src/modules/data_store_updater.ts +7 -13
  56. package/src/modules/instrumentation.ts +17 -3
  57. package/src/modules/l1_synchronizer.ts +116 -563
  58. package/src/modules/pending_chain_validation_tracker.ts +43 -0
  59. package/src/modules/validation.ts +13 -9
  60. package/src/store/block_store.ts +6 -0
  61. package/src/store/log_store_codec.ts +1 -0
  62. package/src/test/fake_l1_state.ts +94 -31
@@ -8,57 +8,39 @@ import { asyncPool } from '@aztec-labs/foundation/async-pool';
8
8
  import { maxBigint } from '@aztec-labs/foundation/bigint';
9
9
  import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec-labs/foundation/branded-types';
10
10
  import { Buffer32 } from '@aztec-labs/foundation/buffer';
11
- import { partition, pick } from '@aztec-labs/foundation/collection';
12
11
  import { Fr } from '@aztec-labs/foundation/curves/bn254';
13
- import { EthAddress } from '@aztec-labs/foundation/eth-address';
14
12
  import { type Logger, createLogger } from '@aztec-labs/foundation/log';
15
13
  import { count } from '@aztec-labs/foundation/string';
16
- import { DateProvider, Timer, elapsed } from '@aztec-labs/foundation/timer';
14
+ import { DateProvider, Timer } from '@aztec-labs/foundation/timer';
17
15
  import { isDefined } from '@aztec-labs/foundation/types';
18
- import {
19
- type ArchiverEmitter,
20
- type L2Block,
21
- L2BlockSourceEvents,
22
- type ValidateCheckpointResult,
23
- } from '@aztec-labs/stdlib/block';
24
- import {
25
- Checkpoint,
26
- type CheckpointData,
27
- type CheckpointInfo,
28
- type L1PublishedData,
29
- PublishedCheckpoint,
30
- } from '@aztec-labs/stdlib/checkpoint';
16
+ import { type ArchiverEmitter, type L2Block, L2BlockSourceEvents } from '@aztec-labs/stdlib/block';
17
+ import type { CheckpointData } from '@aztec-labs/stdlib/checkpoint';
31
18
  import { type L1RollupConstants, getEpochAtSlot, getSlotAtNextL1Block } from '@aztec-labs/stdlib/epoch-helpers';
32
- import type { CoordinationSignatureContext } from '@aztec-labs/stdlib/p2p';
33
19
  import { type Traceable, type Tracer, execInSpan, trackSpan } from '@aztec-labs/telemetry-client';
34
20
 
35
- import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
36
- import {
37
- type ResolvedCheckpointFromCalldata,
38
- getCheckpointBlobDataFromBlobs,
39
- retrieveCheckpointCalldataFromRollup,
40
- retrievedToPublishedCheckpoint,
41
- } from '../l1/data_retrieval.js';
42
21
  import type { RejectedCheckpoint } from '../store/block_store.js';
43
22
  import type { ArchiverDataStores } from '../store/data_stores.js';
44
23
  import type { L2FrontierCache } from '../store/l2_frontier_cache.js';
24
+ import { CheckpointIngestor, type SeenCheckpoint } from './checkpoint_ingestor.js';
45
25
  import { ArchiverDataStoreUpdater, blockLeafCount } from './data_store_updater.js';
46
26
  import { InboxMessageSynchronizer } from './inbox_message_synchronizer.js';
47
27
  import type { ArchiverInstrumentation } from './instrumentation.js';
48
- import { resolveCheckpointAttestationsFromCalldata } from './validation.js';
49
28
 
29
+ /** The rollup contract's view at the L1 head an iteration is pinned to. */
50
30
  type RollupStatus = {
51
31
  provenCheckpointNumber: CheckpointNumber;
52
- provenArchive: string;
32
+ provenArchive: Fr;
53
33
  pendingCheckpointNumber: CheckpointNumber;
54
- pendingArchive: string;
55
- validationResult: ValidateCheckpointResult | undefined;
56
- /** Last valid checkpoint observed on L1 and synced on this iteration */
57
- lastRetrievedCheckpoint?: PublishedCheckpoint;
58
- /** Last checkpoint observed on L1 across both valid and rejected entries on this iteration */
59
- lastSeenCheckpoint?: { checkpointNumber: CheckpointNumber; l1: L1PublishedData };
60
- /** Blocks added while handling checkpoints this iteration, for the aggregate block source update event. */
34
+ pendingArchive: Fr;
35
+ };
36
+
37
+ /** What handling checkpoints produced in one sync iteration. */
38
+ type CheckpointSyncOutcome = {
39
+ rollupStatus: RollupStatus;
40
+ /** Blocks persisted from L1 payloads; a promoted checkpoint's blocks were already local and are excluded. */
61
41
  blocksAdded: L2Block[];
42
+ /** Last checkpoint observed on L1 across both valid and rejected entries on this iteration. */
43
+ lastSeenCheckpoint: SeenCheckpoint | undefined;
62
44
  };
63
45
 
64
46
  /** Bounded Inbox message sync passes (a recovery step each) taken within one archiver sync iteration. */
@@ -75,6 +57,7 @@ export class ArchiverL1Synchronizer implements Traceable {
75
57
 
76
58
  private readonly updater: ArchiverDataStoreUpdater;
77
59
  private readonly messageSynchronizer: InboxMessageSynchronizer;
60
+ private readonly checkpointIngestor: CheckpointIngestor;
78
61
  /**
79
62
  * Set when an Inbox message replacement reached below the checkpointed tip's consumed count. The published chain
80
63
  * is then L1's to reconcile through checkpoint sync; until the checkpointed tip agrees with the message log again,
@@ -85,7 +68,7 @@ export class ArchiverL1Synchronizer implements Traceable {
85
68
 
86
69
  constructor(
87
70
  private readonly publicClient: ViemPublicClient,
88
- private readonly debugClient: ViemPublicDebugClient,
71
+ debugClient: ViemPublicDebugClient,
89
72
  private readonly rollup: RollupContract,
90
73
  private readonly inbox: InboxContract,
91
74
  private readonly stores: ArchiverDataStores,
@@ -95,8 +78,8 @@ export class ArchiverL1Synchronizer implements Traceable {
95
78
  skipPromoteProposedCheckpointDuringL1Sync?: boolean;
96
79
  maxAllowedEthClientDriftSeconds: number;
97
80
  },
98
- private readonly blobClient: BlobClientInterface,
99
- private readonly epochCache: EpochCache,
81
+ blobClient: BlobClientInterface,
82
+ epochCache: EpochCache,
100
83
  private readonly dateProvider: DateProvider,
101
84
  private readonly instrumentation: ArchiverInstrumentation,
102
85
  private readonly l1Constants: L1RollupConstants & {
@@ -122,6 +105,27 @@ export class ArchiverL1Synchronizer implements Traceable {
122
105
  (count, msPerMessage) => this.instrumentation.processNewMessages(count, msPerMessage),
123
106
  this.log.createChild('inbox'),
124
107
  );
108
+ this.checkpointIngestor = new CheckpointIngestor(
109
+ {
110
+ rollup,
111
+ publicClient,
112
+ debugClient,
113
+ blobClient,
114
+ epochCache,
115
+ stores,
116
+ updater: this.updater,
117
+ events,
118
+ instrumentation,
119
+ l1Constants,
120
+ tracer,
121
+ log: this.log,
122
+ },
123
+ () => ({
124
+ batchSizeInL1Blocks: this.getBatchSizeInL1Blocks(),
125
+ skipValidateCheckpointAttestations: this.config.skipValidateCheckpointAttestations ?? false,
126
+ skipPromoteProposedCheckpointDuringL1Sync: this.config.skipPromoteProposedCheckpointDuringL1Sync ?? false,
127
+ }),
128
+ );
125
129
  this.tracer = tracer;
126
130
  }
127
131
 
@@ -159,13 +163,6 @@ export class ArchiverL1Synchronizer implements Traceable {
159
163
  return this.l1Timestamp;
160
164
  }
161
165
 
162
- private getSignatureContext(): CoordinationSignatureContext {
163
- return {
164
- chainId: this.publicClient.chain.id,
165
- rollupAddress: EthAddress.fromString(this.rollup.address),
166
- };
167
- }
168
-
169
166
  /** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */
170
167
  public async testEthereumNodeSynced(): Promise<void> {
171
168
  const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
@@ -239,11 +236,16 @@ export class ArchiverL1Synchronizer implements Traceable {
239
236
  // tip can be reconciled from L1, but the iteration then does not advertise the head as synced.
240
237
  const messageSync = await this.syncL1ToL2Messages(currentL1BlockData, finalizedL1Block);
241
238
 
239
+ // A behind-syncpoint rollback rewinds the persisted scan point but not this iteration's head. Advertising the
240
+ // head as synced now would let the next same-head sync return early before the rewound scan point is re-read,
241
+ // leaving the detected checkpoint absent until another L1 block arrives.
242
+ let rolledBackScanPoint = false;
242
243
  if (currentL1BlockNumber > blocksSynchedTo) {
243
244
  // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
244
245
  // pending chain validation status, proven checkpoint number, and synched L1 block number.
245
- const rollupStatus = await this.handleCheckpoints(blocksSynchedTo, currentL1BlockNumber, initialSyncComplete);
246
- blocksAdded.push(...rollupStatus.blocksAdded);
246
+ const checkpointSync = await this.handleCheckpoints(blocksSynchedTo, currentL1BlockNumber, initialSyncComplete);
247
+ const { rollupStatus } = checkpointSync;
248
+ blocksAdded.push(...checkpointSync.blocksAdded);
247
249
 
248
250
  // Then we try pruning uncheckpointed blocks if a new slot was mined without checkpoints
249
251
  await this.pruneUncheckpointedBlocks(currentL1Timestamp);
@@ -263,12 +265,20 @@ export class ArchiverL1Synchronizer implements Traceable {
263
265
  // We only do this if rollup cant prune on the next submission. Otherwise we will end up
264
266
  // re-syncing the checkpoints we have just unwound above.
265
267
  if (!rollupCanPrune) {
266
- await this.checkForNewCheckpointsBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
268
+ rolledBackScanPoint = await this.checkForNewCheckpointsBeforeL1SyncPoint(
269
+ rollupStatus,
270
+ checkpointSync.lastSeenCheckpoint,
271
+ blocksSynchedTo,
272
+ currentL1BlockNumber,
273
+ );
267
274
  }
268
275
 
269
276
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
270
277
  } else if (await this.checkpointedChainNeedsReconciliation(currentL1BlockData)) {
271
- await this.reconcileCheckpointedChainAtNonAdvancingHead(blocksSynchedTo, currentL1BlockNumber);
278
+ rolledBackScanPoint = await this.reconcileCheckpointedChainAtNonAdvancingHead(
279
+ blocksSynchedTo,
280
+ currentL1BlockNumber,
281
+ );
272
282
  }
273
283
 
274
284
  // Update the finalized L2 checkpoint based on L1 finality.
@@ -279,10 +289,11 @@ export class ArchiverL1Synchronizer implements Traceable {
279
289
  // Readiness (the synced L1 block, which drives the synced L2 slot proposers build on) is only advanced once the
280
290
  // messages agree with L1 at this head and the checkpointed tip agrees with them: while either is pending, nothing
281
291
  // may build on the local tip.
282
- if (messageSync !== 'synced' || this.speculationGate !== undefined) {
292
+ if (messageSync !== 'synced' || this.speculationGate !== undefined || rolledBackScanPoint) {
283
293
  this.log.verbose(`Not advertising L1 block ${currentL1BlockNumber} as synced`, {
284
294
  currentL1BlockNumber,
285
295
  messageSync,
296
+ rolledBackScanPoint,
286
297
  speculationGate: this.speculationGate,
287
298
  recovery: this.messageSynchronizer.getRecoveryProgress(),
288
299
  });
@@ -457,15 +468,6 @@ export class ArchiverL1Synchronizer implements Traceable {
457
468
  return { rollupCanPrune };
458
469
  }
459
470
 
460
- private nextRange(end: bigint, limit: bigint): [bigint, bigint] {
461
- const nextStart = end + 1n;
462
- const nextEnd = nextStart + this.getBatchSizeInL1Blocks();
463
- if (nextEnd > limit) {
464
- return [nextStart, limit];
465
- }
466
- return [nextStart, nextEnd];
467
- }
468
-
469
471
  /**
470
472
  * Runs Inbox message sync passes against the captured head until the messages are synced to it or the per-iteration
471
473
  * pass budget is spent. Each pass is bounded; a recovery that needs more work continues on the next iteration, which
@@ -605,7 +607,7 @@ export class ArchiverL1Synchronizer implements Traceable {
605
607
  private async reconcileCheckpointedChainAtNonAdvancingHead(
606
608
  blocksSynchedTo: bigint,
607
609
  currentL1BlockNumber: bigint,
608
- ): Promise<void> {
610
+ ): Promise<boolean> {
609
611
  this.log.warn(
610
612
  `L1 head ${currentL1BlockNumber} is not past the checkpoint syncpoint ${blocksSynchedTo}; reconciling the checkpointed chain with it`,
611
613
  { blocksSynchedTo, currentL1BlockNumber },
@@ -614,7 +616,7 @@ export class ArchiverL1Synchronizer implements Traceable {
614
616
  if (currentL1BlockNumber < (await this.stores.blocks.getSynchedL1BlockNumber())!) {
615
617
  await this.stores.blocks.setSynchedL1BlockNumber(currentL1BlockNumber);
616
618
  }
617
- await this.checkForNewCheckpointsBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
619
+ return this.checkForNewCheckpointsBeforeL1SyncPoint(rollupStatus, undefined, blocksSynchedTo, currentL1BlockNumber);
618
620
  }
619
621
 
620
622
  /**
@@ -625,10 +627,8 @@ export class ArchiverL1Synchronizer implements Traceable {
625
627
  private async reconcileCheckpointedChain(
626
628
  blocksSynchedTo: bigint,
627
629
  currentL1BlockNumber: bigint,
628
- ): Promise<{ rollupStatus: RollupStatus; fetchCheckpoints: boolean; provenArchive: Fr }> {
630
+ ): Promise<{ rollupStatus: RollupStatus; fetchCheckpoints: boolean }> {
629
631
  const localPendingCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
630
- const initialValidationResult: ValidateCheckpointResult | undefined =
631
- await this.stores.blocks.getPendingChainValidationStatus();
632
632
  const {
633
633
  provenCheckpointNumber,
634
634
  provenArchive,
@@ -640,11 +640,9 @@ export class ArchiverL1Synchronizer implements Traceable {
640
640
  );
641
641
  const rollupStatus: RollupStatus = {
642
642
  provenCheckpointNumber,
643
- provenArchive: provenArchive.toString(),
643
+ provenArchive,
644
644
  pendingCheckpointNumber,
645
- pendingArchive: pendingArchive.toString(),
646
- validationResult: initialValidationResult,
647
- blocksAdded: [],
645
+ pendingArchive,
648
646
  };
649
647
  this.log.trace(`Retrieved rollup status at current L1 block ${currentL1BlockNumber}.`, {
650
648
  localPendingCheckpointNumber,
@@ -662,7 +660,7 @@ export class ArchiverL1Synchronizer implements Traceable {
662
660
  this.log.debug(
663
661
  `No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no checkpoints on chain`,
664
662
  );
665
- return { rollupStatus, fetchCheckpoints: false, provenArchive };
663
+ return { rollupStatus, fetchCheckpoints: false };
666
664
  }
667
665
 
668
666
  await this.updateProvenCheckpoint(provenCheckpointNumber, provenArchive);
@@ -676,7 +674,7 @@ export class ArchiverL1Synchronizer implements Traceable {
676
674
  }
677
675
 
678
676
  const localPendingArchiveRoot = localPendingCheckpoint.archive.root.toString();
679
- const noCheckpointSinceLast = localPendingCheckpoint && pendingArchive.toString() === localPendingArchiveRoot;
677
+ const noCheckpointSinceLast = pendingArchive.toString() === localPendingArchiveRoot;
680
678
  if (noCheckpointSinceLast) {
681
679
  // We believe the following line causes a problem when we encounter L1 re-orgs.
682
680
  // Basically, by setting the synched L1 block number here, we are saying that we have
@@ -692,7 +690,7 @@ export class ArchiverL1Synchronizer implements Traceable {
692
690
  // waits for L1 to produce a block that moves the root again. A "checkpoint refetch still pending" flag
693
691
  // carried out of reconciliation past this optimization would let the next pass fetch at the same head.
694
692
  this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}`);
695
- return { rollupStatus, fetchCheckpoints: false, provenArchive };
693
+ return { rollupStatus, fetchCheckpoints: false };
696
694
  }
697
695
 
698
696
  const localPendingCheckpointInChain = archiveForLocalPendingCheckpointNumber.equals(
@@ -708,27 +706,7 @@ export class ArchiverL1Synchronizer implements Traceable {
708
706
  { localPendingCheckpointNumber, localPendingArchiveRoot, archiveForLocalPendingCheckpointNumber },
709
707
  );
710
708
 
711
- let tipAfterUnwind = localPendingCheckpointNumber;
712
- while (true) {
713
- const candidateCheckpoint = await this.stores.blocks.getCheckpointData(tipAfterUnwind);
714
- if (candidateCheckpoint === undefined) {
715
- break;
716
- }
717
-
718
- const archiveAtContract = await this.rollup.archiveAt(candidateCheckpoint.checkpointNumber);
719
- this.log.trace(
720
- `Checking local checkpoint ${candidateCheckpoint.checkpointNumber} with archive ${candidateCheckpoint.archive.root}`,
721
- {
722
- archiveAtContract,
723
- archiveLocal: candidateCheckpoint.archive.root.toString(),
724
- },
725
- );
726
- if (archiveAtContract.equals(candidateCheckpoint.archive.root)) {
727
- break;
728
- }
729
- tipAfterUnwind--;
730
- }
731
-
709
+ const tipAfterUnwind = await this.findLastCheckpointAlsoOnL1(localPendingCheckpointNumber);
732
710
  const checkpointsToRemove = localPendingCheckpointNumber - tipAfterUnwind;
733
711
  await this.updater.removeCheckpointsAfter(CheckpointNumber(tipAfterUnwind));
734
712
  if (checkpointsToRemove > 0) {
@@ -743,7 +721,35 @@ export class ArchiverL1Synchronizer implements Traceable {
743
721
  }
744
722
  }
745
723
 
746
- return { rollupStatus, fetchCheckpoints: true, provenArchive };
724
+ return { rollupStatus, fetchCheckpoints: true };
725
+ }
726
+
727
+ /**
728
+ * Walks down from the given local checkpoint to the latest one whose archive matches the rollup's, stopping early at
729
+ * a checkpoint missing locally.
730
+ */
731
+ private async findLastCheckpointAlsoOnL1(from: CheckpointNumber): Promise<CheckpointNumber> {
732
+ let tipAfterUnwind = from;
733
+ while (true) {
734
+ const candidateCheckpoint = await this.stores.blocks.getCheckpointData(tipAfterUnwind);
735
+ if (candidateCheckpoint === undefined) {
736
+ break;
737
+ }
738
+
739
+ const archiveAtContract = await this.rollup.archiveAt(candidateCheckpoint.checkpointNumber);
740
+ this.log.trace(
741
+ `Checking local checkpoint ${candidateCheckpoint.checkpointNumber} with archive ${candidateCheckpoint.archive.root}`,
742
+ {
743
+ archiveAtContract,
744
+ archiveLocal: candidateCheckpoint.archive.root.toString(),
745
+ },
746
+ );
747
+ if (archiveAtContract.equals(candidateCheckpoint.archive.root)) {
748
+ break;
749
+ }
750
+ tipAfterUnwind--;
751
+ }
752
+ return tipAfterUnwind;
747
753
  }
748
754
 
749
755
  private async updateProvenCheckpoint(provenCheckpointNumber: CheckpointNumber, provenArchive: Fr): Promise<void> {
@@ -812,489 +818,35 @@ export class ArchiverL1Synchronizer implements Traceable {
812
818
  blocksSynchedTo: bigint,
813
819
  currentL1BlockNumber: bigint,
814
820
  initialSyncComplete: boolean,
815
- ): Promise<RollupStatus> {
816
- const { rollupStatus, fetchCheckpoints, provenArchive } = await this.reconcileCheckpointedChain(
821
+ ): Promise<CheckpointSyncOutcome> {
822
+ const { rollupStatus, fetchCheckpoints } = await this.reconcileCheckpointedChain(
817
823
  blocksSynchedTo,
818
824
  currentL1BlockNumber,
819
825
  );
820
826
  if (!fetchCheckpoints) {
821
- return rollupStatus;
822
- }
823
- const { blocksAdded, validationResult: initialValidationResult } = rollupStatus;
824
-
825
- // Retrieve checkpoints in batches. Each batch is estimated to accommodate up to 'blockBatchSize' L1 blocks,
826
- // computed using the L2 block time vs the L1 block time.
827
- let searchStartBlock: bigint = blocksSynchedTo;
828
- let searchEndBlock: bigint = blocksSynchedTo;
829
- let lastRetrievedCheckpoint: PublishedCheckpoint | undefined;
830
- let lastSeenCheckpoint: { checkpointNumber: CheckpointNumber; l1: L1PublishedData } | undefined;
831
-
832
- do {
833
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
834
-
835
- this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
836
-
837
- // First fetch calldata only, no blobs yet, since we may be able to just get that data out of the proposed chain
838
- const calldataCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', () =>
839
- retrieveCheckpointCalldataFromRollup(
840
- this.rollup,
841
- this.publicClient,
842
- this.debugClient,
843
- searchStartBlock, // TODO(palla/reorg): If the L2 reorg was due to an L1 reorg, we need to start search earlier
844
- searchEndBlock,
845
- this.instrumentation,
846
- this.log,
847
- ),
848
- );
849
-
850
- if (calldataCheckpoints.length === 0) {
851
- // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
852
- // See further details in earlier comments.
853
- this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
854
- continue;
855
- }
856
-
857
- this.log.debug(
858
- `Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
859
- {
860
- lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
861
- searchStartBlock,
862
- searchEndBlock,
863
- },
864
- );
865
-
866
- // Screening below records rejected checkpoints as it goes, and each such write advances the L1 sync point past
867
- // the rejected checkpoint's L1 block before the batch's valid checkpoints are persisted. If anything in the batch
868
- // throws before the batch is persisted, the sync point is restored to where it stood before the batch, so the
869
- // next iteration processes the whole batch again instead of skipping its valid checkpoints. Once the batch is
870
- // persisted the sync point is left alone: replaying it would refetch blobs for checkpoints already stored,
871
- // including promoted ones this node never fetched blobs for, and stall if those blobs are unavailable.
872
- const syncPointBeforeBatch = await this.stores.blocks.getSynchedL1BlockNumber();
873
- let batchPersisted = false;
874
- try {
875
- // Decode and validate attestations from CALLDATA before fetching any blobs, so a checkpoint with invalid
876
- // attestations is rejected without decoding a possibly malformed blob. Runs even when validation is
877
- // disabled, since promotion and persistence need the decoded attestations.
878
- const resolvedCheckpoints = await asyncPool(10, calldataCheckpoints, async calldataCheckpoint => {
879
- const { attestations, validationResult } = await resolveCheckpointAttestationsFromCalldata(
880
- calldataCheckpoint,
881
- this.epochCache,
882
- this.l1Constants,
883
- this.getSignatureContext(),
884
- this.log,
885
- );
886
- return { checkpoint: { ...calldataCheckpoint, attestations }, validationResult };
887
- });
888
-
889
- // Check if the last checkpoint matches a local pending entry (so we can skip blob fetch).
890
- // We only check the last one; if it matches, the blob fetch is skipped for that entry.
891
- // TODO(palla/pipelining): We may have more than a single checkpoint to promote
892
- const lastCalldataCheckpoint = resolvedCheckpoints[resolvedCheckpoints.length - 1].checkpoint;
893
- const promoteResult = await this.tryBuildPublishedCheckpointFromProposed(lastCalldataCheckpoint);
894
- const checkpointToPromote = promoteResult && !('diverged' in promoteResult) ? promoteResult : undefined;
895
- const evictProposedFrom =
896
- promoteResult && 'diverged' in promoteResult ? promoteResult.fromCheckpointNumber : undefined;
897
-
898
- const checkpointsToIngest: ResolvedCheckpointFromCalldata[] = [];
899
-
900
- for (const {
901
- checkpoint: calldataCheckpoint,
902
- validationResult: resolvedValidationResult,
903
- } of resolvedCheckpoints) {
904
- // Check the attestations uploaded by the publisher to L1 are correct.
905
- // Rollup contract does not validate attestations to save on gas, so this
906
- // falls on the nodes to verify offchain and skip those checkpoints.
907
- const validationResult = this.config.skipValidateCheckpointAttestations
908
- ? { valid: true as const }
909
- : resolvedValidationResult;
910
-
911
- // Also skip the checkpoint if it builds on a previously-rejected ancestor. Without
912
- // this, addCheckpoints would throw InitialCheckpointNumberNotSequentialError when the
913
- // ancestor was skipped earlier (e.g. due to invalid attestations), the catch handler
914
- // would roll back the L1 sync point, and the next iteration would re-fetch and re-throw.
915
- const rejectedAncestor = await this.stores.blocks.getRejectedCheckpointByArchiveRoot(
916
- calldataCheckpoint.header.lastArchiveRoot,
917
- );
918
-
919
- // Update the validation result if it has changed, so we can keep track of the first invalid checkpoint
920
- // in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
921
- // There is an exception though: if a checkpoint is invalidated and replaced with another invalid checkpoint,
922
- // we need to update the validation result, since we need to be able to invalidate the new one.
923
- // See test 'chain progresses if an invalid checkpoint is invalidated with an invalid one' for more info.
924
- // Do not update the validation result if there is a rejected ancestor, since in that case we want to keep the
925
- // original invalidation, as the new checkpoint is extending from a previous invalid one.
926
- const validStatusChanged = rollupStatus.validationResult?.valid !== validationResult.valid;
927
- const invalidStatusWithSameCheckpointNumber =
928
- !validationResult.valid &&
929
- rollupStatus.validationResult &&
930
- !rollupStatus.validationResult.valid &&
931
- rollupStatus.validationResult.checkpoint.checkpointNumber === validationResult.checkpoint.checkpointNumber;
932
-
933
- if (!rejectedAncestor && (validStatusChanged || invalidStatusWithSameCheckpointNumber)) {
934
- rollupStatus.validationResult = validationResult;
935
- }
936
-
937
- if (!validationResult.valid) {
938
- this.log.warn(`Skipping checkpoint ${calldataCheckpoint.checkpointNumber} due to invalid attestations`, {
939
- checkpointNumber: calldataCheckpoint.checkpointNumber,
940
- l1BlockNumber: calldataCheckpoint.l1.blockNumber,
941
- ...pick(validationResult, 'reason'),
942
- });
943
-
944
- // Emit event for invalid checkpoint detection
945
- this.events.emit(L2BlockSourceEvents.InvalidAttestationsCheckpointDetected, {
946
- type: L2BlockSourceEvents.InvalidAttestationsCheckpointDetected,
947
- validationResult,
948
- });
949
-
950
- // Persist a rejected-ancestor entry so any later checkpoint that builds on this one
951
- // is detected and skipped (rather than tripping the addCheckpoints consecutive-number
952
- // check and causing the sync point to roll back in a loop).
953
- await this.stores.blocks.addRejectedCheckpoint({
954
- checkpointNumber: calldataCheckpoint.checkpointNumber,
955
- archiveRoot: calldataCheckpoint.archiveRoot,
956
- parentArchiveRoot: calldataCheckpoint.header.lastArchiveRoot,
957
- slotNumber: calldataCheckpoint.header.slotNumber,
958
- l1: calldataCheckpoint.l1,
959
- reason: 'invalid-attestations' as const,
960
- });
961
-
962
- continue;
963
- }
964
-
965
- if (rejectedAncestor) {
966
- const descendantInfo: CheckpointInfo = {
967
- archive: calldataCheckpoint.archiveRoot,
968
- lastArchive: calldataCheckpoint.header.lastArchiveRoot,
969
- slotNumber: calldataCheckpoint.header.slotNumber,
970
- checkpointNumber: calldataCheckpoint.checkpointNumber,
971
- timestamp: calldataCheckpoint.header.timestamp,
972
- };
973
- this.log.warn(
974
- `Skipping checkpoint ${calldataCheckpoint.checkpointNumber} as it is a descendant of ` +
975
- `rejected checkpoint ${rejectedAncestor.checkpointNumber} (${rejectedAncestor.reason})`,
976
- {
977
- checkpointNumber: calldataCheckpoint.checkpointNumber,
978
- l1BlockNumber: calldataCheckpoint.l1.blockNumber,
979
- l1BlockHash: calldataCheckpoint.l1.blockHash,
980
- ancestorCheckpointNumber: rejectedAncestor.checkpointNumber,
981
- ancestorArchiveRoot: rejectedAncestor.archiveRoot.toString(),
982
- ancestorReason: rejectedAncestor.reason,
983
- },
984
- );
985
-
986
- this.events.emit(L2BlockSourceEvents.DescendentOfInvalidAttestationsCheckpointDetected, {
987
- type: L2BlockSourceEvents.DescendentOfInvalidAttestationsCheckpointDetected,
988
- checkpoint: descendantInfo,
989
- ancestorArchiveRoot: rejectedAncestor.archiveRoot,
990
- ancestorCheckpointNumber: rejectedAncestor.checkpointNumber,
991
- });
992
-
993
- // Persist this chainpoint as rejected as well, so we can construct a chain of
994
- // skipped checkpoints starting from the first one with invalid attestations.
995
- await this.stores.blocks.addRejectedCheckpoint({
996
- checkpointNumber: calldataCheckpoint.checkpointNumber,
997
- archiveRoot: calldataCheckpoint.archiveRoot,
998
- parentArchiveRoot: calldataCheckpoint.header.lastArchiveRoot,
999
- slotNumber: calldataCheckpoint.header.slotNumber,
1000
- l1: calldataCheckpoint.l1,
1001
- reason: 'descends-from-invalid-attestations' as const,
1002
- });
1003
-
1004
- continue;
1005
- }
1006
-
1007
- checkpointsToIngest.push(calldataCheckpoint);
1008
- }
1009
-
1010
- // Fetch blobs in parallel only for the surviving (attestation-valid, non-descendant) checkpoints,
1011
- // then build the full published checkpoints. The last calldata checkpoint may be promotable from a
1012
- // local proposed block (checkpointToPromote), in which case it carries no blob to fetch. A missing or
1013
- // undecodable blob throws and propagates, and the batch guard restores the L1 sync point so the fetch is retried.
1014
- const toFetchBlobs = checkpointToPromote
1015
- ? checkpointsToIngest.filter(c => c.checkpointNumber !== checkpointToPromote.checkpoint.number)
1016
- : checkpointsToIngest;
1017
- const blobFetched = await asyncPool(10, toFetchBlobs, async checkpoint =>
1018
- retrievedToPublishedCheckpoint({
1019
- ...checkpoint,
1020
- checkpointBlobData: await getCheckpointBlobDataFromBlobs(
1021
- this.blobClient,
1022
- checkpoint.l1.blockHash,
1023
- checkpoint.blobHashes,
1024
- checkpoint.checkpointNumber,
1025
- this.log,
1026
- !initialSyncComplete,
1027
- checkpoint.parentBeaconBlockRoot,
1028
- checkpoint.l1.timestamp,
1029
- ),
1030
- }),
1031
- );
1032
-
1033
- // Index the built checkpoints by number so we can ingest them in calldata order, slotting in the
1034
- // promoted checkpoint (built from a local proposed block rather than blobs).
1035
- const publishedByNumber = new Map(
1036
- blobFetched.map(publishedCheckpoint => [publishedCheckpoint.checkpoint.number, publishedCheckpoint]),
1037
- );
1038
- if (checkpointToPromote) {
1039
- publishedByNumber.set(checkpointToPromote.checkpoint.number, checkpointToPromote);
1040
- }
1041
-
1042
- const validCheckpoints: PublishedCheckpoint[] = [];
1043
- for (const calldataCheckpoint of checkpointsToIngest) {
1044
- const published = publishedByNumber.get(calldataCheckpoint.checkpointNumber)!;
1045
-
1046
- validCheckpoints.push(published);
1047
- this.log.debug(
1048
- `Ingesting new checkpoint ${published.checkpoint.number} with ${published.checkpoint.blocks.length} blocks`,
1049
- {
1050
- checkpointHash: published.checkpoint.hash(),
1051
- l1BlockNumber: published.l1.blockNumber,
1052
- ...published.checkpoint.header.toInspect(),
1053
- blocks: published.checkpoint.blocks.map(b => b.getStats()),
1054
- },
1055
- );
1056
- }
1057
-
1058
- for (const published of validCheckpoints) {
1059
- this.instrumentation.processCheckpointL1Timing({
1060
- slotNumber: published.checkpoint.header.slotNumber,
1061
- l1Timestamp: published.l1.timestamp,
1062
- l1Constants: this.l1Constants,
1063
- });
1064
- }
1065
-
1066
- try {
1067
- const updatedValidationResult =
1068
- rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
1069
-
1070
- // Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
1071
- // the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
1072
- const [[maybeValidCheckpointToPromote], checkpointsToAdd] = partition(
1073
- validCheckpoints,
1074
- c => c.checkpoint.number === checkpointToPromote?.checkpoint.number,
1075
- );
1076
-
1077
- const [processDuration, result] = await elapsed(() =>
1078
- execInSpan(this.tracer, 'Archiver.addCheckpoints', async () => {
1079
- const addResult = await this.updater.addCheckpoints(
1080
- checkpointsToAdd,
1081
- updatedValidationResult,
1082
- maybeValidCheckpointToPromote && {
1083
- l1: lastCalldataCheckpoint.l1,
1084
- attestations: lastCalldataCheckpoint.attestations,
1085
- verbatimAttestations: lastCalldataCheckpoint.verbatimAttestations,
1086
- checkpoint: maybeValidCheckpointToPromote,
1087
- },
1088
- evictProposedFrom,
1089
- );
1090
- // Set before the span wrappers finish, so a throw while closing the span doesn't count as unpersisted.
1091
- batchPersisted = true;
1092
- return addResult;
1093
- }),
1094
- );
1095
-
1096
- if (validCheckpoints.length > 0) {
1097
- this.instrumentation.processNewCheckpointedBlocks(
1098
- processDuration / validCheckpoints.length,
1099
- validCheckpoints.flatMap(c => c.checkpoint.blocks),
1100
- );
1101
- }
1102
-
1103
- // Record blocks newly fetched from L1 checkpoint payloads as added. The promoted checkpoint (if any) is
1104
- // excluded: its blocks were already in local archiver storage (added via the proposed-block path) so the
1105
- // block stream does not need them re-downloaded.
1106
- blocksAdded.push(...checkpointsToAdd.flatMap(c => c.checkpoint.blocks));
1107
-
1108
- // If blocks were pruned due to conflict with L1 checkpoints, emit event
1109
- if (result.prunedBlocks && result.prunedBlocks.length > 0) {
1110
- const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
1111
- const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
1112
-
1113
- this.log.info(
1114
- `Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`,
1115
- { prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
1116
- );
1117
-
1118
- this.instrumentation.recordPrune('l1_conflict');
1119
-
1120
- // Emit event for listening services to react to the prune.
1121
- // Note: slotNumber comes from the first pruned block. If pruned blocks theoretically spanned multiple slots,
1122
- // only one slot number would be reported (though in practice all blocks in a checkpoint span a single slot).
1123
- this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
1124
- type: L2BlockSourceEvents.L2PruneUncheckpointed,
1125
- slotNumber: prunedSlotNumber,
1126
- blocks: result.prunedBlocks,
1127
- });
1128
- }
1129
- } catch (err) {
1130
- if (err instanceof InitialCheckpointNumberNotSequentialError) {
1131
- const { previousCheckpointNumber, newCheckpointNumber } = err;
1132
- const previousCheckpoint = previousCheckpointNumber
1133
- ? await this.stores.blocks.getCheckpointData(CheckpointNumber(previousCheckpointNumber))
1134
- : undefined;
1135
- const lastFinalizedCheckpoint = await this.stores.blocks.getCheckpointData(
1136
- await this.stores.blocks.getFinalizedCheckpointNumber(),
1137
- );
1138
- const updatedL1SyncPoint =
1139
- previousCheckpoint?.l1.blockNumber ??
1140
- lastFinalizedCheckpoint?.l1.blockNumber ??
1141
- this.l1Constants.l1StartBlock;
1142
- await this.stores.blocks.setSynchedL1BlockNumber(updatedL1SyncPoint);
1143
- this.log.warn(
1144
- `Attempting to insert checkpoint ${newCheckpointNumber} with previous block ${previousCheckpointNumber}. Rolling back L1 sync point to ${updatedL1SyncPoint} to try and fetch the missing blocks.`,
1145
- {
1146
- previousCheckpointNumber,
1147
- previousCheckpoint: previousCheckpoint?.header.toInspect(),
1148
- lastFinalizedCheckpoint: lastFinalizedCheckpoint?.header.toInspect(),
1149
- l1StartBlock: this.l1Constants.l1StartBlock,
1150
- newCheckpointNumber,
1151
- updatedL1SyncPoint,
1152
- },
1153
- );
1154
- }
1155
- throw err;
1156
- }
1157
-
1158
- for (const checkpoint of validCheckpoints) {
1159
- this.log.info(`Downloaded checkpoint ${checkpoint.checkpoint.number}`, {
1160
- checkpointHash: checkpoint.checkpoint.hash(),
1161
- checkpointNumber: checkpoint.checkpoint.number,
1162
- blockCount: checkpoint.checkpoint.blocks.length,
1163
- txCount: checkpoint.checkpoint.blocks.reduce((acc, b) => acc + b.body.txEffects.length, 0),
1164
- header: checkpoint.checkpoint.header.toInspect(),
1165
- archiveRoot: checkpoint.checkpoint.archive.root.toString(),
1166
- archiveNextLeafIndex: checkpoint.checkpoint.archive.nextAvailableLeafIndex,
1167
- });
1168
- }
1169
- lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
1170
- // The last checkpoint seen on L1 this batch (valid or rejected), tracked from calldata since
1171
- // rejected checkpoints are no longer built into PublishedCheckpoints.
1172
- lastSeenCheckpoint = lastCalldataCheckpoint;
1173
- } catch (err) {
1174
- const restoreTo = syncPointBeforeBatch ?? this.l1Constants.l1StartBlock;
1175
- const currentSyncPoint = await this.stores.blocks.getSynchedL1BlockNumber();
1176
- // Only ever lower it, so a deeper rewind made while handling the error (e.g. on a checkpoint gap) is kept.
1177
- if (!batchPersisted && currentSyncPoint !== undefined && currentSyncPoint > restoreTo) {
1178
- this.log.warn(`Restoring L1 sync point to ${restoreTo} after failing to process checkpoints`, {
1179
- currentSyncPoint,
1180
- restoreTo,
1181
- searchStartBlock,
1182
- searchEndBlock,
1183
- });
1184
- await this.stores.blocks.setSynchedL1BlockNumber(restoreTo);
1185
- }
1186
- throw err;
1187
- }
1188
- } while (searchEndBlock < currentL1BlockNumber);
1189
-
1190
- // Important that we update AFTER inserting the blocks.
1191
- await this.updateProvenCheckpoint(rollupStatus.provenCheckpointNumber, provenArchive);
1192
-
1193
- return { ...rollupStatus, lastRetrievedCheckpoint, lastSeenCheckpoint };
1194
- }
1195
-
1196
- /**
1197
- * Checks if a specific checkpoint matches a local pending entry, and if so, loads local data to build
1198
- * a synthetic published checkpoint (skipping blob fetch).
1199
- *
1200
- * Returns { diverged: true, fromCheckpointNumber } when the L1 checkpoint does NOT match local pending
1201
- * data for that number, so the caller can evict the entire pending suffix >= fromCheckpointNumber
1202
- * (those entries chain off the now-invalid local state) within the same addCheckpoints transaction.
1203
- */
1204
- private async tryBuildPublishedCheckpointFromProposed(
1205
- calldataCheckpoint: ResolvedCheckpointFromCalldata | undefined,
1206
- ): Promise<PublishedCheckpoint | { diverged: true; fromCheckpointNumber: CheckpointNumber } | undefined> {
1207
- if (this.config.skipPromoteProposedCheckpointDuringL1Sync || !calldataCheckpoint) {
1208
- return undefined;
827
+ return { rollupStatus, blocksAdded: [], lastSeenCheckpoint: undefined };
1209
828
  }
1210
-
1211
- // Look up the specific pending entry for the checkpoint being mined, not just the tip
1212
- const proposed = await this.stores.blocks.getProposedCheckpointByNumber(calldataCheckpoint.checkpointNumber);
1213
- if (!proposed) {
1214
- return undefined;
1215
- }
1216
-
1217
- if (
1218
- !proposed.header.equals(calldataCheckpoint.header) ||
1219
- !proposed.archive.root.equals(calldataCheckpoint.archiveRoot) ||
1220
- proposed.feeAssetPriceModifier !== calldataCheckpoint.feeAssetPriceModifier
1221
- ) {
1222
- this.log.warn(
1223
- `Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`,
1224
- {
1225
- proposedCheckpointNumber: proposed.checkpointNumber,
1226
- proposedHeader: proposed.header.toInspect(),
1227
- proposedArchiveRoot: proposed.archive.root.toString(),
1228
- proposedFeeAssetPriceModifier: proposed.feeAssetPriceModifier.toString(),
1229
- calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
1230
- calldataHeader: calldataCheckpoint.header.toInspect(),
1231
- calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString(),
1232
- calldataFeeAssetPriceModifier: calldataCheckpoint.feeAssetPriceModifier.toString(),
1233
- },
1234
- );
1235
- // Both the locally-proposed checkpoint and the L1-confirmed one are signed by the
1236
- // slot proposer; emit a divergence event so the slasher can attribute equivocation.
1237
- // Only emit when the slots match — uncheckpointed entries are pruned above so this
1238
- // should always hold, but guard defensively to avoid mis-attributing a slash.
1239
- if (proposed.header.slotNumber === calldataCheckpoint.header.slotNumber) {
1240
- this.events.emit(L2BlockSourceEvents.CheckpointEquivocationDetected, {
1241
- type: L2BlockSourceEvents.CheckpointEquivocationDetected,
1242
- slotNumber: calldataCheckpoint.header.slotNumber,
1243
- checkpointNumber: calldataCheckpoint.checkpointNumber,
1244
- l1ArchiveRoot: calldataCheckpoint.archiveRoot,
1245
- proposedArchiveRoot: proposed.archive.root,
1246
- });
1247
- }
1248
- // Return a divergence signal so the caller can evict pending >= this number
1249
- return { diverged: true, fromCheckpointNumber: proposed.checkpointNumber };
1250
- }
1251
-
1252
- this.log.debug(
1253
- `Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`,
1254
- { proposedHeader: proposed.header.toInspect(), proposedArchiveRoot: proposed.archive.root.toString() },
829
+ // Read after reconciliation, since an unwind resets the stored status to valid.
830
+ const initialValidationStatus = await this.stores.blocks.getPendingChainValidationStatus();
831
+ const { blocksAdded, lastSeenCheckpoint } = await this.checkpointIngestor.ingest(
832
+ blocksSynchedTo,
833
+ currentL1BlockNumber,
834
+ { initialSyncComplete, initialValidationStatus },
1255
835
  );
1256
836
 
1257
- const blocks = await this.stores.blocks.getBlocks({
1258
- from: BlockNumber(proposed.startBlock),
1259
- limit: proposed.blockCount,
1260
- });
1261
- if (blocks.length !== proposed.blockCount) {
1262
- this.log.warn(
1263
- `Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`,
1264
- {
1265
- proposedCheckpointNumber: proposed.checkpointNumber,
1266
- proposedStartBlock: proposed.startBlock,
1267
- proposedBlockCount: proposed.blockCount,
1268
- retrievedBlocks: blocks.map(b => b.number),
1269
- },
1270
- );
1271
- return undefined;
1272
- }
1273
-
1274
- const checkpoint = Checkpoint.from({
1275
- archive: proposed.archive,
1276
- header: proposed.header,
1277
- blocks,
1278
- number: proposed.checkpointNumber,
1279
- feeAssetPriceModifier: proposed.feeAssetPriceModifier,
1280
- });
1281
- const promotedCheckpoint = PublishedCheckpoint.from({
1282
- checkpoint,
1283
- l1: calldataCheckpoint.l1,
1284
- attestations: calldataCheckpoint.attestations,
1285
- verbatimAttestations: calldataCheckpoint.verbatimAttestations,
1286
- });
1287
- this.instrumentation.processCheckpointPromoted();
837
+ // Important that we update AFTER inserting the blocks.
838
+ await this.updateProvenCheckpoint(rollupStatus.provenCheckpointNumber, rollupStatus.provenArchive);
1288
839
 
1289
- return promotedCheckpoint;
840
+ return { rollupStatus, blocksAdded, lastSeenCheckpoint };
1290
841
  }
1291
842
 
1292
843
  private async checkForNewCheckpointsBeforeL1SyncPoint(
1293
844
  status: RollupStatus,
845
+ lastSeenCheckpoint: SeenCheckpoint | undefined,
1294
846
  blocksSynchedTo: bigint,
1295
847
  currentL1BlockNumber: bigint,
1296
- ): Promise<void> {
1297
- const { lastSeenCheckpoint, pendingCheckpointNumber } = status;
848
+ ): Promise<boolean> {
849
+ const { pendingCheckpointNumber } = status;
1298
850
  // Compare the last checkpoint (valid or not) we have (either retrieved in this round or loaded from store)
1299
851
  // with what the rollup contract told us was the latest one (pinned at the currentL1BlockNumber).
1300
852
  const latestLocalCheckpoint = lastSeenCheckpoint ?? (await this.getLocalProgressCheckpoint(status));
@@ -1319,15 +871,18 @@ export class ArchiverL1Synchronizer implements Traceable {
1319
871
  blocksSynchedTo,
1320
872
  currentL1BlockNumber,
1321
873
  ...status,
874
+ lastSeenCheckpoint,
1322
875
  },
1323
876
  );
1324
877
  await this.stores.blocks.setSynchedL1BlockNumber(targetL1BlockNumber);
878
+ return true;
1325
879
  } else {
1326
880
  this.log.trace(`No new checkpoints behind L1 sync point to retrieve.`, {
1327
881
  latestLocalCheckpointNumber,
1328
882
  pendingCheckpointNumber,
1329
883
  });
1330
884
  }
885
+ return false;
1331
886
  }
1332
887
 
1333
888
  /**
@@ -1342,9 +897,7 @@ export class ArchiverL1Synchronizer implements Traceable {
1342
897
  private async getLocalProgressCheckpoint(
1343
898
  status: Pick<RollupStatus, 'pendingArchive'>,
1344
899
  ): Promise<CheckpointData | RejectedCheckpoint | undefined> {
1345
- const rejectedPendingTip = await this.stores.blocks.getRejectedCheckpointByArchiveRoot(
1346
- Fr.fromString(status.pendingArchive),
1347
- );
900
+ const rejectedPendingTip = await this.stores.blocks.getRejectedCheckpointByArchiveRoot(status.pendingArchive);
1348
901
  return (
1349
902
  rejectedPendingTip ??
1350
903
  (await this.stores.blocks.getCheckpointData(await this.stores.blocks.getLatestCheckpointNumber()))