@aztec/archiver 0.0.1-commit.5914bae → 0.0.1-commit.59a0419c6

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 (95) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +7 -5
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +18 -5
  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 +44 -2
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +58 -2
  11. package/dest/factory.d.ts +2 -2
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +3 -4
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -1
  17. package/dest/l1/calldata_retriever.d.ts +1 -1
  18. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  19. package/dest/l1/calldata_retriever.js +2 -1
  20. package/dest/l1/data_retrieval.d.ts +24 -12
  21. package/dest/l1/data_retrieval.d.ts.map +1 -1
  22. package/dest/l1/data_retrieval.js +36 -37
  23. package/dest/l1/validate_historical_logs.d.ts +23 -0
  24. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  25. package/dest/l1/validate_historical_logs.js +108 -0
  26. package/dest/modules/data_source_base.d.ts +6 -4
  27. package/dest/modules/data_source_base.d.ts.map +1 -1
  28. package/dest/modules/data_source_base.js +10 -4
  29. package/dest/modules/data_store_updater.d.ts +15 -10
  30. package/dest/modules/data_store_updater.d.ts.map +1 -1
  31. package/dest/modules/data_store_updater.js +27 -59
  32. package/dest/modules/instrumentation.d.ts +18 -2
  33. package/dest/modules/instrumentation.d.ts.map +1 -1
  34. package/dest/modules/instrumentation.js +32 -6
  35. package/dest/modules/l1_synchronizer.d.ts +6 -2
  36. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  37. package/dest/modules/l1_synchronizer.js +248 -149
  38. package/dest/modules/validation.d.ts +1 -1
  39. package/dest/modules/validation.d.ts.map +1 -1
  40. package/dest/modules/validation.js +2 -2
  41. package/dest/store/block_store.d.ts +46 -5
  42. package/dest/store/block_store.d.ts.map +1 -1
  43. package/dest/store/block_store.js +225 -63
  44. package/dest/store/contract_class_store.d.ts +2 -3
  45. package/dest/store/contract_class_store.d.ts.map +1 -1
  46. package/dest/store/contract_class_store.js +1 -65
  47. package/dest/store/kv_archiver_store.d.ts +35 -14
  48. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  49. package/dest/store/kv_archiver_store.js +40 -14
  50. package/dest/store/l2_tips_cache.d.ts +2 -1
  51. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  52. package/dest/store/l2_tips_cache.js +27 -7
  53. package/dest/store/log_store.d.ts +6 -3
  54. package/dest/store/log_store.d.ts.map +1 -1
  55. package/dest/store/log_store.js +47 -10
  56. package/dest/store/message_store.d.ts +5 -1
  57. package/dest/store/message_store.d.ts.map +1 -1
  58. package/dest/store/message_store.js +20 -8
  59. package/dest/test/fake_l1_state.d.ts +7 -3
  60. package/dest/test/fake_l1_state.d.ts.map +1 -1
  61. package/dest/test/fake_l1_state.js +50 -10
  62. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  63. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  64. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  65. package/dest/test/mock_l2_block_source.d.ts +7 -2
  66. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  67. package/dest/test/mock_l2_block_source.js +28 -3
  68. package/dest/test/noop_l1_archiver.d.ts +1 -1
  69. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  70. package/dest/test/noop_l1_archiver.js +4 -2
  71. package/package.json +13 -13
  72. package/src/archiver.ts +33 -8
  73. package/src/config.ts +22 -2
  74. package/src/errors.ts +94 -2
  75. package/src/factory.ts +2 -3
  76. package/src/index.ts +2 -1
  77. package/src/l1/calldata_retriever.ts +2 -1
  78. package/src/l1/data_retrieval.ts +52 -53
  79. package/src/l1/validate_historical_logs.ts +140 -0
  80. package/src/modules/data_source_base.ts +23 -4
  81. package/src/modules/data_store_updater.ts +43 -85
  82. package/src/modules/instrumentation.ts +47 -7
  83. package/src/modules/l1_synchronizer.ts +321 -185
  84. package/src/modules/validation.ts +2 -2
  85. package/src/store/block_store.ts +295 -73
  86. package/src/store/contract_class_store.ts +1 -103
  87. package/src/store/kv_archiver_store.ts +67 -24
  88. package/src/store/l2_tips_cache.ts +58 -13
  89. package/src/store/log_store.ts +62 -20
  90. package/src/store/message_store.ts +26 -9
  91. package/src/structs/inbox_message.ts +1 -1
  92. package/src/test/fake_l1_state.ts +72 -15
  93. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  94. package/src/test/mock_l2_block_source.ts +37 -2
  95. package/src/test/noop_l1_archiver.ts +3 -1
@@ -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';
386
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
383
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');
@@ -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.
@@ -572,10 +565,11 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
572
565
  }
573
566
  /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */ async updateFinalizedCheckpoint() {
574
567
  try {
575
- const finalizedL1Block = await this.publicClient.getBlock({
576
- blockTag: 'finalized',
577
- includeTransactions: false
578
- });
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
+ }
579
573
  const finalizedL1BlockNumber = finalizedL1Block.number;
580
574
  const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
581
575
  blockNumber: finalizedL1BlockNumber
@@ -583,11 +577,8 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
583
577
  const localFinalizedCheckpointNumber = await this.store.getFinalizedCheckpointNumber();
584
578
  if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
585
579
  await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
586
- const finalizedL2BlockNumber = await this.store.getFinalizedL2BlockNumber();
587
- this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber} (L2 block ${finalizedL2BlockNumber})`, {
580
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
588
581
  finalizedCheckpointNumber,
589
- previousFinalizedCheckpointNumber: localFinalizedCheckpointNumber,
590
- finalizedL2BlockNumber,
591
582
  finalizedL1BlockNumber
592
583
  });
593
584
  }
@@ -608,26 +599,28 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
608
599
  this.log.trace(`No uncheckpointed blocks to prune.`);
609
600
  return;
610
601
  }
611
- // 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);
612
604
  const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
605
+ // What's the slot of the first uncheckpointed block?
613
606
  const [firstUncheckpointedBlockHeader] = await this.store.getBlockHeaders(firstUncheckpointedBlockNumber, 1);
614
607
  const firstUncheckpointedBlockSlot = firstUncheckpointedBlockHeader?.getSlot();
615
- // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
616
- const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
617
- // Prune provisional blocks from slots that have ended without being checkpointed
618
- if (firstUncheckpointedBlockSlot !== undefined && firstUncheckpointedBlockSlot < slotAtNextL1Block) {
619
- this.log.warn(`Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`, {
620
- firstUncheckpointedBlockHeader: firstUncheckpointedBlockHeader.toInspect(),
621
- 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
622
623
  });
623
- const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
624
- if (prunedBlocks.length > 0) {
625
- this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
626
- type: L2BlockSourceEvents.L2PruneUncheckpointed,
627
- slotNumber: firstUncheckpointedBlockSlot,
628
- blocks: prunedBlocks
629
- });
630
- }
631
624
  }
632
625
  }
633
626
  /** Queries the rollup contract on whether a prune can be executed on the immediate next L1 block. */ async canPrune(currentL1BlockNumber, currentL1Timestamp) {
@@ -658,12 +651,14 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
658
651
  const pruneFromSlotNumber = header.slotNumber;
659
652
  const pruneFromEpochNumber = getEpochAtSlot(pruneFromSlotNumber, this.l1Constants);
660
653
  const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
661
- 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({
662
658
  length: checkpointsToUnwind
663
- }).fill(0).map((_, i)=>this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
664
- const checkpoints = await Promise.all(checkpointPromises);
665
- const blockPromises = await Promise.all(checkpoints.filter(isDefined).map((cp)=>this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))));
666
- 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();
667
662
  // Emit an event for listening services to react to the chain prune
668
663
  this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
669
664
  type: L2BlockSourceEvents.L2PruneUnproven,
@@ -697,55 +692,75 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
697
692
  nextEnd
698
693
  ];
699
694
  }
700
- async handleL1ToL2Messages(messagesSyncPoint, currentL1BlockNumber) {
701
- this.log.trace(`Handling L1 to L2 messages from ${messagesSyncPoint.l1BlockNumber} to ${currentL1BlockNumber}.`);
702
- if (currentL1BlockNumber <= messagesSyncPoint.l1BlockNumber) {
703
- 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;
704
705
  }
705
- // Load remote and local inbox states.
706
- const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
707
- const localLastMessage = await this.store.getLastL1ToL2Message();
706
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
708
707
  const remoteMessagesState = await this.inbox.getState({
709
708
  blockNumber: currentL1BlockNumber
710
709
  });
711
- this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
712
- localMessagesInserted,
713
- localLastMessage,
714
- remoteMessagesState
715
- });
716
- // Compare message count and rolling hash. If they match, no need to retrieve anything.
717
- if (remoteMessagesState.totalMessagesInserted === localMessagesInserted && remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer32.ZERO)) {
718
- this.log.trace(`No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`);
719
- 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;
720
715
  }
721
- // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
722
- // Note that we need to fetch it from logs and not from inbox state at the syncpoint l1 block number, since it
723
- // could be older than 128 blocks and non-archive nodes cannot resolve it.
724
- if (localLastMessage) {
725
- const remoteLastMessage = await this.retrieveL1ToL2Message(localLastMessage.leaf);
726
- this.log.trace(`Retrieved remote message for local last`, {
727
- remoteLastMessage,
728
- localLastMessage
729
- });
730
- if (!remoteLastMessage || !remoteLastMessage.rollingHash.equals(localLastMessage.rollingHash)) {
731
- this.log.warn(`Rolling back L1 to L2 messages due to hash mismatch or msg not found.`, {
732
- remoteLastMessage,
733
- messagesSyncPoint,
734
- localLastMessage
735
- });
736
- messagesSyncPoint = await this.rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint);
737
- this.log.debug(`Rolled back L1 to L2 messages to L1 block ${messagesSyncPoint.l1BlockNumber}.`, {
738
- 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
739
726
  });
727
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
728
+ return false;
740
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;
741
743
  }
742
- // 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) {
743
758
  let searchStartBlock = 0n;
744
- let searchEndBlock = messagesSyncPoint.l1BlockNumber;
759
+ let searchEndBlock = fromL1Block;
745
760
  let lastMessage;
746
761
  let messageCount = 0;
747
762
  do {
748
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
763
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
749
764
  this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
750
765
  const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
751
766
  const timer = new Timer();
@@ -760,74 +775,81 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
760
775
  lastMessage = msg;
761
776
  messageCount++;
762
777
  }
763
- }while (searchEndBlock < currentL1BlockNumber)
764
- // Log stats for messages retrieved (if any).
778
+ }while (searchEndBlock < toL1Block)
765
779
  if (messageCount > 0) {
766
780
  this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`, {
767
781
  lastMessage,
768
782
  messageCount
769
783
  });
770
784
  }
771
- // Warn if the resulting rolling hash does not match the remote state we had retrieved.
772
- if (lastMessage && !lastMessage.rollingHash.equals(remoteMessagesState.messagesRollingHash)) {
773
- this.log.warn(`Last message retrieved rolling hash does not match remote state.`, {
774
- lastMessage,
775
- remoteMessagesState
776
- });
777
- }
778
785
  }
779
- async retrieveL1ToL2Message(leaf) {
780
- const currentL1BlockNumber = await this.publicClient.getBlockNumber();
781
- let searchStartBlock = 0n;
782
- let searchEndBlock = this.l1Constants.l1StartBlock - 1n;
783
- do {
784
- [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
785
- const message = await retrieveL1ToL2Message(this.inbox, leaf, searchStartBlock, searchEndBlock);
786
- if (message) {
787
- return message;
788
- }
789
- }while (searchEndBlock < currentL1BlockNumber)
790
- return undefined;
791
- }
792
- async rollbackL1ToL2Messages(localLastMessage, messagesSyncPoint) {
793
- // Slowly go back through our messages until we find the last common message.
794
- // We could query the logs in batch as an optimization, but the depth of the reorg should not be deep, and this
795
- // 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.
796
794
  let commonMsg;
797
- this.log.verbose(`Searching most recent common L1 to L2 message at or before index ${localLastMessage.index}`);
798
- for await (const msg of this.store.iterateL1ToL2Messages({
799
- reverse: true,
800
- 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
801
799
  })){
802
- const remoteMsg = await this.retrieveL1ToL2Message(msg.leaf);
803
800
  const logCtx = {
804
- remoteMsg,
805
- localMsg: msg
801
+ remoteMsg: undefined,
802
+ localMsg,
803
+ remoteMessagesState
806
804
  };
807
- if (remoteMsg && remoteMsg.rollingHash.equals(msg.rollingHash)) {
808
- 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);
809
822
  commonMsg = remoteMsg;
810
823
  break;
811
824
  } else if (remoteMsg) {
812
- 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++;
813
827
  } else {
814
- 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++;
815
830
  }
816
831
  }
817
- // Delete everything after the common message we found.
818
- const lastGoodIndex = commonMsg?.index;
819
- this.log.warn(`Deleting all local L1 to L2 messages after index ${lastGoodIndex ?? 'undefined'}`);
820
- 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
+ }
821
839
  // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
822
840
  // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
823
841
  // after the last common message.
824
842
  const syncPointL1BlockNumber = commonMsg ? commonMsg.l1BlockNumber - 1n : this.l1Constants.l1StartBlock;
825
843
  const syncPointL1BlockHash = await this.getL1BlockHash(syncPointL1BlockNumber);
826
- messagesSyncPoint = {
844
+ const messagesSyncPoint = {
827
845
  l1BlockNumber: syncPointL1BlockNumber,
828
846
  l1BlockHash: syncPointL1BlockHash
829
847
  };
830
- 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
+ });
831
853
  return messagesSyncPoint;
832
854
  }
833
855
  async getL1BlockHash(l1BlockNumber) {
@@ -974,21 +996,37 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
974
996
  do {
975
997
  [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
976
998
  this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
977
- // TODO(md): Retrieve from blob client then from consensus client, then from peers
978
- const retrievedCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointsFromRollup', ()=>retrieveCheckpointsFromRollup(this.rollup, this.publicClient, this.debugClient, this.blobClient, searchStartBlock, searchEndBlock, this.instrumentation, this.log, !initialSyncComplete));
979
- 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) {
980
1002
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
981
1003
  // See further details in earlier comments.
982
1004
  this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
983
1005
  continue;
984
1006
  }
985
- this.log.debug(`Retrieved ${retrievedCheckpoints.length} new checkpoints between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
986
- 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,
987
1009
  searchStartBlock,
988
1010
  searchEndBlock
989
1011
  });
990
- 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;
991
1028
  const validCheckpoints = [];
1029
+ // Now loop through all checkpoints and validate their attestations
992
1030
  for (const published of publishedCheckpoints){
993
1031
  const validationResult = this.config.skipValidateCheckpointAttestations ? {
994
1032
  valid: true
@@ -1038,10 +1076,26 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1038
1076
  blocks: published.checkpoint.blocks.map((b)=>b.getStats())
1039
1077
  });
1040
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
+ }
1041
1086
  try {
1042
1087
  const updatedValidationResult = rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
1043
- const [processDuration, result] = await elapsed(()=>execInSpan(this.tracer, 'Archiver.addCheckpoints', ()=>this.updater.addCheckpoints(validCheckpoints, updatedValidationResult)));
1044
- 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
+ }
1045
1099
  // If blocks were pruned due to conflict with L1 checkpoints, emit event
1046
1100
  if (result.prunedBlocks && result.prunedBlocks.length > 0) {
1047
1101
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
@@ -1086,7 +1140,7 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1086
1140
  });
1087
1141
  }
1088
1142
  lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
1089
- lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
1143
+ lastL1BlockWithCheckpoint = calldataCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
1090
1144
  }while (searchEndBlock < currentL1BlockNumber)
1091
1145
  // Important that we update AFTER inserting the blocks.
1092
1146
  await updateProvenCheckpoint();
@@ -1096,6 +1150,51 @@ _dec = trackSpan('Archiver.syncFromL1'), _dec1 = trackSpan('Archiver.handleEpoch
1096
1150
  lastL1BlockWithCheckpoint
1097
1151
  };
1098
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
+ }
1099
1198
  async checkForNewCheckpointsBeforeL1SyncPoint(status, blocksSynchedTo, currentL1BlockNumber) {
1100
1199
  const { lastRetrievedCheckpoint, pendingCheckpointNumber } = status;
1101
1200
  // Compare the last checkpoint we have (either retrieved in this round or loaded from store) with what the
@@ -14,4 +14,4 @@ export declare function getAttestationInfoFromPublishedCheckpoint({ checkpoint,
14
14
  * Returns true if the attestations are valid and sufficient, false otherwise.
15
15
  */
16
16
  export declare function validateCheckpointAttestations(publishedCheckpoint: PublishedCheckpoint, epochCache: EpochCache, constants: Pick<L1RollupConstants, 'epochDuration'>, logger?: Logger): Promise<Valid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AI,CAAC,iBAAiB,EAAE,eAAe,CAAC,EACnD,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,wBAAwB,CAAC,CA2FnC"}
@@ -1,6 +1,6 @@
1
1
  import { compactArray } from '@aztec/foundation/collection';
2
2
  import { getAttestationInfoFromPayload } from '@aztec/stdlib/block';
3
- import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
3
+ import { computeQuorum, getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
4
4
  import { ConsensusPayload } from '@aztec/stdlib/p2p';
5
5
  /**
6
6
  * Extracts attestation information from a published checkpoint.
@@ -46,7 +46,7 @@ import { ConsensusPayload } from '@aztec/stdlib/p2p';
46
46
  valid: true
47
47
  };
48
48
  }
49
- const requiredAttestationCount = Math.floor(committee.length * 2 / 3) + 1;
49
+ const requiredAttestationCount = computeQuorum(committee.length);
50
50
  const failedValidationResult = (reason)=>({
51
51
  valid: false,
52
52
  reason,