@aztec/sequencer-client 0.0.1-commit.f2ce05ee → 0.0.1-commit.f5a9928

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 +283 -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 +34 -5
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +103 -39
  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 +58 -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 +1 -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 +34 -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 +2 -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 +112 -71
  47. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher.js +571 -392
  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 +886 -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/errors.d.ts +1 -8
  71. package/dest/sequencer/errors.d.ts.map +1 -1
  72. package/dest/sequencer/errors.js +0 -9
  73. package/dest/sequencer/events.d.ts +62 -5
  74. package/dest/sequencer/events.d.ts.map +1 -1
  75. package/dest/sequencer/metrics.d.ts +23 -8
  76. package/dest/sequencer/metrics.d.ts.map +1 -1
  77. package/dest/sequencer/metrics.js +117 -21
  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 +181 -44
  82. package/dest/sequencer/sequencer.d.ts.map +1 -1
  83. package/dest/sequencer/sequencer.js +635 -218
  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 +11 -11
  89. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  90. package/dest/test/mock_checkpoint_builder.js +45 -34
  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 +28 -28
  95. package/src/client/sequencer-client.ts +110 -47
  96. package/src/config.ts +126 -44
  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 +57 -0
  107. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -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 +667 -484
  112. package/src/publisher/write_json.ts +78 -0
  113. package/src/sequencer/automine/README.md +60 -0
  114. package/src/sequencer/automine/automine_factory.ts +152 -0
  115. package/src/sequencer/automine/automine_sequencer.ts +800 -0
  116. package/src/sequencer/automine/index.ts +6 -0
  117. package/src/sequencer/checkpoint_proposal_job.ts +1073 -290
  118. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  119. package/src/sequencer/checkpoint_voter.ts +1 -12
  120. package/src/sequencer/errors.ts +0 -15
  121. package/src/sequencer/events.ts +66 -5
  122. package/src/sequencer/metrics.ts +138 -26
  123. package/src/sequencer/requests_tracker.ts +43 -0
  124. package/src/sequencer/sequencer.ts +745 -243
  125. package/src/sequencer/types.ts +1 -1
  126. package/src/test/index.ts +4 -6
  127. package/src/test/mock_checkpoint_builder.ts +63 -49
  128. package/src/test/utils.ts +64 -10
  129. package/dest/sequencer/timetable.d.ts +0 -87
  130. package/dest/sequencer/timetable.d.ts.map +0 -1
  131. package/dest/sequencer/timetable.js +0 -223
  132. package/src/sequencer/README.md +0 -531
  133. package/src/sequencer/timetable.ts +0 -283
@@ -1,20 +1,35 @@
1
1
  import { getKzg } from '@aztec/blob-lib';
2
- import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
3
- import type { EpochCache } from '@aztec/epoch-cache';
2
+ import { type EpochCache, PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
4
3
  import { NoCommitteeError, type RollupContract } from '@aztec/ethereum/contracts';
5
4
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
6
5
  import { merge, omit, pick } from '@aztec/foundation/collection';
7
6
  import { Fr } from '@aztec/foundation/curves/bn254';
8
7
  import { EthAddress } from '@aztec/foundation/eth-address';
9
- import { createLogger } from '@aztec/foundation/log';
8
+ import { type Logger, createLogger } from '@aztec/foundation/log';
10
9
  import { RunningPromise } from '@aztec/foundation/running-promise';
11
10
  import type { DateProvider } from '@aztec/foundation/timer';
12
11
  import type { TypedEventEmitter } from '@aztec/foundation/types';
13
12
  import type { P2P } from '@aztec/p2p';
14
13
  import type { SlasherClientInterface } from '@aztec/slasher';
15
- import type { L2Block, L2BlockSink, L2BlockSource, ValidateCheckpointResult } from '@aztec/stdlib/block';
16
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
17
- import { getSlotAtTimestamp, getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
14
+ import type {
15
+ BlockData,
16
+ L2BlockSink,
17
+ L2BlockSource,
18
+ ProposedCheckpointSink,
19
+ ValidateCheckpointResult,
20
+ } from '@aztec/stdlib/block';
21
+ import {
22
+ type Checkpoint,
23
+ type ProposedCheckpointData,
24
+ buildCheckpointSimulationOverridesPlan,
25
+ } from '@aztec/stdlib/checkpoint';
26
+ import type { ChainConfig } from '@aztec/stdlib/config';
27
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
28
+ import {
29
+ MIN_PER_BLOCK_ALLOCATION_MULTIPLIER,
30
+ MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER,
31
+ computeNetworkTxGasLimits,
32
+ } from '@aztec/stdlib/gas';
18
33
  import {
19
34
  type ResolvedSequencerConfig,
20
35
  type SequencerConfig,
@@ -22,10 +37,11 @@ import {
22
37
  type WorldStateSynchronizer,
23
38
  } from '@aztec/stdlib/interfaces/server';
24
39
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
40
+ import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
25
41
  import { pickFromSchema } from '@aztec/stdlib/schemas';
26
- import { MerkleTreeId } from '@aztec/stdlib/trees';
42
+ import { ProposerTimetable, buildProposerTimetable } from '@aztec/stdlib/timetable';
27
43
  import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
28
- import { FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec/validator-client';
44
+ import { FullNodeCheckpointsBuilder, NodeKeystoreAdapter, type ValidatorClient } from '@aztec/validator-client';
29
45
 
30
46
  import EventEmitter from 'node:events';
31
47
 
@@ -34,16 +50,27 @@ import type { GlobalVariableBuilder } from '../global_variable_builder/global_bu
34
50
  import type { SequencerPublisherFactory } from '../publisher/sequencer-publisher-factory.js';
35
51
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
36
52
  import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
53
+ import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
37
54
  import { CheckpointVoter } from './checkpoint_voter.js';
38
- import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
55
+ import { SequencerInterruptedError } from './errors.js';
39
56
  import type { SequencerEvents } from './events.js';
40
57
  import { SequencerMetrics } from './metrics.js';
41
- import { SequencerTimetable } from './timetable.js';
58
+ import { RequestsTracker } from './requests_tracker.js';
42
59
  import type { SequencerRollupConstants } from './types.js';
43
60
  import { SequencerState } from './utils.js';
44
61
 
45
62
  export { SequencerState };
46
63
 
64
+ /** Slot snapshot used to prepare a checkpoint proposal. */
65
+ type SequencerSlotContext = {
66
+ slot: SlotNumber;
67
+ targetSlot: SlotNumber;
68
+ epoch: EpochNumber;
69
+ targetEpoch: EpochNumber;
70
+ ts: bigint;
71
+ nowSeconds: bigint;
72
+ };
73
+
47
74
  /**
48
75
  * Sequencer client
49
76
  * - Checks whether it is elected as proposer for the next slot
@@ -53,18 +80,27 @@ export { SequencerState };
53
80
  * - Votes for proposals and slashes on L1
54
81
  */
55
82
  export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<SequencerEvents>) {
56
- private runningPromise?: RunningPromise;
83
+ protected runningPromise?: RunningPromise;
57
84
  private state = SequencerState.STOPPED;
85
+ private stateSlotNumber: SlotNumber | undefined;
86
+ /** Wall-clock time (ms, via the date provider) at which the current state was entered. */
87
+ private stateEnteredAtMs: number;
58
88
  private metrics: SequencerMetrics;
89
+ private checkpointProposalJobMetrics: CheckpointProposalJobMetrics;
90
+ private readonly stateLog: Logger;
91
+
92
+ /** The last slot for which we attempted to perform our fallback duties (votes and/or prune) with degraded block production */
93
+ private lastSlotForFallbackAction: SlotNumber | undefined;
59
94
 
60
- /** The last slot for which we attempted to perform our voting duties with degraded block production */
61
- private lastSlotForFallbackVote: SlotNumber | undefined;
95
+ /** The (checkpoint, slot) of the last invalidation request we successfully simulated, to prevent
96
+ * re-simulating and re-submitting the same invalidation across the many ticks within a single slot. */
97
+ private lastInvalidationAttempt: { slot: SlotNumber; checkpointNumber: CheckpointNumber } | undefined;
62
98
 
63
99
  /** The last slot for which we logged "no committee" warning, to avoid spam */
64
100
  private lastSlotForNoCommitteeWarning: SlotNumber | undefined;
65
101
 
66
102
  /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */
67
- private lastSlotForCheckpointProposalJob: SlotNumber | undefined;
103
+ protected lastSlotForCheckpointProposalJob: SlotNumber | undefined;
68
104
 
69
105
  /** Last successful checkpoint proposed */
70
106
  private lastCheckpointProposed: Checkpoint | undefined;
@@ -72,19 +108,26 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
72
108
  /** The last epoch for which we logged strategy comparison in fisherman mode. */
73
109
  private lastEpochForStrategyComparison: EpochNumber | undefined;
74
110
 
75
- /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */
76
- protected timetable!: SequencerTimetable;
111
+ /** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */
112
+ protected lastCheckpointProposalJob: CheckpointProposalJob | undefined;
113
+
114
+ /**
115
+ * In-flight fire-and-forget requests that {@link stop} interrupts and drains, and {@link pause} awaits
116
+ * untouched: the checkpoint proposal jobs' backgrounded L1 submissions (each job is handed this shared
117
+ * tracker) plus the sequencer's own fallback submissions (votes/prune when we cannot build, or
118
+ * escape-hatch votes). Each fallback send is gated by its wrapper publisher's interruptible target-slot
119
+ * sleep; the tracked interrupt wakes that sleep so the send short-circuits without publishing. A wrapper
120
+ * is created for a single send and is never restarted, so once interrupted its sleeper can never publish
121
+ * a stale-slot tx, even after the pooled publishers are restarted by a later {@link start}.
122
+ */
123
+ protected readonly pendingRequests = new RequestsTracker();
77
124
 
78
- // This shouldn't be here as this gets re-created each time we build/propose a block.
79
- // But we have a number of tests that abuse/rely on this class having a permanent publisher.
80
- // As long as those tests only configure a single publisher they will continue to work.
81
- // This will get re-assigned every time the sequencer goes to build a new block to a publisher that is valid
82
- // for the block proposer.
83
- // TODO(palla/mbps): Remove this field and fix tests
84
- protected publisher: SequencerPublisher | undefined;
125
+ /** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */
126
+ protected timetable!: ProposerTimetable;
85
127
 
86
128
  /** Config for the sequencer */
87
129
  protected config: ResolvedSequencerConfig = DefaultSequencerConfig;
130
+ private readonly signatureContext: CoordinationSignatureContext;
88
131
 
89
132
  constructor(
90
133
  protected publisherFactory: SequencerPublisherFactory,
@@ -93,55 +136,171 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
93
136
  protected p2pClient: P2P,
94
137
  protected worldState: WorldStateSynchronizer,
95
138
  protected slasherClient: SlasherClientInterface | undefined,
96
- protected l2BlockSource: L2BlockSource & L2BlockSink,
139
+ protected l2BlockSource: L2BlockSource & L2BlockSink & ProposedCheckpointSink,
97
140
  protected l1ToL2MessageSource: L1ToL2MessageSource,
98
141
  protected checkpointsBuilder: FullNodeCheckpointsBuilder,
99
142
  protected l1Constants: SequencerRollupConstants,
100
143
  protected dateProvider: DateProvider,
101
144
  protected epochCache: EpochCache,
102
145
  protected rollupContract: RollupContract,
103
- config: SequencerConfig,
146
+ config: SequencerConfig & Pick<ChainConfig, 'l1ChainId' | 'rollupAddress'>,
104
147
  protected telemetry: TelemetryClient = getTelemetryClient(),
105
148
  protected log = createLogger('sequencer'),
106
149
  ) {
107
150
  super();
151
+ this.stateLog = log.createChild('state');
152
+ this.stateEnteredAtMs = this.dateProvider.now();
108
153
 
109
154
  // Add [FISHERMAN] prefix to logger if in fisherman mode
110
155
  if (config.fishermanMode) {
111
156
  this.log = log.createChild('[FISHERMAN]');
112
157
  }
113
158
 
159
+ this.signatureContext = {
160
+ chainId: config.l1ChainId,
161
+ rollupAddress: config.rollupAddress,
162
+ };
114
163
  this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
164
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
115
165
  this.updateConfig(config);
116
166
  }
117
167
 
118
- /** Updates sequencer config by the defined values and updates the timetable */
168
+ /**
169
+ * Updates sequencer config by the defined values and rebuilds the timetable.
170
+ *
171
+ * The merged config is validated against a candidate before being committed: {@link buildTimetable} may
172
+ * reject the candidate (invalid timing geometry, or per-block allocation multipliers below the network
173
+ * minimums). On rejection we leave `this.config` and `this.timetable` untouched and rethrow, so a bad update
174
+ * never leaves the sequencer running with a rejected config and a stale timetable.
175
+ */
119
176
  public updateConfig(config: Partial<SequencerConfig>) {
120
177
  const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
121
- this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowList'));
122
- this.config = merge(this.config, filteredConfig);
123
- this.timetable = new SequencerTimetable(
124
- {
125
- ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
126
- aztecSlotDuration: this.aztecSlotDuration,
127
- l1PublishingTime: this.l1PublishingTime,
128
- p2pPropagationTime: this.config.attestationPropagationTime,
129
- blockDurationMs: this.config.blockDurationMs,
130
- enforce: this.config.enforceTimeTable,
131
- },
132
- this.metrics,
133
- this.log,
134
- );
178
+ const candidate = merge(this.config, filteredConfig);
179
+ let timetable: ProposerTimetable;
180
+ try {
181
+ timetable = this.buildTimetable(candidate);
182
+ } catch (err) {
183
+ this.log.warn(`Rejecting sequencer config update: ${(err as Error).message}`, {
184
+ rejectedConfig: omit(filteredConfig, 'txPublicSetupAllowListExtend'),
185
+ });
186
+ throw err;
187
+ }
188
+ this.config = candidate;
189
+ this.timetable = timetable;
190
+ this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
191
+ }
192
+
193
+ /**
194
+ * Builds the proposer timetable from the given config and L1 constants via the shared
195
+ * {@link buildProposerTimetable} helper, so the sequencer derives the same blocks-per-checkpoint as the p2p
196
+ * layer and `getNodeInfo`. The fast local/e2e profile and budget clamping happen inside
197
+ * {@link ProposerTimetable}.
198
+ *
199
+ * Throws if the timing geometry is invalid or the per-block allocation multipliers are below the network
200
+ * minimums; callers must treat a throw as a rejected config and not commit it.
201
+ */
202
+ private buildTimetable(config: ResolvedSequencerConfig): ProposerTimetable {
203
+ const timetable = buildProposerTimetable(config, this.l1Constants);
204
+
205
+ const maxNumberOfBlocks = timetable.getMaxBlocksPerCheckpoint();
206
+ this.log.info(`Sequencer timetable initialized with ${maxNumberOfBlocks} blocks per slot`, {
207
+ aztecSlotDuration: timetable.aztecSlotDuration,
208
+ ethereumSlotDuration: timetable.ethereumSlotDuration,
209
+ blockDuration: timetable.blockDuration,
210
+ minBlockDuration: timetable.minBlockDuration,
211
+ p2pPropagationTime: timetable.p2pPropagationTime,
212
+ checkpointProposalPrepareTime: timetable.checkpointProposalPrepareTime,
213
+ maxNumberOfBlocks,
214
+ });
215
+
216
+ this.assertConfigMeetsNetworkTxLimits(config, maxNumberOfBlocks);
217
+
218
+ return timetable;
135
219
  }
136
220
 
137
- /** Initializes the sequencer (precomputes tables and creates a publisher). Takes about 3s. */
138
- public async init() {
221
+ /**
222
+ * Checks this node's configured per-block allocation against the network admission limit. A node
223
+ * advertises and admits txs up to the limit derived from the network-minimum multipliers (see
224
+ * {@link computeNetworkTxGasLimits}).
225
+ *
226
+ * Fails startup (and runtime config updates) only when the configured per-block allocation *multipliers*
227
+ * (`perBlockAllocationMultiplier` / `perBlockDAAllocationMultiplier`) are below the network minimums: such
228
+ * a node would accept txs over RPC/gossip that its builder can never pack into a block regardless of block
229
+ * size. Operators may configure a higher (more generous) multiplier, but not a lower one.
230
+ *
231
+ * When the multipliers meet the floor but an absolute per-block gas cap (`maxDABlockGas` / `maxL2BlockGas`)
232
+ * shrinks the builder's effective grant below the network limit, this is legitimate operator
233
+ * restrictiveness — the node simply builds smaller blocks and such txs stay in the pool for other
234
+ * proposers — so we only log a warning rather than failing startup. Restrictive tx-count caps
235
+ * (`maxTxsPerBlock` / `maxTxsPerCheckpoint`) can likewise make the builder skip admitted txs; they are
236
+ * intentionally not modeled here for the same reason.
237
+ */
238
+ private assertConfigMeetsNetworkTxLimits(config: ResolvedSequencerConfig, maxBlocksPerCheckpoint: number) {
239
+ // Mirror CheckpointBuilder.capLimitsByCheckpointBudgets: DA falls back to the general multiplier.
240
+ const l2Multiplier = config.perBlockAllocationMultiplier;
241
+ const daMultiplier = config.perBlockDAAllocationMultiplier ?? l2Multiplier;
242
+
243
+ // The allocation is monotonic in the multiplier, so a multiplier at or above the network minimum
244
+ // guarantees the builder grants at least the network admission limit. Checking the multipliers directly
245
+ // is sufficient (and strictly more conservative than modeling the resulting gas grant).
246
+ if (daMultiplier < MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER) {
247
+ throw new Error(
248
+ `perBlockDAAllocationMultiplier (${daMultiplier}) is below the network minimum ` +
249
+ `${MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
250
+ );
251
+ }
252
+ if (l2Multiplier < MIN_PER_BLOCK_ALLOCATION_MULTIPLIER) {
253
+ throw new Error(
254
+ `perBlockAllocationMultiplier (${l2Multiplier}) is below the network minimum ` +
255
+ `${MIN_PER_BLOCK_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
256
+ );
257
+ }
258
+
259
+ // Absolute per-block gas caps below the network admission limit are legitimate operator restrictiveness:
260
+ // the node simply builds smaller blocks and such txs stay in the pool for other proposers. Warn only.
261
+ const networkLimit = computeNetworkTxGasLimits({
262
+ maxBlocksPerCheckpoint,
263
+ manaCheckpointBudget: this.l1Constants.rollupManaLimit,
264
+ });
265
+ if (config.maxDABlockGas !== undefined && config.maxDABlockGas < networkLimit.daGas) {
266
+ this.log.warn(
267
+ `Sequencer maxDABlockGas (${config.maxDABlockGas}) is below the network DA admission limit ` +
268
+ `(${networkLimit.daGas}): txs declaring more DA gas are admitted over RPC/gossip but will be skipped ` +
269
+ `by this proposer's own blocks and left in the pool for other proposers.`,
270
+ { maxDABlockGas: config.maxDABlockGas, networkDaGas: networkLimit.daGas, maxBlocksPerCheckpoint },
271
+ );
272
+ }
273
+ if (config.maxL2BlockGas !== undefined && config.maxL2BlockGas < networkLimit.l2Gas) {
274
+ this.log.warn(
275
+ `Sequencer maxL2BlockGas (${config.maxL2BlockGas}) is below the network L2 admission limit ` +
276
+ `(${networkLimit.l2Gas}): txs declaring more L2 gas are admitted over RPC/gossip but will be skipped ` +
277
+ `by this proposer's own blocks and left in the pool for other proposers.`,
278
+ { maxL2BlockGas: config.maxL2BlockGas, networkL2Gas: networkLimit.l2Gas, maxBlocksPerCheckpoint },
279
+ );
280
+ }
281
+ }
282
+
283
+ /** Initializes the sequencer (precomputes tables). Takes about 3s. */
284
+ public init() {
139
285
  getKzg();
140
- this.publisher = (await this.publisherFactory.create(undefined)).publisher;
141
286
  }
142
287
 
143
- /** Starts the sequencer and moves to IDLE state. */
288
+ /**
289
+ * Starts (or restarts) the sequencer and moves it to the IDLE state. Idempotent: a start while already
290
+ * running is a no-op, so it never orphans the previous poll loop. A start while STOPPING throws, since the
291
+ * in-flight stop would mark the fresh loop's state STOPPED and orphan it — silently doing nothing would
292
+ * leave the caller believing the sequencer is running when it is on its way to STOPPED. Safe to call after
293
+ * a previous {@link stop} has resolved; the caller must also restart the publishers (see
294
+ * {@link SequencerClient.start}) so L1 publishing is re-enabled.
295
+ */
144
296
  public start() {
297
+ if (this.state === SequencerState.STOPPING) {
298
+ throw new Error('Cannot start sequencer while it is stopping');
299
+ }
300
+ if (this.runningPromise?.isRunning()) {
301
+ this.log.warn('Attempted to start sequencer that is already running');
302
+ return;
303
+ }
145
304
  this.runningPromise = new RunningPromise(
146
305
  this.safeWork.bind(this),
147
306
  this.log,
@@ -152,35 +311,68 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
152
311
  this.log.info('Started sequencer');
153
312
  }
154
313
 
155
- /** Stops the sequencer from building blocks and moves to STOPPED state. */
314
+ /** Triggers an immediate run of the sequencer, bypassing the polling interval. */
315
+ public trigger() {
316
+ return this.runningPromise?.trigger();
317
+ }
318
+
319
+ /**
320
+ * Stops the sequencer from building blocks and moves it to STOPPED state, interrupting the in-flight
321
+ * work() iteration and its pending L1 submissions for a fast shutdown, then draining before returning.
322
+ * Idempotent: a second call while already stopped or stopping is a no-op. Lifecycle calls are expected
323
+ * to be serialized by the caller. For a restartable pause that lets in-flight work finish untouched
324
+ * (e.g. around a test clock warp), use {@link pause} instead.
325
+ */
156
326
  public async stop(): Promise<void> {
327
+ if (this.state === SequencerState.STOPPED || this.state === SequencerState.STOPPING) {
328
+ this.log.debug(`Sequencer already ${this.state.toLowerCase()}, ignoring stop`);
329
+ return;
330
+ }
157
331
  this.log.info(`Stopping sequencer`);
158
332
  this.setState(SequencerState.STOPPING, undefined, { force: true });
159
- this.publisher?.interrupt();
333
+ this.lastCheckpointProposalJob?.interrupt();
334
+ await this.publisherFactory.stopAll();
335
+ // Stop the poll loop and await the in-flight work() iteration. work() registers its fire-and-forget
336
+ // requests synchronously before returning, so once the loop has stopped, pendingRequests holds every
337
+ // request that will ever exist. Interrupting any earlier could miss a request registered by the last
338
+ // in-flight iteration.
160
339
  await this.runningPromise?.stop();
340
+ this.pendingRequests.interruptRequests();
341
+ await this.pendingRequests.awaitRequests();
161
342
  this.setState(SequencerState.STOPPED, undefined, { force: true });
162
343
  this.log.info('Stopped sequencer');
163
344
  }
164
345
 
346
+ /**
347
+ * Gracefully pauses block production so the sequencer can later be resumed with {@link start}: halts the
348
+ * poll loop and waits for the in-flight work() iteration and every pending L1 submission / fallback send
349
+ * to finish, without interrupting them. No interrupt lands mid-build, so no spurious checkpoint-error is
350
+ * emitted and no enqueued checkpoint is dropped. Deliberately does not stop inner services (validator/HA
351
+ * signer, publishers), so the slashing-protection store stays open and the sequencer stays restartable.
352
+ * Used by tests that pause sequencers around an L1 clock warp. Idempotent.
353
+ */
354
+ public async pause(): Promise<void> {
355
+ if (!this.runningPromise?.isRunning()) {
356
+ this.log.debug('Sequencer not running, ignoring pause');
357
+ return;
358
+ }
359
+ this.log.info('Pausing sequencer');
360
+ // Halt the poll loop and let the in-flight iteration finish naturally — no interrupt, and no STOPPING
361
+ // state, since entering STOPPING would make the iteration's own setState calls throw and fail it.
362
+ // work() registers its fire-and-forget requests synchronously before returning, so once the loop has
363
+ // stopped pendingRequests holds every request that will ever exist; awaiting it lets them all finish.
364
+ await this.runningPromise.stop();
365
+ await this.pendingRequests.awaitRequests();
366
+ this.log.info('Paused sequencer');
367
+ }
368
+
165
369
  /** Main sequencer loop with a try/catch */
166
370
  protected async safeWork() {
167
371
  try {
168
372
  await this.work();
169
373
  } catch (err) {
170
374
  this.emit('checkpoint-error', { error: err as Error });
171
- if (err instanceof SequencerTooSlowError) {
172
- // TODO(palla/mbps): Add missing states
173
- // Log as warn only if we had to abort halfway through the block proposal
174
- const logLvl = [SequencerState.INITIALIZING_CHECKPOINT, SequencerState.PROPOSER_CHECK].includes(
175
- err.proposedState,
176
- )
177
- ? ('debug' as const)
178
- : ('warn' as const);
179
- this.log[logLvl](err.message, { now: this.dateProvider.nowInSeconds() });
180
- } else {
181
- // Re-throw other errors
182
- throw err;
183
- }
375
+ throw err;
184
376
  } finally {
185
377
  this.setState(SequencerState.IDLE, undefined);
186
378
  }
@@ -202,14 +394,24 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
202
394
  @trackSpan('Sequencer.work')
203
395
  protected async work() {
204
396
  this.setState(SequencerState.SYNCHRONIZING, undefined);
205
- const { slot, ts, now, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
397
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
206
398
 
207
399
  // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
208
- const checkpointProposalJob = await this.prepareCheckpointProposal(epoch, slot, ts, now);
400
+ const checkpointProposalJob = await this.prepareCheckpointProposal(
401
+ slot,
402
+ targetSlot,
403
+ epoch,
404
+ targetEpoch,
405
+ ts,
406
+ nowSeconds,
407
+ );
209
408
  if (!checkpointProposalJob) {
210
409
  return;
211
410
  }
212
411
 
412
+ // Track the job so we can await its pending L1 submission during shutdown
413
+ this.lastCheckpointProposalJob = checkpointProposalJob;
414
+
213
415
  // Execute the checkpoint proposal job
214
416
  const checkpoint = await checkpointProposalJob.execute();
215
417
 
@@ -218,64 +420,76 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
218
420
  this.lastCheckpointProposed = checkpoint;
219
421
  }
220
422
 
221
- // Log fee strategy comparison if on fisherman
423
+ // Log fee strategy comparison if on fisherman (uses target epoch since we mirror the proposer's perspective)
222
424
  if (
223
425
  this.config.fishermanMode &&
224
- (this.lastEpochForStrategyComparison === undefined || epoch > this.lastEpochForStrategyComparison)
426
+ (this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)
225
427
  ) {
226
- this.logStrategyComparison(epoch, checkpointProposalJob.getPublisher());
227
- this.lastEpochForStrategyComparison = epoch;
428
+ this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
429
+ this.lastEpochForStrategyComparison = targetEpoch;
228
430
  }
229
431
 
230
432
  return checkpoint;
231
433
  }
232
434
 
435
+ /** Returns slot and target slot from a single clock snapshot. */
436
+ protected getSlotContextInNextL1Slot(): SequencerSlotContext {
437
+ const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
438
+ const targetSlot = SlotNumber(slot + PROPOSER_PIPELINING_SLOT_OFFSET);
439
+ return { slot, targetSlot, epoch, targetEpoch: getEpochAtSlot(targetSlot, this.l1Constants), ts, nowSeconds };
440
+ }
441
+
233
442
  /**
234
443
  * Prepares the checkpoint proposal by performing all necessary checks and setup.
235
444
  * This is the initial step in the main loop.
236
445
  * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
237
446
  */
238
447
  @trackSpan('Sequencer.prepareCheckpointProposal')
239
- private async prepareCheckpointProposal(
240
- epoch: EpochNumber,
448
+ protected async prepareCheckpointProposal(
241
449
  slot: SlotNumber,
450
+ targetSlot: SlotNumber,
451
+ epoch: EpochNumber,
452
+ targetEpoch: EpochNumber,
242
453
  ts: bigint,
243
- now: bigint,
454
+ nowSeconds: bigint,
244
455
  ): Promise<CheckpointProposalJob | undefined> {
245
- // Check we have not already processed this slot (cheapest check)
246
- // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
247
- // running against actual time (eg when we use sandbox-style automining)
248
- if (
249
- this.lastSlotForCheckpointProposalJob &&
250
- this.lastSlotForCheckpointProposalJob >= slot &&
251
- this.config.enforceTimeTable
252
- ) {
253
- this.log.trace(`Slot ${slot} has already been processed`);
456
+ // Check we have not already processed this target slot (cheapest check).
457
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot) {
458
+ this.log.trace(`Target slot ${targetSlot} has already been processed`);
254
459
  return undefined;
255
460
  }
256
461
 
257
- // But if we have already proposed for this slot, the we definitely have to skip it, automining or not
258
- if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= slot) {
259
- this.log.trace(`Slot ${slot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`);
462
+ // But if we have already proposed for this slot, then we definitely have to skip it, automining or not
463
+ if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= targetSlot) {
464
+ this.log.trace(
465
+ `Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`,
466
+ );
260
467
  return undefined;
261
468
  }
262
469
 
263
- // Check all components are synced to latest as seen by the archiver (queries all subsystems)
264
- const syncedTo = await this.checkSync({ ts, slot });
265
- if (!syncedTo) {
266
- await this.tryVoteWhenSyncFails({ slot, ts });
470
+ // Test-only: skip proposing for explicitly paused slots. Attestation paths run in the validator
471
+ // client and are not gated by this hook, so paused proposers still attest to others' proposals.
472
+ if (this.config.pauseProposingForSlots?.some(s => s === targetSlot)) {
473
+ this.log.warn(`Skipping proposal for paused slot ${targetSlot} (test-only pauseProposingForSlots hook)`, {
474
+ targetSlot,
475
+ });
267
476
  return undefined;
268
477
  }
269
478
 
270
- // If escape hatch is open for this epoch, do not start checkpoint proposal work and do not attempt invalidations.
479
+ // Cheap proposer check first: most nodes are not the proposer for most slots, so gate the
480
+ // expensive multi-subsystem checkSync (and the rest of the build path) behind it. Computed once
481
+ // here and reused for the escape-hatch voting path below. No setState/timing gate on this path:
482
+ // the build-start deadline gate runs only on the proposer build path after a successful checkSync.
483
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
484
+
485
+ // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
271
486
  // Still perform governance/slashing voting (as proposer) once per slot.
272
- const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(epoch);
487
+ // When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
488
+ const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
273
489
 
274
490
  if (isEscapeHatchOpen) {
275
- this.setState(SequencerState.PROPOSER_CHECK, slot);
276
- const [canPropose, proposer] = await this.checkCanPropose(slot);
277
491
  if (canPropose) {
278
- await this.tryVoteWhenEscapeHatchOpen({ slot, proposer });
492
+ await this.tryVoteWhenEscapeHatchOpen({ slot, targetSlot, proposer });
279
493
  } else {
280
494
  this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
281
495
  slot,
@@ -286,36 +500,104 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
286
500
  return undefined;
287
501
  }
288
502
 
503
+ // If we are not the proposer, check whether we should invalidate an invalid pending chain (a
504
+ // liveness backstop) and bail before any sync work or build-timing gate. This reads only the
505
+ // archiver's pending-chain validation status, which is authoritative on its own, instead of
506
+ // running the full sync check. Wrapped in try/catch because this leaner path skips the broader
507
+ // proposed-checkpoint/tip coherence screen that checkSync applied, so transient archiver
508
+ // incoherence surfaces as a quiet skip rather than a work-loop error.
509
+ if (!canPropose) {
510
+ try {
511
+ const pendingChainValidationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
512
+ await this.considerInvalidatingCheckpoint(pendingChainValidationStatus, slot);
513
+ } catch (err) {
514
+ this.log.warn(`Failed to consider invalidating checkpoint`, { err, slot, targetSlot });
515
+ }
516
+ return undefined;
517
+ }
518
+
519
+ // Explicit build-loop entry gate: if we are past the latest useful block-building start for the
520
+ // target slot, abandon building for this slot. The proposer prioritizes the ideal L1-publish path
521
+ // and does not plan around the late consensus-handoff path. This is the proposer build path's
522
+ // timing gate; it runs only after we know we are the synced proposer, so non-proposer invalidation
523
+ // and escape-hatch voting (which returned above) are never gated by build timing. Vote-only paths
524
+ // still run when block building is abandoned.
525
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
526
+ const nowForStartGate = this.dateProvider.now() / 1000;
527
+ if (nowForStartGate > startDeadline) {
528
+ this.log.debug(`Past start deadline for slot ${targetSlot}, abandoning block building`, {
529
+ targetSlot,
530
+ nowForStartGate,
531
+ startDeadline,
532
+ });
533
+ // Mark the slot as attempted so a deadline abort is not retried within the same slot. Vote-only actions
534
+ // still need to run because sync can succeed even when it is too late to start building a checkpoint.
535
+ await this.tryVoteAndPruneWhenCannotBuild({ slot, targetSlot });
536
+ this.lastSlotForCheckpointProposalJob = targetSlot;
537
+ return undefined;
538
+ }
539
+
540
+ // A proposal that cannot reach the committee is worse than not proposing: the slot is burned, and a
541
+ // node holding enough committee seats to reach quorum on its own would publish a checkpoint whose tx
542
+ // data was never gossiped to anyone, which is indistinguishable from data withholding. Skip building
543
+ // while peerless, but keep the vote/prune duties below. Only applies when p2p is enabled: setups that
544
+ // disable it (sandbox, single node, automine) legitimately propose with no peers.
545
+ const connectivity = await this.p2pClient.getP2PConnectivity();
546
+ const minPeersToPropose = this.config.minPeersToPropose;
547
+ if (connectivity.enabled && connectivity.connectedPeers < minPeersToPropose) {
548
+ this.log.warn(`Skipping checkpoint proposal for slot ${targetSlot} since we have too few connected peers`, {
549
+ targetSlot,
550
+ connectedPeers: connectivity.connectedPeers,
551
+ minPeersToPropose,
552
+ });
553
+ this.metrics.recordCheckpointPrecheckFailed('no_peers');
554
+ // Mark the slot as attempted so the gate is not re-evaluated on every tick within the slot. Vote-only
555
+ // actions still run: L1 duties (governance/slashing votes, prune) do not depend on gossip.
556
+ await this.tryVoteAndPruneWhenCannotBuild({ slot, targetSlot });
557
+ this.lastSlotForCheckpointProposalJob = targetSlot;
558
+ return undefined;
559
+ }
560
+
561
+ // We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
562
+ // Now run the full sync check before building.
563
+ const syncedTo = await this.checkSync({ ts, slot });
564
+ if (!syncedTo) {
565
+ return undefined;
566
+ }
567
+
289
568
  // Next checkpoint follows from the last synced one
290
569
  const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
291
570
 
292
571
  const logCtx = {
293
- now,
294
- syncedToL1Ts: syncedTo.l1Timestamp,
295
- syncedToL2Slot: getSlotAtTimestamp(syncedTo.l1Timestamp, this.l1Constants),
572
+ nowSeconds,
573
+ syncedToL2Slot: syncedTo.syncedL2Slot,
296
574
  slot,
575
+ targetSlot,
297
576
  slotTs: ts,
298
577
  checkpointNumber,
299
578
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex'),
300
579
  };
301
580
 
302
- // Check that we are a proposer for the next slot
303
- this.setState(SequencerState.PROPOSER_CHECK, slot);
304
- const [canPropose, proposer] = await this.checkCanPropose(slot);
581
+ // We are the synced proposer within the build window; enter the proposer-check state and build.
582
+ this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
305
583
 
306
- // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
307
- if (!canPropose) {
308
- await this.considerInvalidatingCheckpoint(syncedTo, slot);
584
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
585
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
586
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
587
+ if (checkpointNumber > confirmedCkpt + 2) {
588
+ this.log.verbose(
589
+ `Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`,
590
+ );
309
591
  return undefined;
310
592
  }
311
593
 
312
- // Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
313
- if (syncedTo.block && syncedTo.block.header.getSlot() >= slot) {
594
+ // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
595
+ if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
314
596
  this.log.warn(
315
- `Cannot propose block at next L2 slot ${slot} since that slot was taken by block ${syncedTo.blockNumber}`,
316
- { ...logCtx, block: syncedTo.block.header.toInspect() },
597
+ `Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`,
598
+ { ...logCtx, block: syncedTo.blockData.header.toInspect() },
317
599
  );
318
- this.metrics.recordBlockProposalPrecheckFailed('slot_already_taken');
600
+ this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
319
601
  return undefined;
320
602
  }
321
603
 
@@ -326,86 +608,168 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
326
608
  const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
327
609
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
328
610
  this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
329
- this.publisher = publisher;
330
611
 
331
- // In fisherman mode, set the actual proposer's address for simulations
332
- if (this.config.fishermanMode && proposer) {
333
- publisher.setProposerAddressForSimulation(proposer);
334
- this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
612
+ // Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
613
+ // Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
614
+ // will invalidate the currently invalid checkpoint on L1.
615
+ const invalidateCheckpoint =
616
+ syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid
617
+ ? undefined
618
+ : await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
619
+
620
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
621
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
622
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
623
+ let archiveForCheck = syncedTo.archive;
624
+
625
+ if (syncedTo.hasProposedCheckpoint) {
626
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
627
+ this.log.verbose(
628
+ `Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`,
629
+ { targetSlot, parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1) },
630
+ );
631
+ // Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
632
+ // own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
633
+ // view and can transiently diverge from the proposed parent (e.g. before the proposed
634
+ // parent's blocks have been applied locally); diverging here would cause the canProposeAt
635
+ // override to set archives[pending] to one value while we present another for comparison.
636
+ archiveForCheck = syncedTo.proposedCheckpointData!.archive.root;
637
+ } else if (invalidateCheckpoint) {
638
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
639
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
640
+ archiveForCheck = invalidateCheckpoint.lastArchive;
641
+ this.metrics.recordPipelineDepth(0);
642
+ } else {
643
+ this.metrics.recordPipelineDepth(0);
335
644
  }
336
645
 
337
- // Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
338
- const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
646
+ // Build the simulation plan: pending/proven override from pipelining or invalidation (or the
647
+ // current snapshot when neither applies, to short-circuit any pending prune in simulation),
648
+ // plus the parent checkpoint cell and fee header when pipelining.
649
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
650
+ checkpointNumber,
651
+ proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
652
+ invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
653
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
654
+ rollup: this.rollupContract,
655
+ signatureContext: this.signatureContext,
656
+ log: this.log,
657
+ });
339
658
 
340
- // Check with the rollup contract if we can indeed propose at the next L2 slot. This check should not fail
341
- // if all the previous checks are good, but we do it just in case.
342
- const canProposeCheck = await publisher.canProposeAtNextEthBlock(
343
- syncedTo.archive,
659
+ // The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
660
+ // so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
661
+ // simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
662
+ // actually fire at the target slot without it — so observers can spot "we are building
663
+ // optimistically across a pruning boundary" in the logs.
664
+ const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
665
+ if (provenOverride !== undefined && (await this.l2BlockSource.isPruneDueAtSlot(targetSlot))) {
666
+ this.log.warn(
667
+ `Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`,
668
+ { checkpointNumber, slot, targetSlot, provenOverride },
669
+ );
670
+ }
671
+
672
+ this.emit('preparing-checkpoint', {
673
+ targetSlot,
674
+ checkpointNumber,
675
+ hadProposedParent: syncedTo.hasProposedCheckpoint,
676
+ provenOverride,
677
+ simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending,
678
+ });
679
+
680
+ const canProposeCheck = await publisher.canProposeAt(
681
+ archiveForCheck,
344
682
  proposer ?? EthAddress.ZERO,
345
- invalidateCheckpoint,
683
+ simulationOverridesPlan,
346
684
  );
347
685
 
686
+ const proposeContext = {
687
+ hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
688
+ proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
689
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
690
+ isInvalidating: !!invalidateCheckpoint,
691
+ invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
692
+ archiveForCheck: archiveForCheck.toString(),
693
+ overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
694
+ overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
695
+ overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader,
696
+ };
697
+
348
698
  if (canProposeCheck === undefined) {
349
699
  this.log.warn(
350
700
  `Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`,
351
- logCtx,
701
+ { ...logCtx, ...proposeContext },
352
702
  );
353
703
  this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed', slot });
354
- this.metrics.recordBlockProposalPrecheckFailed('rollup_contract_check_failed');
704
+ this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
355
705
  return undefined;
356
706
  }
357
707
 
358
- if (canProposeCheck.slot !== slot) {
708
+ if (canProposeCheck.slot !== targetSlot) {
359
709
  this.log.warn(
360
- `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}.`,
361
- { ...logCtx, rollup: canProposeCheck, expectedSlot: slot },
710
+ `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}.`,
711
+ { ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: targetSlot },
362
712
  );
363
713
  this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch', slot });
364
- this.metrics.recordBlockProposalPrecheckFailed('slot_mismatch');
714
+ this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
365
715
  return undefined;
366
716
  }
367
717
 
368
718
  if (canProposeCheck.checkpointNumber !== checkpointNumber) {
369
719
  this.log.warn(
370
720
  `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}.`,
371
- { ...logCtx, rollup: canProposeCheck, expectedSlot: slot },
721
+ { ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: slot },
372
722
  );
373
723
  this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch', slot });
374
- this.metrics.recordBlockProposalPrecheckFailed('block_number_mismatch');
724
+ this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
375
725
  return undefined;
376
726
  }
377
727
 
378
- this.lastSlotForCheckpointProposalJob = slot;
379
- this.log.info(`Preparing checkpoint proposal ${checkpointNumber} at slot ${slot}`, { ...logCtx, proposer });
728
+ this.lastSlotForCheckpointProposalJob = targetSlot;
729
+
730
+ await this.p2pClient.prepareForSlot(targetSlot);
731
+ this.log.info(
732
+ `Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`,
733
+ {
734
+ ...logCtx,
735
+ ...proposeContext,
736
+ proposer,
737
+ },
738
+ );
380
739
 
381
740
  // Create and return the checkpoint proposal job
382
741
  return this.createCheckpointProposalJob(
383
- epoch,
384
- slot,
742
+ targetSlot,
743
+ targetEpoch,
385
744
  checkpointNumber,
386
745
  syncedTo.blockNumber,
746
+ syncedTo.checkpointedCheckpointNumber,
387
747
  proposer,
388
748
  publisher,
389
749
  attestorAddress,
390
750
  invalidateCheckpoint,
751
+ syncedTo.proposedCheckpointData,
391
752
  );
392
753
  }
393
754
 
394
755
  protected createCheckpointProposalJob(
395
- epoch: EpochNumber,
396
- slot: SlotNumber,
756
+ targetSlot: SlotNumber,
757
+ targetEpoch: EpochNumber,
397
758
  checkpointNumber: CheckpointNumber,
398
759
  syncedToBlockNumber: BlockNumber,
760
+ checkpointedCheckpointNumber: CheckpointNumber,
399
761
  proposer: EthAddress | undefined,
400
762
  publisher: SequencerPublisher,
401
763
  attestorAddress: EthAddress,
402
764
  invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
765
+ proposedCheckpointData?: ProposedCheckpointData,
403
766
  ): CheckpointProposalJob {
404
767
  return new CheckpointProposalJob(
405
- epoch,
406
- slot,
768
+ targetSlot,
769
+ targetEpoch,
407
770
  checkpointNumber,
408
771
  syncedToBlockNumber,
772
+ checkpointedCheckpointNumber,
409
773
  proposer,
410
774
  publisher,
411
775
  attestorAddress,
@@ -419,23 +783,36 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
419
783
  this.checkpointsBuilder,
420
784
  this.l2BlockSource,
421
785
  this.l1Constants,
786
+ this.signatureContext,
422
787
  this.config,
423
788
  this.timetable,
424
789
  this.slasherClient,
425
790
  this.epochCache,
426
791
  this.dateProvider,
427
792
  this.metrics,
793
+ this.checkpointProposalJobMetrics.createRecorder(),
428
794
  this,
795
+ this.pendingRequests,
429
796
  this.setState.bind(this),
430
797
  this.tracer,
431
798
  this.log.getBindings(),
799
+ proposedCheckpointData,
432
800
  );
433
801
  }
434
802
 
435
803
  /**
436
- * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
804
+ * Returns the current sequencer state.
805
+ */
806
+ public getState(): SequencerState {
807
+ return this.state;
808
+ }
809
+
810
+ /**
811
+ * Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
812
+ * records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
437
813
  * @param proposedState - The new state to transition to.
438
- * @param slotNumber - The current slot number.
814
+ * @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
815
+ * and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
439
816
  * @param force - Whether to force the transition even if the sequencer is stopped.
440
817
  */
441
818
  protected setState(
@@ -451,25 +828,39 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
451
828
  this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
452
829
  return;
453
830
  }
454
- let secondsIntoSlot = undefined;
455
- if (slotNumber !== undefined) {
456
- secondsIntoSlot = this.getSecondsIntoSlot(slotNumber);
457
- this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
458
- }
831
+ const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
832
+
833
+ const oldState = this.state;
834
+ const oldStateSlotNumber = this.stateSlotNumber;
835
+ const stateChanged = proposedState !== oldState;
836
+ // Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
837
+ // calls, read from the date provider so it tracks simulated time under a test/manual clock.
838
+ const transitionAtMs = this.dateProvider.now();
839
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
459
840
 
460
841
  const boringStates = [SequencerState.IDLE, SequencerState.SYNCHRONIZING];
461
842
  const logLevel =
462
- boringStates.includes(proposedState) && boringStates.includes(this.state)
463
- ? ('trace' as const)
464
- : ('debug' as const);
465
- this.log[logLevel](`Transitioning from ${this.state} to ${proposedState}`, { slotNumber, secondsIntoSlot });
843
+ boringStates.includes(proposedState) && boringStates.includes(oldState) ? ('trace' as const) : ('debug' as const);
844
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
845
+ oldState,
846
+ newState: proposedState,
847
+ slotNumber,
848
+ stateSlotNumber: oldStateSlotNumber,
849
+ secondsIntoBuildFrame,
850
+ ...(stateChanged && { stateDurationMs: Math.ceil(stateDurationMs) }),
851
+ });
466
852
 
467
853
  this.emit('state-changed', {
468
- oldState: this.state,
854
+ oldState,
469
855
  newState: proposedState,
470
- secondsIntoSlot,
471
- slot: slotNumber,
856
+ secondsIntoBuildFrame,
857
+ targetSlot: slotNumber,
472
858
  });
859
+ if (stateChanged) {
860
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
861
+ this.stateEnteredAtMs = transitionAtMs;
862
+ this.stateSlotNumber = slotNumber;
863
+ }
473
864
  this.state = proposedState;
474
865
  }
475
866
 
@@ -478,16 +869,15 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
478
869
  * We don't check against the previous block submitted since it may have been reorg'd out.
479
870
  */
480
871
  protected async checkSync(args: { ts: bigint; slot: SlotNumber }): Promise<SequencerSyncCheckResult | undefined> {
481
- // Check that the archiver and dependencies have synced to the previous L1 slot at least
482
- // TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
483
- // cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
484
- const l1Timestamp = await this.l2BlockSource.getL1Timestamp();
485
- const { slot, ts } = args;
486
- if (l1Timestamp === undefined || l1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration) < ts) {
872
+ // Check that the archiver has fully synced the L2 slot before the one we want to propose in.
873
+ // The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
874
+ // See getSyncedL2SlotNumber for how missed L1 blocks are handled.
875
+ const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
876
+ const { slot } = args;
877
+ if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
487
878
  this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
488
879
  slot,
489
- ts,
490
- l1Timestamp,
880
+ syncedL2Slot,
491
881
  });
492
882
  return undefined;
493
883
  }
@@ -497,54 +887,95 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
497
887
  number: syncSummary.latestBlockNumber,
498
888
  hash: syncSummary.latestBlockHash,
499
889
  })),
500
- this.l2BlockSource.getL2Tips().then(t => t.proposed),
890
+ this.l2BlockSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
501
891
  this.p2pClient.getStatus().then(p2p => p2p.syncedToL2Block),
502
- this.l1ToL2MessageSource.getL2Tips().then(t => t.proposed),
892
+ this.l1ToL2MessageSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
503
893
  this.l2BlockSource.getPendingChainValidationStatus(),
894
+ this.l2BlockSource.getProposedCheckpointData(),
504
895
  ] as const);
505
896
 
506
- const [worldState, l2BlockSource, p2p, l1ToL2MessageSource, pendingChainValidationStatus] = syncedBlocks;
897
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] =
898
+ syncedBlocks;
507
899
 
508
- // 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,
509
- // as the world state can compute the new genesis block hash, but other components use the hardcoded constant.
510
- // TODO(palla/mbps): Fix the above. All components should be able to handle dynamic genesis block hashes.
511
900
  const result =
512
- (l2BlockSource.number === 0 && worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSource.number === 0) ||
513
- (worldState.hash === l2BlockSource.hash &&
514
- p2p.hash === l2BlockSource.hash &&
515
- l1ToL2MessageSource.hash === l2BlockSource.hash);
901
+ worldState.hash === l2Tips.proposed.hash &&
902
+ p2p.hash === l2Tips.proposed.hash &&
903
+ l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash &&
904
+ l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash &&
905
+ l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
516
906
 
517
907
  if (!result) {
518
- this.log.debug(`Sequencer sync check failed`, { worldState, l2BlockSource, p2p, l1ToL2MessageSource });
908
+ this.log.debug(`Sequencer sync check failed`, {
909
+ worldState,
910
+ l2BlockSource: l2Tips.proposed,
911
+ p2p,
912
+ l1ToL2MessageSourceTips,
913
+ });
519
914
  return undefined;
520
915
  }
521
916
 
522
- // Special case for genesis state
523
917
  const blockNumber = worldState.number;
524
- if (blockNumber < INITIAL_L2_BLOCK_NUM) {
525
- const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
526
- return {
527
- checkpointNumber: CheckpointNumber.ZERO,
528
- blockNumber: BlockNumber.ZERO,
529
- archive,
530
- l1Timestamp,
531
- pendingChainValidationStatus,
918
+ const blockData = await this.l2BlockSource.getBlockData({ number: blockNumber });
919
+ if (!blockData) {
920
+ this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
921
+ blockNumber,
922
+ l2Tips,
923
+ syncedL2Slot,
924
+ ...args,
925
+ });
926
+ return undefined;
927
+ }
928
+
929
+ // Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
930
+ // proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
931
+ // our world-state tip past the checkpointed tip — while the proposing node never published the
932
+ // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
933
+ // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
934
+ // once their build slot ends; this guard is the correctness barrier during the grace window before.
935
+ // `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
936
+ // the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
937
+ // on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
938
+ if (
939
+ blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number &&
940
+ proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber
941
+ ) {
942
+ const logCtx = {
943
+ blockCheckpointNumber: blockData.checkpointNumber,
944
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
945
+ proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
946
+ blockNumber: blockData.header.getBlockNumber(),
947
+ blockSlot: blockData.header.getSlot(),
948
+ syncedL2Slot,
949
+ ...args,
532
950
  };
951
+
952
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
953
+ return undefined;
533
954
  }
534
955
 
535
- const block = await this.l2BlockSource.getL2Block(blockNumber);
536
- if (!block) {
537
- // this shouldn't really happen because a moment ago we checked that all components were in sync
538
- this.log.error(`Failed to get L2 block ${blockNumber} from the archiver with all components in sync`);
956
+ const hasProposedCheckpoint = proposedCheckpointData !== undefined;
957
+
958
+ // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
959
+ // The checkpoint number to build is derived as blockData.checkpointNumber + 1
960
+ if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
961
+ this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
962
+ proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
963
+ blockCheckpointNumber: blockData.checkpointNumber,
964
+ syncedL2Slot,
965
+ ...args,
966
+ });
539
967
  return undefined;
540
968
  }
541
969
 
542
970
  return {
543
- block,
544
- blockNumber: block.number,
545
- checkpointNumber: block.checkpointNumber,
546
- archive: block.archive.root,
547
- l1Timestamp,
971
+ blockData,
972
+ blockNumber: blockData.header.getBlockNumber(),
973
+ checkpointNumber: blockData.checkpointNumber,
974
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
975
+ archive: blockData.archive.root,
976
+ hasProposedCheckpoint,
977
+ proposedCheckpointData,
978
+ syncedL2Slot,
548
979
  pendingChainValidationStatus,
549
980
  };
550
981
  }
@@ -553,20 +984,20 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
553
984
  * Checks if we are the proposer for the next slot.
554
985
  * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
555
986
  */
556
- protected async checkCanPropose(slot: SlotNumber): Promise<[boolean, EthAddress | undefined]> {
987
+ protected async checkCanPropose(targetSlot: SlotNumber): Promise<[boolean, EthAddress | undefined]> {
557
988
  let proposer: EthAddress | undefined;
558
989
 
559
990
  try {
560
- proposer = await this.epochCache.getProposerAttesterAddressInSlot(slot);
991
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
561
992
  } catch (e) {
562
993
  if (e instanceof NoCommitteeError) {
563
- if (this.lastSlotForNoCommitteeWarning !== slot) {
564
- this.lastSlotForNoCommitteeWarning = slot;
565
- this.log.warn(`Cannot propose at next L2 slot ${slot} since the committee does not exist on L1`);
994
+ if (this.lastSlotForNoCommitteeWarning !== targetSlot) {
995
+ this.lastSlotForNoCommitteeWarning = targetSlot;
996
+ this.log.warn(`Cannot propose at target slot ${targetSlot} since the committee does not exist on L1`);
566
997
  }
567
998
  return [false, undefined];
568
999
  }
569
- this.log.error(`Error getting proposer for slot ${slot}`, e);
1000
+ this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
570
1001
  return [false, undefined];
571
1002
  }
572
1003
 
@@ -583,55 +1014,56 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
583
1014
  const weAreProposer = validatorAddresses.some(addr => addr.equals(proposer));
584
1015
 
585
1016
  if (!weAreProposer) {
586
- this.log.debug(`Cannot propose at slot ${slot} since we are not a proposer`, { validatorAddresses, proposer });
1017
+ this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
1018
+ targetSlot,
1019
+ validatorAddresses,
1020
+ proposer,
1021
+ });
587
1022
  return [false, proposer];
588
1023
  }
589
1024
 
1025
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
1026
+ targetSlot,
1027
+ proposer,
1028
+ });
590
1029
  return [true, proposer];
591
1030
  }
592
1031
 
593
1032
  /**
594
- * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
595
- * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
1033
+ * Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
1034
+ * block-building window. This allows the sequencer to participate in governance/slashing votes even when it
1035
+ * cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
596
1036
  */
597
- @trackSpan('Seqeuencer.tryVoteWhenSyncFails', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
598
- protected async tryVoteWhenSyncFails(args: { slot: SlotNumber; ts: bigint }): Promise<void> {
599
- const { slot } = args;
1037
+ @trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
1038
+ protected async tryVoteAndPruneWhenCannotBuild(args: { slot: SlotNumber; targetSlot: SlotNumber }): Promise<void> {
1039
+ const { slot, targetSlot } = args;
600
1040
 
601
1041
  // Prevent duplicate attempts in the same slot
602
- if (this.lastSlotForFallbackVote === slot) {
603
- this.log.trace(`Already attempted to vote in slot ${slot} (skipping)`);
1042
+ if (this.lastSlotForFallbackAction === slot) {
1043
+ this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
604
1044
  return;
605
1045
  }
606
1046
 
607
- // Check if we're past the max time for initializing a proposal
608
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
609
- const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_CHECKPOINT);
1047
+ // Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
1048
+ // Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
1049
+ // build-start deadline can miss the whole fallback window when the target advances with the clock.
1050
+ const nowSeconds = this.dateProvider.now() / 1000;
1051
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
610
1052
 
611
- // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
612
- // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
613
- if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
614
- this.log.trace(`Not attempting to vote since there is still time for block building`, {
615
- secondsIntoSlot,
616
- maxAllowedTime,
617
- });
618
- return;
619
- }
620
-
621
- this.log.trace(`Sync for slot ${slot} failed, checking for voting opportunities`, {
622
- secondsIntoSlot,
623
- maxAllowedTime,
1053
+ this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
1054
+ nowSeconds,
1055
+ startDeadline,
624
1056
  });
625
1057
 
626
1058
  // Check if we're a proposer or proposal is open
627
- const [canPropose, proposer] = await this.checkCanPropose(slot);
1059
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
628
1060
  if (!canPropose) {
629
1061
  this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
630
1062
  return;
631
1063
  }
632
1064
 
633
1065
  // Mark this slot as attempted
634
- this.lastSlotForFallbackVote = slot;
1066
+ this.lastSlotForFallbackAction = slot;
635
1067
 
636
1068
  // Get a publisher for voting
637
1069
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
@@ -641,9 +1073,9 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
641
1073
  slot,
642
1074
  });
643
1075
 
644
- // Enqueue governance and slashing votes
1076
+ // Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
645
1077
  const voter = new CheckpointVoter(
646
- slot,
1078
+ targetSlot,
647
1079
  publisher,
648
1080
  attestorAddress,
649
1081
  this.validatorClient,
@@ -656,13 +1088,41 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
656
1088
  const votesPromises = voter.enqueueVotes();
657
1089
  const votes = await Promise.all(votesPromises);
658
1090
 
659
- if (votes.every(p => !p)) {
660
- this.log.debug(`No votes to enqueue for slot ${slot}`);
1091
+ // Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
1092
+ // recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
1093
+ const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
1094
+
1095
+ // Bail if nothing to do
1096
+ if (votes.every(p => !p) && !pruneEnqueued) {
1097
+ this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
661
1098
  return;
662
1099
  }
663
1100
 
664
- this.log.info(`Voting in slot ${slot} despite sync failure`, { slot });
665
- await publisher.sendRequests();
1101
+ const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
1102
+ this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
1103
+ slot,
1104
+ pruneEnqueued,
1105
+ governanceVoteEnqueued: !!governanceVoteEnqueued,
1106
+ slashingVoteEnqueued: !!slashingVoteEnqueued,
1107
+ });
1108
+
1109
+ // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
1110
+ // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
1111
+ // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
1112
+ // work loop while waiting for the target slot to start, but track it so stop() can drain it.
1113
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1114
+ this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, { slot });
1115
+ });
1116
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
1117
+ }
1118
+
1119
+ private async tryEnqueuePruneIfPrunable(targetSlot: SlotNumber, publisher: SequencerPublisher): Promise<boolean> {
1120
+ try {
1121
+ return await publisher.enqueuePruneIfPrunable(targetSlot);
1122
+ } catch (err) {
1123
+ this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, { targetSlot });
1124
+ return false;
1125
+ }
666
1126
  }
667
1127
 
668
1128
  /**
@@ -672,25 +1132,34 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
672
1132
  @trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
673
1133
  protected async tryVoteWhenEscapeHatchOpen(args: {
674
1134
  slot: SlotNumber;
1135
+ targetSlot: SlotNumber;
675
1136
  proposer: EthAddress | undefined;
676
1137
  }): Promise<void> {
677
- const { slot, proposer } = args;
1138
+ const { slot, targetSlot, proposer } = args;
678
1139
 
679
1140
  // Prevent duplicate attempts in the same slot
680
- if (this.lastSlotForFallbackVote === slot) {
1141
+ if (this.lastSlotForFallbackAction === slot) {
681
1142
  this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
682
1143
  return;
683
1144
  }
684
1145
 
685
1146
  // Mark this slot as attempted
686
- this.lastSlotForFallbackVote = slot;
1147
+ this.lastSlotForFallbackAction = slot;
687
1148
 
688
1149
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
689
1150
 
690
- this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, { slot, attestorAddress });
1151
+ this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
1152
+ slot,
1153
+ targetSlot,
1154
+ attestorAddress,
1155
+ });
691
1156
 
1157
+ // Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
1158
+ // Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
1159
+ // L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
1160
+ // sign for `targetSlot` and delay submission to the start of `targetSlot`.
692
1161
  const voter = new CheckpointVoter(
693
- slot,
1162
+ targetSlot,
694
1163
  publisher,
695
1164
  attestorAddress,
696
1165
  this.validatorClient,
@@ -709,8 +1178,17 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
709
1178
  return;
710
1179
  }
711
1180
 
712
- this.log.info(`Voting in slot ${slot} (escape hatch open)`, { slot });
713
- await publisher.sendRequests();
1181
+ this.log.info(`Voting in slot ${slot} (escape hatch open)`, { slot, targetSlot });
1182
+ // Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
1183
+ // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1184
+ // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1185
+ // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1186
+ // waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
1187
+ // stop() can drain it.
1188
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1189
+ this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, { slot, targetSlot });
1190
+ });
1191
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
714
1192
  }
715
1193
 
716
1194
  /**
@@ -718,17 +1196,34 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
718
1196
  * has been there without being invalidated and whether the sequencer is in the committee or not. We always
719
1197
  * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
720
1198
  * and if they fail, any sequencer will try as well.
1199
+ * @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
1200
+ * @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
721
1201
  */
722
1202
  protected async considerInvalidatingCheckpoint(
723
- syncedTo: SequencerSyncCheckResult,
1203
+ pendingChainValidationStatus: ValidateCheckpointResult,
724
1204
  currentSlot: SlotNumber,
725
1205
  ): Promise<void> {
726
- const { pendingChainValidationStatus, l1Timestamp } = syncedTo;
727
1206
  if (pendingChainValidationStatus.valid) {
728
1207
  return;
729
1208
  }
730
1209
 
731
1210
  const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1211
+
1212
+ // Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
1213
+ // The guard is keyed by (checkpoint, slot) — so a different invalid checkpoint surfacing later in
1214
+ // the same slot is not suppressed — and is set only after a request is successfully simulated below,
1215
+ // so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
1216
+ if (
1217
+ this.lastInvalidationAttempt?.slot === currentSlot &&
1218
+ this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber
1219
+ ) {
1220
+ this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
1221
+ currentSlot,
1222
+ invalidCheckpointNumber,
1223
+ });
1224
+ return;
1225
+ }
1226
+
732
1227
  const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
733
1228
  const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
734
1229
  const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
@@ -738,7 +1233,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
738
1233
 
739
1234
  const logData = {
740
1235
  invalidL1Timestamp: invalidCheckpointTimestamp,
741
- l1Timestamp,
742
1236
  invalidCheckpoint: pendingChainValidationStatus.checkpoint,
743
1237
  secondsBeforeInvalidatingBlockAsCommitteeMember,
744
1238
  secondsBeforeInvalidatingBlockAsNonCommitteeMember,
@@ -791,6 +1285,10 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
791
1285
  return;
792
1286
  }
793
1287
 
1288
+ // We produced a valid invalidation request; record it so further ticks within this slot skip the
1289
+ // committee lookup, simulation, and submission above for this same invalid checkpoint.
1290
+ this.lastInvalidationAttempt = { slot: currentSlot, checkpointNumber: invalidCheckpointNumber };
1291
+
794
1292
  this.log.info(
795
1293
  invalidateAsCommitteeMember
796
1294
  ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member`
@@ -837,13 +1335,13 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
837
1335
  });
838
1336
  }
839
1337
 
840
- private getSlotStartBuildTimestamp(slotNumber: SlotNumber): number {
841
- return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
842
- }
843
-
844
- private getSecondsIntoSlot(slotNumber: SlotNumber): number {
845
- const slotStartTimestamp = this.getSlotStartBuildTimestamp(slotNumber);
846
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1338
+ /**
1339
+ * Wall-clock seconds elapsed since the build-frame start of the given target slot
1340
+ * (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
1341
+ */
1342
+ private getSecondsIntoBuildFrame(targetSlot: SlotNumber): number {
1343
+ const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
1344
+ return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
847
1345
  }
848
1346
 
849
1347
  public get aztecSlotDuration() {
@@ -866,20 +1364,24 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
866
1364
  return this.validatorClient?.getValidatorAddresses();
867
1365
  }
868
1366
 
869
- public getConfig() {
870
- return this.config;
1367
+ /** Updates the publisher factory's node keystore adapter after a keystore reload. */
1368
+ public updatePublisherNodeKeyStore(adapter: NodeKeystoreAdapter): void {
1369
+ this.publisherFactory.updateNodeKeyStore(adapter);
871
1370
  }
872
1371
 
873
- private get l1PublishingTime(): number {
874
- return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
1372
+ public getConfig() {
1373
+ return this.config;
875
1374
  }
876
1375
  }
877
1376
 
878
1377
  type SequencerSyncCheckResult = {
879
- block?: L2Block;
1378
+ blockData?: BlockData;
880
1379
  checkpointNumber: CheckpointNumber;
1380
+ checkpointedCheckpointNumber: CheckpointNumber;
881
1381
  blockNumber: BlockNumber;
882
1382
  archive: Fr;
883
- l1Timestamp: bigint;
1383
+ hasProposedCheckpoint: boolean;
1384
+ proposedCheckpointData?: ProposedCheckpointData;
1385
+ syncedL2Slot: SlotNumber;
884
1386
  pendingChainValidationStatus: ValidateCheckpointResult;
885
1387
  };