@aztec/sequencer-client 0.0.1-commit.c31f2472 → 0.0.1-commit.c52d6e7

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 (133) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +34 -11
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +77 -39
  5. package/dest/config.d.ts +33 -6
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +100 -46
  8. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  9. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  10. package/dest/global_variable_builder/fee_predictor.js +138 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_provider.js +80 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +13 -28
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +9 -66
  17. package/dest/global_variable_builder/index.d.ts +4 -2
  18. package/dest/global_variable_builder/index.d.ts.map +1 -1
  19. package/dest/global_variable_builder/index.js +2 -0
  20. package/dest/publisher/config.d.ts +51 -17
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +131 -42
  23. package/dest/publisher/index.d.ts +2 -1
  24. package/dest/publisher/index.d.ts.map +1 -1
  25. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  26. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  27. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  28. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  29. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  31. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +98 -0
  32. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  33. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
  34. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  35. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  36. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
  37. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  38. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  39. package/dest/publisher/l1_tx_failed_store/index.js +3 -0
  40. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  41. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  42. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  43. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -5
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +27 -3
  46. package/dest/publisher/sequencer-publisher.d.ts +123 -68
  47. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher.js +775 -364
  49. package/dest/publisher/write_json.d.ts +11 -0
  50. package/dest/publisher/write_json.d.ts.map +1 -0
  51. package/dest/publisher/write_json.js +57 -0
  52. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  53. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  54. package/dest/sequencer/automine/automine_factory.js +85 -0
  55. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  56. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  57. package/dest/sequencer/automine/automine_sequencer.js +696 -0
  58. package/dest/sequencer/automine/index.d.ts +3 -0
  59. package/dest/sequencer/automine/index.d.ts.map +1 -0
  60. package/dest/sequencer/automine/index.js +2 -0
  61. package/dest/sequencer/checkpoint_proposal_job.d.ts +99 -20
  62. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  63. package/dest/sequencer/checkpoint_proposal_job.js +926 -286
  64. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  65. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  66. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  67. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  68. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  69. package/dest/sequencer/checkpoint_voter.js +2 -5
  70. package/dest/sequencer/events.d.ts +62 -5
  71. package/dest/sequencer/events.d.ts.map +1 -1
  72. package/dest/sequencer/metrics.d.ts +23 -8
  73. package/dest/sequencer/metrics.d.ts.map +1 -1
  74. package/dest/sequencer/metrics.js +117 -21
  75. package/dest/sequencer/missing_committee.d.ts +72 -0
  76. package/dest/sequencer/missing_committee.d.ts.map +1 -0
  77. package/dest/sequencer/missing_committee.js +139 -0
  78. package/dest/sequencer/requests_tracker.d.ts +22 -0
  79. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  80. package/dest/sequencer/requests_tracker.js +33 -0
  81. package/dest/sequencer/sequencer.d.ts +182 -44
  82. package/dest/sequencer/sequencer.d.ts.map +1 -1
  83. package/dest/sequencer/sequencer.js +623 -216
  84. package/dest/sequencer/types.d.ts +2 -2
  85. package/dest/sequencer/types.d.ts.map +1 -1
  86. package/dest/test/index.d.ts +5 -7
  87. package/dest/test/index.d.ts.map +1 -1
  88. package/dest/test/mock_checkpoint_builder.d.ts +12 -12
  89. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  90. package/dest/test/mock_checkpoint_builder.js +45 -36
  91. package/dest/test/utils.d.ts +17 -3
  92. package/dest/test/utils.d.ts.map +1 -1
  93. package/dest/test/utils.js +28 -9
  94. package/package.json +29 -29
  95. package/src/client/sequencer-client.ts +110 -47
  96. package/src/config.ts +127 -55
  97. package/src/global_variable_builder/README.md +44 -0
  98. package/src/global_variable_builder/fee_predictor.ts +182 -0
  99. package/src/global_variable_builder/fee_provider.ts +97 -0
  100. package/src/global_variable_builder/global_builder.ts +20 -89
  101. package/src/global_variable_builder/index.ts +3 -1
  102. package/src/publisher/config.ts +173 -40
  103. package/src/publisher/index.ts +3 -0
  104. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  105. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  106. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +164 -0
  107. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
  108. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  109. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  110. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  111. package/src/publisher/sequencer-publisher.ts +885 -461
  112. package/src/publisher/write_json.ts +78 -0
  113. package/src/sequencer/README.md +162 -450
  114. package/src/sequencer/automine/README.md +60 -0
  115. package/src/sequencer/automine/automine_factory.ts +152 -0
  116. package/src/sequencer/automine/automine_sequencer.ts +800 -0
  117. package/src/sequencer/automine/index.ts +6 -0
  118. package/src/sequencer/checkpoint_proposal_job.ts +1131 -325
  119. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  120. package/src/sequencer/checkpoint_voter.ts +1 -12
  121. package/src/sequencer/events.ts +66 -5
  122. package/src/sequencer/metrics.ts +132 -25
  123. package/src/sequencer/missing_committee.ts +192 -0
  124. package/src/sequencer/requests_tracker.ts +43 -0
  125. package/src/sequencer/sequencer.ts +737 -241
  126. package/src/sequencer/types.ts +1 -1
  127. package/src/test/index.ts +4 -6
  128. package/src/test/mock_checkpoint_builder.ts +65 -53
  129. package/src/test/utils.ts +64 -10
  130. package/dest/sequencer/timetable.d.ts +0 -90
  131. package/dest/sequencer/timetable.d.ts.map +0 -1
  132. package/dest/sequencer/timetable.js +0 -226
  133. package/src/sequencer/timetable.ts +0 -282
@@ -372,29 +372,32 @@ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
372
372
  }
373
373
  var _dec, _dec1, _dec2, _dec3, _initProto;
374
374
  import { getKzg } from '@aztec/blob-lib';
375
- import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
375
+ import { PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
376
376
  import { NoCommitteeError } from '@aztec/ethereum/contracts';
377
- import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
377
+ import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
378
378
  import { merge, omit, pick } from '@aztec/foundation/collection';
379
- import { Fr } from '@aztec/foundation/curves/bn254';
380
379
  import { EthAddress } from '@aztec/foundation/eth-address';
381
380
  import { createLogger } from '@aztec/foundation/log';
382
381
  import { RunningPromise } from '@aztec/foundation/running-promise';
383
- import { getSlotAtTimestamp, getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
382
+ import { buildCheckpointSimulationOverridesPlan } from '@aztec/stdlib/checkpoint';
383
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
384
+ import { MIN_PER_BLOCK_ALLOCATION_MULTIPLIER, MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER, computeNetworkTxGasLimits } from '@aztec/stdlib/gas';
384
385
  import { SequencerConfigSchema } from '@aztec/stdlib/interfaces/server';
385
386
  import { pickFromSchema } from '@aztec/stdlib/schemas';
386
- import { MerkleTreeId } from '@aztec/stdlib/trees';
387
+ import { buildProposerTimetable } from '@aztec/stdlib/timetable';
387
388
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
388
389
  import EventEmitter from 'node:events';
389
390
  import { DefaultSequencerConfig } from '../config.js';
390
391
  import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
392
+ import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
391
393
  import { CheckpointVoter } from './checkpoint_voter.js';
392
- import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
394
+ import { SequencerInterruptedError } from './errors.js';
393
395
  import { SequencerMetrics } from './metrics.js';
394
- import { SequencerTimetable } from './timetable.js';
396
+ import { logMissingCommittee } from './missing_committee.js';
397
+ import { RequestsTracker } from './requests_tracker.js';
395
398
  import { SequencerState } from './utils.js';
396
399
  export { SequencerState };
397
- _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpointProposal'), _dec2 = trackSpan('Seqeuencer.tryVoteWhenSyncFails', ({ slot })=>({
400
+ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpointProposal'), _dec2 = trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot })=>({
398
401
  [Attributes.SLOT_NUMBER]: slot
399
402
  })), _dec3 = trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot })=>({
400
403
  [Attributes.SLOT_NUMBER]: slot
@@ -437,7 +440,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
437
440
  [
438
441
  _dec2,
439
442
  2,
440
- "tryVoteWhenSyncFails"
443
+ "tryVoteAndPruneWhenCannotBuild"
441
444
  ],
442
445
  [
443
446
  _dec3,
@@ -448,47 +451,161 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
448
451
  }
449
452
  runningPromise;
450
453
  state;
454
+ stateSlotNumber;
455
+ /** Wall-clock time (ms, via the date provider) at which the current state was entered. */ stateEnteredAtMs;
451
456
  metrics;
452
- /** The last slot for which we attempted to perform our voting duties with degraded block production */ lastSlotForFallbackVote;
457
+ checkpointProposalJobMetrics;
458
+ stateLog;
459
+ /** The last slot for which we attempted to perform our fallback duties (votes and/or prune) with degraded block production */ lastSlotForFallbackAction;
460
+ /** The (checkpoint, slot) of the last invalidation request we successfully simulated, to prevent
461
+ * re-simulating and re-submitting the same invalidation across the many ticks within a single slot. */ lastInvalidationAttempt;
462
+ /** The last epoch for which we logged a "no committee" diagnostic, to avoid per-slot log spam. */ lastEpochForNoCommitteeLog;
453
463
  /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */ lastSlotForCheckpointProposalJob;
454
464
  /** Last successful checkpoint proposed */ lastCheckpointProposed;
455
465
  /** The last epoch for which we logged strategy comparison in fisherman mode. */ lastEpochForStrategyComparison;
456
- /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */ timetable;
457
- // This shouldn't be here as this gets re-created each time we build/propose a block.
458
- // But we have a number of tests that abuse/rely on this class having a permanent publisher.
459
- // As long as those tests only configure a single publisher they will continue to work.
460
- // This will get re-assigned every time the sequencer goes to build a new block to a publisher that is valid
461
- // for the block proposer.
462
- // TODO(palla/mbps): Remove this field and fix tests
463
- publisher;
466
+ /** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */ lastCheckpointProposalJob;
467
+ /**
468
+ * In-flight fire-and-forget requests that {@link stop} interrupts and drains, and {@link pause} awaits
469
+ * untouched: the checkpoint proposal jobs' backgrounded L1 submissions (each job is handed this shared
470
+ * tracker) plus the sequencer's own fallback submissions (votes/prune when we cannot build, or
471
+ * escape-hatch votes). Each fallback send is gated by its wrapper publisher's interruptible target-slot
472
+ * sleep; the tracked interrupt wakes that sleep so the send short-circuits without publishing. A wrapper
473
+ * is created for a single send and is never restarted, so once interrupted its sleeper can never publish
474
+ * a stale-slot tx, even after the pooled publishers are restarted by a later {@link start}.
475
+ */ pendingRequests;
476
+ /** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */ timetable;
464
477
  /** Config for the sequencer */ config;
478
+ signatureContext;
465
479
  constructor(publisherFactory, validatorClient, globalsBuilder, p2pClient, worldState, slasherClient, l2BlockSource, l1ToL2MessageSource, checkpointsBuilder, l1Constants, dateProvider, epochCache, rollupContract, config, telemetry = getTelemetryClient(), log = createLogger('sequencer')){
466
- super(), this.publisherFactory = publisherFactory, this.validatorClient = validatorClient, this.globalsBuilder = globalsBuilder, this.p2pClient = p2pClient, this.worldState = worldState, this.slasherClient = slasherClient, this.l2BlockSource = l2BlockSource, this.l1ToL2MessageSource = l1ToL2MessageSource, this.checkpointsBuilder = checkpointsBuilder, this.l1Constants = l1Constants, this.dateProvider = dateProvider, this.epochCache = epochCache, this.rollupContract = rollupContract, this.telemetry = telemetry, this.log = log, this.state = (_initProto(this), SequencerState.STOPPED), this.config = DefaultSequencerConfig;
480
+ super(), this.publisherFactory = publisherFactory, this.validatorClient = validatorClient, this.globalsBuilder = globalsBuilder, this.p2pClient = p2pClient, this.worldState = worldState, this.slasherClient = slasherClient, this.l2BlockSource = l2BlockSource, this.l1ToL2MessageSource = l1ToL2MessageSource, this.checkpointsBuilder = checkpointsBuilder, this.l1Constants = l1Constants, this.dateProvider = dateProvider, this.epochCache = epochCache, this.rollupContract = rollupContract, this.telemetry = telemetry, this.log = log, this.state = (_initProto(this), SequencerState.STOPPED), this.pendingRequests = new RequestsTracker(), this.config = DefaultSequencerConfig;
481
+ this.stateLog = log.createChild('state');
482
+ this.stateEnteredAtMs = this.dateProvider.now();
467
483
  // Add [FISHERMAN] prefix to logger if in fisherman mode
468
484
  if (config.fishermanMode) {
469
485
  this.log = log.createChild('[FISHERMAN]');
470
486
  }
487
+ this.signatureContext = {
488
+ chainId: config.l1ChainId,
489
+ rollupAddress: config.rollupAddress
490
+ };
471
491
  this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
492
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
472
493
  this.updateConfig(config);
473
494
  }
474
- /** Updates sequencer config by the defined values and updates the timetable */ updateConfig(config) {
495
+ /**
496
+ * Updates sequencer config by the defined values and rebuilds the timetable.
497
+ *
498
+ * The merged config is validated against a candidate before being committed: {@link buildTimetable} may
499
+ * reject the candidate (invalid timing geometry, or per-block allocation multipliers below the network
500
+ * minimums). On rejection we leave `this.config` and `this.timetable` untouched and rethrow, so a bad update
501
+ * never leaves the sequencer running with a rejected config and a stale timetable.
502
+ */ updateConfig(config) {
475
503
  const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
476
- this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowList'));
477
- this.config = merge(this.config, filteredConfig);
478
- this.timetable = new SequencerTimetable({
479
- ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
480
- aztecSlotDuration: this.aztecSlotDuration,
481
- l1PublishingTime: this.l1PublishingTime,
482
- p2pPropagationTime: this.config.attestationPropagationTime,
483
- blockDurationMs: this.config.blockDurationMs,
484
- enforce: this.config.enforceTimeTable
485
- }, this.metrics, this.log);
504
+ const candidate = merge(this.config, filteredConfig);
505
+ let timetable;
506
+ try {
507
+ timetable = this.buildTimetable(candidate);
508
+ } catch (err) {
509
+ this.log.warn(`Rejecting sequencer config update: ${err.message}`, {
510
+ rejectedConfig: omit(filteredConfig, 'txPublicSetupAllowListExtend')
511
+ });
512
+ throw err;
513
+ }
514
+ this.config = candidate;
515
+ this.timetable = timetable;
516
+ this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
517
+ }
518
+ /**
519
+ * Builds the proposer timetable from the given config and L1 constants via the shared
520
+ * {@link buildProposerTimetable} helper, so the sequencer derives the same blocks-per-checkpoint as the p2p
521
+ * layer and `getNodeInfo`. The fast local/e2e profile and budget clamping happen inside
522
+ * {@link ProposerTimetable}.
523
+ *
524
+ * Throws if the timing geometry is invalid or the per-block allocation multipliers are below the network
525
+ * minimums; callers must treat a throw as a rejected config and not commit it.
526
+ */ buildTimetable(config) {
527
+ const timetable = buildProposerTimetable(config, this.l1Constants);
528
+ const maxNumberOfBlocks = timetable.getMaxBlocksPerCheckpoint();
529
+ this.log.info(`Sequencer timetable initialized with ${maxNumberOfBlocks} blocks per slot`, {
530
+ aztecSlotDuration: timetable.aztecSlotDuration,
531
+ ethereumSlotDuration: timetable.ethereumSlotDuration,
532
+ blockDuration: timetable.blockDuration,
533
+ minBlockDuration: timetable.minBlockDuration,
534
+ p2pPropagationTime: timetable.p2pPropagationTime,
535
+ checkpointProposalPrepareTime: timetable.checkpointProposalPrepareTime,
536
+ maxNumberOfBlocks
537
+ });
538
+ this.assertConfigMeetsNetworkTxLimits(config, maxNumberOfBlocks);
539
+ return timetable;
540
+ }
541
+ /**
542
+ * Checks this node's configured per-block allocation against the network admission limit. A node
543
+ * advertises and admits txs up to the limit derived from the network-minimum multipliers (see
544
+ * {@link computeNetworkTxGasLimits}).
545
+ *
546
+ * Fails startup (and runtime config updates) only when the configured per-block allocation *multipliers*
547
+ * (`perBlockAllocationMultiplier` / `perBlockDAAllocationMultiplier`) are below the network minimums: such
548
+ * a node would accept txs over RPC/gossip that its builder can never pack into a block regardless of block
549
+ * size. Operators may configure a higher (more generous) multiplier, but not a lower one.
550
+ *
551
+ * When the multipliers meet the floor but an absolute per-block gas cap (`maxDABlockGas` / `maxL2BlockGas`)
552
+ * shrinks the builder's effective grant below the network limit, this is legitimate operator
553
+ * restrictiveness — the node simply builds smaller blocks and such txs stay in the pool for other
554
+ * proposers — so we only log a warning rather than failing startup. Restrictive tx-count caps
555
+ * (`maxTxsPerBlock` / `maxTxsPerCheckpoint`) can likewise make the builder skip admitted txs; they are
556
+ * intentionally not modeled here for the same reason.
557
+ */ assertConfigMeetsNetworkTxLimits(config, maxBlocksPerCheckpoint) {
558
+ // Mirror CheckpointBuilder.capLimitsByCheckpointBudgets: DA falls back to the general multiplier.
559
+ const l2Multiplier = config.perBlockAllocationMultiplier;
560
+ const daMultiplier = config.perBlockDAAllocationMultiplier ?? l2Multiplier;
561
+ // The allocation is monotonic in the multiplier, so a multiplier at or above the network minimum
562
+ // guarantees the builder grants at least the network admission limit. Checking the multipliers directly
563
+ // is sufficient (and strictly more conservative than modeling the resulting gas grant).
564
+ if (daMultiplier < MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER) {
565
+ throw new Error(`perBlockDAAllocationMultiplier (${daMultiplier}) is below the network minimum ` + `${MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`);
566
+ }
567
+ if (l2Multiplier < MIN_PER_BLOCK_ALLOCATION_MULTIPLIER) {
568
+ throw new Error(`perBlockAllocationMultiplier (${l2Multiplier}) is below the network minimum ` + `${MIN_PER_BLOCK_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`);
569
+ }
570
+ // Absolute per-block gas caps below the network admission limit are legitimate operator restrictiveness:
571
+ // the node simply builds smaller blocks and such txs stay in the pool for other proposers. Warn only.
572
+ const networkLimit = computeNetworkTxGasLimits({
573
+ maxBlocksPerCheckpoint,
574
+ manaCheckpointBudget: this.l1Constants.rollupManaLimit
575
+ });
576
+ if (config.maxDABlockGas !== undefined && config.maxDABlockGas < networkLimit.daGas) {
577
+ this.log.warn(`Sequencer maxDABlockGas (${config.maxDABlockGas}) is below the network DA admission limit ` + `(${networkLimit.daGas}): txs declaring more DA gas are admitted over RPC/gossip but will be skipped ` + `by this proposer's own blocks and left in the pool for other proposers.`, {
578
+ maxDABlockGas: config.maxDABlockGas,
579
+ networkDaGas: networkLimit.daGas,
580
+ maxBlocksPerCheckpoint
581
+ });
582
+ }
583
+ if (config.maxL2BlockGas !== undefined && config.maxL2BlockGas < networkLimit.l2Gas) {
584
+ this.log.warn(`Sequencer maxL2BlockGas (${config.maxL2BlockGas}) is below the network L2 admission limit ` + `(${networkLimit.l2Gas}): txs declaring more L2 gas are admitted over RPC/gossip but will be skipped ` + `by this proposer's own blocks and left in the pool for other proposers.`, {
585
+ maxL2BlockGas: config.maxL2BlockGas,
586
+ networkL2Gas: networkLimit.l2Gas,
587
+ maxBlocksPerCheckpoint
588
+ });
589
+ }
486
590
  }
487
- /** Initializes the sequencer (precomputes tables and creates a publisher). Takes about 3s. */ async init() {
591
+ /** Initializes the sequencer (precomputes tables). Takes about 3s. */ init() {
488
592
  getKzg();
489
- this.publisher = (await this.publisherFactory.create(undefined)).publisher;
490
593
  }
491
- /** Starts the sequencer and moves to IDLE state. */ start() {
594
+ /**
595
+ * Starts (or restarts) the sequencer and moves it to the IDLE state. Idempotent: a start while already
596
+ * running is a no-op, so it never orphans the previous poll loop. A start while STOPPING throws, since the
597
+ * in-flight stop would mark the fresh loop's state STOPPED and orphan it — silently doing nothing would
598
+ * leave the caller believing the sequencer is running when it is on its way to STOPPED. Safe to call after
599
+ * a previous {@link stop} has resolved; the caller must also restart the publishers (see
600
+ * {@link SequencerClient.start}) so L1 publishing is re-enabled.
601
+ */ start() {
602
+ if (this.state === SequencerState.STOPPING) {
603
+ throw new Error('Cannot start sequencer while it is stopping');
604
+ }
605
+ if (this.runningPromise?.isRunning()) {
606
+ this.log.warn('Attempted to start sequencer that is already running');
607
+ return;
608
+ }
492
609
  this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.config.sequencerPollingIntervalMS);
493
610
  this.setState(SequencerState.IDLE, undefined, {
494
611
  force: true
@@ -496,18 +613,59 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
496
613
  this.runningPromise.start();
497
614
  this.log.info('Started sequencer');
498
615
  }
499
- /** Stops the sequencer from building blocks and moves to STOPPED state. */ async stop() {
616
+ /** Triggers an immediate run of the sequencer, bypassing the polling interval. */ trigger() {
617
+ return this.runningPromise?.trigger();
618
+ }
619
+ /**
620
+ * Stops the sequencer from building blocks and moves it to STOPPED state, interrupting the in-flight
621
+ * work() iteration and its pending L1 submissions for a fast shutdown, then draining before returning.
622
+ * Idempotent: a second call while already stopped or stopping is a no-op. Lifecycle calls are expected
623
+ * to be serialized by the caller. For a restartable pause that lets in-flight work finish untouched
624
+ * (e.g. around a test clock warp), use {@link pause} instead.
625
+ */ async stop() {
626
+ if (this.state === SequencerState.STOPPED || this.state === SequencerState.STOPPING) {
627
+ this.log.debug(`Sequencer already ${this.state.toLowerCase()}, ignoring stop`);
628
+ return;
629
+ }
500
630
  this.log.info(`Stopping sequencer`);
501
631
  this.setState(SequencerState.STOPPING, undefined, {
502
632
  force: true
503
633
  });
504
- this.publisher?.interrupt();
634
+ this.lastCheckpointProposalJob?.interrupt();
635
+ await this.publisherFactory.stopAll();
636
+ // Stop the poll loop and await the in-flight work() iteration. work() registers its fire-and-forget
637
+ // requests synchronously before returning, so once the loop has stopped, pendingRequests holds every
638
+ // request that will ever exist. Interrupting any earlier could miss a request registered by the last
639
+ // in-flight iteration.
505
640
  await this.runningPromise?.stop();
641
+ this.pendingRequests.interruptRequests();
642
+ await this.pendingRequests.awaitRequests();
506
643
  this.setState(SequencerState.STOPPED, undefined, {
507
644
  force: true
508
645
  });
509
646
  this.log.info('Stopped sequencer');
510
647
  }
648
+ /**
649
+ * Gracefully pauses block production so the sequencer can later be resumed with {@link start}: halts the
650
+ * poll loop and waits for the in-flight work() iteration and every pending L1 submission / fallback send
651
+ * to finish, without interrupting them. No interrupt lands mid-build, so no spurious checkpoint-error is
652
+ * emitted and no enqueued checkpoint is dropped. Deliberately does not stop inner services (validator/HA
653
+ * signer, publishers), so the slashing-protection store stays open and the sequencer stays restartable.
654
+ * Used by tests that pause sequencers around an L1 clock warp. Idempotent.
655
+ */ async pause() {
656
+ if (!this.runningPromise?.isRunning()) {
657
+ this.log.debug('Sequencer not running, ignoring pause');
658
+ return;
659
+ }
660
+ this.log.info('Pausing sequencer');
661
+ // Halt the poll loop and let the in-flight iteration finish naturally — no interrupt, and no STOPPING
662
+ // state, since entering STOPPING would make the iteration's own setState calls throw and fail it.
663
+ // work() registers its fire-and-forget requests synchronously before returning, so once the loop has
664
+ // stopped pendingRequests holds every request that will ever exist; awaiting it lets them all finish.
665
+ await this.runningPromise.stop();
666
+ await this.pendingRequests.awaitRequests();
667
+ this.log.info('Paused sequencer');
668
+ }
511
669
  /** Main sequencer loop with a try/catch */ async safeWork() {
512
670
  try {
513
671
  await this.work();
@@ -515,20 +673,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
515
673
  this.emit('checkpoint-error', {
516
674
  error: err
517
675
  });
518
- if (err instanceof SequencerTooSlowError) {
519
- // TODO(palla/mbps): Add missing states
520
- // Log as warn only if we had to abort halfway through the block proposal
521
- const logLvl = [
522
- SequencerState.INITIALIZING_CHECKPOINT,
523
- SequencerState.PROPOSER_CHECK
524
- ].includes(err.proposedState) ? 'debug' : 'warn';
525
- this.log[logLvl](err.message, {
526
- now: this.dateProvider.nowInSeconds()
527
- });
528
- } else {
529
- // Re-throw other errors
530
- throw err;
531
- }
676
+ throw err;
532
677
  } finally{
533
678
  this.setState(SequencerState.IDLE, undefined);
534
679
  }
@@ -547,63 +692,76 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
547
692
  * - Submit checkpoint
548
693
  */ async work() {
549
694
  this.setState(SequencerState.SYNCHRONIZING, undefined);
550
- const { slot, ts, now, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
695
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
551
696
  // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
552
- const checkpointProposalJob = await this.prepareCheckpointProposal(epoch, slot, ts, now);
697
+ const checkpointProposalJob = await this.prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds);
553
698
  if (!checkpointProposalJob) {
554
699
  return;
555
700
  }
701
+ // Track the job so we can await its pending L1 submission during shutdown
702
+ this.lastCheckpointProposalJob = checkpointProposalJob;
556
703
  // Execute the checkpoint proposal job
557
704
  const checkpoint = await checkpointProposalJob.execute();
558
705
  // Update last checkpoint proposed (currently unused)
559
706
  if (checkpoint) {
560
707
  this.lastCheckpointProposed = checkpoint;
561
708
  }
562
- // Log fee strategy comparison if on fisherman
563
- if (this.config.fishermanMode && (this.lastEpochForStrategyComparison === undefined || epoch > this.lastEpochForStrategyComparison)) {
564
- this.logStrategyComparison(epoch, checkpointProposalJob.getPublisher());
565
- this.lastEpochForStrategyComparison = epoch;
709
+ // Log fee strategy comparison if on fisherman (uses target epoch since we mirror the proposer's perspective)
710
+ if (this.config.fishermanMode && (this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)) {
711
+ this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
712
+ this.lastEpochForStrategyComparison = targetEpoch;
566
713
  }
567
714
  return checkpoint;
568
715
  }
716
+ /** Returns slot and target slot from a single clock snapshot. */ getSlotContextInNextL1Slot() {
717
+ const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
718
+ const targetSlot = SlotNumber(slot + PROPOSER_PIPELINING_SLOT_OFFSET);
719
+ return {
720
+ slot,
721
+ targetSlot,
722
+ epoch,
723
+ targetEpoch: getEpochAtSlot(targetSlot, this.l1Constants),
724
+ ts,
725
+ nowSeconds
726
+ };
727
+ }
569
728
  /**
570
729
  * Prepares the checkpoint proposal by performing all necessary checks and setup.
571
730
  * This is the initial step in the main loop.
572
731
  * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
573
- */ async prepareCheckpointProposal(epoch, slot, ts, now) {
574
- // Check we have not already processed this slot (cheapest check)
575
- // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
576
- // running against actual time (eg when we use sandbox-style automining)
577
- if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= slot && this.config.enforceTimeTable) {
578
- this.log.trace(`Slot ${slot} has already been processed`);
732
+ */ async prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds) {
733
+ // Check we have not already processed this target slot (cheapest check).
734
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot) {
735
+ this.log.trace(`Target slot ${targetSlot} has already been processed`);
579
736
  return undefined;
580
737
  }
581
- // But if we have already proposed for this slot, the we definitely have to skip it, automining or not
582
- if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= slot) {
583
- this.log.trace(`Slot ${slot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`);
738
+ // But if we have already proposed for this slot, then we definitely have to skip it, automining or not
739
+ if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= targetSlot) {
740
+ this.log.trace(`Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`);
584
741
  return undefined;
585
742
  }
586
- // Check all components are synced to latest as seen by the archiver (queries all subsystems)
587
- const syncedTo = await this.checkSync({
588
- ts,
589
- slot
590
- });
591
- if (!syncedTo) {
592
- await this.tryVoteWhenSyncFails({
593
- slot,
594
- ts
743
+ // Test-only: skip proposing for explicitly paused slots. Attestation paths run in the validator
744
+ // client and are not gated by this hook, so paused proposers still attest to others' proposals.
745
+ if (this.config.pauseProposingForSlots?.some((s)=>s === targetSlot)) {
746
+ this.log.warn(`Skipping proposal for paused slot ${targetSlot} (test-only pauseProposingForSlots hook)`, {
747
+ targetSlot
595
748
  });
596
749
  return undefined;
597
750
  }
598
- // If escape hatch is open for this epoch, do not start checkpoint proposal work and do not attempt invalidations.
751
+ // Cheap proposer check first: most nodes are not the proposer for most slots, so gate the
752
+ // expensive multi-subsystem checkSync (and the rest of the build path) behind it. Computed once
753
+ // here and reused for the escape-hatch voting path below. No setState/timing gate on this path:
754
+ // the build-start deadline gate runs only on the proposer build path after a successful checkSync.
755
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
756
+ // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
599
757
  // Still perform governance/slashing voting (as proposer) once per slot.
600
- const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(epoch);
758
+ // When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
759
+ const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
601
760
  if (isEscapeHatchOpen) {
602
- this.setState(SequencerState.PROPOSER_CHECK, slot);
603
- const [canPropose, proposer] = await this.checkCanPropose(slot);
604
761
  if (canPropose) {
605
762
  await this.tryVoteWhenEscapeHatchOpen({
606
763
  slot,
764
+ targetSlot,
607
765
  proposer
608
766
  });
609
767
  } else {
@@ -615,32 +773,84 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
615
773
  }
616
774
  return undefined;
617
775
  }
776
+ // If we are not the proposer, check whether we should invalidate an invalid pending chain (a
777
+ // liveness backstop) and bail before any sync work or build-timing gate. This reads only the
778
+ // archiver's pending-chain validation status, which is authoritative on its own, instead of
779
+ // running the full sync check. Wrapped in try/catch because this leaner path skips the broader
780
+ // proposed-checkpoint/tip coherence screen that checkSync applied, so transient archiver
781
+ // incoherence surfaces as a quiet skip rather than a work-loop error.
782
+ if (!canPropose) {
783
+ try {
784
+ const pendingChainValidationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
785
+ await this.considerInvalidatingCheckpoint(pendingChainValidationStatus, slot);
786
+ } catch (err) {
787
+ this.log.warn(`Failed to consider invalidating checkpoint`, {
788
+ err,
789
+ slot,
790
+ targetSlot
791
+ });
792
+ }
793
+ return undefined;
794
+ }
795
+ // Explicit build-loop entry gate: if we are past the latest useful block-building start for the
796
+ // target slot, abandon building for this slot. The proposer prioritizes the ideal L1-publish path
797
+ // and does not plan around the late consensus-handoff path. This is the proposer build path's
798
+ // timing gate; it runs only after we know we are the synced proposer, so non-proposer invalidation
799
+ // and escape-hatch voting (which returned above) are never gated by build timing. Vote-only paths
800
+ // still run when block building is abandoned.
801
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
802
+ const nowForStartGate = this.dateProvider.now() / 1000;
803
+ if (nowForStartGate > startDeadline) {
804
+ this.log.debug(`Past start deadline for slot ${targetSlot}, abandoning block building`, {
805
+ targetSlot,
806
+ nowForStartGate,
807
+ startDeadline
808
+ });
809
+ // Mark the slot as attempted so a deadline abort is not retried within the same slot. Vote-only actions
810
+ // still need to run because sync can succeed even when it is too late to start building a checkpoint.
811
+ await this.tryVoteAndPruneWhenCannotBuild({
812
+ slot,
813
+ targetSlot
814
+ });
815
+ this.lastSlotForCheckpointProposalJob = targetSlot;
816
+ return undefined;
817
+ }
818
+ // We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
819
+ // Now run the full sync check before building.
820
+ const syncedTo = await this.checkSync({
821
+ ts,
822
+ slot
823
+ });
824
+ if (!syncedTo) {
825
+ return undefined;
826
+ }
618
827
  // Next checkpoint follows from the last synced one
619
828
  const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
620
829
  const logCtx = {
621
- now,
622
- syncedToL1Ts: syncedTo.l1Timestamp,
623
- syncedToL2Slot: getSlotAtTimestamp(syncedTo.l1Timestamp, this.l1Constants),
830
+ nowSeconds,
831
+ syncedToL2Slot: syncedTo.syncedL2Slot,
624
832
  slot,
833
+ targetSlot,
625
834
  slotTs: ts,
626
835
  checkpointNumber,
627
836
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex')
628
837
  };
629
- // Check that we are a proposer for the next slot
630
- this.setState(SequencerState.PROPOSER_CHECK, slot);
631
- const [canPropose, proposer] = await this.checkCanPropose(slot);
632
- // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
633
- if (!canPropose) {
634
- await this.considerInvalidatingCheckpoint(syncedTo, slot);
838
+ // We are the synced proposer within the build window; enter the proposer-check state and build.
839
+ this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
840
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
841
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
842
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
843
+ if (checkpointNumber > confirmedCkpt + 2) {
844
+ this.log.verbose(`Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`);
635
845
  return undefined;
636
846
  }
637
- // Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
638
- if (syncedTo.block && syncedTo.block.header.getSlot() >= slot) {
639
- this.log.warn(`Cannot propose block at next L2 slot ${slot} since that slot was taken by block ${syncedTo.blockNumber}`, {
847
+ // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
848
+ if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
849
+ this.log.warn(`Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`, {
640
850
  ...logCtx,
641
- block: syncedTo.block.header.toInspect()
851
+ block: syncedTo.blockData.header.toInspect()
642
852
  });
643
- this.metrics.recordBlockProposalPrecheckFailed('slot_already_taken');
853
+ this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
644
854
  return undefined;
645
855
  }
646
856
  // We now need to get ourselves a publisher.
@@ -650,42 +860,109 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
650
860
  const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
651
861
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
652
862
  this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
653
- this.publisher = publisher;
654
- // In fisherman mode, set the actual proposer's address for simulations
655
- if (this.config.fishermanMode && proposer) {
656
- publisher.setProposerAddressForSimulation(proposer);
657
- this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
658
- }
659
- // Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
660
- const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
661
- // Check with the rollup contract if we can indeed propose at the next L2 slot. This check should not fail
662
- // if all the previous checks are good, but we do it just in case.
663
- const canProposeCheck = await publisher.canProposeAtNextEthBlock(syncedTo.archive, proposer ?? EthAddress.ZERO, invalidateCheckpoint);
863
+ // Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
864
+ // Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
865
+ // will invalidate the currently invalid checkpoint on L1.
866
+ const invalidateCheckpoint = syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid ? undefined : await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
867
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
868
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
869
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
870
+ let archiveForCheck = syncedTo.archive;
871
+ if (syncedTo.hasProposedCheckpoint) {
872
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
873
+ this.log.verbose(`Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`, {
874
+ targetSlot,
875
+ parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1)
876
+ });
877
+ // Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
878
+ // own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
879
+ // view and can transiently diverge from the proposed parent (e.g. before the proposed
880
+ // parent's blocks have been applied locally); diverging here would cause the canProposeAt
881
+ // override to set archives[pending] to one value while we present another for comparison.
882
+ archiveForCheck = syncedTo.proposedCheckpointData.archive.root;
883
+ } else if (invalidateCheckpoint) {
884
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
885
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
886
+ archiveForCheck = invalidateCheckpoint.lastArchive;
887
+ this.metrics.recordPipelineDepth(0);
888
+ } else {
889
+ this.metrics.recordPipelineDepth(0);
890
+ }
891
+ // Build the simulation plan: pending/proven override from pipelining or invalidation (or the
892
+ // current snapshot when neither applies, to short-circuit any pending prune in simulation),
893
+ // plus the parent checkpoint cell and fee header when pipelining.
894
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
895
+ checkpointNumber,
896
+ proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
897
+ invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
898
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
899
+ rollup: this.rollupContract,
900
+ signatureContext: this.signatureContext,
901
+ log: this.log
902
+ });
903
+ // The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
904
+ // so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
905
+ // simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
906
+ // actually fire at the target slot without it — so observers can spot "we are building
907
+ // optimistically across a pruning boundary" in the logs.
908
+ const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
909
+ if (provenOverride !== undefined && await this.l2BlockSource.isPruneDueAtSlot(targetSlot)) {
910
+ this.log.warn(`Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`, {
911
+ checkpointNumber,
912
+ slot,
913
+ targetSlot,
914
+ provenOverride
915
+ });
916
+ }
917
+ this.emit('preparing-checkpoint', {
918
+ targetSlot,
919
+ checkpointNumber,
920
+ hadProposedParent: syncedTo.hasProposedCheckpoint,
921
+ provenOverride,
922
+ simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending
923
+ });
924
+ const canProposeCheck = await publisher.canProposeAt(archiveForCheck, proposer ?? EthAddress.ZERO, simulationOverridesPlan);
925
+ const proposeContext = {
926
+ hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
927
+ proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
928
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
929
+ isInvalidating: !!invalidateCheckpoint,
930
+ invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
931
+ archiveForCheck: archiveForCheck.toString(),
932
+ overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
933
+ overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
934
+ overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader
935
+ };
664
936
  if (canProposeCheck === undefined) {
665
- this.log.warn(`Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`, logCtx);
937
+ this.log.warn(`Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`, {
938
+ ...logCtx,
939
+ ...proposeContext
940
+ });
666
941
  this.emit('proposer-rollup-check-failed', {
667
942
  reason: 'Rollup contract check failed',
668
943
  slot
669
944
  });
670
- this.metrics.recordBlockProposalPrecheckFailed('rollup_contract_check_failed');
945
+ this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
671
946
  return undefined;
672
947
  }
673
- if (canProposeCheck.slot !== slot) {
674
- this.log.warn(`Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${slot} but got ${canProposeCheck.slot}.`, {
948
+ if (canProposeCheck.slot !== targetSlot) {
949
+ this.log.warn(`Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${targetSlot} but got ${canProposeCheck.slot}.`, {
675
950
  ...logCtx,
951
+ ...proposeContext,
676
952
  rollup: canProposeCheck,
677
- expectedSlot: slot
953
+ expectedSlot: targetSlot
678
954
  });
679
955
  this.emit('proposer-rollup-check-failed', {
680
956
  reason: 'Slot mismatch',
681
957
  slot
682
958
  });
683
- this.metrics.recordBlockProposalPrecheckFailed('slot_mismatch');
959
+ this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
684
960
  return undefined;
685
961
  }
686
962
  if (canProposeCheck.checkpointNumber !== checkpointNumber) {
687
963
  this.log.warn(`Cannot propose due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected checkpoint ${checkpointNumber} but got ${canProposeCheck.checkpointNumber}.`, {
688
964
  ...logCtx,
965
+ ...proposeContext,
689
966
  rollup: canProposeCheck,
690
967
  expectedSlot: slot
691
968
  });
@@ -693,24 +970,33 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
693
970
  reason: 'Block mismatch',
694
971
  slot
695
972
  });
696
- this.metrics.recordBlockProposalPrecheckFailed('block_number_mismatch');
973
+ this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
697
974
  return undefined;
698
975
  }
699
- this.lastSlotForCheckpointProposalJob = slot;
700
- this.log.info(`Preparing checkpoint proposal ${checkpointNumber} at slot ${slot}`, {
976
+ this.lastSlotForCheckpointProposalJob = targetSlot;
977
+ await this.p2pClient.prepareForSlot(targetSlot);
978
+ this.log.info(`Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`, {
701
979
  ...logCtx,
980
+ ...proposeContext,
702
981
  proposer
703
982
  });
704
983
  // Create and return the checkpoint proposal job
705
- return this.createCheckpointProposalJob(epoch, slot, checkpointNumber, syncedTo.blockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint);
984
+ return this.createCheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedTo.blockNumber, syncedTo.checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, syncedTo.proposedCheckpointData);
706
985
  }
707
- createCheckpointProposalJob(epoch, slot, checkpointNumber, syncedToBlockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint) {
708
- return new CheckpointProposalJob(epoch, slot, checkpointNumber, syncedToBlockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, this.validatorClient, this.globalsBuilder, this.p2pClient, this.worldState, this.l1ToL2MessageSource, this.l2BlockSource, this.checkpointsBuilder, this.l2BlockSource, this.l1Constants, this.config, this.timetable, this.slasherClient, this.epochCache, this.dateProvider, this.metrics, this, this.setState.bind(this), this.tracer, this.log.getBindings());
986
+ createCheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, proposedCheckpointData) {
987
+ return new CheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, this.validatorClient, this.globalsBuilder, this.p2pClient, this.worldState, this.l1ToL2MessageSource, this.l2BlockSource, this.checkpointsBuilder, this.l2BlockSource, this.l1Constants, this.signatureContext, this.config, this.timetable, this.slasherClient, this.epochCache, this.dateProvider, this.metrics, this.checkpointProposalJobMetrics.createRecorder(), this, this.pendingRequests, this.setState.bind(this), this.tracer, this.log.getBindings(), proposedCheckpointData);
709
988
  }
710
989
  /**
711
- * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
990
+ * Returns the current sequencer state.
991
+ */ getState() {
992
+ return this.state;
993
+ }
994
+ /**
995
+ * Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
996
+ * records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
712
997
  * @param proposedState - The new state to transition to.
713
- * @param slotNumber - The current slot number.
998
+ * @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
999
+ * and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
714
1000
  * @param force - Whether to force the transition even if the sequencer is stopped.
715
1001
  */ setState(proposedState, slotNumber, opts = {}) {
716
1002
  if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
@@ -721,42 +1007,55 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
721
1007
  this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
722
1008
  return;
723
1009
  }
724
- let secondsIntoSlot = undefined;
725
- if (slotNumber !== undefined) {
726
- secondsIntoSlot = this.getSecondsIntoSlot(slotNumber);
727
- this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
728
- }
1010
+ const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
1011
+ const oldState = this.state;
1012
+ const oldStateSlotNumber = this.stateSlotNumber;
1013
+ const stateChanged = proposedState !== oldState;
1014
+ // Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
1015
+ // calls, read from the date provider so it tracks simulated time under a test/manual clock.
1016
+ const transitionAtMs = this.dateProvider.now();
1017
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
729
1018
  const boringStates = [
730
1019
  SequencerState.IDLE,
731
1020
  SequencerState.SYNCHRONIZING
732
1021
  ];
733
- const logLevel = boringStates.includes(proposedState) && boringStates.includes(this.state) ? 'trace' : 'debug';
734
- this.log[logLevel](`Transitioning from ${this.state} to ${proposedState}`, {
1022
+ const logLevel = boringStates.includes(proposedState) && boringStates.includes(oldState) ? 'trace' : 'debug';
1023
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
1024
+ oldState,
1025
+ newState: proposedState,
735
1026
  slotNumber,
736
- secondsIntoSlot
1027
+ stateSlotNumber: oldStateSlotNumber,
1028
+ secondsIntoBuildFrame,
1029
+ ...stateChanged && {
1030
+ stateDurationMs: Math.ceil(stateDurationMs)
1031
+ }
737
1032
  });
738
1033
  this.emit('state-changed', {
739
- oldState: this.state,
1034
+ oldState,
740
1035
  newState: proposedState,
741
- secondsIntoSlot,
742
- slot: slotNumber
1036
+ secondsIntoBuildFrame,
1037
+ targetSlot: slotNumber
743
1038
  });
1039
+ if (stateChanged) {
1040
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
1041
+ this.stateEnteredAtMs = transitionAtMs;
1042
+ this.stateSlotNumber = slotNumber;
1043
+ }
744
1044
  this.state = proposedState;
745
1045
  }
746
1046
  /**
747
1047
  * Returns whether all dependencies have caught up.
748
1048
  * We don't check against the previous block submitted since it may have been reorg'd out.
749
1049
  */ async checkSync(args) {
750
- // Check that the archiver and dependencies have synced to the previous L1 slot at least
751
- // TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
752
- // cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
753
- const l1Timestamp = await this.l2BlockSource.getL1Timestamp();
754
- const { slot, ts } = args;
755
- if (l1Timestamp === undefined || l1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration) < ts) {
1050
+ // Check that the archiver has fully synced the L2 slot before the one we want to propose in.
1051
+ // The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
1052
+ // See getSyncedL2SlotNumber for how missed L1 blocks are handled.
1053
+ const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
1054
+ const { slot } = args;
1055
+ if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
756
1056
  this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
757
1057
  slot,
758
- ts,
759
- l1Timestamp
1058
+ syncedL2Slot
760
1059
  });
761
1060
  return undefined;
762
1061
  }
@@ -765,68 +1064,115 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
765
1064
  number: syncSummary.latestBlockNumber,
766
1065
  hash: syncSummary.latestBlockHash
767
1066
  })),
768
- this.l2BlockSource.getL2Tips().then((t)=>t.proposed),
1067
+ this.l2BlockSource.getL2Tips().then((t)=>({
1068
+ proposed: t.proposed,
1069
+ checkpointed: t.checkpointed
1070
+ })),
769
1071
  this.p2pClient.getStatus().then((p2p)=>p2p.syncedToL2Block),
770
- this.l1ToL2MessageSource.getL2Tips().then((t)=>t.proposed),
771
- this.l2BlockSource.getPendingChainValidationStatus()
1072
+ this.l1ToL2MessageSource.getL2Tips().then((t)=>({
1073
+ proposed: t.proposed,
1074
+ checkpointed: t.checkpointed
1075
+ })),
1076
+ this.l2BlockSource.getPendingChainValidationStatus(),
1077
+ this.l2BlockSource.getProposedCheckpointData()
772
1078
  ]);
773
- const [worldState, l2BlockSource, p2p, l1ToL2MessageSource, pendingChainValidationStatus] = syncedBlocks;
774
- // Handle zero as a special case, since the block hash won't match across services if we're changing the prefilled data for the genesis block,
775
- // as the world state can compute the new genesis block hash, but other components use the hardcoded constant.
776
- // TODO(palla/mbps): Fix the above. All components should be able to handle dynamic genesis block hashes.
777
- const result = l2BlockSource.number === 0 && worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSource.number === 0 || worldState.hash === l2BlockSource.hash && p2p.hash === l2BlockSource.hash && l1ToL2MessageSource.hash === l2BlockSource.hash;
1079
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] = syncedBlocks;
1080
+ const result = worldState.hash === l2Tips.proposed.hash && p2p.hash === l2Tips.proposed.hash && l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash && l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash && l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
778
1081
  if (!result) {
779
1082
  this.log.debug(`Sequencer sync check failed`, {
780
1083
  worldState,
781
- l2BlockSource,
1084
+ l2BlockSource: l2Tips.proposed,
782
1085
  p2p,
783
- l1ToL2MessageSource
1086
+ l1ToL2MessageSourceTips
784
1087
  });
785
1088
  return undefined;
786
1089
  }
787
- // Special case for genesis state
788
1090
  const blockNumber = worldState.number;
789
- if (blockNumber < INITIAL_L2_BLOCK_NUM) {
790
- const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
791
- return {
792
- checkpointNumber: CheckpointNumber.ZERO,
793
- blockNumber: BlockNumber.ZERO,
794
- archive,
795
- l1Timestamp,
796
- pendingChainValidationStatus
1091
+ const blockData = await this.l2BlockSource.getBlockData({
1092
+ number: blockNumber
1093
+ });
1094
+ if (!blockData) {
1095
+ this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
1096
+ blockNumber,
1097
+ l2Tips,
1098
+ syncedL2Slot,
1099
+ ...args
1100
+ });
1101
+ return undefined;
1102
+ }
1103
+ // Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
1104
+ // proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
1105
+ // our world-state tip past the checkpointed tip — while the proposing node never published the
1106
+ // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
1107
+ // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
1108
+ // once their build slot ends; this guard is the correctness barrier during the grace window before.
1109
+ // `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
1110
+ // the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
1111
+ // on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
1112
+ if (blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number && proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber) {
1113
+ const logCtx = {
1114
+ blockCheckpointNumber: blockData.checkpointNumber,
1115
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
1116
+ proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
1117
+ blockNumber: blockData.header.getBlockNumber(),
1118
+ blockSlot: blockData.header.getSlot(),
1119
+ syncedL2Slot,
1120
+ ...args
797
1121
  };
1122
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
1123
+ return undefined;
798
1124
  }
799
- const block = await this.l2BlockSource.getL2Block(blockNumber);
800
- if (!block) {
801
- // this shouldn't really happen because a moment ago we checked that all components were in sync
802
- this.log.error(`Failed to get L2 block ${blockNumber} from the archiver with all components in sync`);
1125
+ const hasProposedCheckpoint = proposedCheckpointData !== undefined;
1126
+ // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
1127
+ // The checkpoint number to build is derived as blockData.checkpointNumber + 1
1128
+ if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
1129
+ this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
1130
+ proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
1131
+ blockCheckpointNumber: blockData.checkpointNumber,
1132
+ syncedL2Slot,
1133
+ ...args
1134
+ });
803
1135
  return undefined;
804
1136
  }
805
1137
  return {
806
- block,
807
- blockNumber: block.number,
808
- checkpointNumber: block.checkpointNumber,
809
- archive: block.archive.root,
810
- l1Timestamp,
1138
+ blockData,
1139
+ blockNumber: blockData.header.getBlockNumber(),
1140
+ checkpointNumber: blockData.checkpointNumber,
1141
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
1142
+ archive: blockData.archive.root,
1143
+ hasProposedCheckpoint,
1144
+ proposedCheckpointData,
1145
+ syncedL2Slot,
811
1146
  pendingChainValidationStatus
812
1147
  };
813
1148
  }
814
1149
  /**
815
1150
  * Checks if we are the proposer for the next slot.
816
1151
  * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
817
- */ async checkCanPropose(slot) {
1152
+ */ async checkCanPropose(targetSlot) {
818
1153
  let proposer;
819
1154
  try {
820
- proposer = await this.epochCache.getProposerAttesterAddressInSlot(slot);
1155
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
821
1156
  } catch (e) {
822
1157
  if (e instanceof NoCommitteeError) {
823
- this.log.warn(`Cannot propose at next L2 slot ${slot} since the committee does not exist on L1`);
1158
+ const targetEpoch = getEpochAtSlot(targetSlot, this.l1Constants);
1159
+ if (this.lastEpochForNoCommitteeLog !== targetEpoch) {
1160
+ this.lastEpochForNoCommitteeLog = targetEpoch;
1161
+ await logMissingCommittee(targetSlot, targetEpoch, {
1162
+ epochCache: this.epochCache,
1163
+ rollupContract: this.rollupContract,
1164
+ l2BlockSource: this.l2BlockSource,
1165
+ l1Constants: this.l1Constants,
1166
+ dateProvider: this.dateProvider,
1167
+ logger: this.log
1168
+ });
1169
+ }
824
1170
  return [
825
1171
  false,
826
1172
  undefined
827
1173
  ];
828
1174
  }
829
- this.log.error(`Error getting proposer for slot ${slot}`, e);
1175
+ this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
830
1176
  return [
831
1177
  false,
832
1178
  undefined
@@ -849,7 +1195,8 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
849
1195
  const validatorAddresses = this.validatorClient.getValidatorAddresses();
850
1196
  const weAreProposer = validatorAddresses.some((addr)=>addr.equals(proposer));
851
1197
  if (!weAreProposer) {
852
- this.log.debug(`Cannot propose at slot ${slot} since we are not a proposer`, {
1198
+ this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
1199
+ targetSlot,
853
1200
  validatorAddresses,
854
1201
  proposer
855
1202
  });
@@ -858,39 +1205,37 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
858
1205
  proposer
859
1206
  ];
860
1207
  }
1208
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
1209
+ targetSlot,
1210
+ proposer
1211
+ });
861
1212
  return [
862
1213
  true,
863
1214
  proposer
864
1215
  ];
865
1216
  }
866
1217
  /**
867
- * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
868
- * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
869
- */ async tryVoteWhenSyncFails(args) {
870
- const { slot } = args;
1218
+ * Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
1219
+ * block-building window. This allows the sequencer to participate in governance/slashing votes even when it
1220
+ * cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
1221
+ */ async tryVoteAndPruneWhenCannotBuild(args) {
1222
+ const { slot, targetSlot } = args;
871
1223
  // Prevent duplicate attempts in the same slot
872
- if (this.lastSlotForFallbackVote === slot) {
873
- this.log.trace(`Already attempted to vote in slot ${slot} (skipping)`);
1224
+ if (this.lastSlotForFallbackAction === slot) {
1225
+ this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
874
1226
  return;
875
1227
  }
876
- // Check if we're past the max time for initializing a proposal
877
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
878
- const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_CHECKPOINT);
879
- // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
880
- // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
881
- if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
882
- this.log.trace(`Not attempting to vote since there is still time for block building`, {
883
- secondsIntoSlot,
884
- maxAllowedTime
885
- });
886
- return;
887
- }
888
- this.log.trace(`Sync for slot ${slot} failed, checking for voting opportunities`, {
889
- secondsIntoSlot,
890
- maxAllowedTime
1228
+ // Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
1229
+ // Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
1230
+ // build-start deadline can miss the whole fallback window when the target advances with the clock.
1231
+ const nowSeconds = this.dateProvider.now() / 1000;
1232
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
1233
+ this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
1234
+ nowSeconds,
1235
+ startDeadline
891
1236
  });
892
1237
  // Check if we're a proposer or proposal is open
893
- const [canPropose, proposer] = await this.checkCanPropose(slot);
1238
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
894
1239
  if (!canPropose) {
895
1240
  this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, {
896
1241
  slot,
@@ -899,44 +1244,76 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
899
1244
  return;
900
1245
  }
901
1246
  // Mark this slot as attempted
902
- this.lastSlotForFallbackVote = slot;
1247
+ this.lastSlotForFallbackAction = slot;
903
1248
  // Get a publisher for voting
904
1249
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
905
1250
  this.log.debug(`Attempting to vote despite sync failure at slot ${slot}`, {
906
1251
  attestorAddress,
907
1252
  slot
908
1253
  });
909
- // Enqueue governance and slashing votes
910
- const voter = new CheckpointVoter(slot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
1254
+ // Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
1255
+ const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
911
1256
  const votesPromises = voter.enqueueVotes();
912
1257
  const votes = await Promise.all(votesPromises);
913
- if (votes.every((p)=>!p)) {
914
- this.log.debug(`No votes to enqueue for slot ${slot}`);
1258
+ // Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
1259
+ // recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
1260
+ const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
1261
+ // Bail if nothing to do
1262
+ if (votes.every((p)=>!p) && !pruneEnqueued) {
1263
+ this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
915
1264
  return;
916
1265
  }
917
- this.log.info(`Voting in slot ${slot} despite sync failure`, {
918
- slot
1266
+ const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
1267
+ this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
1268
+ slot,
1269
+ pruneEnqueued,
1270
+ governanceVoteEnqueued: !!governanceVoteEnqueued,
1271
+ slashingVoteEnqueued: !!slashingVoteEnqueued
1272
+ });
1273
+ // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
1274
+ // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
1275
+ // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
1276
+ // work loop while waiting for the target slot to start, but track it so stop() can drain it.
1277
+ const send = publisher.sendRequestsAt(targetSlot).catch((err)=>{
1278
+ this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, {
1279
+ slot
1280
+ });
919
1281
  });
920
- await publisher.sendRequests();
1282
+ this.pendingRequests.trackRequest(send, ()=>publisher.interrupt());
1283
+ }
1284
+ async tryEnqueuePruneIfPrunable(targetSlot, publisher) {
1285
+ try {
1286
+ return await publisher.enqueuePruneIfPrunable(targetSlot);
1287
+ } catch (err) {
1288
+ this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, {
1289
+ targetSlot
1290
+ });
1291
+ return false;
1292
+ }
921
1293
  }
922
1294
  /**
923
1295
  * Tries to vote on slashing actions and governance proposals when escape hatch is open.
924
1296
  * This allows the sequencer to participate in voting without performing checkpoint proposal work.
925
1297
  */ async tryVoteWhenEscapeHatchOpen(args) {
926
- const { slot, proposer } = args;
1298
+ const { slot, targetSlot, proposer } = args;
927
1299
  // Prevent duplicate attempts in the same slot
928
- if (this.lastSlotForFallbackVote === slot) {
1300
+ if (this.lastSlotForFallbackAction === slot) {
929
1301
  this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
930
1302
  return;
931
1303
  }
932
1304
  // Mark this slot as attempted
933
- this.lastSlotForFallbackVote = slot;
1305
+ this.lastSlotForFallbackAction = slot;
934
1306
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
935
1307
  this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
936
1308
  slot,
1309
+ targetSlot,
937
1310
  attestorAddress
938
1311
  });
939
- const voter = new CheckpointVoter(slot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
1312
+ // Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
1313
+ // Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
1314
+ // L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
1315
+ // sign for `targetSlot` and delay submission to the start of `targetSlot`.
1316
+ const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
940
1317
  const votesPromises = voter.enqueueVotes();
941
1318
  const votes = await Promise.all(votesPromises);
942
1319
  if (votes.every((p)=>!p)) {
@@ -944,28 +1321,52 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
944
1321
  return;
945
1322
  }
946
1323
  this.log.info(`Voting in slot ${slot} (escape hatch open)`, {
947
- slot
1324
+ slot,
1325
+ targetSlot
948
1326
  });
949
- await publisher.sendRequests();
1327
+ // Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
1328
+ // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1329
+ // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1330
+ // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1331
+ // waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
1332
+ // stop() can drain it.
1333
+ const send = publisher.sendRequestsAt(targetSlot).catch((err)=>{
1334
+ this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, {
1335
+ slot,
1336
+ targetSlot
1337
+ });
1338
+ });
1339
+ this.pendingRequests.trackRequest(send, ()=>publisher.interrupt());
950
1340
  }
951
1341
  /**
952
1342
  * Considers invalidating a block if the pending chain is invalid. Depends on how long the invalid block
953
1343
  * has been there without being invalidated and whether the sequencer is in the committee or not. We always
954
1344
  * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
955
1345
  * and if they fail, any sequencer will try as well.
956
- */ async considerInvalidatingCheckpoint(syncedTo, currentSlot) {
957
- const { pendingChainValidationStatus, l1Timestamp } = syncedTo;
1346
+ * @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
1347
+ * @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
1348
+ */ async considerInvalidatingCheckpoint(pendingChainValidationStatus, currentSlot) {
958
1349
  if (pendingChainValidationStatus.valid) {
959
1350
  return;
960
1351
  }
961
1352
  const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1353
+ // Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
1354
+ // The guard is keyed by (checkpoint, slot) — so a different invalid checkpoint surfacing later in
1355
+ // the same slot is not suppressed — and is set only after a request is successfully simulated below,
1356
+ // so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
1357
+ if (this.lastInvalidationAttempt?.slot === currentSlot && this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber) {
1358
+ this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
1359
+ currentSlot,
1360
+ invalidCheckpointNumber
1361
+ });
1362
+ return;
1363
+ }
962
1364
  const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
963
1365
  const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
964
1366
  const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
965
1367
  const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } = this.config;
966
1368
  const logData = {
967
1369
  invalidL1Timestamp: invalidCheckpointTimestamp,
968
- l1Timestamp,
969
1370
  invalidCheckpoint: pendingChainValidationStatus.checkpoint,
970
1371
  secondsBeforeInvalidatingBlockAsCommitteeMember,
971
1372
  secondsBeforeInvalidatingBlockAsNonCommitteeMember,
@@ -999,6 +1400,12 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
999
1400
  this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
1000
1401
  return;
1001
1402
  }
1403
+ // We produced a valid invalidation request; record it so further ticks within this slot skip the
1404
+ // committee lookup, simulation, and submission above for this same invalid checkpoint.
1405
+ this.lastInvalidationAttempt = {
1406
+ slot: currentSlot,
1407
+ checkpointNumber: invalidCheckpointNumber
1408
+ };
1002
1409
  this.log.info(invalidateAsCommitteeMember ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member` : `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`, logData);
1003
1410
  publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
1004
1411
  if (!this.config.fishermanMode) {
@@ -1034,12 +1441,12 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
1034
1441
  }))
1035
1442
  });
1036
1443
  }
1037
- getSlotStartBuildTimestamp(slotNumber) {
1038
- return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
1039
- }
1040
- getSecondsIntoSlot(slotNumber) {
1041
- const slotStartTimestamp = this.getSlotStartBuildTimestamp(slotNumber);
1042
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1444
+ /**
1445
+ * Wall-clock seconds elapsed since the build-frame start of the given target slot
1446
+ * (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
1447
+ */ getSecondsIntoBuildFrame(targetSlot) {
1448
+ const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
1449
+ return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
1043
1450
  }
1044
1451
  get aztecSlotDuration() {
1045
1452
  return this.l1Constants.slotDuration;
@@ -1056,10 +1463,10 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
1056
1463
  getValidatorAddresses() {
1057
1464
  return this.validatorClient?.getValidatorAddresses();
1058
1465
  }
1466
+ /** Updates the publisher factory's node keystore adapter after a keystore reload. */ updatePublisherNodeKeyStore(adapter) {
1467
+ this.publisherFactory.updateNodeKeyStore(adapter);
1468
+ }
1059
1469
  getConfig() {
1060
1470
  return this.config;
1061
1471
  }
1062
- get l1PublishingTime() {
1063
- return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
1064
- }
1065
1472
  }