@aztec/sequencer-client 0.0.1-commit.993d52e → 0.0.1-commit.9a89641

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 +23 -5
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +63 -36
  5. package/dest/config.d.ts +32 -4
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +76 -32
  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 -26
  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 +23 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +36 -6
  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 +3 -5
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +16 -3
  46. package/dest/publisher/sequencer-publisher.d.ts +112 -65
  47. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher.js +758 -388
  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 +75 -19
  62. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  63. package/dest/sequencer/checkpoint_proposal_job.js +846 -264
  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 +13 -10
  73. package/dest/sequencer/metrics.d.ts.map +1 -1
  74. package/dest/sequencer/metrics.js +45 -20
  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 +167 -41
  82. package/dest/sequencer/sequencer.d.ts.map +1 -1
  83. package/dest/sequencer/sequencer.js +604 -200
  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 +3 -3
  87. package/dest/test/index.d.ts.map +1 -1
  88. package/dest/test/mock_checkpoint_builder.d.ts +7 -9
  89. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  90. package/dest/test/mock_checkpoint_builder.js +39 -30
  91. package/dest/test/utils.d.ts +15 -1
  92. package/dest/test/utils.d.ts.map +1 -1
  93. package/dest/test/utils.js +25 -7
  94. package/package.json +29 -29
  95. package/src/client/sequencer-client.ts +90 -45
  96. package/src/config.ts +92 -33
  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 +19 -88
  101. package/src/global_variable_builder/index.ts +3 -1
  102. package/src/publisher/config.ts +71 -7
  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 +18 -6
  111. package/src/publisher/sequencer-publisher.ts +847 -474
  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 +1002 -298
  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 +57 -24
  123. package/src/sequencer/missing_committee.ts +192 -0
  124. package/src/sequencer/requests_tracker.ts +43 -0
  125. package/src/sequencer/sequencer.ts +711 -223
  126. package/src/sequencer/types.ts +1 -1
  127. package/src/test/index.ts +2 -2
  128. package/src/test/mock_checkpoint_builder.ts +51 -48
  129. package/src/test/utils.ts +61 -10
  130. package/dest/sequencer/timetable.d.ts +0 -87
  131. package/dest/sequencer/timetable.d.ts.map +0 -1
  132. package/dest/sequencer/timetable.js +0 -223
  133. package/src/sequencer/timetable.ts +0 -283
@@ -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,40 +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;
453
- /** The last slot for which we logged "no committee" warning, to avoid spam */ lastSlotForNoCommitteeWarning;
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;
454
463
  /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */ lastSlotForCheckpointProposalJob;
455
464
  /** Last successful checkpoint proposed */ lastCheckpointProposed;
456
465
  /** The last epoch for which we logged strategy comparison in fisherman mode. */ lastEpochForStrategyComparison;
457
- /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */ timetable;
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;
458
477
  /** Config for the sequencer */ config;
478
+ signatureContext;
459
479
  constructor(publisherFactory, validatorClient, globalsBuilder, p2pClient, worldState, slasherClient, l2BlockSource, l1ToL2MessageSource, checkpointsBuilder, l1Constants, dateProvider, epochCache, rollupContract, config, telemetry = getTelemetryClient(), log = createLogger('sequencer')){
460
- 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();
461
483
  // Add [FISHERMAN] prefix to logger if in fisherman mode
462
484
  if (config.fishermanMode) {
463
485
  this.log = log.createChild('[FISHERMAN]');
464
486
  }
487
+ this.signatureContext = {
488
+ chainId: config.l1ChainId,
489
+ rollupAddress: config.rollupAddress
490
+ };
465
491
  this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
492
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
466
493
  this.updateConfig(config);
467
494
  }
468
- /** 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) {
469
503
  const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
470
- this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowList'));
471
- this.config = merge(this.config, filteredConfig);
472
- this.timetable = new SequencerTimetable({
473
- ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
474
- aztecSlotDuration: this.aztecSlotDuration,
475
- l1PublishingTime: this.l1PublishingTime,
476
- p2pPropagationTime: this.config.attestationPropagationTime,
477
- blockDurationMs: this.config.blockDurationMs,
478
- enforce: this.config.enforceTimeTable
479
- }, 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
+ }
480
590
  }
481
591
  /** Initializes the sequencer (precomputes tables). Takes about 3s. */ init() {
482
592
  getKzg();
483
593
  }
484
- /** 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
+ }
485
609
  this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.config.sequencerPollingIntervalMS);
486
610
  this.setState(SequencerState.IDLE, undefined, {
487
611
  force: true
@@ -489,18 +613,59 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
489
613
  this.runningPromise.start();
490
614
  this.log.info('Started sequencer');
491
615
  }
492
- /** 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
+ }
493
630
  this.log.info(`Stopping sequencer`);
494
631
  this.setState(SequencerState.STOPPING, undefined, {
495
632
  force: true
496
633
  });
497
- this.publisherFactory.interruptAll();
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.
498
640
  await this.runningPromise?.stop();
641
+ this.pendingRequests.interruptRequests();
642
+ await this.pendingRequests.awaitRequests();
499
643
  this.setState(SequencerState.STOPPED, undefined, {
500
644
  force: true
501
645
  });
502
646
  this.log.info('Stopped sequencer');
503
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
+ }
504
669
  /** Main sequencer loop with a try/catch */ async safeWork() {
505
670
  try {
506
671
  await this.work();
@@ -508,19 +673,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
508
673
  this.emit('checkpoint-error', {
509
674
  error: err
510
675
  });
511
- if (err instanceof SequencerTooSlowError) {
512
- // Log as warn only if we had to abort halfway through the block proposal
513
- const logLvl = [
514
- SequencerState.INITIALIZING_CHECKPOINT,
515
- SequencerState.PROPOSER_CHECK
516
- ].includes(err.proposedState) ? 'debug' : 'warn';
517
- this.log[logLvl](err.message, {
518
- now: this.dateProvider.nowInSeconds()
519
- });
520
- } else {
521
- // Re-throw other errors
522
- throw err;
523
- }
676
+ throw err;
524
677
  } finally{
525
678
  this.setState(SequencerState.IDLE, undefined);
526
679
  }
@@ -539,63 +692,76 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
539
692
  * - Submit checkpoint
540
693
  */ async work() {
541
694
  this.setState(SequencerState.SYNCHRONIZING, undefined);
542
- const { slot, ts, now, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
695
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
543
696
  // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
544
- const checkpointProposalJob = await this.prepareCheckpointProposal(epoch, slot, ts, now);
697
+ const checkpointProposalJob = await this.prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds);
545
698
  if (!checkpointProposalJob) {
546
699
  return;
547
700
  }
701
+ // Track the job so we can await its pending L1 submission during shutdown
702
+ this.lastCheckpointProposalJob = checkpointProposalJob;
548
703
  // Execute the checkpoint proposal job
549
704
  const checkpoint = await checkpointProposalJob.execute();
550
705
  // Update last checkpoint proposed (currently unused)
551
706
  if (checkpoint) {
552
707
  this.lastCheckpointProposed = checkpoint;
553
708
  }
554
- // Log fee strategy comparison if on fisherman
555
- if (this.config.fishermanMode && (this.lastEpochForStrategyComparison === undefined || epoch > this.lastEpochForStrategyComparison)) {
556
- this.logStrategyComparison(epoch, checkpointProposalJob.getPublisher());
557
- 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;
558
713
  }
559
714
  return checkpoint;
560
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
+ }
561
728
  /**
562
729
  * Prepares the checkpoint proposal by performing all necessary checks and setup.
563
730
  * This is the initial step in the main loop.
564
731
  * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
565
- */ async prepareCheckpointProposal(epoch, slot, ts, now) {
566
- // Check we have not already processed this slot (cheapest check)
567
- // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
568
- // running against actual time (eg when we use sandbox-style automining)
569
- if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= slot && this.config.enforceTimeTable) {
570
- 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`);
571
736
  return undefined;
572
737
  }
573
- // But if we have already proposed for this slot, the we definitely have to skip it, automining or not
574
- if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= slot) {
575
- 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}`);
576
741
  return undefined;
577
742
  }
578
- // Check all components are synced to latest as seen by the archiver (queries all subsystems)
579
- const syncedTo = await this.checkSync({
580
- ts,
581
- slot
582
- });
583
- if (!syncedTo) {
584
- await this.tryVoteWhenSyncFails({
585
- slot,
586
- 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
587
748
  });
588
749
  return undefined;
589
750
  }
590
- // 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.
591
757
  // Still perform governance/slashing voting (as proposer) once per slot.
592
- 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);
593
760
  if (isEscapeHatchOpen) {
594
- this.setState(SequencerState.PROPOSER_CHECK, slot);
595
- const [canPropose, proposer] = await this.checkCanPropose(slot);
596
761
  if (canPropose) {
597
762
  await this.tryVoteWhenEscapeHatchOpen({
598
763
  slot,
764
+ targetSlot,
599
765
  proposer
600
766
  });
601
767
  } else {
@@ -607,28 +773,80 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
607
773
  }
608
774
  return undefined;
609
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
+ }
610
827
  // Next checkpoint follows from the last synced one
611
828
  const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
612
829
  const logCtx = {
613
- now,
614
- syncedToL1Ts: syncedTo.l1Timestamp,
615
- syncedToL2Slot: getSlotAtTimestamp(syncedTo.l1Timestamp, this.l1Constants),
830
+ nowSeconds,
831
+ syncedToL2Slot: syncedTo.syncedL2Slot,
616
832
  slot,
833
+ targetSlot,
617
834
  slotTs: ts,
618
835
  checkpointNumber,
619
836
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex')
620
837
  };
621
- // Check that we are a proposer for the next slot
622
- this.setState(SequencerState.PROPOSER_CHECK, slot);
623
- const [canPropose, proposer] = await this.checkCanPropose(slot);
624
- // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
625
- if (!canPropose) {
626
- 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})`);
627
845
  return undefined;
628
846
  }
629
- // Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
630
- if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= slot) {
631
- 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}`, {
632
850
  ...logCtx,
633
851
  block: syncedTo.blockData.header.toInspect()
634
852
  });
@@ -642,18 +860,84 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
642
860
  const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
643
861
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
644
862
  this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
645
- // In fisherman mode, set the actual proposer's address for simulations
646
- if (this.config.fishermanMode && proposer) {
647
- publisher.setProposerAddressForSimulation(proposer);
648
- this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
649
- }
650
- // Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
651
- const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
652
- // Check with the rollup contract if we can indeed propose at the next L2 slot. This check should not fail
653
- // if all the previous checks are good, but we do it just in case.
654
- 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
+ };
655
936
  if (canProposeCheck === undefined) {
656
- 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
+ });
657
941
  this.emit('proposer-rollup-check-failed', {
658
942
  reason: 'Rollup contract check failed',
659
943
  slot
@@ -661,11 +945,12 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
661
945
  this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
662
946
  return undefined;
663
947
  }
664
- if (canProposeCheck.slot !== slot) {
665
- 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}.`, {
666
950
  ...logCtx,
951
+ ...proposeContext,
667
952
  rollup: canProposeCheck,
668
- expectedSlot: slot
953
+ expectedSlot: targetSlot
669
954
  });
670
955
  this.emit('proposer-rollup-check-failed', {
671
956
  reason: 'Slot mismatch',
@@ -677,6 +962,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
677
962
  if (canProposeCheck.checkpointNumber !== checkpointNumber) {
678
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}.`, {
679
964
  ...logCtx,
965
+ ...proposeContext,
680
966
  rollup: canProposeCheck,
681
967
  expectedSlot: slot
682
968
  });
@@ -687,17 +973,18 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
687
973
  this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
688
974
  return undefined;
689
975
  }
690
- this.lastSlotForCheckpointProposalJob = slot;
691
- await this.p2pClient.prepareForSlot(slot);
692
- 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}`, {
693
979
  ...logCtx,
980
+ ...proposeContext,
694
981
  proposer
695
982
  });
696
983
  // Create and return the checkpoint proposal job
697
- 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);
698
985
  }
699
- createCheckpointProposalJob(epoch, slot, checkpointNumber, syncedToBlockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint) {
700
- 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);
701
988
  }
702
989
  /**
703
990
  * Returns the current sequencer state.
@@ -705,9 +992,11 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
705
992
  return this.state;
706
993
  }
707
994
  /**
708
- * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
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.
709
997
  * @param proposedState - The new state to transition to.
710
- * @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.
711
1000
  * @param force - Whether to force the transition even if the sequencer is stopped.
712
1001
  */ setState(proposedState, slotNumber, opts = {}) {
713
1002
  if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
@@ -718,42 +1007,55 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
718
1007
  this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
719
1008
  return;
720
1009
  }
721
- let secondsIntoSlot = undefined;
722
- if (slotNumber !== undefined) {
723
- secondsIntoSlot = this.getSecondsIntoSlot(slotNumber);
724
- this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
725
- }
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;
726
1018
  const boringStates = [
727
1019
  SequencerState.IDLE,
728
1020
  SequencerState.SYNCHRONIZING
729
1021
  ];
730
- const logLevel = boringStates.includes(proposedState) && boringStates.includes(this.state) ? 'trace' : 'debug';
731
- 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,
732
1026
  slotNumber,
733
- secondsIntoSlot
1027
+ stateSlotNumber: oldStateSlotNumber,
1028
+ secondsIntoBuildFrame,
1029
+ ...stateChanged && {
1030
+ stateDurationMs: Math.ceil(stateDurationMs)
1031
+ }
734
1032
  });
735
1033
  this.emit('state-changed', {
736
- oldState: this.state,
1034
+ oldState,
737
1035
  newState: proposedState,
738
- secondsIntoSlot,
739
- slot: slotNumber
1036
+ secondsIntoBuildFrame,
1037
+ targetSlot: slotNumber
740
1038
  });
1039
+ if (stateChanged) {
1040
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
1041
+ this.stateEnteredAtMs = transitionAtMs;
1042
+ this.stateSlotNumber = slotNumber;
1043
+ }
741
1044
  this.state = proposedState;
742
1045
  }
743
1046
  /**
744
1047
  * Returns whether all dependencies have caught up.
745
1048
  * We don't check against the previous block submitted since it may have been reorg'd out.
746
1049
  */ async checkSync(args) {
747
- // Check that the archiver and dependencies have synced to the previous L1 slot at least
748
- // TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
749
- // cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
750
- const l1Timestamp = await this.l2BlockSource.getL1Timestamp();
751
- const { slot, ts } = args;
752
- 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) {
753
1056
  this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
754
1057
  slot,
755
- ts,
756
- l1Timestamp
1058
+ syncedL2Slot
757
1059
  });
758
1060
  return undefined;
759
1061
  }
@@ -762,71 +1064,115 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
762
1064
  number: syncSummary.latestBlockNumber,
763
1065
  hash: syncSummary.latestBlockHash
764
1066
  })),
765
- this.l2BlockSource.getL2Tips().then((t)=>t.proposed),
1067
+ this.l2BlockSource.getL2Tips().then((t)=>({
1068
+ proposed: t.proposed,
1069
+ checkpointed: t.checkpointed
1070
+ })),
766
1071
  this.p2pClient.getStatus().then((p2p)=>p2p.syncedToL2Block),
767
- this.l1ToL2MessageSource.getL2Tips().then((t)=>t.proposed),
768
- 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()
769
1078
  ]);
770
- const [worldState, l2BlockSource, p2p, l1ToL2MessageSource, pendingChainValidationStatus] = syncedBlocks;
771
- // 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,
772
- // as the world state can compute the new genesis block hash, but other components use the hardcoded constant.
773
- // TODO(palla/mbps): Fix the above. All components should be able to handle dynamic genesis block hashes.
774
- 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;
775
1081
  if (!result) {
776
1082
  this.log.debug(`Sequencer sync check failed`, {
777
1083
  worldState,
778
- l2BlockSource,
1084
+ l2BlockSource: l2Tips.proposed,
779
1085
  p2p,
780
- l1ToL2MessageSource
1086
+ l1ToL2MessageSourceTips
781
1087
  });
782
1088
  return undefined;
783
1089
  }
784
- // Special case for genesis state
785
1090
  const blockNumber = worldState.number;
786
- if (blockNumber < INITIAL_L2_BLOCK_NUM) {
787
- const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
788
- return {
789
- checkpointNumber: CheckpointNumber.ZERO,
790
- blockNumber: BlockNumber.ZERO,
791
- archive,
792
- l1Timestamp,
793
- 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
794
1121
  };
1122
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
1123
+ return undefined;
795
1124
  }
796
- const blockData = await this.l2BlockSource.getBlockData(blockNumber);
797
- if (!blockData) {
798
- // this shouldn't really happen because a moment ago we checked that all components were in sync
799
- this.log.error(`Failed to get L2 block data ${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
+ });
800
1135
  return undefined;
801
1136
  }
802
1137
  return {
803
1138
  blockData,
804
1139
  blockNumber: blockData.header.getBlockNumber(),
805
1140
  checkpointNumber: blockData.checkpointNumber,
1141
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
806
1142
  archive: blockData.archive.root,
807
- l1Timestamp,
1143
+ hasProposedCheckpoint,
1144
+ proposedCheckpointData,
1145
+ syncedL2Slot,
808
1146
  pendingChainValidationStatus
809
1147
  };
810
1148
  }
811
1149
  /**
812
1150
  * Checks if we are the proposer for the next slot.
813
1151
  * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
814
- */ async checkCanPropose(slot) {
1152
+ */ async checkCanPropose(targetSlot) {
815
1153
  let proposer;
816
1154
  try {
817
- proposer = await this.epochCache.getProposerAttesterAddressInSlot(slot);
1155
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
818
1156
  } catch (e) {
819
1157
  if (e instanceof NoCommitteeError) {
820
- if (this.lastSlotForNoCommitteeWarning !== slot) {
821
- this.lastSlotForNoCommitteeWarning = slot;
822
- 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
+ });
823
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
919
1272
  });
920
- await publisher.sendRequests();
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
+ });
1281
+ });
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
1326
+ });
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
+ });
948
1338
  });
949
- await publisher.sendRequests();
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;
@@ -1062,7 +1469,4 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
1062
1469
  getConfig() {
1063
1470
  return this.config;
1064
1471
  }
1065
- get l1PublishingTime() {
1066
- return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
1067
- }
1068
1472
  }