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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +22 -11
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +152 -145
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +16 -4
  8. package/dest/errors.d.ts +61 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +88 -14
  11. package/dest/factory.d.ts +4 -5
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +33 -27
  14. package/dest/index.d.ts +4 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +3 -1
  17. package/dest/l1/bin/retrieve-calldata.js +36 -33
  18. package/dest/l1/calldata_retriever.d.ts +74 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +197 -260
  21. package/dest/l1/data_retrieval.d.ts +26 -17
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +42 -47
  24. package/dest/l1/spire_proposer.d.ts +5 -5
  25. package/dest/l1/spire_proposer.d.ts.map +1 -1
  26. package/dest/l1/spire_proposer.js +9 -17
  27. package/dest/l1/validate_historical_logs.d.ts +23 -0
  28. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  29. package/dest/l1/validate_historical_logs.js +108 -0
  30. package/dest/modules/data_source_base.d.ts +18 -7
  31. package/dest/modules/data_source_base.d.ts.map +1 -1
  32. package/dest/modules/data_source_base.js +51 -77
  33. package/dest/modules/data_store_updater.d.ts +35 -15
  34. package/dest/modules/data_store_updater.d.ts.map +1 -1
  35. package/dest/modules/data_store_updater.js +139 -96
  36. package/dest/modules/instrumentation.d.ts +21 -3
  37. package/dest/modules/instrumentation.d.ts.map +1 -1
  38. package/dest/modules/instrumentation.js +41 -8
  39. package/dest/modules/l1_synchronizer.d.ts +11 -9
  40. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  41. package/dest/modules/l1_synchronizer.js +304 -151
  42. package/dest/modules/validation.d.ts +4 -3
  43. package/dest/modules/validation.d.ts.map +1 -1
  44. package/dest/modules/validation.js +6 -6
  45. package/dest/store/block_store.d.ts +98 -28
  46. package/dest/store/block_store.d.ts.map +1 -1
  47. package/dest/store/block_store.js +465 -138
  48. package/dest/store/contract_class_store.d.ts +2 -3
  49. package/dest/store/contract_class_store.d.ts.map +1 -1
  50. package/dest/store/contract_class_store.js +7 -67
  51. package/dest/store/contract_instance_store.d.ts +1 -1
  52. package/dest/store/contract_instance_store.d.ts.map +1 -1
  53. package/dest/store/contract_instance_store.js +6 -2
  54. package/dest/store/kv_archiver_store.d.ts +85 -24
  55. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  56. package/dest/store/kv_archiver_store.js +106 -27
  57. package/dest/store/l2_tips_cache.d.ts +20 -0
  58. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  59. package/dest/store/l2_tips_cache.js +109 -0
  60. package/dest/store/log_store.d.ts +6 -3
  61. package/dest/store/log_store.d.ts.map +1 -1
  62. package/dest/store/log_store.js +150 -55
  63. package/dest/store/message_store.d.ts +5 -1
  64. package/dest/store/message_store.d.ts.map +1 -1
  65. package/dest/store/message_store.js +21 -9
  66. package/dest/test/fake_l1_state.d.ts +25 -1
  67. package/dest/test/fake_l1_state.d.ts.map +1 -1
  68. package/dest/test/fake_l1_state.js +166 -32
  69. package/dest/test/mock_archiver.d.ts +1 -1
  70. package/dest/test/mock_archiver.d.ts.map +1 -1
  71. package/dest/test/mock_archiver.js +3 -2
  72. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  73. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  74. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  75. package/dest/test/mock_l2_block_source.d.ts +35 -5
  76. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  77. package/dest/test/mock_l2_block_source.js +182 -89
  78. package/dest/test/mock_structs.d.ts +4 -1
  79. package/dest/test/mock_structs.d.ts.map +1 -1
  80. package/dest/test/mock_structs.js +13 -1
  81. package/dest/test/noop_l1_archiver.d.ts +4 -1
  82. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  83. package/dest/test/noop_l1_archiver.js +9 -3
  84. package/package.json +13 -13
  85. package/src/archiver.ts +187 -164
  86. package/src/config.ts +23 -2
  87. package/src/errors.ts +133 -22
  88. package/src/factory.ts +47 -24
  89. package/src/index.ts +3 -1
  90. package/src/l1/README.md +25 -68
  91. package/src/l1/bin/retrieve-calldata.ts +46 -39
  92. package/src/l1/calldata_retriever.ts +261 -379
  93. package/src/l1/data_retrieval.ts +58 -69
  94. package/src/l1/spire_proposer.ts +7 -15
  95. package/src/l1/validate_historical_logs.ts +140 -0
  96. package/src/modules/data_source_base.ts +95 -98
  97. package/src/modules/data_store_updater.ts +168 -126
  98. package/src/modules/instrumentation.ts +56 -9
  99. package/src/modules/l1_synchronizer.ts +384 -188
  100. package/src/modules/validation.ts +10 -9
  101. package/src/store/block_store.ts +569 -174
  102. package/src/store/contract_class_store.ts +8 -106
  103. package/src/store/contract_instance_store.ts +8 -5
  104. package/src/store/kv_archiver_store.ts +167 -41
  105. package/src/store/l2_tips_cache.ts +134 -0
  106. package/src/store/log_store.ts +221 -63
  107. package/src/store/message_store.ts +27 -10
  108. package/src/structs/inbox_message.ts +1 -1
  109. package/src/test/fake_l1_state.ts +213 -42
  110. package/src/test/mock_archiver.ts +3 -2
  111. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  112. package/src/test/mock_l2_block_source.ts +230 -82
  113. package/src/test/mock_structs.ts +20 -6
  114. package/src/test/noop_l1_archiver.ts +10 -2
@@ -371,20 +371,26 @@ 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';
380
+ import { EthAddress } from '@aztec/foundation/eth-address';
378
381
  import { createLogger } from '@aztec/foundation/log';
382
+ import { retryTimes } from '@aztec/foundation/retry';
379
383
  import { count } from '@aztec/foundation/string';
380
384
  import { Timer, elapsed } from '@aztec/foundation/timer';
381
- import { isDefined } from '@aztec/foundation/types';
385
+ import { isDefined, isErrorClass } from '@aztec/foundation/types';
382
386
  import { L2BlockSourceEvents } from '@aztec/stdlib/block';
387
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
383
388
  import { getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
384
389
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
385
390
  import { execInSpan, trackSpan } from '@aztec/telemetry-client';
386
391
  import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
387
- import { retrieveCheckpointsFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from '../l1/data_retrieval.js';
392
+ import { getCheckpointBlobDataFromBlobs, retrieveCheckpointCalldataFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from '../l1/data_retrieval.js';
393
+ import { MessageStoreError } from '../store/message_store.js';
388
394
  import { ArchiverDataStoreUpdater } from './data_store_updater.js';
389
395
  import { validateCheckpointAttestations } from './validation.js';
390
396
  _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpochPrune'), _dec2 = trackSpan('Archiver.handleL1ToL2Messages'), _dec3 = trackSpan('Archiver.handleCheckpoints');
@@ -396,7 +402,6 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
396
402
  debugClient;
397
403
  rollup;
398
404
  inbox;
399
- l1Addresses;
400
405
  store;
401
406
  config;
402
407
  blobClient;
@@ -435,12 +440,11 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
435
440
  l1Timestamp;
436
441
  updater;
437
442
  tracer;
438
- constructor(publicClient, debugClient, rollup, inbox, l1Addresses, store, config, blobClient, epochCache, dateProvider, instrumentation, l1Constants, events, tracer, log = createLogger('archiver:l1-sync')){
443
+ constructor(publicClient, debugClient, rollup, inbox, store, config, blobClient, epochCache, dateProvider, instrumentation, l1Constants, events, tracer, l2TipsCache, log = createLogger('archiver:l1-sync')){
439
444
  this.publicClient = publicClient;
440
445
  this.debugClient = debugClient;
441
446
  this.rollup = rollup;
442
447
  this.inbox = inbox;
443
- this.l1Addresses = l1Addresses;
444
448
  this.store = store;
445
449
  this.config = config;
446
450
  this.blobClient = blobClient;
@@ -451,7 +455,9 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
451
455
  this.events = events;
452
456
  this.log = log;
453
457
  _initProto(this);
454
- this.updater = new ArchiverDataStoreUpdater(this.store);
458
+ this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache, {
459
+ rollupManaLimit: l1Constants.rollupManaLimit
460
+ });
455
461
  this.tracer = tracer;
456
462
  }
457
463
  /** Sets new config */ setConfig(newConfig) {
@@ -463,6 +469,12 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
463
469
  /** Returns the last L1 timestamp that was synced. */ getL1Timestamp() {
464
470
  return this.l1Timestamp;
465
471
  }
472
+ getSignatureContext() {
473
+ return {
474
+ chainId: this.publicClient.chain.id,
475
+ rollupAddress: EthAddress.fromString(this.rollup.address)
476
+ };
477
+ }
466
478
  /** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */ async testEthereumNodeSynced() {
467
479
  const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
468
480
  if (maxAllowedDelay === 0) {
@@ -477,12 +489,20 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
477
489
  }
478
490
  }
479
491
  async syncFromL1(initialSyncComplete) {
492
+ // In between the various calls to L1, the block number can move meaning some of the following
493
+ // calls will return data for blocks that were not present during earlier calls. To combat this
494
+ // we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
495
+ // captured at the top of this function.
480
496
  const currentL1Block = await this.publicClient.getBlock({
481
497
  includeTransactions: false
482
498
  });
483
499
  const currentL1BlockNumber = currentL1Block.number;
484
500
  const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
485
501
  const currentL1Timestamp = currentL1Block.timestamp;
502
+ const currentL1BlockData = {
503
+ l1BlockNumber: currentL1BlockNumber,
504
+ l1BlockHash: currentL1BlockHash
505
+ };
486
506
  if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
487
507
  this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
488
508
  return;
@@ -498,36 +518,16 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
498
518
  maxAllowedDelay
499
519
  });
500
520
  }
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();
521
+ // Load sync point for blocks defaulting to start block
522
+ const { blocksSynchedTo = this.l1Constants.l1StartBlock } = await this.store.getSynchPoint();
506
523
  this.log.debug(`Starting new archiver sync iteration`, {
507
524
  blocksSynchedTo,
508
- messagesSynchedTo,
509
- currentL1BlockNumber,
510
- currentL1BlockHash
525
+ currentL1BlockData
511
526
  });
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 **********
527
+ // 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.
528
+ // 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
529
+ // block, when that wouldn't be the case, since L1 to L2 messages would need another iteration.
530
+ await retryTimes(()=>this.handleL1ToL2Messages(currentL1BlockData), 'Handling L1 to L2 messages', 3, 0.1);
531
531
  if (currentL1BlockNumber > blocksSynchedTo) {
532
532
  // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
533
533
  // pending chain validation status, proven checkpoint number, and synched L1 block number.
@@ -555,6 +555,8 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
555
555
  }
556
556
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
557
557
  }
558
+ // Update the finalized L2 checkpoint based on L1 finality.
559
+ await this.updateFinalizedCheckpoint();
558
560
  // After syncing has completed, update the current l1 block number and timestamp,
559
561
  // otherwise we risk announcing to the world that we've synced to a given point,
560
562
  // but the corresponding blocks have not been processed (see #12631).
@@ -568,6 +570,32 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
568
570
  l1BlockNumberAtEnd
569
571
  });
570
572
  }
573
+ /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */ async updateFinalizedCheckpoint() {
574
+ try {
575
+ const finalizedL1Block = await getFinalizedL1Block(this.publicClient);
576
+ if (!finalizedL1Block) {
577
+ this.log.trace(`Skipping finalized checkpoint update: L1 has no finalized block yet.`);
578
+ return;
579
+ }
580
+ const finalizedL1BlockNumber = finalizedL1Block.number;
581
+ const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
582
+ blockNumber: finalizedL1BlockNumber
583
+ });
584
+ const localFinalizedCheckpointNumber = await this.store.getFinalizedCheckpointNumber();
585
+ if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
586
+ await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
587
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
588
+ finalizedCheckpointNumber,
589
+ finalizedL1BlockNumber
590
+ });
591
+ }
592
+ } catch (err) {
593
+ // The rollup contract may not exist at the finalized L1 block right after deployment.
594
+ if (!err?.message?.includes('returned no data')) {
595
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
596
+ }
597
+ }
598
+ }
571
599
  /** Prune all proposed local blocks that should have been checkpointed by now. */ async pruneUncheckpointedBlocks(currentL1Timestamp) {
572
600
  const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
573
601
  this.store.getCheckpointedL2BlockNumber(),
@@ -578,26 +606,28 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
578
606
  this.log.trace(`No uncheckpointed blocks to prune.`);
579
607
  return;
580
608
  }
581
- // What's the slot of the first uncheckpointed block?
609
+ // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
610
+ const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
582
611
  const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
612
+ // What's the slot of the first uncheckpointed block?
583
613
  const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
584
614
  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 slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
587
- // Prune provisional blocks from slots that have ended without being checkpointed
588
- if (firstUncheckpointedBlockSlot !== undefined && firstUncheckpointedBlockSlot < slotAtNextL1Block) {
589
- this.log.warn(`Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`, {
590
- firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(),
591
- slotAtNextL1Block
615
+ if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
616
+ return;
617
+ }
618
+ // Prune provisional blocks from slots that have ended without being checkpointed.
619
+ // This also clears any proposed checkpoint whose blocks are being pruned.
620
+ this.log.warn(`Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`, {
621
+ firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(),
622
+ slotAtNextL1Block
623
+ });
624
+ const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
625
+ if (prunedBlocks.length > 0) {
626
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
627
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
628
+ slotNumber: firstUncheckpointedBlockSlot,
629
+ blocks: prunedBlocks
592
630
  });
593
- const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
594
- if (prunedBlocks.length > 0) {
595
- this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
596
- type: L2BlockSourceEvents.L2PruneUncheckpointed,
597
- slotNumber: firstUncheckpointedBlockSlot,
598
- blocks: prunedBlocks
599
- });
600
- }
601
631
  }
602
632
  }
603
633
  /** Queries the rollup contract on whether a prune can be executed on the immediate next L1 block. */ async canPrune(currentL1BlockNumber, currentL1Timestamp) {
@@ -628,12 +658,14 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
628
658
  const pruneFromSlotNumber = header.slotNumber;
629
659
  const pruneFromEpochNumber = getEpochAtSlot(pruneFromSlotNumber, this.l1Constants);
630
660
  const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
631
- const checkpointPromises = Array.from({
661
+ // Fetch checkpoints and blocks in bounded batches to avoid unbounded concurrent
662
+ // promises when the gap between local pending and proven checkpoint numbers is large.
663
+ const BATCH_SIZE = 10;
664
+ const indices = Array.from({
632
665
  length: checkpointsToUnwind
633
- }).fill(0).map((_, i)=>this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
634
- const checkpoints = await Promise.all(checkpointPromises);
635
- const blockPromises = await Promise.all(checkpoints.filter(isDefined).map((cp)=>this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))));
636
- const newBlocks = blockPromises.filter(isDefined).flat();
666
+ }, (_, i)=>CheckpointNumber(i + pruneFrom));
667
+ const checkpoints = (await asyncPool(BATCH_SIZE, indices, (idx)=>this.store.getCheckpointData(idx))).filter(isDefined);
668
+ const newBlocks = (await asyncPool(BATCH_SIZE, checkpoints, (cp)=>this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)))).filter(isDefined).flat();
637
669
  // Emit an event for listening services to react to the chain prune
638
670
  this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
639
671
  type: L2BlockSourceEvents.L2PruneUnproven,
@@ -667,55 +699,75 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
667
699
  nextEnd
668
700
  ];
669
701
  }
670
- async handleL1ToL2Messages(messagesSyncPoint, currentL1BlockNumber) {
671
- this.log.trace(`Handling L1 to L2 messages from ${messagesSyncPoint.l1BlockNumber} to ${currentL1BlockNumber}.`);
672
- if (currentL1BlockNumber <= messagesSyncPoint.l1BlockNumber) {
673
- return;
702
+ async handleL1ToL2Messages(currentL1Block) {
703
+ // Load the syncpoint, which may have been updated in a previous iteration
704
+ const { messagesSynchedTo = {
705
+ l1BlockNumber: this.l1Constants.l1StartBlock,
706
+ l1BlockHash: this.l1Constants.l1StartBlockHash
707
+ } } = await this.store.getSynchPoint();
708
+ // Nothing to do if L1 block number has not moved forward
709
+ const currentL1BlockNumber = currentL1Block.l1BlockNumber;
710
+ if (currentL1BlockNumber <= messagesSynchedTo.l1BlockNumber) {
711
+ return true;
674
712
  }
675
- // Load remote and local inbox states.
676
- const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
677
- const localLastMessage = await this.store.getLastL1ToL2Message();
713
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
678
714
  const remoteMessagesState = await this.inbox.getState({
679
715
  blockNumber: currentL1BlockNumber
680
716
  });
681
- this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
682
- localMessagesInserted,
683
- localLastMessage,
684
- remoteMessagesState
685
- });
686
- // Compare message count and rolling hash. If they match, no need to retrieve anything.
687
- if (remoteMessagesState.totalMessagesInserted === localMessagesInserted && remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer32.ZERO)) {
688
- this.log.trace(`No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`);
689
- return;
717
+ const localLastMessage = await this.store.getLastL1ToL2Message();
718
+ if (await this.localStateMatches(localLastMessage, remoteMessagesState)) {
719
+ this.log.trace(`Local L1 to L2 messages are already in sync with remote at L1 block ${currentL1BlockNumber}`);
720
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
721
+ return true;
690
722
  }
691
- // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
692
- // Note that we need to fetch it from logs and not from inbox state at the syncpoint l1 block number, since it
693
- // could be older than 128 blocks and non-archive nodes cannot resolve it.
694
- if (localLastMessage) {
695
- const remoteLastMessage = await this.retrieveL1ToL2Message(localLastMessage.leaf);
696
- this.log.trace(`Retrieved remote message for local last`, {
697
- remoteLastMessage,
698
- localLastMessage
699
- });
700
- if (!remoteLastMessage || !remoteLastMessage.rollingHash.equals(localLastMessage.rollingHash)) {
701
- this.log.warn(`Rolling back L1 to L2 messages due to hash mismatch or msg not found.`, {
702
- remoteLastMessage,
703
- messagesSyncPoint,
704
- localLastMessage
705
- });
706
- messagesSyncPoint = await this.rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint);
707
- this.log.debug(`Rolled back L1 to L2 messages to L1 block ${messagesSyncPoint.l1BlockNumber}.`, {
708
- messagesSyncPoint
723
+ // If not, then we are out of sync. Most likely there are new messages on the inbox, so we try retrieving them.
724
+ // However, it could also be the case that there was an L1 reorg and our syncpoint is no longer valid.
725
+ // If that's the case, we'd get an exception out of the message store since the rolling hash of the first message
726
+ // we try to insert would not match the one in the db, in which case we rollback to the last common message with L1.
727
+ try {
728
+ await this.retrieveAndStoreMessages(messagesSynchedTo.l1BlockNumber, currentL1BlockNumber);
729
+ } catch (error) {
730
+ if (isErrorClass(error, MessageStoreError)) {
731
+ this.log.warn(`Failed to store L1 to L2 messages retrieved from L1: ${error.message}. Rolling back syncpoint to retry.`, {
732
+ inboxMessage: error.inboxMessage
709
733
  });
734
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
735
+ return false;
710
736
  }
737
+ throw error;
711
738
  }
712
- // Retrieve and save messages in batches. Each batch is estimated to acommodate up to L2 'blockBatchSize' blocks,
739
+ // Note that, if there are no new messages to insert, but there was an L1 reorg that pruned out last messages,
740
+ // we'd notice by comparing our local state with the remote one again, and seeing they don't match even after
741
+ // our sync attempt. In this case, we also rollback our syncpoint, and trigger a retry.
742
+ const localLastMessageAfterSync = await this.store.getLastL1ToL2Message();
743
+ if (!await this.localStateMatches(localLastMessageAfterSync, remoteMessagesState)) {
744
+ this.log.warn(`Local L1 to L2 messages state does not match remote after sync attempt. Rolling back syncpoint to retry.`, {
745
+ localLastMessageAfterSync,
746
+ remoteMessagesState
747
+ });
748
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
749
+ return false;
750
+ }
751
+ // Advance the syncpoint after a successful sync
752
+ await this.store.setMessageSyncState(currentL1Block, remoteMessagesState.treeInProgress);
753
+ return true;
754
+ }
755
+ /** Checks if the local rolling hash and message count matches the remote state */ async localStateMatches(localLastMessage, remoteState) {
756
+ const localMessageCount = await this.store.getTotalL1ToL2MessageCount();
757
+ this.log.trace(`Comparing local and remote inbox state`, {
758
+ localMessageCount,
759
+ localLastMessage,
760
+ remoteState
761
+ });
762
+ return remoteState.totalMessagesInserted === localMessageCount && remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO);
763
+ }
764
+ /** Retrieves L1 to L2 messages from L1 in batches and stores them. */ async retrieveAndStoreMessages(fromL1Block, toL1Block) {
713
765
  let searchStartBlock = 0n;
714
- let searchEndBlock = messagesSyncPoint.l1BlockNumber;
766
+ let searchEndBlock = fromL1Block;
715
767
  let lastMessage;
716
768
  let messageCount = 0;
717
769
  do {
718
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
770
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
719
771
  this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
720
772
  const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
721
773
  const timer = new Timer();
@@ -730,74 +782,81 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
730
782
  lastMessage = msg;
731
783
  messageCount++;
732
784
  }
733
- }while (searchEndBlock < currentL1BlockNumber)
734
- // Log stats for messages retrieved (if any).
785
+ }while (searchEndBlock < toL1Block)
735
786
  if (messageCount > 0) {
736
787
  this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`, {
737
788
  lastMessage,
738
789
  messageCount
739
790
  });
740
791
  }
741
- // Warn if the resulting rolling hash does not match the remote state we had retrieved.
742
- if (lastMessage && !lastMessage.rollingHash.equals(remoteMessagesState.messagesRollingHash)) {
743
- this.log.warn(`Last message retrieved rolling hash does not match remote state.`, {
744
- lastMessage,
745
- remoteMessagesState
746
- });
747
- }
748
- }
749
- async retrieveL1ToL2Message(leaf) {
750
- const currentL1BlockNumber = await this.publicClient.getBlockNumber();
751
- let searchStartBlock = 0n;
752
- let searchEndBlock = this.l1Constants.l1StartBlock - 1n;
753
- do {
754
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
755
- const message = await retrieveL1ToL2Message(this.inbox, leaf, searchStartBlock, searchEndBlock);
756
- if (message) {
757
- return message;
758
- }
759
- }while (searchEndBlock < currentL1BlockNumber)
760
- return undefined;
761
792
  }
762
- async rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint) {
763
- // Slowly go back through our messages until we find the last common message.
764
- // We could query the logs in batch as an optimization, but the depth of the reorg should not be deep, and this
765
- // is a very rare case, so it's fine to query one log at a time.
793
+ /**
794
+ * 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.
795
+ * If no common message is found, rolls back all messages and sets the syncpoint to the start block.
796
+ */ async rollbackL1ToL2Messages(remoteMessagesState) {
797
+ const { treeInProgress: remoteTreeInProgress, messagesRollingHash: remoteRollingHash } = remoteMessagesState;
798
+ // Slowly go back through our messages until we find the last common message. We could query the logs in
799
+ // batch as an optimization, but the depth of the reorg should not be deep, and this is a very rare case,
800
+ // so it's fine to query one log at a time.
766
801
  let commonMsg;
767
- this.log.verbose(`Searching most recent common L1 to L2 message at or before index ${localLastMessage.index}`);
768
- for await (const msg of this.store.iterateL1ToL2Messages({
769
- reverse: true,
770
- end: localLastMessage.index
802
+ let messagesToDelete = 0;
803
+ this.log.verbose(`Searching most recent common L1 to L2 message`);
804
+ for await (const localMsg of this.store.iterateL1ToL2Messages({
805
+ reverse: true
771
806
  })){
772
- const remoteMsg = await this.retrieveL1ToL2Message(msg.leaf);
773
807
  const logCtx = {
774
- remoteMsg,
775
- localMsg: msg
808
+ remoteMsg: undefined,
809
+ localMsg,
810
+ remoteMessagesState
776
811
  };
777
- if (remoteMsg && remoteMsg.rollingHash.equals(msg.rollingHash)) {
778
- this.log.verbose(`Found most recent common L1 to L2 message at index ${msg.index} on L1 block ${msg.l1BlockNumber}`, logCtx);
812
+ // First check if the local message rolling hash matches the current rolling hash of the inbox contract,
813
+ // which means we just need to rollback some local messages and we should be back in sync. This means there
814
+ // was an L1 reorg that removed some of the messages we had, but no new messages were added compared.
815
+ if (localMsg.rollingHash.equals(remoteRollingHash)) {
816
+ this.log.info(`Found common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber} matching current remote state`, logCtx);
817
+ commonMsg = localMsg;
818
+ break;
819
+ }
820
+ // If there's no match with the current remote state, check if the message exists on the inbox contract at all
821
+ // by looking at the inbox events. If the L1 reorg *added* new messages in addition to deleting existing ones,
822
+ // then the current remote state's rolling hash will not match anything we have locally, so we need to check existence
823
+ // of individual messages via logs. Note we use logs and not historical queries so we don't have to depend on
824
+ // an archival rpc node, since the message could be from a long time ago if we're catching up with syncing.
825
+ const remoteMsg = await retrieveL1ToL2Message(this.inbox, localMsg);
826
+ logCtx.remoteMsg = remoteMsg;
827
+ if (remoteMsg && remoteMsg.rollingHash.equals(localMsg.rollingHash)) {
828
+ this.log.info(`Found most recent common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber}`, logCtx);
779
829
  commonMsg = remoteMsg;
780
830
  break;
781
831
  } else if (remoteMsg) {
782
- this.log.debug(`Local L1 to L2 message with index ${msg.index} has different rolling hash`, logCtx);
832
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} has different rolling hash`, logCtx);
833
+ messagesToDelete++;
783
834
  } else {
784
- this.log.debug(`Local L1 to L2 message with index ${msg.index} not found on L1`, logCtx);
835
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} not found on L1`, logCtx);
836
+ messagesToDelete++;
785
837
  }
786
838
  }
787
- // Delete everything after the common message we found.
788
- const lastGoodIndex = commonMsg?.index;
789
- this.log.warn(`Deleting all local L1 to L2 messages after index ${lastGoodIndex ?? 'undefined'}`);
790
- await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
839
+ // Delete everything after the common message we found, if anything needs to be deleted.
840
+ // Do not exit early if there are no messages to delete, we still want to update the syncpoint.
841
+ if (messagesToDelete > 0) {
842
+ const lastGoodIndex = commonMsg?.index;
843
+ this.log.warn(`Rolling back all local L1 to L2 messages after index ${lastGoodIndex ?? 'initial'}`);
844
+ await this.store.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
845
+ }
791
846
  // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
792
847
  // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
793
848
  // after the last common message.
794
849
  const syncPointL1BlockNumber = commonMsg ? commonMsg.l1BlockNumber - 1n : this.l1Constants.l1StartBlock;
795
850
  const syncPointL1BlockHash = await this.getL1BlockHash(syncPointL1BlockNumber);
796
- messagesSyncPoint = {
851
+ const messagesSyncPoint = {
797
852
  l1BlockNumber: syncPointL1BlockNumber,
798
853
  l1BlockHash: syncPointL1BlockHash
799
854
  };
800
- await this.store.setMessageSynchedL1Block(messagesSyncPoint);
855
+ await this.store.setMessageSyncState(messagesSyncPoint, remoteTreeInProgress);
856
+ this.log.verbose(`Updated messages syncpoint to L1 block ${syncPointL1BlockNumber}`, {
857
+ ...messagesSyncPoint,
858
+ remoteTreeInProgress
859
+ });
801
860
  return messagesSyncPoint;
802
861
  }
803
862
  async getL1BlockHash(l1BlockNumber) {
@@ -837,7 +896,7 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
837
896
  if (provenCheckpointNumber === 0) {
838
897
  const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
839
898
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
840
- await this.store.setProvenCheckpointNumber(provenCheckpointNumber);
899
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
841
900
  this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, {
842
901
  provenCheckpointNumber
843
902
  });
@@ -854,20 +913,20 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
854
913
  if (localCheckpointForDestinationProvenCheckpointNumber && provenArchive.equals(localCheckpointForDestinationProvenCheckpointNumber.archive.root)) {
855
914
  const localProvenCheckpointNumber = await this.store.getProvenCheckpointNumber();
856
915
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
857
- await this.store.setProvenCheckpointNumber(provenCheckpointNumber);
916
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
858
917
  this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, {
859
918
  provenCheckpointNumber
860
919
  });
861
920
  const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
862
921
  const provenEpochNumber = getEpochAtSlot(provenSlotNumber, this.l1Constants);
863
- const lastBlockNumberInCheckpoint = localCheckpointForDestinationProvenCheckpointNumber.startBlock + localCheckpointForDestinationProvenCheckpointNumber.numBlocks - 1;
922
+ const lastBlockNumberInCheckpoint = localCheckpointForDestinationProvenCheckpointNumber.startBlock + localCheckpointForDestinationProvenCheckpointNumber.blockCount - 1;
864
923
  this.events.emit(L2BlockSourceEvents.L2BlockProven, {
865
924
  type: L2BlockSourceEvents.L2BlockProven,
866
925
  blockNumber: BlockNumber(lastBlockNumberInCheckpoint),
867
926
  slotNumber: provenSlotNumber,
868
927
  epochNumber: provenEpochNumber
869
928
  });
870
- this.instrumentation.updateLastProvenBlock(lastBlockNumberInCheckpoint);
929
+ this.instrumentation.updateLastProvenCheckpoint(localCheckpointForDestinationProvenCheckpointNumber);
871
930
  } else {
872
931
  this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
873
932
  }
@@ -944,25 +1003,43 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
944
1003
  do {
945
1004
  [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
946
1005
  this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
947
- // TODO(md): Retrieve from blob client then from consensus client, then from peers
948
- 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));
949
- if (retrievedCheckpoints.length === 0) {
1006
+ // First fetch calldata only, no blobs yet, since we may be able to just get that data out of the proposed chain
1007
+ const calldataCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', ()=>retrieveCheckpointCalldataFromRollup(this.rollup, this.publicClient, this.debugClient, searchStartBlock, searchEndBlock, this.instrumentation, this.log));
1008
+ if (calldataCheckpoints.length === 0) {
950
1009
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
951
1010
  // See further details in earlier comments.
952
1011
  this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
953
1012
  continue;
954
1013
  }
955
- this.log.debug(`Retrieved ${retrievedCheckpoints.length} new checkpoints between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
956
- lastProcessedCheckpoint: retrievedCheckpoints[retrievedCheckpoints.length - 1].l1,
1014
+ this.log.debug(`Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
1015
+ lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
957
1016
  searchStartBlock,
958
1017
  searchEndBlock
959
1018
  });
960
- const publishedCheckpoints = await Promise.all(retrievedCheckpoints.map((b)=>retrievedToPublishedCheckpoint(b)));
1019
+ // Check if the last checkpoint matches a local pending entry (so we can skip blob fetch).
1020
+ // We only check the last one; if it matches, the blob fetch is skipped for that entry.
1021
+ // TODO(palla/pipelining): We may have more than a single checkpoint to promote
1022
+ const lastCalldataCheckpoint = calldataCheckpoints[calldataCheckpoints.length - 1];
1023
+ const promoteResult = await this.tryBuildPublishedCheckpointFromProposed(lastCalldataCheckpoint);
1024
+ const checkpointToPromote = promoteResult && !('diverged' in promoteResult) ? promoteResult : undefined;
1025
+ const evictProposedFrom = promoteResult && 'diverged' in promoteResult ? promoteResult.fromCheckpointNumber : undefined;
1026
+ // Then fetch blobs in parallel and build the full published checkpoints
1027
+ const toFetchBlobs = checkpointToPromote ? calldataCheckpoints.slice(0, -1) : calldataCheckpoints;
1028
+ const blobFetched = await asyncPool(10, toFetchBlobs, async (checkpoint)=>retrievedToPublishedCheckpoint({
1029
+ ...checkpoint,
1030
+ checkpointBlobData: await getCheckpointBlobDataFromBlobs(this.blobClient, checkpoint.l1.blockHash, checkpoint.blobHashes, checkpoint.checkpointNumber, this.log, !initialSyncComplete, checkpoint.parentBeaconBlockRoot, checkpoint.l1.timestamp)
1031
+ }));
1032
+ // And add the promoted checkpoint to the list of all checkpoints
1033
+ const publishedCheckpoints = checkpointToPromote ? [
1034
+ ...blobFetched,
1035
+ checkpointToPromote
1036
+ ] : blobFetched;
961
1037
  const validCheckpoints = [];
1038
+ // Now loop through all checkpoints and validate their attestations
962
1039
  for (const published of publishedCheckpoints){
963
1040
  const validationResult = this.config.skipValidateCheckpointAttestations ? {
964
1041
  valid: true
965
- } : await validateCheckpointAttestations(published, this.epochCache, this.l1Constants, this.log);
1042
+ } : await validateCheckpointAttestations(published, this.epochCache, this.l1Constants, this.getSignatureContext(), this.log);
966
1043
  // Only update the validation result if it has changed, so we can keep track of the first invalid checkpoint
967
1044
  // in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
968
1045
  // There is an exception though: if a checkpoint is invalidated and replaced with another invalid checkpoint,
@@ -1008,15 +1085,31 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1008
1085
  blocks: published.checkpoint.blocks.map((b)=>b.getStats())
1009
1086
  });
1010
1087
  }
1088
+ for (const published of validCheckpoints){
1089
+ this.instrumentation.processCheckpointL1Timing({
1090
+ slotNumber: published.checkpoint.header.slotNumber,
1091
+ l1Timestamp: published.l1.timestamp,
1092
+ l1Constants: this.l1Constants
1093
+ });
1094
+ }
1011
1095
  try {
1012
1096
  const updatedValidationResult = rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
1013
- const [processDuration, result] = await elapsed(()=>execInSpan(this.tracer, 'Archiver.addCheckpoints', ()=>this.updater.addCheckpoints(validCheckpoints, updatedValidationResult)));
1014
- this.instrumentation.processNewBlocks(processDuration / validCheckpoints.length, validCheckpoints.flatMap((c)=>c.checkpoint.blocks));
1097
+ // Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
1098
+ // the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
1099
+ const [[maybeValidCheckpointToPromote], checkpointsToAdd] = partition(validCheckpoints, (c)=>c.checkpoint.number === checkpointToPromote?.checkpoint.number);
1100
+ const [processDuration, result] = await elapsed(()=>execInSpan(this.tracer, 'Archiver.addCheckpoints', ()=>this.updater.addCheckpoints(checkpointsToAdd, updatedValidationResult, maybeValidCheckpointToPromote && {
1101
+ l1: lastCalldataCheckpoint.l1,
1102
+ attestations: lastCalldataCheckpoint.attestations,
1103
+ checkpoint: maybeValidCheckpointToPromote
1104
+ }, evictProposedFrom)));
1105
+ if (checkpointsToAdd.length > 0) {
1106
+ this.instrumentation.processNewCheckpointedBlocks(processDuration / checkpointsToAdd.length, checkpointsToAdd.flatMap((c)=>c.checkpoint.blocks));
1107
+ }
1015
1108
  // If blocks were pruned due to conflict with L1 checkpoints, emit event
1016
1109
  if (result.prunedBlocks && result.prunedBlocks.length > 0) {
1017
1110
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
1018
1111
  const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
1019
- this.log.warn(`Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`, {
1112
+ this.log.info(`Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`, {
1020
1113
  prunedBlocks: result.prunedBlocks.map((b)=>b.toBlockInfo()),
1021
1114
  prunedSlotNumber,
1022
1115
  prunedCheckpointNumber
@@ -1056,7 +1149,7 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1056
1149
  });
1057
1150
  }
1058
1151
  lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
1059
- lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
1152
+ lastL1BlockWithCheckpoint = calldataCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
1060
1153
  }while (searchEndBlock < currentL1BlockNumber)
1061
1154
  // Important that we update AFTER inserting the blocks.
1062
1155
  await updateProvenCheckpoint();
@@ -1066,6 +1159,66 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1066
1159
  lastL1BlockWithCheckpoint
1067
1160
  };
1068
1161
  }
1162
+ /**
1163
+ * Checks if a specific checkpoint matches a local pending entry, and if so, loads local data to build
1164
+ * a synthetic published checkpoint (skipping blob fetch).
1165
+ *
1166
+ * Returns { diverged: true, fromCheckpointNumber } when the L1 checkpoint does NOT match local pending
1167
+ * data for that number, so the caller can evict the entire pending suffix >= fromCheckpointNumber
1168
+ * (those entries chain off the now-invalid local state) within the same addCheckpoints transaction.
1169
+ */ async tryBuildPublishedCheckpointFromProposed(calldataCheckpoint) {
1170
+ if (this.config.skipPromoteProposedCheckpointDuringL1Sync || !calldataCheckpoint) {
1171
+ return undefined;
1172
+ }
1173
+ // Look up the specific pending entry for the checkpoint being mined, not just the tip
1174
+ const proposed = await this.store.getProposedCheckpointByNumber(calldataCheckpoint.checkpointNumber);
1175
+ if (!proposed) {
1176
+ return undefined;
1177
+ }
1178
+ if (!proposed.header.equals(calldataCheckpoint.header) || !proposed.archive.root.equals(calldataCheckpoint.archiveRoot)) {
1179
+ this.log.warn(`Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`, {
1180
+ proposedCheckpointNumber: proposed.checkpointNumber,
1181
+ proposedHeader: proposed.header.toInspect(),
1182
+ proposedArchiveRoot: proposed.archive.root.toString(),
1183
+ calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
1184
+ calldataHeader: calldataCheckpoint.header.toInspect(),
1185
+ calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString()
1186
+ });
1187
+ // Return a divergence signal so the caller can evict pending >= this number
1188
+ return {
1189
+ diverged: true,
1190
+ fromCheckpointNumber: proposed.checkpointNumber
1191
+ };
1192
+ }
1193
+ this.log.debug(`Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`, {
1194
+ proposedHeader: proposed.header.toInspect(),
1195
+ proposedArchiveRoot: proposed.archive.root.toString()
1196
+ });
1197
+ const blocks = await this.store.getBlocks(BlockNumber(proposed.startBlock), proposed.blockCount);
1198
+ if (blocks.length !== proposed.blockCount) {
1199
+ this.log.warn(`Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`, {
1200
+ proposedCheckpointNumber: proposed.checkpointNumber,
1201
+ proposedStartBlock: proposed.startBlock,
1202
+ proposedBlockCount: proposed.blockCount,
1203
+ retrievedBlocks: blocks.map((b)=>b.number)
1204
+ });
1205
+ return undefined;
1206
+ }
1207
+ const checkpoint = Checkpoint.from({
1208
+ archive: proposed.archive,
1209
+ header: proposed.header,
1210
+ blocks,
1211
+ number: proposed.checkpointNumber,
1212
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier
1213
+ });
1214
+ const promotedCheckpoint = PublishedCheckpoint.from({
1215
+ checkpoint,
1216
+ l1: calldataCheckpoint.l1,
1217
+ attestations: calldataCheckpoint.attestations
1218
+ });
1219
+ this.instrumentation.processCheckpointPromoted();
1220
+ return promotedCheckpoint;
1221
+ }
1069
1222
  async checkForNewCheckpointsBeforeL1SyncPoint(status, blocksSynchedTo, currentL1BlockNumber) {
1070
1223
  const { lastRetrievedCheckpoint, pendingCheckpointNumber } = status;
1071
1224
  // Compare the last checkpoint we have (either retrieved in this round or loaded from store) with what the