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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +16 -10
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +110 -122
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +15 -3
  8. package/dest/errors.d.ts +55 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +74 -15
  11. package/dest/factory.d.ts +5 -4
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +34 -29
  14. package/dest/index.d.ts +4 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +3 -1
  17. package/dest/l1/bin/retrieve-calldata.js +36 -33
  18. package/dest/l1/calldata_retriever.d.ts +73 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +191 -259
  21. package/dest/l1/data_retrieval.d.ts +26 -17
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +43 -48
  24. package/dest/l1/spire_proposer.d.ts +5 -5
  25. package/dest/l1/spire_proposer.d.ts.map +1 -1
  26. package/dest/l1/spire_proposer.js +9 -17
  27. package/dest/l1/validate_historical_logs.d.ts +23 -0
  28. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  29. package/dest/l1/validate_historical_logs.js +108 -0
  30. package/dest/l1/validate_trace.d.ts +6 -3
  31. package/dest/l1/validate_trace.d.ts.map +1 -1
  32. package/dest/l1/validate_trace.js +13 -9
  33. package/dest/modules/data_source_base.d.ts +17 -10
  34. package/dest/modules/data_source_base.d.ts.map +1 -1
  35. package/dest/modules/data_source_base.js +39 -77
  36. package/dest/modules/data_store_updater.d.ts +50 -26
  37. package/dest/modules/data_store_updater.d.ts.map +1 -1
  38. package/dest/modules/data_store_updater.js +169 -130
  39. package/dest/modules/instrumentation.d.ts +21 -3
  40. package/dest/modules/instrumentation.d.ts.map +1 -1
  41. package/dest/modules/instrumentation.js +58 -18
  42. package/dest/modules/l1_synchronizer.d.ts +10 -9
  43. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  44. package/dest/modules/l1_synchronizer.js +285 -157
  45. package/dest/modules/validation.d.ts +1 -1
  46. package/dest/modules/validation.d.ts.map +1 -1
  47. package/dest/modules/validation.js +2 -2
  48. package/dest/store/block_store.d.ts +85 -36
  49. package/dest/store/block_store.d.ts.map +1 -1
  50. package/dest/store/block_store.js +433 -162
  51. package/dest/store/contract_class_store.d.ts +2 -3
  52. package/dest/store/contract_class_store.d.ts.map +1 -1
  53. package/dest/store/contract_class_store.js +16 -72
  54. package/dest/store/contract_instance_store.d.ts +1 -1
  55. package/dest/store/contract_instance_store.d.ts.map +1 -1
  56. package/dest/store/contract_instance_store.js +6 -2
  57. package/dest/store/kv_archiver_store.d.ts +76 -32
  58. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  59. package/dest/store/kv_archiver_store.js +92 -37
  60. package/dest/store/l2_tips_cache.d.ts +20 -0
  61. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  62. package/dest/store/l2_tips_cache.js +109 -0
  63. package/dest/store/log_store.d.ts +6 -3
  64. package/dest/store/log_store.d.ts.map +1 -1
  65. package/dest/store/log_store.js +151 -56
  66. package/dest/store/message_store.d.ts +5 -1
  67. package/dest/store/message_store.d.ts.map +1 -1
  68. package/dest/store/message_store.js +21 -9
  69. package/dest/test/fake_l1_state.d.ts +24 -1
  70. package/dest/test/fake_l1_state.d.ts.map +1 -1
  71. package/dest/test/fake_l1_state.js +145 -28
  72. package/dest/test/index.js +3 -1
  73. package/dest/test/mock_archiver.d.ts +1 -1
  74. package/dest/test/mock_archiver.d.ts.map +1 -1
  75. package/dest/test/mock_archiver.js +3 -2
  76. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  77. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  78. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  79. package/dest/test/mock_l2_block_source.d.ts +31 -10
  80. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  81. package/dest/test/mock_l2_block_source.js +163 -92
  82. package/dest/test/mock_structs.d.ts +6 -2
  83. package/dest/test/mock_structs.d.ts.map +1 -1
  84. package/dest/test/mock_structs.js +20 -6
  85. package/dest/test/noop_l1_archiver.d.ts +26 -0
  86. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  87. package/dest/test/noop_l1_archiver.js +74 -0
  88. package/package.json +14 -13
  89. package/src/archiver.ts +150 -146
  90. package/src/config.ts +22 -2
  91. package/src/errors.ts +116 -26
  92. package/src/factory.ts +49 -26
  93. package/src/index.ts +3 -1
  94. package/src/l1/README.md +25 -68
  95. package/src/l1/bin/retrieve-calldata.ts +46 -39
  96. package/src/l1/calldata_retriever.ts +250 -379
  97. package/src/l1/data_retrieval.ts +59 -70
  98. package/src/l1/spire_proposer.ts +7 -15
  99. package/src/l1/validate_historical_logs.ts +140 -0
  100. package/src/l1/validate_trace.ts +24 -6
  101. package/src/modules/data_source_base.ts +81 -101
  102. package/src/modules/data_store_updater.ts +202 -160
  103. package/src/modules/instrumentation.ts +71 -19
  104. package/src/modules/l1_synchronizer.ts +365 -197
  105. package/src/modules/validation.ts +2 -2
  106. package/src/store/block_store.ts +546 -206
  107. package/src/store/contract_class_store.ts +16 -110
  108. package/src/store/contract_instance_store.ts +8 -5
  109. package/src/store/kv_archiver_store.ts +143 -53
  110. package/src/store/l2_tips_cache.ts +134 -0
  111. package/src/store/log_store.ts +225 -67
  112. package/src/store/message_store.ts +27 -10
  113. package/src/structs/inbox_message.ts +1 -1
  114. package/src/test/fake_l1_state.ts +193 -32
  115. package/src/test/index.ts +3 -0
  116. package/src/test/mock_archiver.ts +3 -2
  117. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  118. package/src/test/mock_l2_block_source.ts +217 -90
  119. package/src/test/mock_structs.ts +42 -12
  120. package/src/test/noop_l1_archiver.ts +117 -0
@@ -371,20 +371,25 @@ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
371
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
372
  }
373
373
  var _dec, _dec1, _dec2, _dec3, _initProto;
374
+ import { getFinalizedL1Block } from '@aztec/ethereum/queries';
375
+ import { asyncPool } from '@aztec/foundation/async-pool';
374
376
  import { maxBigint } from '@aztec/foundation/bigint';
375
377
  import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
376
- import { Buffer32 } from '@aztec/foundation/buffer';
377
- import { pick } from '@aztec/foundation/collection';
378
+ import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
379
+ import { partition, pick } from '@aztec/foundation/collection';
378
380
  import { createLogger } from '@aztec/foundation/log';
381
+ import { retryTimes } from '@aztec/foundation/retry';
379
382
  import { count } from '@aztec/foundation/string';
380
383
  import { Timer, elapsed } from '@aztec/foundation/timer';
381
- import { isDefined } from '@aztec/foundation/types';
384
+ import { isDefined, isErrorClass } from '@aztec/foundation/types';
382
385
  import { L2BlockSourceEvents } from '@aztec/stdlib/block';
383
- import { getEpochAtSlot, getSlotAtTimestamp } from '@aztec/stdlib/epoch-helpers';
386
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
387
+ import { getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
384
388
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
385
389
  import { execInSpan, trackSpan } from '@aztec/telemetry-client';
386
390
  import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
387
- import { retrieveCheckpointsFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from '../l1/data_retrieval.js';
391
+ import { getCheckpointBlobDataFromBlobs, retrieveCheckpointCalldataFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from '../l1/data_retrieval.js';
392
+ import { MessageStoreError } from '../store/message_store.js';
388
393
  import { ArchiverDataStoreUpdater } from './data_store_updater.js';
389
394
  import { validateCheckpointAttestations } from './validation.js';
390
395
  _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpochPrune'), _dec2 = trackSpan('Archiver.handleL1ToL2Messages'), _dec3 = trackSpan('Archiver.handleCheckpoints');
@@ -396,7 +401,6 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
396
401
  debugClient;
397
402
  rollup;
398
403
  inbox;
399
- l1Addresses;
400
404
  store;
401
405
  config;
402
406
  blobClient;
@@ -435,12 +439,11 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
435
439
  l1Timestamp;
436
440
  updater;
437
441
  tracer;
438
- constructor(publicClient, debugClient, rollup, inbox, l1Addresses, store, config, blobClient, epochCache, dateProvider, instrumentation, l1Constants, events, tracer, log = createLogger('archiver:l1-sync')){
442
+ constructor(publicClient, debugClient, rollup, inbox, store, config, blobClient, epochCache, dateProvider, instrumentation, l1Constants, events, tracer, l2TipsCache, log = createLogger('archiver:l1-sync')){
439
443
  this.publicClient = publicClient;
440
444
  this.debugClient = debugClient;
441
445
  this.rollup = rollup;
442
446
  this.inbox = inbox;
443
- this.l1Addresses = l1Addresses;
444
447
  this.store = store;
445
448
  this.config = config;
446
449
  this.blobClient = blobClient;
@@ -451,7 +454,9 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
451
454
  this.events = events;
452
455
  this.log = log;
453
456
  _initProto(this);
454
- this.updater = new ArchiverDataStoreUpdater(this.store);
457
+ this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache, {
458
+ rollupManaLimit: l1Constants.rollupManaLimit
459
+ });
455
460
  this.tracer = tracer;
456
461
  }
457
462
  /** Sets new config */ setConfig(newConfig) {
@@ -477,12 +482,20 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
477
482
  }
478
483
  }
479
484
  async syncFromL1(initialSyncComplete) {
485
+ // In between the various calls to L1, the block number can move meaning some of the following
486
+ // calls will return data for blocks that were not present during earlier calls. To combat this
487
+ // we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
488
+ // captured at the top of this function.
480
489
  const currentL1Block = await this.publicClient.getBlock({
481
490
  includeTransactions: false
482
491
  });
483
492
  const currentL1BlockNumber = currentL1Block.number;
484
493
  const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
485
494
  const currentL1Timestamp = currentL1Block.timestamp;
495
+ const currentL1BlockData = {
496
+ l1BlockNumber: currentL1BlockNumber,
497
+ l1BlockHash: currentL1BlockHash
498
+ };
486
499
  if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
487
500
  this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
488
501
  return;
@@ -498,36 +511,16 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
498
511
  maxAllowedDelay
499
512
  });
500
513
  }
501
- // Load sync point for blocks and messages defaulting to start block
502
- const { blocksSynchedTo = this.l1Constants.l1StartBlock, messagesSynchedTo = {
503
- l1BlockNumber: this.l1Constants.l1StartBlock,
504
- l1BlockHash: this.l1Constants.l1StartBlockHash
505
- } } = await this.store.getSynchPoint();
514
+ // Load sync point for blocks defaulting to start block
515
+ const { blocksSynchedTo = this.l1Constants.l1StartBlock } = await this.store.getSynchPoint();
506
516
  this.log.debug(`Starting new archiver sync iteration`, {
507
517
  blocksSynchedTo,
508
- messagesSynchedTo,
509
- currentL1BlockNumber,
510
- currentL1BlockHash
518
+ currentL1BlockData
511
519
  });
512
- // ********** Ensuring Consistency of data pulled from L1 **********
513
- /**
514
- * There are a number of calls in this sync operation to L1 for retrieving
515
- * events and transaction data. There are a couple of things we need to bear in mind
516
- * to ensure that data is read exactly once.
517
- *
518
- * The first is the problem of eventually consistent ETH service providers like Infura.
519
- * Each L1 read operation will query data from the last L1 block that it saw emit its kind of data.
520
- * (so pending L1 to L2 messages will read from the last L1 block that emitted a message and so on)
521
- * This will mean the archiver will lag behind L1 and will only advance when there's L2-relevant activity on the chain.
522
- *
523
- * The second is that in between the various calls to L1, the block number can move meaning some
524
- * of the following calls will return data for blocks that were not present during earlier calls.
525
- * To combat this for the time being we simply ensure that all data retrieval methods only retrieve
526
- * data up to the currentBlockNumber captured at the top of this function. We might want to improve on this
527
- * in future but for the time being it should give us the guarantees that we need
528
- */ // ********** Events that are processed per L1 block **********
529
- await this.handleL1ToL2Messages(messagesSynchedTo, currentL1BlockNumber);
530
- // ********** Events that are processed per checkpoint **********
520
+ // 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.
521
+ // 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
522
+ // block, when that wouldn't be the case, since L1 to L2 messages would need another iteration.
523
+ await retryTimes(()=>this.handleL1ToL2Messages(currentL1BlockData), 'Handling L1 to L2 messages', 3, 0.1);
531
524
  if (currentL1BlockNumber > blocksSynchedTo) {
532
525
  // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
533
526
  // pending chain validation status, proven checkpoint number, and synched L1 block number.
@@ -555,6 +548,8 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
555
548
  }
556
549
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
557
550
  }
551
+ // Update the finalized L2 checkpoint based on L1 finality.
552
+ await this.updateFinalizedCheckpoint();
558
553
  // After syncing has completed, update the current l1 block number and timestamp,
559
554
  // otherwise we risk announcing to the world that we've synced to a given point,
560
555
  // but the corresponding blocks have not been processed (see #12631).
@@ -568,6 +563,32 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
568
563
  l1BlockNumberAtEnd
569
564
  });
570
565
  }
566
+ /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */ async updateFinalizedCheckpoint() {
567
+ try {
568
+ const finalizedL1Block = await getFinalizedL1Block(this.publicClient);
569
+ if (!finalizedL1Block) {
570
+ this.log.trace(`Skipping finalized checkpoint update: L1 has no finalized block yet.`);
571
+ return;
572
+ }
573
+ const finalizedL1BlockNumber = finalizedL1Block.number;
574
+ const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
575
+ blockNumber: finalizedL1BlockNumber
576
+ });
577
+ const localFinalizedCheckpointNumber = await this.store.getFinalizedCheckpointNumber();
578
+ if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
579
+ await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
580
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
581
+ finalizedCheckpointNumber,
582
+ finalizedL1BlockNumber
583
+ });
584
+ }
585
+ } catch (err) {
586
+ // The rollup contract may not exist at the finalized L1 block right after deployment.
587
+ if (!err?.message?.includes('returned no data')) {
588
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
589
+ }
590
+ }
591
+ }
571
592
  /** Prune all proposed local blocks that should have been checkpointed by now. */ async pruneUncheckpointedBlocks(currentL1Timestamp) {
572
593
  const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
573
594
  this.store.getCheckpointedL2BlockNumber(),
@@ -578,27 +599,28 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
578
599
  this.log.trace(`No uncheckpointed blocks to prune.`);
579
600
  return;
580
601
  }
581
- // What's the slot of the first uncheckpointed block?
602
+ // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
603
+ const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
582
604
  const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
605
+ // What's the slot of the first uncheckpointed block?
583
606
  const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
584
607
  const firstUncheckpointedBlockSlot = firstUncheckpointedBlockHeader?.getSlot();
585
- // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
586
- const nextL1BlockTimestamp = currentL1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration);
587
- const slotAtNextL1Block = getSlotAtTimestamp(nextL1BlockTimestamp, this.l1Constants);
588
- // Prune provisional blocks from slots that have ended without being checkpointed
589
- if (firstUncheckpointedBlockSlot !== undefined && firstUncheckpointedBlockSlot < slotAtNextL1Block) {
590
- this.log.warn(`Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`, {
591
- firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(),
592
- slotAtNextL1Block
608
+ if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
609
+ return;
610
+ }
611
+ // Prune provisional blocks from slots that have ended without being checkpointed.
612
+ // This also clears any proposed checkpoint whose blocks are being pruned.
613
+ this.log.warn(`Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`, {
614
+ firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(),
615
+ slotAtNextL1Block
616
+ });
617
+ const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
618
+ if (prunedBlocks.length > 0) {
619
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
620
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
621
+ slotNumber: firstUncheckpointedBlockSlot,
622
+ blocks: prunedBlocks
593
623
  });
594
- const prunedBlocks = await this.updater.removeBlocksAfter(lastCheckpointedBlockNumber);
595
- if (prunedBlocks.length > 0) {
596
- this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
597
- type: L2BlockSourceEvents.L2PruneUncheckpointed,
598
- slotNumber: firstUncheckpointedBlockSlot,
599
- blocks: prunedBlocks
600
- });
601
- }
602
624
  }
603
625
  }
604
626
  /** Queries the rollup contract on whether a prune can be executed on the immediate next L1 block. */ async canPrune(currentL1BlockNumber, currentL1Timestamp) {
@@ -629,12 +651,14 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
629
651
  const pruneFromSlotNumber = header.slotNumber;
630
652
  const pruneFromEpochNumber = getEpochAtSlot(pruneFromSlotNumber, this.l1Constants);
631
653
  const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
632
- const checkpointPromises = Array.from({
654
+ // Fetch checkpoints and blocks in bounded batches to avoid unbounded concurrent
655
+ // promises when the gap between local pending and proven checkpoint numbers is large.
656
+ const BATCH_SIZE = 10;
657
+ const indices = Array.from({
633
658
  length: checkpointsToUnwind
634
- }).fill(0).map((_, i)=>this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
635
- const checkpoints = await Promise.all(checkpointPromises);
636
- const blockPromises = await Promise.all(checkpoints.filter(isDefined).map((cp)=>this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))));
637
- const newBlocks = blockPromises.filter(isDefined).flat();
659
+ }, (_, i)=>CheckpointNumber(i + pruneFrom));
660
+ const checkpoints = (await asyncPool(BATCH_SIZE, indices, (idx)=>this.store.getCheckpointData(idx))).filter(isDefined);
661
+ const newBlocks = (await asyncPool(BATCH_SIZE, checkpoints, (cp)=>this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)))).filter(isDefined).flat();
638
662
  // Emit an event for listening services to react to the chain prune
639
663
  this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
640
664
  type: L2BlockSourceEvents.L2PruneUnproven,
@@ -642,8 +666,8 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
642
666
  blocks: newBlocks
643
667
  });
644
668
  this.log.debug(`L2 prune from ${provenCheckpointNumber + 1} to ${localPendingCheckpointNumber} will occur on next checkpoint submission.`);
645
- await this.updater.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
646
- this.log.warn(`Unwound ${count(checkpointsToUnwind, 'checkpoint')} from checkpoint ${localPendingCheckpointNumber} ` + `to ${provenCheckpointNumber} due to predicted reorg at L1 block ${currentL1BlockNumber}. ` + `Updated latest checkpoint is ${await this.store.getSynchedCheckpointNumber()}.`);
669
+ await this.updater.removeCheckpointsAfter(provenCheckpointNumber);
670
+ this.log.warn(`Removed ${count(checkpointsToUnwind, 'checkpoint')} after checkpoint ${provenCheckpointNumber} ` + `due to predicted reorg at L1 block ${currentL1BlockNumber}. ` + `Updated latest checkpoint is ${await this.store.getSynchedCheckpointNumber()}.`);
647
671
  this.instrumentation.processPrune(timer.ms());
648
672
  // TODO(palla/reorg): Do we need to set the block synched L1 block number here?
649
673
  // Seems like the next iteration should handle this.
@@ -668,55 +692,75 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
668
692
  nextEnd
669
693
  ];
670
694
  }
671
- async handleL1ToL2Messages(messagesSyncPoint, currentL1BlockNumber) {
672
- this.log.trace(`Handling L1 to L2 messages from ${messagesSyncPoint.l1BlockNumber} to ${currentL1BlockNumber}.`);
673
- if (currentL1BlockNumber <= messagesSyncPoint.l1BlockNumber) {
674
- return;
695
+ async handleL1ToL2Messages(currentL1Block) {
696
+ // Load the syncpoint, which may have been updated in a previous iteration
697
+ const { messagesSynchedTo = {
698
+ l1BlockNumber: this.l1Constants.l1StartBlock,
699
+ l1BlockHash: this.l1Constants.l1StartBlockHash
700
+ } } = await this.store.getSynchPoint();
701
+ // Nothing to do if L1 block number has not moved forward
702
+ const currentL1BlockNumber = currentL1Block.l1BlockNumber;
703
+ if (currentL1BlockNumber <= messagesSynchedTo.l1BlockNumber) {
704
+ return true;
675
705
  }
676
- // Load remote and local inbox states.
677
- const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
678
- const localLastMessage = await this.store.getLastL1ToL2Message();
706
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
679
707
  const remoteMessagesState = await this.inbox.getState({
680
708
  blockNumber: currentL1BlockNumber
681
709
  });
682
- this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
683
- localMessagesInserted,
684
- localLastMessage,
685
- remoteMessagesState
686
- });
687
- // Compare message count and rolling hash. If they match, no need to retrieve anything.
688
- if (remoteMessagesState.totalMessagesInserted === localMessagesInserted && remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer32.ZERO)) {
689
- this.log.trace(`No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`);
690
- return;
710
+ const localLastMessage = await this.store.getLastL1ToL2Message();
711
+ if (await this.localStateMatches(localLastMessage, remoteMessagesState)) {
712
+ this.log.trace(`Local L1 to L2 messages are already in sync with remote at L1 block ${currentL1BlockNumber}`);
713
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
714
+ return true;
691
715
  }
692
- // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
693
- // Note that we need to fetch it from logs and not from inbox state at the syncpoint l1 block number, since it
694
- // could be older than 128 blocks and non-archive nodes cannot resolve it.
695
- if (localLastMessage) {
696
- const remoteLastMessage = await this.retrieveL1ToL2Message(localLastMessage.leaf);
697
- this.log.trace(`Retrieved remote message for local last`, {
698
- remoteLastMessage,
699
- localLastMessage
700
- });
701
- if (!remoteLastMessage || !remoteLastMessage.rollingHash.equals(localLastMessage.rollingHash)) {
702
- this.log.warn(`Rolling back L1 to L2 messages due to hash mismatch or msg not found.`, {
703
- remoteLastMessage,
704
- messagesSyncPoint,
705
- localLastMessage
706
- });
707
- messagesSyncPoint = await this.rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint);
708
- this.log.debug(`Rolled back L1 to L2 messages to L1 block ${messagesSyncPoint.l1BlockNumber}.`, {
709
- messagesSyncPoint
716
+ // If not, then we are out of sync. Most likely there are new messages on the inbox, so we try retrieving them.
717
+ // However, it could also be the case that there was an L1 reorg and our syncpoint is no longer valid.
718
+ // If that's the case, we'd get an exception out of the message store since the rolling hash of the first message
719
+ // we try to insert would not match the one in the db, in which case we rollback to the last common message with L1.
720
+ try {
721
+ await this.retrieveAndStoreMessages(messagesSynchedTo.l1BlockNumber, currentL1BlockNumber);
722
+ } catch (error) {
723
+ if (isErrorClass(error, MessageStoreError)) {
724
+ this.log.warn(`Failed to store L1 to L2 messages retrieved from L1: ${error.message}. Rolling back syncpoint to retry.`, {
725
+ inboxMessage: error.inboxMessage
710
726
  });
727
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
728
+ return false;
711
729
  }
730
+ throw error;
731
+ }
732
+ // Note that, if there are no new messages to insert, but there was an L1 reorg that pruned out last messages,
733
+ // we'd notice by comparing our local state with the remote one again, and seeing they don't match even after
734
+ // our sync attempt. In this case, we also rollback our syncpoint, and trigger a retry.
735
+ const localLastMessageAfterSync = await this.store.getLastL1ToL2Message();
736
+ if (!await this.localStateMatches(localLastMessageAfterSync, remoteMessagesState)) {
737
+ this.log.warn(`Local L1 to L2 messages state does not match remote after sync attempt. Rolling back syncpoint to retry.`, {
738
+ localLastMessageAfterSync,
739
+ remoteMessagesState
740
+ });
741
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
742
+ return false;
712
743
  }
713
- // Retrieve and save messages in batches. Each batch is estimated to acommodate up to L2 'blockBatchSize' blocks,
744
+ // Advance the syncpoint after a successful sync
745
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
746
+ return true;
747
+ }
748
+ /** Checks if the local rolling hash and message count matches the remote state */ async localStateMatches(localLastMessage, remoteState) {
749
+ const localMessageCount = await this.store.getTotalL1ToL2MessageCount();
750
+ this.log.trace(`Comparing local and remote inbox state`, {
751
+ localMessageCount,
752
+ localLastMessage,
753
+ remoteState
754
+ });
755
+ return remoteState.totalMessagesInserted === localMessageCount && remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO);
756
+ }
757
+ /** Retrieves L1 to L2 messages from L1 in batches and stores them. */ async retrieveAndStoreMessages(fromL1Block, toL1Block) {
714
758
  let searchStartBlock = 0n;
715
- let searchEndBlock = messagesSyncPoint.l1BlockNumber;
759
+ let searchEndBlock = fromL1Block;
716
760
  let lastMessage;
717
761
  let messageCount = 0;
718
762
  do {
719
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
763
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
720
764
  this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
721
765
  const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
722
766
  const timer = new Timer();
@@ -731,74 +775,81 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
731
775
  lastMessage = msg;
732
776
  messageCount++;
733
777
  }
734
- }while (searchEndBlock < currentL1BlockNumber)
735
- // Log stats for messages retrieved (if any).
778
+ }while (searchEndBlock < toL1Block)
736
779
  if (messageCount > 0) {
737
780
  this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`, {
738
781
  lastMessage,
739
782
  messageCount
740
783
  });
741
784
  }
742
- // Warn if the resulting rolling hash does not match the remote state we had retrieved.
743
- if (lastMessage && !lastMessage.rollingHash.equals(remoteMessagesState.messagesRollingHash)) {
744
- this.log.warn(`Last message retrieved rolling hash does not match remote state.`, {
745
- lastMessage,
746
- remoteMessagesState
747
- });
748
- }
749
785
  }
750
- async retrieveL1ToL2Message(leaf) {
751
- const currentL1BlockNumber = await this.publicClient.getBlockNumber();
752
- let searchStartBlock = 0n;
753
- let searchEndBlock = this.l1Constants.l1StartBlock - 1n;
754
- do {
755
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
756
- const message = await retrieveL1ToL2Message(this.inbox, leaf, searchStartBlock, searchEndBlock);
757
- if (message) {
758
- return message;
759
- }
760
- }while (searchEndBlock < currentL1BlockNumber)
761
- return undefined;
762
- }
763
- async rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint) {
764
- // Slowly go back through our messages until we find the last common message.
765
- // We could query the logs in batch as an optimization, but the depth of the reorg should not be deep, and this
766
- // is a very rare case, so it's fine to query one log at a time.
786
+ /**
787
+ * 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.
788
+ * If no common message is found, rolls back all messages and sets the syncpoint to the start block.
789
+ */ async rollbackL1ToL2Messages(remoteMessagesState) {
790
+ const { treeInProgress: remoteTreeInProgress, messagesRollingHash: remoteRollingHash } = remoteMessagesState;
791
+ // Slowly go back through our messages until we find the last common message. We could query the logs in
792
+ // batch as an optimization, but the depth of the reorg should not be deep, and this is a very rare case,
793
+ // so it's fine to query one log at a time.
767
794
  let commonMsg;
768
- this.log.verbose(`Searching most recent common L1 to L2 message at or before index ${localLastMessage.index}`);
769
- for await (const msg of this.store.iterateL1ToL2Messages({
770
- reverse: true,
771
- end: localLastMessage.index
795
+ let messagesToDelete = 0;
796
+ this.log.verbose(`Searching most recent common L1 to L2 message`);
797
+ for await (const localMsg of this.store.iterateL1ToL2Messages({
798
+ reverse: true
772
799
  })){
773
- const remoteMsg = await this.retrieveL1ToL2Message(msg.leaf);
774
800
  const logCtx = {
775
- remoteMsg,
776
- localMsg: msg
801
+ remoteMsg: undefined,
802
+ localMsg,
803
+ remoteMessagesState
777
804
  };
778
- if (remoteMsg && remoteMsg.rollingHash.equals(msg.rollingHash)) {
779
- this.log.verbose(`Found most recent common L1 to L2 message at index ${msg.index} on L1 block ${msg.l1BlockNumber}`, logCtx);
805
+ // First check if the local message rolling hash matches the current rolling hash of the inbox contract,
806
+ // which means we just need to rollback some local messages and we should be back in sync. This means there
807
+ // was an L1 reorg that removed some of the messages we had, but no new messages were added compared.
808
+ if (localMsg.rollingHash.equals(remoteRollingHash)) {
809
+ this.log.info(`Found common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber} matching current remote state`, logCtx);
810
+ commonMsg = localMsg;
811
+ break;
812
+ }
813
+ // If there's no match with the current remote state, check if the message exists on the inbox contract at all
814
+ // by looking at the inbox events. If the L1 reorg *added* new messages in addition to deleting existing ones,
815
+ // then the current remote state's rolling hash will not match anything we have locally, so we need to check existence
816
+ // of individual messages via logs. Note we use logs and not historical queries so we don't have to depend on
817
+ // an archival rpc node, since the message could be from a long time ago if we're catching up with syncing.
818
+ const remoteMsg = await retrieveL1ToL2Message(this.inbox, localMsg);
819
+ logCtx.remoteMsg = remoteMsg;
820
+ if (remoteMsg && remoteMsg.rollingHash.equals(localMsg.rollingHash)) {
821
+ this.log.info(`Found most recent common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber}`, logCtx);
780
822
  commonMsg = remoteMsg;
781
823
  break;
782
824
  } else if (remoteMsg) {
783
- this.log.debug(`Local L1 to L2 message with index ${msg.index} has different rolling hash`, logCtx);
825
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} has different rolling hash`, logCtx);
826
+ messagesToDelete++;
784
827
  } else {
785
- this.log.debug(`Local L1 to L2 message with index ${msg.index} not found on L1`, logCtx);
828
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} not found on L1`, logCtx);
829
+ messagesToDelete++;
786
830
  }
787
831
  }
788
- // Delete everything after the common message we found.
789
- const lastGoodIndex = commonMsg?.index;
790
- this.log.warn(`Deleting all local L1 to L2 messages after index ${lastGoodIndex ?? 'undefined'}`);
791
- await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
832
+ // Delete everything after the common message we found, if anything needs to be deleted.
833
+ // Do not exit early if there are no messages to delete, we still want to update the syncpoint.
834
+ if (messagesToDelete > 0) {
835
+ const lastGoodIndex = commonMsg?.index;
836
+ this.log.warn(`Rolling back all local L1 to L2 messages after index ${lastGoodIndex ?? 'initial'}`);
837
+ await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
838
+ }
792
839
  // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
793
840
  // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
794
841
  // after the last common message.
795
842
  const syncPointL1BlockNumber = commonMsg ? commonMsg.l1BlockNumber - 1n : this.l1Constants.l1StartBlock;
796
843
  const syncPointL1BlockHash = await this.getL1BlockHash(syncPointL1BlockNumber);
797
- messagesSyncPoint = {
844
+ const messagesSyncPoint = {
798
845
  l1BlockNumber: syncPointL1BlockNumber,
799
846
  l1BlockHash: syncPointL1BlockHash
800
847
  };
801
- await this.store.setMessageSynchedL1Block(messagesSyncPoint);
848
+ await this.store.setMessageSyncState(messagesSyncPoint, remoteTreeInProgress);
849
+ this.log.verbose(`Updated messages syncpoint to L1 block ${syncPointL1BlockNumber}`, {
850
+ ...messagesSyncPoint,
851
+ remoteTreeInProgress
852
+ });
802
853
  return messagesSyncPoint;
803
854
  }
804
855
  async getL1BlockHash(l1BlockNumber) {
@@ -838,7 +889,7 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
838
889
  if (provenCheckpointNumber === 0) {
839
890
  const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
840
891
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
841
- await this.store.setProvenCheckpointNumber(provenCheckpointNumber);
892
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
842
893
  this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, {
843
894
  provenCheckpointNumber
844
895
  });
@@ -855,20 +906,20 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
855
906
  if (localCheckpointForDestinationProvenCheckpointNumber && provenArchive.equals(localCheckpointForDestinationProvenCheckpointNumber.archive.root)) {
856
907
  const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
857
908
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
858
- await this.store.setProvenCheckpointNumber(provenCheckpointNumber);
909
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
859
910
  this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, {
860
911
  provenCheckpointNumber
861
912
  });
862
913
  const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
863
914
  const provenEpochNumber = getEpochAtSlot(provenSlotNumber, this.l1Constants);
864
- const lastBlockNumberInCheckpoint = localCheckpointForDestinationProvenCheckpointNumber.startBlock + localCheckpointForDestinationProvenCheckpointNumber.numBlocks - 1;
915
+ const lastBlockNumberInCheckpoint = localCheckpointForDestinationProvenCheckpointNumber.startBlock + localCheckpointForDestinationProvenCheckpointNumber.blockCount - 1;
865
916
  this.events.emit(L2BlockSourceEvents.L2BlockProven, {
866
917
  type: L2BlockSourceEvents.L2BlockProven,
867
918
  blockNumber: BlockNumber(lastBlockNumberInCheckpoint),
868
919
  slotNumber: provenSlotNumber,
869
920
  epochNumber: provenEpochNumber
870
921
  });
871
- this.instrumentation.updateLastProvenBlock(lastBlockNumberInCheckpoint);
922
+ this.instrumentation.updateLastProvenCheckpoint(localCheckpointForDestinationProvenCheckpointNumber);
872
923
  } else {
873
924
  this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
874
925
  }
@@ -931,9 +982,9 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
931
982
  }
932
983
  tipAfterUnwind--;
933
984
  }
934
- const checkpointsToUnwind = localPendingCheckpointNumber - tipAfterUnwind;
935
- await this.updater.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
936
- this.log.warn(`Unwound ${count(checkpointsToUnwind, 'checkpoint')} from checkpoint ${localPendingCheckpointNumber} ` + `due to mismatched checkpoint hashes at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest checkpoint is ${await this.store.getSynchedCheckpointNumber()}.`);
985
+ const checkpointsToRemove = localPendingCheckpointNumber - tipAfterUnwind;
986
+ await this.updater.removeCheckpointsAfter(CheckpointNumber(tipAfterUnwind));
987
+ this.log.warn(`Removed ${count(checkpointsToRemove, 'checkpoint')} after checkpoint ${tipAfterUnwind} ` + `due to mismatched checkpoint hashes at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest checkpoint is ${await this.store.getSynchedCheckpointNumber()}.`);
937
988
  }
938
989
  }
939
990
  // Retrieve checkpoints in batches. Each batch is estimated to accommodate up to 'blockBatchSize' L1 blocks,
@@ -945,21 +996,37 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
945
996
  do {
946
997
  [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
947
998
  this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
948
- // TODO(md): Retrieve from blob client then from consensus client, then from peers
949
- const retrievedCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointsFromRollup', ()=>retrieveCheckpointsFromRollup(this.rollup, this.publicClient, this.debugClient, this.blobClient, searchStartBlock, searchEndBlock, this.l1Addresses, this.instrumentation, this.log, !initialSyncComplete));
950
- if (retrievedCheckpoints.length === 0) {
999
+ // First fetch calldata only, no blobs yet, since we may be able to just get that data out of the proposed chain
1000
+ const calldataCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', ()=>retrieveCheckpointCalldataFromRollup(this.rollup, this.publicClient, this.debugClient, searchStartBlock, searchEndBlock, this.instrumentation, this.log));
1001
+ if (calldataCheckpoints.length === 0) {
951
1002
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
952
1003
  // See further details in earlier comments.
953
1004
  this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
954
1005
  continue;
955
1006
  }
956
- this.log.debug(`Retrieved ${retrievedCheckpoints.length} new checkpoints between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
957
- lastProcessedCheckpoint: retrievedCheckpoints[retrievedCheckpoints.length - 1].l1,
1007
+ this.log.debug(`Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
1008
+ lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
958
1009
  searchStartBlock,
959
1010
  searchEndBlock
960
1011
  });
961
- const publishedCheckpoints = await Promise.all(retrievedCheckpoints.map((b)=>retrievedToPublishedCheckpoint(b)));
1012
+ // Check if the last checkpoint matches the proposed one (so we can skip blob fetch).
1013
+ // We only check the last one because the proposed checkpoint is always the most recent one,
1014
+ // and if it's in a multi-checkpoint batch it will always be last (sorted by L1 block number).
1015
+ const lastCalldataCheckpoint = calldataCheckpoints[calldataCheckpoints.length - 1];
1016
+ const checkpointToPromote = await this.tryBuildPublishedCheckpointFromProposed(lastCalldataCheckpoint);
1017
+ // Then fetch blobs in parallel and build the full published checkpoints
1018
+ const toFetchBlobs = checkpointToPromote ? calldataCheckpoints.slice(0, -1) : calldataCheckpoints;
1019
+ const blobFetched = await asyncPool(10, toFetchBlobs, async (checkpoint)=>retrievedToPublishedCheckpoint({
1020
+ ...checkpoint,
1021
+ checkpointBlobData: await getCheckpointBlobDataFromBlobs(this.blobClient, checkpoint.l1.blockHash, checkpoint.blobHashes, checkpoint.checkpointNumber, this.log, !initialSyncComplete, checkpoint.parentBeaconBlockRoot, checkpoint.l1.timestamp)
1022
+ }));
1023
+ // And add the promoted checkpoint to the list of all checkpoints
1024
+ const publishedCheckpoints = checkpointToPromote ? [
1025
+ ...blobFetched,
1026
+ checkpointToPromote
1027
+ ] : blobFetched;
962
1028
  const validCheckpoints = [];
1029
+ // Now loop through all checkpoints and validate their attestations
963
1030
  for (const published of publishedCheckpoints){
964
1031
  const validationResult = this.config.skipValidateCheckpointAttestations ? {
965
1032
  valid: true
@@ -1009,15 +1076,31 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1009
1076
  blocks: published.checkpoint.blocks.map((b)=>b.getStats())
1010
1077
  });
1011
1078
  }
1079
+ for (const published of validCheckpoints){
1080
+ this.instrumentation.processCheckpointL1Timing({
1081
+ slotNumber: published.checkpoint.header.slotNumber,
1082
+ l1Timestamp: published.l1.timestamp,
1083
+ l1Constants: this.l1Constants
1084
+ });
1085
+ }
1012
1086
  try {
1013
1087
  const updatedValidationResult = rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
1014
- const [processDuration, result] = await elapsed(()=>execInSpan(this.tracer, 'Archiver.setCheckpointData', ()=>this.updater.setNewCheckpointData(validCheckpoints, updatedValidationResult)));
1015
- this.instrumentation.processNewBlocks(processDuration / validCheckpoints.length, validCheckpoints.flatMap((c)=>c.checkpoint.blocks));
1088
+ // Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
1089
+ // the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
1090
+ const [[maybeValidCheckpointToPromote], checkpointsToAdd] = partition(validCheckpoints, (c)=>c.checkpoint.number === checkpointToPromote?.checkpoint.number);
1091
+ const [processDuration, result] = await elapsed(()=>execInSpan(this.tracer, 'Archiver.addCheckpoints', ()=>this.updater.addCheckpoints(checkpointsToAdd, updatedValidationResult, maybeValidCheckpointToPromote && {
1092
+ l1: lastCalldataCheckpoint.l1,
1093
+ attestations: lastCalldataCheckpoint.attestations,
1094
+ checkpoint: maybeValidCheckpointToPromote
1095
+ })));
1096
+ if (checkpointsToAdd.length > 0) {
1097
+ this.instrumentation.processNewCheckpointedBlocks(processDuration / checkpointsToAdd.length, checkpointsToAdd.flatMap((c)=>c.checkpoint.blocks));
1098
+ }
1016
1099
  // If blocks were pruned due to conflict with L1 checkpoints, emit event
1017
1100
  if (result.prunedBlocks && result.prunedBlocks.length > 0) {
1018
1101
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
1019
1102
  const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
1020
- this.log.warn(`Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`, {
1103
+ this.log.info(`Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`, {
1021
1104
  prunedBlocks: result.prunedBlocks.map((b)=>b.toBlockInfo()),
1022
1105
  prunedSlotNumber,
1023
1106
  prunedCheckpointNumber
@@ -1057,7 +1140,7 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1057
1140
  });
1058
1141
  }
1059
1142
  lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
1060
- lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
1143
+ lastL1BlockWithCheckpoint = calldataCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
1061
1144
  }while (searchEndBlock < currentL1BlockNumber)
1062
1145
  // Important that we update AFTER inserting the blocks.
1063
1146
  await updateProvenCheckpoint();
@@ -1067,6 +1150,51 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1067
1150
  lastL1BlockWithCheckpoint
1068
1151
  };
1069
1152
  }
1153
+ /** Checks if this checkpoint matches the local proposed one, and if so, loads local data to build a synthetic published checkpoint. */ async tryBuildPublishedCheckpointFromProposed(calldataCheckpoint) {
1154
+ const proposed = await this.store.getProposedCheckpointOnly();
1155
+ if (this.config.skipPromoteProposedCheckpointDuringL1Sync || !proposed || !calldataCheckpoint || proposed.checkpointNumber !== calldataCheckpoint.checkpointNumber) {
1156
+ return undefined;
1157
+ }
1158
+ if (!proposed.header.equals(calldataCheckpoint.header) || !proposed.archive.root.equals(calldataCheckpoint.archiveRoot)) {
1159
+ this.log.warn(`Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`, {
1160
+ proposedCheckpointNumber: proposed.checkpointNumber,
1161
+ proposedHeader: proposed.header.toInspect(),
1162
+ proposedArchiveRoot: proposed.archive.root.toString(),
1163
+ calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
1164
+ calldataHeader: calldataCheckpoint.header.toInspect(),
1165
+ calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString()
1166
+ });
1167
+ return undefined;
1168
+ }
1169
+ this.log.debug(`Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`, {
1170
+ proposedHeader: proposed.header.toInspect(),
1171
+ proposedArchiveRoot: proposed.archive.root.toString()
1172
+ });
1173
+ const blocks = await this.store.getBlocks(BlockNumber(proposed.startBlock), proposed.blockCount);
1174
+ if (blocks.length !== proposed.blockCount) {
1175
+ this.log.warn(`Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`, {
1176
+ proposedCheckpointNumber: proposed.checkpointNumber,
1177
+ proposedStartBlock: proposed.startBlock,
1178
+ proposedBlockCount: proposed.blockCount,
1179
+ retrievedBlocks: blocks.map((b)=>b.number)
1180
+ });
1181
+ return undefined;
1182
+ }
1183
+ const checkpoint = Checkpoint.from({
1184
+ archive: proposed.archive,
1185
+ header: proposed.header,
1186
+ blocks,
1187
+ number: proposed.checkpointNumber,
1188
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier
1189
+ });
1190
+ const promotedCheckpoint = PublishedCheckpoint.from({
1191
+ checkpoint,
1192
+ l1: calldataCheckpoint.l1,
1193
+ attestations: calldataCheckpoint.attestations
1194
+ });
1195
+ this.instrumentation.processCheckpointPromoted();
1196
+ return promotedCheckpoint;
1197
+ }
1070
1198
  async checkForNewCheckpointsBeforeL1SyncPoint(status, blocksSynchedTo, currentL1BlockNumber) {
1071
1199
  const { lastRetrievedCheckpoint, pendingCheckpointNumber } = status;
1072
1200
  // Compare the last checkpoint we have (either retrieved in this round or loaded from store) with what the