@aztec/archiver 0.0.1-commit.d431d1c → 0.0.1-commit.d58ff9d0

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 (138) hide show
  1. package/README.md +28 -11
  2. package/dest/archiver.d.ts +80 -21
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +347 -167
  5. package/dest/config.d.ts +7 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +38 -14
  8. package/dest/errors.d.ts +60 -9
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +88 -13
  11. package/dest/factory.d.ts +13 -6
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +59 -39
  14. package/dest/index.d.ts +12 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +11 -2
  17. package/dest/l1/bin/retrieve-calldata.js +35 -32
  18. package/dest/l1/calldata_retriever.d.ts +81 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +202 -260
  21. package/dest/l1/data_retrieval.d.ts +32 -18
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +45 -50
  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/trace_tx.d.ts +12 -66
  28. package/dest/l1/trace_tx.d.ts.map +1 -1
  29. package/dest/l1/validate_historical_logs.d.ts +23 -0
  30. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  31. package/dest/l1/validate_historical_logs.js +108 -0
  32. package/dest/l1/validate_trace.d.ts +6 -3
  33. package/dest/l1/validate_trace.d.ts.map +1 -1
  34. package/dest/l1/validate_trace.js +13 -9
  35. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  36. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  37. package/dest/modules/contract_data_source_adapter.js +32 -0
  38. package/dest/modules/data_source_base.d.ts +75 -48
  39. package/dest/modules/data_source_base.d.ts.map +1 -1
  40. package/dest/modules/data_source_base.js +251 -220
  41. package/dest/modules/data_store_updater.d.ts +65 -29
  42. package/dest/modules/data_store_updater.d.ts.map +1 -1
  43. package/dest/modules/data_store_updater.js +242 -153
  44. package/dest/modules/instrumentation.d.ts +30 -4
  45. package/dest/modules/instrumentation.d.ts.map +1 -1
  46. package/dest/modules/instrumentation.js +83 -20
  47. package/dest/modules/l1_synchronizer.d.ts +16 -14
  48. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  49. package/dest/modules/l1_synchronizer.js +493 -225
  50. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  51. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  52. package/dest/modules/outbox_trees_resolver.js +162 -0
  53. package/dest/modules/validation.d.ts +30 -7
  54. package/dest/modules/validation.d.ts.map +1 -1
  55. package/dest/modules/validation.js +35 -17
  56. package/dest/store/block_store.d.ts +200 -75
  57. package/dest/store/block_store.d.ts.map +1 -1
  58. package/dest/store/block_store.js +802 -276
  59. package/dest/store/contract_class_store.d.ts +17 -4
  60. package/dest/store/contract_class_store.d.ts.map +1 -1
  61. package/dest/store/contract_class_store.js +51 -73
  62. package/dest/store/contract_instance_store.d.ts +28 -1
  63. package/dest/store/contract_instance_store.d.ts.map +1 -1
  64. package/dest/store/contract_instance_store.js +54 -2
  65. package/dest/store/data_stores.d.ts +68 -0
  66. package/dest/store/data_stores.d.ts.map +1 -0
  67. package/dest/store/data_stores.js +54 -0
  68. package/dest/store/function_names_cache.d.ts +17 -0
  69. package/dest/store/function_names_cache.d.ts.map +1 -0
  70. package/dest/store/function_names_cache.js +30 -0
  71. package/dest/store/l2_tips_cache.d.ts +25 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +26 -0
  74. package/dest/store/log_store.d.ts +42 -37
  75. package/dest/store/log_store.d.ts.map +1 -1
  76. package/dest/store/log_store.js +262 -388
  77. package/dest/store/log_store_codec.d.ts +78 -0
  78. package/dest/store/log_store_codec.d.ts.map +1 -0
  79. package/dest/store/log_store_codec.js +110 -0
  80. package/dest/store/message_store.d.ts +11 -1
  81. package/dest/store/message_store.d.ts.map +1 -1
  82. package/dest/store/message_store.js +51 -9
  83. package/dest/test/fake_l1_state.d.ts +28 -4
  84. package/dest/test/fake_l1_state.d.ts.map +1 -1
  85. package/dest/test/fake_l1_state.js +166 -32
  86. package/dest/test/index.js +3 -1
  87. package/dest/test/mock_archiver.d.ts +1 -1
  88. package/dest/test/mock_archiver.d.ts.map +1 -1
  89. package/dest/test/mock_archiver.js +3 -2
  90. package/dest/test/mock_l2_block_source.d.ts +65 -51
  91. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  92. package/dest/test/mock_l2_block_source.js +309 -215
  93. package/dest/test/mock_structs.d.ts +6 -2
  94. package/dest/test/mock_structs.d.ts.map +1 -1
  95. package/dest/test/mock_structs.js +26 -12
  96. package/dest/test/noop_l1_archiver.d.ts +34 -0
  97. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  98. package/dest/test/noop_l1_archiver.js +88 -0
  99. package/package.json +15 -14
  100. package/src/archiver.ts +458 -198
  101. package/src/config.ts +43 -13
  102. package/src/errors.ts +134 -21
  103. package/src/factory.ts +87 -36
  104. package/src/index.ts +19 -2
  105. package/src/l1/README.md +25 -68
  106. package/src/l1/bin/retrieve-calldata.ts +45 -33
  107. package/src/l1/calldata_retriever.ts +267 -379
  108. package/src/l1/data_retrieval.ts +70 -74
  109. package/src/l1/spire_proposer.ts +7 -15
  110. package/src/l1/validate_historical_logs.ts +140 -0
  111. package/src/l1/validate_trace.ts +24 -6
  112. package/src/modules/contract_data_source_adapter.ts +46 -0
  113. package/src/modules/data_source_base.ts +336 -288
  114. package/src/modules/data_store_updater.ts +287 -187
  115. package/src/modules/instrumentation.ts +86 -21
  116. package/src/modules/l1_synchronizer.ts +667 -278
  117. package/src/modules/outbox_trees_resolver.ts +199 -0
  118. package/src/modules/validation.ts +80 -23
  119. package/src/store/block_store.ts +984 -352
  120. package/src/store/contract_class_store.ts +57 -107
  121. package/src/store/contract_instance_store.ts +68 -5
  122. package/src/store/data_stores.ts +104 -0
  123. package/src/store/function_names_cache.ts +37 -0
  124. package/src/store/l2_tips_cache.ts +35 -0
  125. package/src/store/log_store.ts +305 -500
  126. package/src/store/log_store_codec.ts +143 -0
  127. package/src/store/message_store.ts +60 -10
  128. package/src/structs/inbox_message.ts +1 -1
  129. package/src/test/fake_l1_state.ts +215 -44
  130. package/src/test/index.ts +3 -0
  131. package/src/test/mock_archiver.ts +3 -2
  132. package/src/test/mock_l2_block_source.ts +381 -246
  133. package/src/test/mock_structs.ts +50 -17
  134. package/src/test/noop_l1_archiver.ts +158 -0
  135. package/dest/store/kv_archiver_store.d.ts +0 -336
  136. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  137. package/dest/store/kv_archiver_store.js +0 -443
  138. package/src/store/kv_archiver_store.ts +0 -631
package/dest/archiver.js CHANGED
@@ -371,23 +371,30 @@ 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, _initProto;
374
- import { GENESIS_BLOCK_HEADER_HASH, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
375
374
  import { BlockTagTooOldError } from '@aztec/ethereum/contracts';
376
- import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
375
+ import { BlockNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
377
376
  import { Buffer32 } from '@aztec/foundation/buffer';
378
377
  import { merge } from '@aztec/foundation/collection';
379
378
  import { EthAddress } from '@aztec/foundation/eth-address';
380
379
  import { createLogger } from '@aztec/foundation/log';
381
380
  import { promiseWithResolvers } from '@aztec/foundation/promise';
382
381
  import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/running-promise';
383
- import { GENESIS_CHECKPOINT_HEADER_HASH } from '@aztec/stdlib/block';
384
- import { getEpochNumberAtTimestamp, getSlotAtTimestamp, getSlotRangeForEpoch, getTimestampRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
382
+ import { elapsed } from '@aztec/foundation/timer';
383
+ import { L2BlockSourceEvents, l2TipsEqual } from '@aztec/stdlib/block';
384
+ import { getEpochAtSlot, getSlotAtNextL1Block, getSlotRangeForEpoch, getTimestampForSlot, getTimestampRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
385
+ import { ConsensusTimetable } from '@aztec/stdlib/timetable';
385
386
  import { trackSpan } from '@aztec/telemetry-client';
386
387
  import { mapArchiverConfig } from './config.js';
387
- import { NoBlobBodiesFoundError } from './errors.js';
388
+ import { BlockAlreadyCheckpointedError, BlockOrCheckpointSlotExpiredError, NoBlobBodiesFoundError } from './errors.js';
389
+ import { validateAndLogHistoricalLogsAvailability } from './l1/validate_historical_logs.js';
388
390
  import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
389
391
  import { ArchiverDataSourceBase } from './modules/data_source_base.js';
390
392
  import { ArchiverDataStoreUpdater } from './modules/data_store_updater.js';
393
+ import { OutboxTreesResolver } from './modules/outbox_trees_resolver.js';
394
+ import { backupArchiverDataStores, getArchiverSynchPoint } from './store/data_stores.js';
395
+ const noCheckpointProposalPresence = {
396
+ hasCheckpointProposalForSlot: ()=>Promise.resolve(false)
397
+ };
391
398
  _dec = trackSpan('Archiver.sync');
392
399
  /**
393
400
  * Pulls checkpoints in a non-blocking manner and provides interface for their retrieval.
@@ -397,11 +404,14 @@ _dec = trackSpan('Archiver.sync');
397
404
  publicClient;
398
405
  debugClient;
399
406
  rollup;
407
+ outbox;
400
408
  l1Addresses;
401
- dataStore;
409
+ dataStores;
402
410
  config;
403
411
  blobClient;
404
412
  l1Constants;
413
+ dateProvider;
414
+ checkpointProposalPresence;
405
415
  log;
406
416
  static{
407
417
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
@@ -415,37 +425,73 @@ _dec = trackSpan('Archiver.sync');
415
425
  /** Event emitter for archiver events (L2BlockProven, L2PruneUnproven, L2PruneUncheckpointed, etc). */ events;
416
426
  /** A loop in which we will be continually fetching new checkpoints. */ runningPromise;
417
427
  /** L1 synchronizer that handles fetching checkpoints and messages from L1. */ synchronizer;
428
+ /** Resolver for L2-to-L1 message membership witnesses, built over this archiver's read view. */ outboxTreesResolver;
418
429
  initialSyncComplete;
419
430
  initialSyncPromise;
420
- /** Queue of blocks to be added to the store, processed by the sync loop. */ blockQueue;
431
+ /** Queue of blocks and checkpoints to be added to the store, processed by the sync loop. */ inboundQueue;
421
432
  /** Helper to handle updates to the store */ updater;
433
+ /** In-memory cache for L2 chain tips. */ l2TipsCache;
434
+ /** Consensus timing model used for proposed-checkpoint arrival expectations. */ timetable;
422
435
  tracer;
436
+ instrumentation;
423
437
  /**
424
438
  * Creates a new instance of the Archiver.
425
439
  * @param publicClient - A client for interacting with the Ethereum node.
426
440
  * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
427
441
  * @param rollup - Rollup contract instance.
442
+ * @param outbox - Outbox contract instance, used to read per-epoch L2-to-L1 message roots.
428
443
  * @param inbox - Inbox contract instance.
429
- * @param l1Addresses - L1 contract addresses (registry, governance proposer, slash factory, slashing proposer).
430
- * @param dataStore - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
444
+ * @param l1Addresses - L1 contract addresses (registry, governance proposer, slashing proposer).
445
+ * @param dataStores - Archiver substores for storage & retrieval of blocks, encrypted logs & contract data.
431
446
  * @param config - Archiver configuration options.
432
447
  * @param blobClient - Client for retrieving blob data.
433
- * @param epochCache - Cache for epoch-related data.
434
- * @param dateProvider - Provider for current date/time.
435
448
  * @param instrumentation - Instrumentation for metrics and tracing.
436
449
  * @param l1Constants - L1 rollup constants.
450
+ * @param synchronizer - L1 synchronizer that handles fetching checkpoints and messages from L1.
451
+ * @param events - Event emitter shared with the synchronizer.
452
+ * @param initialHeader - Genesis block header.
453
+ * @param initialBlockHash - Precomputed hash of the genesis block header.
454
+ * @param l2TipsCache - In-memory cache for L2 chain tips.
455
+ * @param dateProvider - Provider for current date/time, used for wall-clock orphan-block pruning.
437
456
  * @param log - A logger.
438
- */ constructor(publicClient, debugClient, rollup, l1Addresses, dataStore, config, blobClient, instrumentation, l1Constants, synchronizer, events, log = createLogger('archiver')){
439
- super(dataStore, l1Constants), this.publicClient = publicClient, this.debugClient = debugClient, this.rollup = rollup, this.l1Addresses = l1Addresses, this.dataStore = dataStore, this.config = config, this.blobClient = blobClient, this.l1Constants = l1Constants, this.log = log, this.initialSyncComplete = (_initProto(this), false), this.blockQueue = [];
457
+ */ constructor(publicClient, debugClient, rollup, outbox, l1Addresses, dataStores, config, blobClient, instrumentation, l1Constants, synchronizer, events, initialHeader, initialBlockHash, l2TipsCache, dateProvider, checkpointProposalPresence = noCheckpointProposalPresence, log = createLogger('archiver')){
458
+ super(dataStores, l1Constants, initialHeader, initialBlockHash, l1Constants.genesisArchiveRoot), this.publicClient = publicClient, this.debugClient = debugClient, this.rollup = rollup, this.outbox = outbox, this.l1Addresses = l1Addresses, this.dataStores = dataStores, this.config = config, this.blobClient = blobClient, this.l1Constants = l1Constants, this.dateProvider = dateProvider, this.checkpointProposalPresence = checkpointProposalPresence, this.log = log, this.initialSyncComplete = (_initProto(this), false), this.inboundQueue = [];
440
459
  this.tracer = instrumentation.tracer;
460
+ this.instrumentation = instrumentation;
441
461
  this.initialSyncPromise = promiseWithResolvers();
442
462
  this.synchronizer = synchronizer;
443
463
  this.events = events;
444
- this.updater = new ArchiverDataStoreUpdater(this.dataStore);
464
+ this.l2TipsCache = l2TipsCache;
465
+ this.timetable = new ConsensusTimetable({
466
+ l1Constants,
467
+ blockDuration: this.config.blockDuration,
468
+ checkpointProposalSyncGrace: this.config.checkpointProposalSyncGrace
469
+ });
470
+ this.updater = new ArchiverDataStoreUpdater(this.dataStores, this.l2TipsCache, {
471
+ rollupManaLimit: l1Constants.rollupManaLimit
472
+ });
473
+ // The resolver reads its witness data from this archiver and pins its lazy Outbox-root fetches
474
+ // to the archiver's synced L1 block. No method on `this` is invoked during construction.
475
+ this.outboxTreesResolver = new OutboxTreesResolver(this.outbox, this, ()=>Promise.resolve(this.getL1BlockNumber()), l1Constants.epochDuration);
445
476
  // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
446
477
  // are done as fast as possible. This then gets updated once the initial sync completes.
447
478
  this.runningPromise = new RunningPromise(()=>this.sync(), this.log, this.config.pollingIntervalMs / 10, makeLoggingErrorHandler(this.log, NoBlobBodiesFoundError, BlockTagTooOldError));
448
479
  }
480
+ /**
481
+ * Returns the L2-to-L1 membership witness for `message` emitted by tx `txHash`. The node selects
482
+ * the smallest partial-proof root on the Outbox that covers the tx's checkpoint and builds the
483
+ * witness against it.
484
+ *
485
+ * The node reads the Outbox roots lazily, pinned to its synced L1 block, so the witness reflects
486
+ * the node's synced view. Returns `undefined` if the tx isn't yet in a block/epoch or no covering
487
+ * root has landed on L1 as of the synced block.
488
+ *
489
+ * Caveat: roots are cached only for the current synced L1 block and re-fetched once the node
490
+ * advances, so a reorg is picked up on the next synced-block advance rather than re-validated per
491
+ * request.
492
+ */ getL2ToL1MembershipWitness(txHash, message, messageIndexInTx) {
493
+ return this.outboxTreesResolver.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
494
+ }
449
495
  /** Updates archiver config */ updateConfig(newConfig) {
450
496
  this.config = merge(this.config, mapArchiverConfig(newConfig));
451
497
  this.synchronizer.setConfig(this.config);
@@ -459,11 +505,17 @@ _dec = trackSpan('Archiver.sync');
459
505
  }
460
506
  await this.blobClient.testSources();
461
507
  await this.synchronizer.testEthereumNodeSynced();
462
- await validateAndLogTraceAvailability(this.debugClient, this.config.ethereumAllowNoDebugHosts ?? false);
508
+ await validateAndLogTraceAvailability(this.debugClient, this.config.ethereumAllowNoDebugHosts ?? false, this.log.getBindings());
509
+ await validateAndLogHistoricalLogsAvailability(this.publicClient, {
510
+ rollupAddress: this.l1Addresses.rollupAddress,
511
+ inboxAddress: this.l1Addresses.inboxAddress,
512
+ registryAddress: this.l1Addresses.registryAddress,
513
+ governanceProposerAddress: this.l1Addresses.governanceProposerAddress
514
+ }, this.config.skipHistoricalLogsCheck ?? false, this.log.getBindings());
463
515
  // Log initial state for the archiver
464
516
  const { l1StartBlock } = this.l1Constants;
465
- const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await this.store.getSynchPoint();
466
- const currentL2Checkpoint = await this.getSynchedCheckpointNumber();
517
+ const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await getArchiverSynchPoint(this.stores);
518
+ const currentL2Checkpoint = await this.getCheckpointNumber();
467
519
  this.log.info(`Starting archiver sync to rollup contract ${this.rollup.address} from L1 block ${blocksSynchedTo} and L2 checkpoint ${currentL2Checkpoint}`, {
468
520
  blocksSynchedTo,
469
521
  messagesSynchedTo,
@@ -478,6 +530,16 @@ _dec = trackSpan('Archiver.sync');
478
530
  syncImmediate() {
479
531
  return this.runningPromise.trigger();
480
532
  }
533
+ /** Sets the proposal-presence provider used by orphan proposed-block pruning. */ setCheckpointProposalPresence(checkpointProposalPresence) {
534
+ this.checkpointProposalPresence = checkpointProposalPresence;
535
+ }
536
+ trySyncImmediate() {
537
+ try {
538
+ return this.syncImmediate();
539
+ } catch (err) {
540
+ this.log.error(`Failed to trigger immediate archiver sync: ${err}`, err);
541
+ }
542
+ }
481
543
  /**
482
544
  * Queues a block to be added to the archiver store and triggers processing.
483
545
  * The block will be processed by the sync loop.
@@ -485,43 +547,91 @@ _dec = trackSpan('Archiver.sync');
485
547
  * @param block - The L2 block to add.
486
548
  * @returns A promise that resolves when the block has been added to the store, or rejects on error.
487
549
  */ addBlock(block) {
488
- return new Promise((resolve, reject)=>{
489
- this.blockQueue.push({
490
- block,
491
- resolve,
492
- reject
493
- });
494
- this.log.debug(`Queued block ${block.number} for processing`);
495
- // Trigger an immediate sync, but don't wait for it - the promise resolves when the block is processed
496
- this.syncImmediate().catch((err)=>{
497
- this.log.error(`Sync immediate call failed: ${err}`);
498
- });
550
+ const promise = promiseWithResolvers();
551
+ this.inboundQueue.push({
552
+ block,
553
+ ...promise,
554
+ type: 'block'
555
+ });
556
+ this.log.debug(`Queued block ${block.number} for processing`);
557
+ void this.trySyncImmediate();
558
+ return promise.promise;
559
+ }
560
+ /**
561
+ * Queues a new proposed checkpoint into the archiver store.
562
+ * Checks that the checkpoint is not for an L2 slot already synced from L1.
563
+ * Resolves once the checkpoint has been processed.
564
+ */ addProposedCheckpoint(pending) {
565
+ const promise = promiseWithResolvers();
566
+ this.inboundQueue.push({
567
+ checkpoint: pending,
568
+ ...promise,
569
+ type: 'checkpoint'
499
570
  });
571
+ this.log.debug(`Queued checkpoint ${pending.checkpointNumber} for processing`);
572
+ void this.trySyncImmediate();
573
+ return promise.promise;
500
574
  }
501
575
  /**
502
- * Processes all queued blocks, adding them to the store.
576
+ * Processes all queued blocks and checkpoints, adding them to the store.
503
577
  * Called at the beginning of each sync iteration.
504
- * Blocks are processed in the order they were queued.
505
- */ async processQueuedBlocks() {
506
- if (this.blockQueue.length === 0) {
507
- return;
578
+ * Items are processed in the order they were queued.
579
+ */ async processInboundQueue() {
580
+ const blocksAdded = [];
581
+ if (this.inboundQueue.length === 0) {
582
+ return blocksAdded;
508
583
  }
509
- // Take all blocks from the queue
510
- const queuedItems = this.blockQueue.splice(0, this.blockQueue.length);
511
- this.log.debug(`Processing ${queuedItems.length} queued block(s)`);
512
- // Process each block individually to properly resolve/reject each promise
513
- for (const { block, resolve, reject } of queuedItems){
584
+ // Take all items from the queue
585
+ const queuedItems = this.inboundQueue.splice(0, this.inboundQueue.length);
586
+ this.log.debug(`Processing ${queuedItems.length} queued inbound items`);
587
+ // Calculate slot threshold for validation
588
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
589
+ const slotAtNextL1Block = l1Timestamp === undefined ? undefined : getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
590
+ // Helpers for manipulating blocks and checkpoints in the queue
591
+ const getSlot = (item)=>item.type === 'block' ? item.block.header.globalVariables.slotNumber : item.checkpoint.header.slotNumber;
592
+ const getNumber = (item)=>item.type === 'block' ? item.block.number : item.checkpoint.checkpointNumber;
593
+ // Process each item individually to properly resolve/reject each promise
594
+ for (const item of queuedItems){
595
+ const { resolve, reject, type } = item;
596
+ const itemSlot = getSlot(item);
597
+ const itemNumber = getNumber(item);
598
+ if (slotAtNextL1Block !== undefined && itemSlot < slotAtNextL1Block) {
599
+ const nextSlotTimestamp = getTimestampForSlot(slotAtNextL1Block, this.l1Constants);
600
+ this.log.warn(`Rejecting proposed ${type} ${itemNumber} for past slot ${itemSlot} (current ${slotAtNextL1Block})`, {
601
+ number: itemNumber,
602
+ type,
603
+ l1Timestamp,
604
+ slotAtNextL1Block,
605
+ nextSlotTimestamp
606
+ });
607
+ reject(new BlockOrCheckpointSlotExpiredError(itemSlot, nextSlotTimestamp, l1Timestamp));
608
+ continue;
609
+ }
514
610
  try {
515
- await this.updater.addBlocks([
516
- block
517
- ]);
518
- this.log.debug(`Added block ${block.number} to store`);
611
+ if (type === 'block') {
612
+ const [durationMs] = await elapsed(()=>this.updater.addProposedBlock(item.block));
613
+ this.instrumentation.processNewProposedBlock(durationMs, item.block);
614
+ blocksAdded.push(item.block);
615
+ } else {
616
+ await this.updater.addProposedCheckpoint(item.checkpoint);
617
+ }
618
+ this.log.debug(`Added ${type} ${itemNumber} to store`);
519
619
  resolve();
520
620
  } catch (err) {
521
- this.log.error(`Failed to add block ${block.number} to store: ${err.message}`);
621
+ if (err instanceof BlockAlreadyCheckpointedError) {
622
+ this.log.debug(`Proposed block ${itemNumber} matches already checkpointed block, ignoring late proposal`);
623
+ // A late proposal that matches an already-checkpointed block adds nothing new, so it is not appended.
624
+ resolve();
625
+ continue;
626
+ }
627
+ this.log.error(`Failed to add ${type} ${itemNumber} to store: ${err.message}`, err, {
628
+ number: itemNumber,
629
+ type
630
+ });
522
631
  reject(err);
523
632
  }
524
633
  }
634
+ return blocksAdded;
525
635
  }
526
636
  waitForInitialSync() {
527
637
  return this.initialSyncPromise.promise;
@@ -529,14 +639,112 @@ _dec = trackSpan('Archiver.sync');
529
639
  /**
530
640
  * Fetches logs from L1 contracts and processes them.
531
641
  */ async sync() {
642
+ // Capture the tips before any mutation so the aggregate event can report what moved this pass.
643
+ const fromTips = await this.getL2Tips();
644
+ // Accumulate the blocks added across the pass's sub-steps (queued proposals + L1 checkpoint payloads).
645
+ const blocksAdded = [];
532
646
  // Process any queued blocks first, before doing L1 sync
533
- await this.processQueuedBlocks();
647
+ blocksAdded.push(...await this.processInboundQueue());
534
648
  // Now perform L1 sync
535
- await this.syncFromL1();
649
+ blocksAdded.push(...await this.syncFromL1());
650
+ // Prune proposed blocks with no corresponding proposed checkpoint after the appropriate materialization deadline.
651
+ await this.pruneOrphanProposedBlocks();
652
+ // Emit a single aggregate update event after all pass work has committed and the tips cache has refreshed,
653
+ // so `toTips` and the source state observed by listeners are consistent with the event payload. The pass
654
+ // mutated state if the tips moved (added blocks, a prune, or a thin tier movement) or blocks were added; a
655
+ // fully-synced no-op pass emits nothing.
656
+ const toTips = await this.getL2Tips();
657
+ if (!l2TipsEqual(fromTips, toTips) || blocksAdded.length > 0) {
658
+ this.events.emit(L2BlockSourceEvents.L2BlockSourceUpdated, {
659
+ type: L2BlockSourceEvents.L2BlockSourceUpdated,
660
+ fromTips,
661
+ toTips,
662
+ blocksAdded
663
+ });
664
+ }
665
+ }
666
+ /**
667
+ * Prunes a block-only local tip that was built atop a checkpoint that was never itself proposed.
668
+ *
669
+ * Under pipelining, a proposer publishes the blocks for a checkpoint (block-only proposals) before
670
+ * assembling and publishing the enclosing proposed checkpoint at the end of the build slot. A node
671
+ * that received those blocks but never the proposed checkpoint is left with an orphan tip it must not build on.
672
+ * If no checkpoint proposal was received for the orphan slot, we prune after the receive deadline plus local
673
+ * tolerance. If a checkpoint proposal was received but has not materialized into proposed archiver state,
674
+ * we prune after the consensus materialization deadline.
675
+ *
676
+ * The uncheckpointed suffix is scanned in order. Blocks covered by proposed checkpoints are left in
677
+ * place; the first block not covered by a proposed checkpoint starts the orphan suffix to prune.
678
+ */ async pruneOrphanProposedBlocks() {
679
+ if (this.config.skipOrphanProposedBlockPruning) {
680
+ return;
681
+ }
682
+ const tips = await this.getL2Tips();
683
+ const now = BigInt(this.dateProvider.nowInSeconds());
684
+ // Frontier block covered by a proposed (or, falling back, confirmed) checkpoint. Blocks beyond it
685
+ // have no enclosing checkpoint proposal and are the orphan-pruning candidates.
686
+ const proposedCheckpointBlockNumber = await this.stores.blocks.getProposedCheckpointL2BlockNumber();
687
+ // The proposed tip is a proposed-checkpointed block, so there are no orphan proposed blocks to prune
688
+ if (proposedCheckpointBlockNumber === tips.proposed.number) {
689
+ this.log.trace(`No orphan proposed blocks to prune: proposed tip ${tips.proposed.number} is checkpointed`, {
690
+ proposed: tips.proposed,
691
+ proposedCheckpointBlockNumber
692
+ });
693
+ return;
694
+ }
695
+ // Load the blocks that are candidates for pruning (ie blocks without a proposed checkpoint covering them)
696
+ const blocksWithoutProposedCheckpoint = await this.stores.blocks.getBlocksData({
697
+ from: BlockNumber(proposedCheckpointBlockNumber + 1),
698
+ limit: tips.proposed.number - proposedCheckpointBlockNumber
699
+ });
700
+ // Iterate through them in order, the first one with a slot that should have received a proposed checkpoint
701
+ // is the first orphan block, and all blocks after it are also orphaned and should be pruned.
702
+ let lastSlotChecked = undefined;
703
+ for (const blockData of blocksWithoutProposedCheckpoint){
704
+ // No need to recheck if this block had the same slot as the previous one.
705
+ const blockSlot = blockData.header.getSlot();
706
+ const blockNumber = blockData.header.getBlockNumber();
707
+ if (lastSlotChecked !== undefined && blockSlot === lastSlotChecked) {
708
+ continue;
709
+ }
710
+ lastSlotChecked = blockSlot;
711
+ const hasCheckpointProposal = await this.checkpointProposalPresence.hasCheckpointProposalForSlot(blockSlot);
712
+ const deadlineType = hasCheckpointProposal ? 'checkpoint-proposal-synced' : 'checkpoint-proposal-received';
713
+ const selectedDeadline = BigInt(hasCheckpointProposal ? this.timetable.getCheckpointProposalSyncedDeadline(blockSlot) : Math.ceil(this.timetable.getCheckpointProposalReceiveDeadline(blockSlot) + this.config.orphanPruneNoProposalTolerance));
714
+ // If it's still not checkpointed once strictly past the selected deadline, prune it along with all blocks after
715
+ // it. A proposal may still legitimately arrive or materialize at exactly its deadline, so the tip is only
716
+ // orphaned once that instant has fully elapsed.
717
+ if (now > selectedDeadline) {
718
+ const pruneAfterBlockNumber = BlockNumber(blockNumber - 1);
719
+ this.log.warn(`Pruning orphan blocks after block ${pruneAfterBlockNumber}: block at slot ${blockSlot} belongs to ` + `checkpoint ${blockData.checkpointNumber} which has no matching proposed checkpoint`, {
720
+ firstUncheckpointedBlockHeader: blockData.header.toInspect(),
721
+ blockCheckpointNumber: blockData.checkpointNumber,
722
+ blockNumber,
723
+ blockSlot,
724
+ hasCheckpointProposal,
725
+ deadlineType,
726
+ selectedDeadline,
727
+ now
728
+ });
729
+ const prunedBlocks = await this.updater.removeBlocksWithoutProposedCheckpointAfter(pruneAfterBlockNumber);
730
+ if (prunedBlocks.length > 0) {
731
+ this.instrumentation.recordPrune('orphan');
732
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
733
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
734
+ slotNumber: blockSlot,
735
+ blocks: prunedBlocks
736
+ });
737
+ }
738
+ return;
739
+ }
740
+ }
741
+ this.log.trace('No orphan proposed blocks to prune: all uncheckpointed blocks are still within deadline', {
742
+ blocksWithoutProposedCheckpoint: blocksWithoutProposedCheckpoint.map((b)=>b.header.toInspect())
743
+ });
536
744
  }
537
745
  async syncFromL1() {
538
746
  // Delegate to the L1 synchronizer
539
- await this.synchronizer.syncFromL1(this.initialSyncComplete);
747
+ const blocksAdded = await this.synchronizer.syncFromL1(this.initialSyncComplete);
540
748
  // Check if we've completed initial sync
541
749
  const currentL1BlockNumber = this.synchronizer.getL1BlockNumber();
542
750
  if (currentL1BlockNumber !== undefined && !this.initialSyncComplete) {
@@ -544,7 +752,7 @@ _dec = trackSpan('Archiver.sync');
544
752
  if (currentL1BlockNumber + 1n >= l1BlockNumberAtEnd) {
545
753
  this.log.info(`Initial archiver sync to L1 block ${currentL1BlockNumber} complete`, {
546
754
  l1BlockNumber: currentL1BlockNumber,
547
- syncPoint: await this.store.getSynchPoint(),
755
+ syncPoint: await getArchiverSynchPoint(this.stores),
548
756
  ...await this.getL2Tips()
549
757
  });
550
758
  this.runningPromise.setPollingIntervalMS(this.config.pollingIntervalMs);
@@ -552,6 +760,7 @@ _dec = trackSpan('Archiver.sync');
552
760
  this.initialSyncPromise.resolve();
553
761
  }
554
762
  }
763
+ return blocksAdded;
555
764
  }
556
765
  /** Resumes the archiver after a stop. */ resume() {
557
766
  if (this.runningPromise.isRunning()) {
@@ -570,7 +779,7 @@ _dec = trackSpan('Archiver.sync');
570
779
  return Promise.resolve();
571
780
  }
572
781
  backupTo(destPath) {
573
- return this.dataStore.backupTo(destPath);
782
+ return backupArchiverDataStores(this.dataStores, destPath);
574
783
  }
575
784
  getL1Constants() {
576
785
  return Promise.resolve(this.l1Constants);
@@ -592,17 +801,53 @@ _dec = trackSpan('Archiver.sync');
592
801
  getL1Timestamp() {
593
802
  return Promise.resolve(this.synchronizer.getL1Timestamp());
594
803
  }
595
- getL2SlotNumber() {
804
+ async getSyncedL2SlotNumber() {
805
+ // The synced L2 slot is the latest slot for which we have all L1 data,
806
+ // either because we have seen all L1 blocks for that slot, or because
807
+ // we have seen the corresponding checkpoint.
808
+ let slotFromL1Sync;
596
809
  const l1Timestamp = this.synchronizer.getL1Timestamp();
597
- return Promise.resolve(l1Timestamp === undefined ? undefined : getSlotAtTimestamp(l1Timestamp, this.l1Constants));
810
+ if (l1Timestamp !== undefined) {
811
+ const nextL1BlockSlot = getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
812
+ if (Number(nextL1BlockSlot) > 0) {
813
+ slotFromL1Sync = SlotNumber.add(nextL1BlockSlot, -1);
814
+ }
815
+ }
816
+ let slotFromCheckpoint;
817
+ const latestCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
818
+ if (latestCheckpointNumber > 0) {
819
+ const checkpointData = await this.stores.blocks.getCheckpointData(latestCheckpointNumber);
820
+ if (checkpointData) {
821
+ slotFromCheckpoint = checkpointData.header.slotNumber;
822
+ }
823
+ }
824
+ if (slotFromL1Sync === undefined && slotFromCheckpoint === undefined) {
825
+ return undefined;
826
+ }
827
+ return SlotNumber(Math.max(slotFromL1Sync ?? 0, slotFromCheckpoint ?? 0));
598
828
  }
599
- getL2EpochNumber() {
600
- const l1Timestamp = this.synchronizer.getL1Timestamp();
601
- return Promise.resolve(l1Timestamp === undefined ? undefined : getEpochNumberAtTimestamp(l1Timestamp, this.l1Constants));
829
+ async getSyncedL2EpochNumber() {
830
+ const syncedSlot = await this.getSyncedL2SlotNumber();
831
+ if (syncedSlot === undefined) {
832
+ return undefined;
833
+ }
834
+ // An epoch is fully synced when all its slots are synced.
835
+ // We check if syncedSlot is the last slot of its epoch; if so, that epoch is fully synced.
836
+ // Otherwise, only the previous epoch is fully synced.
837
+ const epoch = getEpochAtSlot(syncedSlot, this.l1Constants);
838
+ const [, endSlot] = getSlotRangeForEpoch(epoch, this.l1Constants);
839
+ if (syncedSlot >= endSlot) {
840
+ return epoch;
841
+ }
842
+ return Number(epoch) > 0 ? EpochNumber(Number(epoch) - 1) : undefined;
602
843
  }
603
844
  async isEpochComplete(epochNumber) {
604
- // The epoch is complete if the current L2 block is the last one in the epoch (or later)
605
- const header = await this.getBlockHeader('latest');
845
+ // The epoch is complete if the current checkpointed L2 block is the last one in the epoch (or later).
846
+ // We use the checkpointed block number (synced from L1) instead of 'latest' to avoid returning true
847
+ // prematurely when proposed blocks have been pushed to the archiver but not yet checkpointed on L1.
848
+ const header = (await this.getBlockData({
849
+ tag: 'checkpointed'
850
+ }))?.header;
606
851
  const slot = header ? header.globalVariables.slotNumber : undefined;
607
852
  const [_startSlot, endSlot] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
608
853
  if (slot && slot >= endSlot) {
@@ -627,117 +872,52 @@ _dec = trackSpan('Archiver.sync');
627
872
  /** Returns whether the archiver has completed an initial sync run successfully. */ isInitialSyncComplete() {
628
873
  return this.initialSyncComplete;
629
874
  }
630
- unwindCheckpoints(from, checkpointsToUnwind) {
631
- return this.updater.unwindCheckpoints(from, checkpointsToUnwind);
875
+ removeCheckpointsAfter(checkpointNumber) {
876
+ return this.updater.removeCheckpointsAfter(checkpointNumber);
877
+ }
878
+ /**
879
+ * Removes all uncheckpointed blocks strictly after `blockNumber`, along with the proposed checkpoints
880
+ * that referenced them. Used by the AutomineSequencer to undo a local insert whose propose tx failed
881
+ * to land on L1 (no reorg needed — nothing reached L1). Refuses to touch checkpointed blocks.
882
+ */ removeUncheckpointedBlocksAfter(blockNumber) {
883
+ return this.updater.removeUncheckpointedBlocksAfter(blockNumber);
632
884
  }
633
885
  /** Used by TXE to add checkpoints directly without syncing from L1. */ async addCheckpoints(checkpoints, pendingChainValidationStatus) {
634
- await this.updater.setNewCheckpointData(checkpoints, pendingChainValidationStatus);
886
+ await this.updater.addCheckpoints(checkpoints, pendingChainValidationStatus);
635
887
  return true;
636
888
  }
637
- async getL2Tips() {
638
- const [latestBlockNumber, provenBlockNumber, checkpointedBlockNumber] = await Promise.all([
639
- this.getBlockNumber(),
640
- this.getProvenBlockNumber(),
641
- this.getCheckpointedBlockNumber()
642
- ]);
643
- // TODO(#13569): Compute proper finalized block number based on L1 finalized block.
644
- // We just force it 2 epochs worth of proven data for now.
645
- // NOTE: update end-to-end/src/e2e_epochs/epochs_empty_blocks.test.ts as that uses finalized blocks in computations
646
- const finalizedBlockNumber = BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2, 0));
647
- const beforeInitialblockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
648
- // Get the latest block header and checkpointed blocks for proven, finalised and checkpointed blocks
649
- const [latestBlockHeader, provenCheckpointedBlock, finalizedCheckpointedBlock, checkpointedBlock] = await Promise.all([
650
- latestBlockNumber > beforeInitialblockNumber ? this.getBlockHeader(latestBlockNumber) : undefined,
651
- provenBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(provenBlockNumber) : undefined,
652
- finalizedBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(finalizedBlockNumber) : undefined,
653
- checkpointedBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(checkpointedBlockNumber) : undefined
654
- ]);
655
- if (latestBlockNumber > beforeInitialblockNumber && !latestBlockHeader) {
656
- throw new Error(`Failed to retrieve latest block header for block ${latestBlockNumber}`);
657
- }
658
- // Checkpointed blocks must exist for proven, finalized and checkpointed tips if they are beyond the initial block number.
659
- if (checkpointedBlockNumber > beforeInitialblockNumber && !checkpointedBlock?.block.header) {
660
- throw new Error(`Failed to retrieve checkpointed block header for block ${checkpointedBlockNumber} (latest block is ${latestBlockNumber})`);
661
- }
662
- if (provenBlockNumber > beforeInitialblockNumber && !provenCheckpointedBlock?.block.header) {
663
- throw new Error(`Failed to retrieve proven checkpointed for block ${provenBlockNumber} (latest block is ${latestBlockNumber})`);
664
- }
665
- if (finalizedBlockNumber > beforeInitialblockNumber && !finalizedCheckpointedBlock?.block.header) {
666
- throw new Error(`Failed to retrieve finalized block header for block ${finalizedBlockNumber} (latest block is ${latestBlockNumber})`);
667
- }
668
- const latestBlockHeaderHash = await latestBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
669
- const provenBlockHeaderHash = await provenCheckpointedBlock?.block.header?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
670
- const finalizedBlockHeaderHash = await finalizedCheckpointedBlock?.block.header?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
671
- const checkpointedBlockHeaderHash = await checkpointedBlock?.block.header?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
672
- // Now attempt to retrieve checkpoints for proven, finalised and checkpointed blocks
673
- const [[provenBlockCheckpoint], [finalizedBlockCheckpoint], [checkpointedBlockCheckpoint]] = await Promise.all([
674
- provenCheckpointedBlock !== undefined ? await this.getPublishedCheckpoints(provenCheckpointedBlock?.checkpointNumber, 1) : [
675
- undefined
676
- ],
677
- finalizedCheckpointedBlock !== undefined ? await this.getPublishedCheckpoints(finalizedCheckpointedBlock?.checkpointNumber, 1) : [
678
- undefined
679
- ],
680
- checkpointedBlock !== undefined ? await this.getPublishedCheckpoints(checkpointedBlock?.checkpointNumber, 1) : [
681
- undefined
682
- ]
683
- ]);
684
- const initialcheckpointId = {
685
- number: CheckpointNumber.ZERO,
686
- hash: GENESIS_CHECKPOINT_HEADER_HASH.toString()
687
- };
688
- const makeCheckpointId = (checkpoint)=>{
689
- if (checkpoint === undefined) {
690
- return initialcheckpointId;
691
- }
692
- return {
693
- number: checkpoint.checkpoint.number,
694
- hash: checkpoint.checkpoint.hash().toString()
695
- };
696
- };
697
- const l2Tips = {
698
- proposed: {
699
- number: latestBlockNumber,
700
- hash: latestBlockHeaderHash.toString()
701
- },
702
- proven: {
703
- block: {
704
- number: provenBlockNumber,
705
- hash: provenBlockHeaderHash.toString()
706
- },
707
- checkpoint: makeCheckpointId(provenBlockCheckpoint)
708
- },
709
- finalized: {
710
- block: {
711
- number: finalizedBlockNumber,
712
- hash: finalizedBlockHeaderHash.toString()
713
- },
714
- checkpoint: makeCheckpointId(finalizedBlockCheckpoint)
715
- },
716
- checkpointed: {
717
- block: {
718
- number: checkpointedBlockNumber,
719
- hash: checkpointedBlockHeaderHash.toString()
720
- },
721
- checkpoint: makeCheckpointId(checkpointedBlockCheckpoint)
722
- }
723
- };
724
- return l2Tips;
889
+ getL2Tips() {
890
+ return this.l2TipsCache.getL2Tips();
725
891
  }
726
892
  async rollbackTo(targetL2BlockNumber) {
727
- // TODO(pw/mbps): This still assumes 1 block per checkpoint
728
893
  const currentBlocks = await this.getL2Tips();
729
894
  const currentL2Block = currentBlocks.proposed.number;
730
895
  const currentProvenBlock = currentBlocks.proven.block.number;
731
896
  if (targetL2BlockNumber >= currentL2Block) {
732
897
  throw new Error(`Target L2 block ${targetL2BlockNumber} must be less than current L2 block ${currentL2Block}`);
733
898
  }
734
- const blocksToUnwind = currentL2Block - targetL2BlockNumber;
735
- const targetL2Block = await this.store.getCheckpointedBlock(targetL2BlockNumber);
736
- if (!targetL2Block) {
899
+ const checkpointedTip = await this.stores.blocks.getCheckpointedL2BlockNumber();
900
+ if (targetL2BlockNumber > checkpointedTip) {
901
+ throw new Error(`Target L2 block ${targetL2BlockNumber} is not checkpointed yet`);
902
+ }
903
+ const targetBlockData = await this.stores.blocks.getBlockData({
904
+ number: targetL2BlockNumber
905
+ });
906
+ if (!targetBlockData) {
737
907
  throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
738
908
  }
739
- const targetL1BlockNumber = targetL2Block.l1.blockNumber;
740
- const targetCheckpointNumber = CheckpointNumber.fromBlockNumber(targetL2BlockNumber);
909
+ const targetCheckpointNumber = targetBlockData.checkpointNumber;
910
+ // Rollback operates at checkpoint granularity: the target block must be the last block of its checkpoint.
911
+ const checkpointData = await this.stores.blocks.getCheckpointData(targetCheckpointNumber);
912
+ if (!checkpointData) {
913
+ throw new Error(`Checkpoint ${targetCheckpointNumber} not found for block ${targetL2BlockNumber}`);
914
+ }
915
+ const lastBlockInCheckpoint = BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
916
+ if (targetL2BlockNumber !== lastBlockInCheckpoint) {
917
+ const previousCheckpointBoundary = checkpointData.startBlock > 1 ? BlockNumber(checkpointData.startBlock - 1) : BlockNumber(0);
918
+ throw new Error(`Target L2 block ${targetL2BlockNumber} is not at a checkpoint boundary. ` + `Checkpoint ${targetCheckpointNumber} spans blocks ${checkpointData.startBlock} to ${lastBlockInCheckpoint}. ` + `Use block ${lastBlockInCheckpoint} to roll back to this checkpoint, ` + `or block ${previousCheckpointBoundary} to roll back to the previous one.`);
919
+ }
920
+ const targetL1BlockNumber = checkpointData.l1.blockNumber;
741
921
  const targetL1Block = await this.publicClient.getBlock({
742
922
  blockNumber: targetL1BlockNumber,
743
923
  includeTransactions: false
@@ -746,24 +926,24 @@ _dec = trackSpan('Archiver.sync');
746
926
  throw new Error(`Missing L1 block ${targetL1BlockNumber}`);
747
927
  }
748
928
  const targetL1BlockHash = Buffer32.fromString(targetL1Block.hash);
749
- this.log.info(`Unwinding ${blocksToUnwind} checkpoints from L2 block ${currentL2Block}`);
750
- await this.updater.unwindCheckpoints(CheckpointNumber(currentL2Block), blocksToUnwind);
751
- this.log.info(`Unwinding L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
752
- await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
929
+ this.log.info(`Removing checkpoints after checkpoint ${targetCheckpointNumber} (target block ${targetL2BlockNumber})`);
930
+ await this.updater.removeCheckpointsAfter(targetCheckpointNumber);
931
+ this.log.info(`Rolling back L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
932
+ await this.stores.messages.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
753
933
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
754
- await this.store.setCheckpointSynchedL1BlockNumber(targetL1BlockNumber);
755
- await this.store.setMessageSynchedL1Block({
934
+ await this.stores.blocks.setSynchedL1BlockNumber(targetL1BlockNumber);
935
+ await this.stores.messages.setMessageSyncState({
756
936
  l1BlockNumber: targetL1BlockNumber,
757
937
  l1BlockHash: targetL1BlockHash
758
- });
938
+ }, undefined);
759
939
  if (targetL2BlockNumber < currentProvenBlock) {
760
- this.log.info(`Clearing proven L2 block number`);
761
- await this.store.setProvenCheckpointNumber(CheckpointNumber.ZERO);
762
- }
763
- // TODO(palla/reorg): Set the finalized block when we add support for it.
764
- // if (targetL2BlockNumber < currentFinalizedBlock) {
765
- // this.log.info(`Clearing finalized L2 block number`);
766
- // await this.store.setFinalizedL2BlockNumber(0);
767
- // }
940
+ this.log.info(`Rolling back proven L2 checkpoint to ${targetCheckpointNumber}`);
941
+ await this.updater.setProvenCheckpointNumber(targetCheckpointNumber);
942
+ }
943
+ const currentFinalizedBlock = currentBlocks.finalized.block.number;
944
+ if (targetL2BlockNumber < currentFinalizedBlock) {
945
+ this.log.info(`Rolling back finalized L2 checkpoint to ${targetCheckpointNumber}`);
946
+ await this.updater.setFinalizedCheckpointNumber(targetCheckpointNumber);
947
+ }
768
948
  }
769
949
  }