@aztec/sequencer-client 0.0.1-commit.2ed92850 → 0.0.1-commit.3100065

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 (137) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +34 -11
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +77 -39
  5. package/dest/config.d.ts +32 -6
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +94 -46
  8. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  9. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  10. package/dest/global_variable_builder/fee_predictor.js +138 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_provider.js +80 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +13 -28
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +9 -66
  17. package/dest/global_variable_builder/index.d.ts +4 -2
  18. package/dest/global_variable_builder/index.d.ts.map +1 -1
  19. package/dest/global_variable_builder/index.js +2 -0
  20. package/dest/publisher/config.d.ts +51 -17
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +131 -42
  23. package/dest/publisher/index.d.ts +2 -1
  24. package/dest/publisher/index.d.ts.map +1 -1
  25. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  26. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  27. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  28. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  29. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  31. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +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-metrics.d.ts +1 -1
  47. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  49. package/dest/publisher/sequencer-publisher.d.ts +107 -68
  50. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  51. package/dest/publisher/sequencer-publisher.js +545 -363
  52. package/dest/publisher/write_json.d.ts +11 -0
  53. package/dest/publisher/write_json.d.ts.map +1 -0
  54. package/dest/publisher/write_json.js +57 -0
  55. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  56. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  57. package/dest/sequencer/automine/automine_factory.js +85 -0
  58. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  59. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  60. package/dest/sequencer/automine/automine_sequencer.js +690 -0
  61. package/dest/sequencer/automine/index.d.ts +3 -0
  62. package/dest/sequencer/automine/index.d.ts.map +1 -0
  63. package/dest/sequencer/automine/index.js +2 -0
  64. package/dest/sequencer/checkpoint_proposal_job.d.ts +101 -22
  65. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  66. package/dest/sequencer/checkpoint_proposal_job.js +922 -286
  67. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  68. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  69. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  70. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  71. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  72. package/dest/sequencer/checkpoint_voter.js +2 -5
  73. package/dest/sequencer/errors.d.ts +1 -8
  74. package/dest/sequencer/errors.d.ts.map +1 -1
  75. package/dest/sequencer/errors.js +0 -9
  76. package/dest/sequencer/events.d.ts +62 -5
  77. package/dest/sequencer/events.d.ts.map +1 -1
  78. package/dest/sequencer/metrics.d.ts +23 -8
  79. package/dest/sequencer/metrics.d.ts.map +1 -1
  80. package/dest/sequencer/metrics.js +142 -36
  81. package/dest/sequencer/requests_tracker.d.ts +22 -0
  82. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  83. package/dest/sequencer/requests_tracker.js +33 -0
  84. package/dest/sequencer/sequencer.d.ts +181 -44
  85. package/dest/sequencer/sequencer.d.ts.map +1 -1
  86. package/dest/sequencer/sequencer.js +614 -216
  87. package/dest/sequencer/types.d.ts +2 -2
  88. package/dest/sequencer/types.d.ts.map +1 -1
  89. package/dest/test/index.d.ts +5 -7
  90. package/dest/test/index.d.ts.map +1 -1
  91. package/dest/test/mock_checkpoint_builder.d.ts +12 -12
  92. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  93. package/dest/test/mock_checkpoint_builder.js +45 -36
  94. package/dest/test/utils.d.ts +17 -3
  95. package/dest/test/utils.d.ts.map +1 -1
  96. package/dest/test/utils.js +28 -9
  97. package/package.json +28 -28
  98. package/src/client/sequencer-client.ts +110 -47
  99. package/src/config.ts +120 -55
  100. package/src/global_variable_builder/README.md +44 -0
  101. package/src/global_variable_builder/fee_predictor.ts +182 -0
  102. package/src/global_variable_builder/fee_provider.ts +97 -0
  103. package/src/global_variable_builder/global_builder.ts +20 -89
  104. package/src/global_variable_builder/index.ts +3 -1
  105. package/src/publisher/config.ts +173 -40
  106. package/src/publisher/index.ts +3 -0
  107. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  108. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  109. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  110. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  111. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  112. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  113. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  114. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  115. package/src/publisher/sequencer-publisher.ts +635 -460
  116. package/src/publisher/write_json.ts +78 -0
  117. package/src/sequencer/automine/README.md +60 -0
  118. package/src/sequencer/automine/automine_factory.ts +152 -0
  119. package/src/sequencer/automine/automine_sequencer.ts +796 -0
  120. package/src/sequencer/automine/index.ts +6 -0
  121. package/src/sequencer/checkpoint_proposal_job.ts +1133 -326
  122. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  123. package/src/sequencer/checkpoint_voter.ts +1 -12
  124. package/src/sequencer/errors.ts +0 -15
  125. package/src/sequencer/events.ts +66 -5
  126. package/src/sequencer/metrics.ts +164 -39
  127. package/src/sequencer/requests_tracker.ts +43 -0
  128. package/src/sequencer/sequencer.ts +729 -242
  129. package/src/sequencer/types.ts +1 -1
  130. package/src/test/index.ts +4 -6
  131. package/src/test/mock_checkpoint_builder.ts +65 -53
  132. package/src/test/utils.ts +64 -10
  133. package/dest/sequencer/timetable.d.ts +0 -90
  134. package/dest/sequencer/timetable.d.ts.map +0 -1
  135. package/dest/sequencer/timetable.js +0 -226
  136. package/src/sequencer/README.md +0 -531
  137. package/src/sequencer/timetable.ts +0 -282
@@ -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,15 +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;
94
+
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;
59
98
 
60
- /** The last slot for which we attempted to perform our voting duties with degraded block production */
61
- private lastSlotForFallbackVote: SlotNumber | undefined;
99
+ /** The last slot for which we logged "no committee" warning, to avoid spam */
100
+ private lastSlotForNoCommitteeWarning: SlotNumber | undefined;
62
101
 
63
102
  /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */
64
- private lastSlotForCheckpointProposalJob: SlotNumber | undefined;
103
+ protected lastSlotForCheckpointProposalJob: SlotNumber | undefined;
65
104
 
66
105
  /** Last successful checkpoint proposed */
67
106
  private lastCheckpointProposed: Checkpoint | undefined;
@@ -69,19 +108,26 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
69
108
  /** The last epoch for which we logged strategy comparison in fisherman mode. */
70
109
  private lastEpochForStrategyComparison: EpochNumber | undefined;
71
110
 
72
- /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */
73
- 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;
74
113
 
75
- // This shouldn't be here as this gets re-created each time we build/propose a block.
76
- // But we have a number of tests that abuse/rely on this class having a permanent publisher.
77
- // As long as those tests only configure a single publisher they will continue to work.
78
- // This will get re-assigned every time the sequencer goes to build a new block to a publisher that is valid
79
- // for the block proposer.
80
- // TODO(palla/mbps): Remove this field and fix tests
81
- protected publisher: SequencerPublisher | undefined;
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();
124
+
125
+ /** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */
126
+ protected timetable!: ProposerTimetable;
82
127
 
83
128
  /** Config for the sequencer */
84
129
  protected config: ResolvedSequencerConfig = DefaultSequencerConfig;
130
+ private readonly signatureContext: CoordinationSignatureContext;
85
131
 
86
132
  constructor(
87
133
  protected publisherFactory: SequencerPublisherFactory,
@@ -90,55 +136,171 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
90
136
  protected p2pClient: P2P,
91
137
  protected worldState: WorldStateSynchronizer,
92
138
  protected slasherClient: SlasherClientInterface | undefined,
93
- protected l2BlockSource: L2BlockSource & L2BlockSink,
139
+ protected l2BlockSource: L2BlockSource & L2BlockSink & ProposedCheckpointSink,
94
140
  protected l1ToL2MessageSource: L1ToL2MessageSource,
95
141
  protected checkpointsBuilder: FullNodeCheckpointsBuilder,
96
142
  protected l1Constants: SequencerRollupConstants,
97
143
  protected dateProvider: DateProvider,
98
144
  protected epochCache: EpochCache,
99
145
  protected rollupContract: RollupContract,
100
- config: SequencerConfig,
146
+ config: SequencerConfig & Pick<ChainConfig, 'l1ChainId' | 'rollupAddress'>,
101
147
  protected telemetry: TelemetryClient = getTelemetryClient(),
102
148
  protected log = createLogger('sequencer'),
103
149
  ) {
104
150
  super();
151
+ this.stateLog = log.createChild('state');
152
+ this.stateEnteredAtMs = this.dateProvider.now();
105
153
 
106
154
  // Add [FISHERMAN] prefix to logger if in fisherman mode
107
155
  if (config.fishermanMode) {
108
156
  this.log = log.createChild('[FISHERMAN]');
109
157
  }
110
158
 
159
+ this.signatureContext = {
160
+ chainId: config.l1ChainId,
161
+ rollupAddress: config.rollupAddress,
162
+ };
111
163
  this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
164
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
112
165
  this.updateConfig(config);
113
166
  }
114
167
 
115
- /** 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
+ */
116
176
  public updateConfig(config: Partial<SequencerConfig>) {
117
177
  const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
118
- this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowList'));
119
- this.config = merge(this.config, filteredConfig);
120
- this.timetable = new SequencerTimetable(
121
- {
122
- ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
123
- aztecSlotDuration: this.aztecSlotDuration,
124
- l1PublishingTime: this.l1PublishingTime,
125
- p2pPropagationTime: this.config.attestationPropagationTime,
126
- blockDurationMs: this.config.blockDurationMs,
127
- enforce: this.config.enforceTimeTable,
128
- },
129
- this.metrics,
130
- this.log,
131
- );
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;
132
219
  }
133
220
 
134
- /** Initializes the sequencer (precomputes tables and creates a publisher). Takes about 3s. */
135
- 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() {
136
285
  getKzg();
137
- this.publisher = (await this.publisherFactory.create(undefined)).publisher;
138
286
  }
139
287
 
140
- /** 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
+ */
141
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
+ }
142
304
  this.runningPromise = new RunningPromise(
143
305
  this.safeWork.bind(this),
144
306
  this.log,
@@ -149,35 +311,68 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
149
311
  this.log.info('Started sequencer');
150
312
  }
151
313
 
152
- /** 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
+ */
153
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
+ }
154
331
  this.log.info(`Stopping sequencer`);
155
332
  this.setState(SequencerState.STOPPING, undefined, { force: true });
156
- 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.
157
339
  await this.runningPromise?.stop();
340
+ this.pendingRequests.interruptRequests();
341
+ await this.pendingRequests.awaitRequests();
158
342
  this.setState(SequencerState.STOPPED, undefined, { force: true });
159
343
  this.log.info('Stopped sequencer');
160
344
  }
161
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
+
162
369
  /** Main sequencer loop with a try/catch */
163
370
  protected async safeWork() {
164
371
  try {
165
372
  await this.work();
166
373
  } catch (err) {
167
374
  this.emit('checkpoint-error', { error: err as Error });
168
- if (err instanceof SequencerTooSlowError) {
169
- // TODO(palla/mbps): Add missing states
170
- // Log as warn only if we had to abort halfway through the block proposal
171
- const logLvl = [SequencerState.INITIALIZING_CHECKPOINT, SequencerState.PROPOSER_CHECK].includes(
172
- err.proposedState,
173
- )
174
- ? ('debug' as const)
175
- : ('warn' as const);
176
- this.log[logLvl](err.message, { now: this.dateProvider.nowInSeconds() });
177
- } else {
178
- // Re-throw other errors
179
- throw err;
180
- }
375
+ throw err;
181
376
  } finally {
182
377
  this.setState(SequencerState.IDLE, undefined);
183
378
  }
@@ -199,14 +394,24 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
199
394
  @trackSpan('Sequencer.work')
200
395
  protected async work() {
201
396
  this.setState(SequencerState.SYNCHRONIZING, undefined);
202
- const { slot, ts, now, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
397
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
203
398
 
204
399
  // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
205
- 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
+ );
206
408
  if (!checkpointProposalJob) {
207
409
  return;
208
410
  }
209
411
 
412
+ // Track the job so we can await its pending L1 submission during shutdown
413
+ this.lastCheckpointProposalJob = checkpointProposalJob;
414
+
210
415
  // Execute the checkpoint proposal job
211
416
  const checkpoint = await checkpointProposalJob.execute();
212
417
 
@@ -215,64 +420,76 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
215
420
  this.lastCheckpointProposed = checkpoint;
216
421
  }
217
422
 
218
- // 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)
219
424
  if (
220
425
  this.config.fishermanMode &&
221
- (this.lastEpochForStrategyComparison === undefined || epoch > this.lastEpochForStrategyComparison)
426
+ (this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)
222
427
  ) {
223
- this.logStrategyComparison(epoch, checkpointProposalJob.getPublisher());
224
- this.lastEpochForStrategyComparison = epoch;
428
+ this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
429
+ this.lastEpochForStrategyComparison = targetEpoch;
225
430
  }
226
431
 
227
432
  return checkpoint;
228
433
  }
229
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
+
230
442
  /**
231
443
  * Prepares the checkpoint proposal by performing all necessary checks and setup.
232
444
  * This is the initial step in the main loop.
233
445
  * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
234
446
  */
235
447
  @trackSpan('Sequencer.prepareCheckpointProposal')
236
- private async prepareCheckpointProposal(
237
- epoch: EpochNumber,
448
+ protected async prepareCheckpointProposal(
238
449
  slot: SlotNumber,
450
+ targetSlot: SlotNumber,
451
+ epoch: EpochNumber,
452
+ targetEpoch: EpochNumber,
239
453
  ts: bigint,
240
- now: bigint,
454
+ nowSeconds: bigint,
241
455
  ): Promise<CheckpointProposalJob | undefined> {
242
- // Check we have not already processed this slot (cheapest check)
243
- // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
244
- // running against actual time (eg when we use sandbox-style automining)
245
- if (
246
- this.lastSlotForCheckpointProposalJob &&
247
- this.lastSlotForCheckpointProposalJob >= slot &&
248
- this.config.enforceTimeTable
249
- ) {
250
- 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`);
251
459
  return undefined;
252
460
  }
253
461
 
254
- // But if we have already proposed for this slot, the we definitely have to skip it, automining or not
255
- if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= slot) {
256
- 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
+ );
257
467
  return undefined;
258
468
  }
259
469
 
260
- // Check all components are synced to latest as seen by the archiver (queries all subsystems)
261
- const syncedTo = await this.checkSync({ ts, slot });
262
- if (!syncedTo) {
263
- 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
+ });
264
476
  return undefined;
265
477
  }
266
478
 
267
- // 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.
268
486
  // Still perform governance/slashing voting (as proposer) once per slot.
269
- 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);
270
489
 
271
490
  if (isEscapeHatchOpen) {
272
- this.setState(SequencerState.PROPOSER_CHECK, slot);
273
- const [canPropose, proposer] = await this.checkCanPropose(slot);
274
491
  if (canPropose) {
275
- await this.tryVoteWhenEscapeHatchOpen({ slot, proposer });
492
+ await this.tryVoteWhenEscapeHatchOpen({ slot, targetSlot, proposer });
276
493
  } else {
277
494
  this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
278
495
  slot,
@@ -283,36 +500,83 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
283
500
  return undefined;
284
501
  }
285
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
+ // We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
541
+ // Now run the full sync check before building.
542
+ const syncedTo = await this.checkSync({ ts, slot });
543
+ if (!syncedTo) {
544
+ return undefined;
545
+ }
546
+
286
547
  // Next checkpoint follows from the last synced one
287
548
  const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
288
549
 
289
550
  const logCtx = {
290
- now,
291
- syncedToL1Ts: syncedTo.l1Timestamp,
292
- syncedToL2Slot: getSlotAtTimestamp(syncedTo.l1Timestamp, this.l1Constants),
551
+ nowSeconds,
552
+ syncedToL2Slot: syncedTo.syncedL2Slot,
293
553
  slot,
554
+ targetSlot,
294
555
  slotTs: ts,
295
556
  checkpointNumber,
296
557
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex'),
297
558
  };
298
559
 
299
- // Check that we are a proposer for the next slot
300
- this.setState(SequencerState.PROPOSER_CHECK, slot);
301
- const [canPropose, proposer] = await this.checkCanPropose(slot);
560
+ // We are the synced proposer within the build window; enter the proposer-check state and build.
561
+ this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
302
562
 
303
- // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
304
- if (!canPropose) {
305
- await this.considerInvalidatingCheckpoint(syncedTo, slot);
563
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
564
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
565
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
566
+ if (checkpointNumber > confirmedCkpt + 2) {
567
+ this.log.verbose(
568
+ `Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`,
569
+ );
306
570
  return undefined;
307
571
  }
308
572
 
309
- // Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
310
- if (syncedTo.block && syncedTo.block.header.getSlot() >= slot) {
573
+ // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
574
+ if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
311
575
  this.log.warn(
312
- `Cannot propose block at next L2 slot ${slot} since that slot was taken by block ${syncedTo.blockNumber}`,
313
- { ...logCtx, block: syncedTo.block.header.toInspect() },
576
+ `Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`,
577
+ { ...logCtx, block: syncedTo.blockData.header.toInspect() },
314
578
  );
315
- this.metrics.recordBlockProposalPrecheckFailed('slot_already_taken');
579
+ this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
316
580
  return undefined;
317
581
  }
318
582
 
@@ -323,86 +587,168 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
323
587
  const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
324
588
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
325
589
  this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
326
- this.publisher = publisher;
327
590
 
328
- // In fisherman mode, set the actual proposer's address for simulations
329
- if (this.config.fishermanMode && proposer) {
330
- publisher.setProposerAddressForSimulation(proposer);
331
- this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
591
+ // Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
592
+ // Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
593
+ // will invalidate the currently invalid checkpoint on L1.
594
+ const invalidateCheckpoint =
595
+ syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid
596
+ ? undefined
597
+ : await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
598
+
599
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
600
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
601
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
602
+ let archiveForCheck = syncedTo.archive;
603
+
604
+ if (syncedTo.hasProposedCheckpoint) {
605
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
606
+ this.log.verbose(
607
+ `Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`,
608
+ { targetSlot, parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1) },
609
+ );
610
+ // Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
611
+ // own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
612
+ // view and can transiently diverge from the proposed parent (e.g. before the proposed
613
+ // parent's blocks have been applied locally); diverging here would cause the canProposeAt
614
+ // override to set archives[pending] to one value while we present another for comparison.
615
+ archiveForCheck = syncedTo.proposedCheckpointData!.archive.root;
616
+ } else if (invalidateCheckpoint) {
617
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
618
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
619
+ archiveForCheck = invalidateCheckpoint.lastArchive;
620
+ this.metrics.recordPipelineDepth(0);
621
+ } else {
622
+ this.metrics.recordPipelineDepth(0);
332
623
  }
333
624
 
334
- // Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
335
- const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
625
+ // Build the simulation plan: pending/proven override from pipelining or invalidation (or the
626
+ // current snapshot when neither applies, to short-circuit any pending prune in simulation),
627
+ // plus the parent checkpoint cell and fee header when pipelining.
628
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
629
+ checkpointNumber,
630
+ proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
631
+ invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
632
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
633
+ rollup: this.rollupContract,
634
+ signatureContext: this.signatureContext,
635
+ log: this.log,
636
+ });
637
+
638
+ // The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
639
+ // so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
640
+ // simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
641
+ // actually fire at the target slot without it — so observers can spot "we are building
642
+ // optimistically across a pruning boundary" in the logs.
643
+ const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
644
+ if (provenOverride !== undefined && (await this.l2BlockSource.isPruneDueAtSlot(targetSlot))) {
645
+ this.log.warn(
646
+ `Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`,
647
+ { checkpointNumber, slot, targetSlot, provenOverride },
648
+ );
649
+ }
336
650
 
337
- // Check with the rollup contract if we can indeed propose at the next L2 slot. This check should not fail
338
- // if all the previous checks are good, but we do it just in case.
339
- const canProposeCheck = await publisher.canProposeAtNextEthBlock(
340
- syncedTo.archive,
651
+ this.emit('preparing-checkpoint', {
652
+ targetSlot,
653
+ checkpointNumber,
654
+ hadProposedParent: syncedTo.hasProposedCheckpoint,
655
+ provenOverride,
656
+ simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending,
657
+ });
658
+
659
+ const canProposeCheck = await publisher.canProposeAt(
660
+ archiveForCheck,
341
661
  proposer ?? EthAddress.ZERO,
342
- invalidateCheckpoint,
662
+ simulationOverridesPlan,
343
663
  );
344
664
 
665
+ const proposeContext = {
666
+ hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
667
+ proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
668
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
669
+ isInvalidating: !!invalidateCheckpoint,
670
+ invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
671
+ archiveForCheck: archiveForCheck.toString(),
672
+ overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
673
+ overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
674
+ overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader,
675
+ };
676
+
345
677
  if (canProposeCheck === undefined) {
346
678
  this.log.warn(
347
679
  `Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`,
348
- logCtx,
680
+ { ...logCtx, ...proposeContext },
349
681
  );
350
682
  this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed', slot });
351
- this.metrics.recordBlockProposalPrecheckFailed('rollup_contract_check_failed');
683
+ this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
352
684
  return undefined;
353
685
  }
354
686
 
355
- if (canProposeCheck.slot !== slot) {
687
+ if (canProposeCheck.slot !== targetSlot) {
356
688
  this.log.warn(
357
- `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}.`,
358
- { ...logCtx, rollup: canProposeCheck, expectedSlot: slot },
689
+ `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}.`,
690
+ { ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: targetSlot },
359
691
  );
360
692
  this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch', slot });
361
- this.metrics.recordBlockProposalPrecheckFailed('slot_mismatch');
693
+ this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
362
694
  return undefined;
363
695
  }
364
696
 
365
697
  if (canProposeCheck.checkpointNumber !== checkpointNumber) {
366
698
  this.log.warn(
367
699
  `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}.`,
368
- { ...logCtx, rollup: canProposeCheck, expectedSlot: slot },
700
+ { ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: slot },
369
701
  );
370
702
  this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch', slot });
371
- this.metrics.recordBlockProposalPrecheckFailed('block_number_mismatch');
703
+ this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
372
704
  return undefined;
373
705
  }
374
706
 
375
- this.lastSlotForCheckpointProposalJob = slot;
376
- this.log.info(`Preparing checkpoint proposal ${checkpointNumber} at slot ${slot}`, { ...logCtx, proposer });
707
+ this.lastSlotForCheckpointProposalJob = targetSlot;
708
+
709
+ await this.p2pClient.prepareForSlot(targetSlot);
710
+ this.log.info(
711
+ `Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`,
712
+ {
713
+ ...logCtx,
714
+ ...proposeContext,
715
+ proposer,
716
+ },
717
+ );
377
718
 
378
719
  // Create and return the checkpoint proposal job
379
720
  return this.createCheckpointProposalJob(
380
- epoch,
381
- slot,
721
+ targetSlot,
722
+ targetEpoch,
382
723
  checkpointNumber,
383
724
  syncedTo.blockNumber,
725
+ syncedTo.checkpointedCheckpointNumber,
384
726
  proposer,
385
727
  publisher,
386
728
  attestorAddress,
387
729
  invalidateCheckpoint,
730
+ syncedTo.proposedCheckpointData,
388
731
  );
389
732
  }
390
733
 
391
734
  protected createCheckpointProposalJob(
392
- epoch: EpochNumber,
393
- slot: SlotNumber,
735
+ targetSlot: SlotNumber,
736
+ targetEpoch: EpochNumber,
394
737
  checkpointNumber: CheckpointNumber,
395
738
  syncedToBlockNumber: BlockNumber,
739
+ checkpointedCheckpointNumber: CheckpointNumber,
396
740
  proposer: EthAddress | undefined,
397
741
  publisher: SequencerPublisher,
398
742
  attestorAddress: EthAddress,
399
743
  invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
744
+ proposedCheckpointData?: ProposedCheckpointData,
400
745
  ): CheckpointProposalJob {
401
746
  return new CheckpointProposalJob(
402
- epoch,
403
- slot,
747
+ targetSlot,
748
+ targetEpoch,
404
749
  checkpointNumber,
405
750
  syncedToBlockNumber,
751
+ checkpointedCheckpointNumber,
406
752
  proposer,
407
753
  publisher,
408
754
  attestorAddress,
@@ -416,23 +762,36 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
416
762
  this.checkpointsBuilder,
417
763
  this.l2BlockSource,
418
764
  this.l1Constants,
765
+ this.signatureContext,
419
766
  this.config,
420
767
  this.timetable,
421
768
  this.slasherClient,
422
769
  this.epochCache,
423
770
  this.dateProvider,
424
771
  this.metrics,
772
+ this.checkpointProposalJobMetrics.createRecorder(),
425
773
  this,
774
+ this.pendingRequests,
426
775
  this.setState.bind(this),
427
- this.log,
428
776
  this.tracer,
777
+ this.log.getBindings(),
778
+ proposedCheckpointData,
429
779
  );
430
780
  }
431
781
 
432
782
  /**
433
- * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
783
+ * Returns the current sequencer state.
784
+ */
785
+ public getState(): SequencerState {
786
+ return this.state;
787
+ }
788
+
789
+ /**
790
+ * Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
791
+ * records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
434
792
  * @param proposedState - The new state to transition to.
435
- * @param slotNumber - The current slot number.
793
+ * @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
794
+ * and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
436
795
  * @param force - Whether to force the transition even if the sequencer is stopped.
437
796
  */
438
797
  protected setState(
@@ -448,25 +807,39 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
448
807
  this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
449
808
  return;
450
809
  }
451
- let secondsIntoSlot = undefined;
452
- if (slotNumber !== undefined) {
453
- secondsIntoSlot = this.getSecondsIntoSlot(slotNumber);
454
- this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
455
- }
810
+ const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
811
+
812
+ const oldState = this.state;
813
+ const oldStateSlotNumber = this.stateSlotNumber;
814
+ const stateChanged = proposedState !== oldState;
815
+ // Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
816
+ // calls, read from the date provider so it tracks simulated time under a test/manual clock.
817
+ const transitionAtMs = this.dateProvider.now();
818
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
456
819
 
457
820
  const boringStates = [SequencerState.IDLE, SequencerState.SYNCHRONIZING];
458
821
  const logLevel =
459
- boringStates.includes(proposedState) && boringStates.includes(this.state)
460
- ? ('trace' as const)
461
- : ('debug' as const);
462
- this.log[logLevel](`Transitioning from ${this.state} to ${proposedState}`, { slotNumber, secondsIntoSlot });
822
+ boringStates.includes(proposedState) && boringStates.includes(oldState) ? ('trace' as const) : ('debug' as const);
823
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
824
+ oldState,
825
+ newState: proposedState,
826
+ slotNumber,
827
+ stateSlotNumber: oldStateSlotNumber,
828
+ secondsIntoBuildFrame,
829
+ ...(stateChanged && { stateDurationMs: Math.ceil(stateDurationMs) }),
830
+ });
463
831
 
464
832
  this.emit('state-changed', {
465
- oldState: this.state,
833
+ oldState,
466
834
  newState: proposedState,
467
- secondsIntoSlot,
468
- slot: slotNumber,
835
+ secondsIntoBuildFrame,
836
+ targetSlot: slotNumber,
469
837
  });
838
+ if (stateChanged) {
839
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
840
+ this.stateEnteredAtMs = transitionAtMs;
841
+ this.stateSlotNumber = slotNumber;
842
+ }
470
843
  this.state = proposedState;
471
844
  }
472
845
 
@@ -475,16 +848,15 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
475
848
  * We don't check against the previous block submitted since it may have been reorg'd out.
476
849
  */
477
850
  protected async checkSync(args: { ts: bigint; slot: SlotNumber }): Promise<SequencerSyncCheckResult | undefined> {
478
- // Check that the archiver and dependencies have synced to the previous L1 slot at least
479
- // TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
480
- // cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
481
- const l1Timestamp = await this.l2BlockSource.getL1Timestamp();
482
- const { slot, ts } = args;
483
- if (l1Timestamp === undefined || l1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration) < ts) {
851
+ // Check that the archiver has fully synced the L2 slot before the one we want to propose in.
852
+ // The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
853
+ // See getSyncedL2SlotNumber for how missed L1 blocks are handled.
854
+ const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
855
+ const { slot } = args;
856
+ if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
484
857
  this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
485
858
  slot,
486
- ts,
487
- l1Timestamp,
859
+ syncedL2Slot,
488
860
  });
489
861
  return undefined;
490
862
  }
@@ -494,54 +866,95 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
494
866
  number: syncSummary.latestBlockNumber,
495
867
  hash: syncSummary.latestBlockHash,
496
868
  })),
497
- this.l2BlockSource.getL2Tips().then(t => t.proposed),
869
+ this.l2BlockSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
498
870
  this.p2pClient.getStatus().then(p2p => p2p.syncedToL2Block),
499
- this.l1ToL2MessageSource.getL2Tips().then(t => t.proposed),
871
+ this.l1ToL2MessageSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
500
872
  this.l2BlockSource.getPendingChainValidationStatus(),
873
+ this.l2BlockSource.getProposedCheckpointData(),
501
874
  ] as const);
502
875
 
503
- const [worldState, l2BlockSource, p2p, l1ToL2MessageSource, pendingChainValidationStatus] = syncedBlocks;
876
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] =
877
+ syncedBlocks;
504
878
 
505
- // 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,
506
- // as the world state can compute the new genesis block hash, but other components use the hardcoded constant.
507
- // TODO(palla/mbps): Fix the above. All components should be able to handle dynamic genesis block hashes.
508
879
  const result =
509
- (l2BlockSource.number === 0 && worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSource.number === 0) ||
510
- (worldState.hash === l2BlockSource.hash &&
511
- p2p.hash === l2BlockSource.hash &&
512
- l1ToL2MessageSource.hash === l2BlockSource.hash);
880
+ worldState.hash === l2Tips.proposed.hash &&
881
+ p2p.hash === l2Tips.proposed.hash &&
882
+ l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash &&
883
+ l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash &&
884
+ l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
513
885
 
514
886
  if (!result) {
515
- this.log.debug(`Sequencer sync check failed`, { worldState, l2BlockSource, p2p, l1ToL2MessageSource });
887
+ this.log.debug(`Sequencer sync check failed`, {
888
+ worldState,
889
+ l2BlockSource: l2Tips.proposed,
890
+ p2p,
891
+ l1ToL2MessageSourceTips,
892
+ });
516
893
  return undefined;
517
894
  }
518
895
 
519
- // Special case for genesis state
520
896
  const blockNumber = worldState.number;
521
- if (blockNumber < INITIAL_L2_BLOCK_NUM) {
522
- const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
523
- return {
524
- checkpointNumber: CheckpointNumber.ZERO,
525
- blockNumber: BlockNumber.ZERO,
526
- archive,
527
- l1Timestamp,
528
- pendingChainValidationStatus,
897
+ const blockData = await this.l2BlockSource.getBlockData({ number: blockNumber });
898
+ if (!blockData) {
899
+ this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
900
+ blockNumber,
901
+ l2Tips,
902
+ syncedL2Slot,
903
+ ...args,
904
+ });
905
+ return undefined;
906
+ }
907
+
908
+ // Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
909
+ // proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
910
+ // our world-state tip past the checkpointed tip — while the proposing node never published the
911
+ // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
912
+ // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
913
+ // once their build slot ends; this guard is the correctness barrier during the grace window before.
914
+ // `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
915
+ // the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
916
+ // on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
917
+ if (
918
+ blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number &&
919
+ proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber
920
+ ) {
921
+ const logCtx = {
922
+ blockCheckpointNumber: blockData.checkpointNumber,
923
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
924
+ proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
925
+ blockNumber: blockData.header.getBlockNumber(),
926
+ blockSlot: blockData.header.getSlot(),
927
+ syncedL2Slot,
928
+ ...args,
529
929
  };
930
+
931
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
932
+ return undefined;
530
933
  }
531
934
 
532
- const block = await this.l2BlockSource.getL2Block(blockNumber);
533
- if (!block) {
534
- // this shouldn't really happen because a moment ago we checked that all components were in sync
535
- this.log.error(`Failed to get L2 block ${blockNumber} from the archiver with all components in sync`);
935
+ const hasProposedCheckpoint = proposedCheckpointData !== undefined;
936
+
937
+ // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
938
+ // The checkpoint number to build is derived as blockData.checkpointNumber + 1
939
+ if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
940
+ this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
941
+ proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
942
+ blockCheckpointNumber: blockData.checkpointNumber,
943
+ syncedL2Slot,
944
+ ...args,
945
+ });
536
946
  return undefined;
537
947
  }
538
948
 
539
949
  return {
540
- block,
541
- blockNumber: block.number,
542
- checkpointNumber: block.checkpointNumber,
543
- archive: block.archive.root,
544
- l1Timestamp,
950
+ blockData,
951
+ blockNumber: blockData.header.getBlockNumber(),
952
+ checkpointNumber: blockData.checkpointNumber,
953
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
954
+ archive: blockData.archive.root,
955
+ hasProposedCheckpoint,
956
+ proposedCheckpointData,
957
+ syncedL2Slot,
545
958
  pendingChainValidationStatus,
546
959
  };
547
960
  }
@@ -550,17 +963,20 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
550
963
  * Checks if we are the proposer for the next slot.
551
964
  * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
552
965
  */
553
- protected async checkCanPropose(slot: SlotNumber): Promise<[boolean, EthAddress | undefined]> {
966
+ protected async checkCanPropose(targetSlot: SlotNumber): Promise<[boolean, EthAddress | undefined]> {
554
967
  let proposer: EthAddress | undefined;
555
968
 
556
969
  try {
557
- proposer = await this.epochCache.getProposerAttesterAddressInSlot(slot);
970
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
558
971
  } catch (e) {
559
972
  if (e instanceof NoCommitteeError) {
560
- this.log.warn(`Cannot propose at next L2 slot ${slot} since the committee does not exist on L1`);
973
+ if (this.lastSlotForNoCommitteeWarning !== targetSlot) {
974
+ this.lastSlotForNoCommitteeWarning = targetSlot;
975
+ this.log.warn(`Cannot propose at target slot ${targetSlot} since the committee does not exist on L1`);
976
+ }
561
977
  return [false, undefined];
562
978
  }
563
- this.log.error(`Error getting proposer for slot ${slot}`, e);
979
+ this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
564
980
  return [false, undefined];
565
981
  }
566
982
 
@@ -577,55 +993,56 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
577
993
  const weAreProposer = validatorAddresses.some(addr => addr.equals(proposer));
578
994
 
579
995
  if (!weAreProposer) {
580
- this.log.debug(`Cannot propose at slot ${slot} since we are not a proposer`, { validatorAddresses, proposer });
996
+ this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
997
+ targetSlot,
998
+ validatorAddresses,
999
+ proposer,
1000
+ });
581
1001
  return [false, proposer];
582
1002
  }
583
1003
 
1004
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
1005
+ targetSlot,
1006
+ proposer,
1007
+ });
584
1008
  return [true, proposer];
585
1009
  }
586
1010
 
587
1011
  /**
588
- * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
589
- * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
1012
+ * Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
1013
+ * block-building window. This allows the sequencer to participate in governance/slashing votes even when it
1014
+ * cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
590
1015
  */
591
- @trackSpan('Seqeuencer.tryVoteWhenSyncFails', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
592
- protected async tryVoteWhenSyncFails(args: { slot: SlotNumber; ts: bigint }): Promise<void> {
593
- const { slot } = args;
1016
+ @trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
1017
+ protected async tryVoteAndPruneWhenCannotBuild(args: { slot: SlotNumber; targetSlot: SlotNumber }): Promise<void> {
1018
+ const { slot, targetSlot } = args;
594
1019
 
595
1020
  // Prevent duplicate attempts in the same slot
596
- if (this.lastSlotForFallbackVote === slot) {
597
- this.log.trace(`Already attempted to vote in slot ${slot} (skipping)`);
1021
+ if (this.lastSlotForFallbackAction === slot) {
1022
+ this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
598
1023
  return;
599
1024
  }
600
1025
 
601
- // Check if we're past the max time for initializing a proposal
602
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
603
- const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_CHECKPOINT);
604
-
605
- // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
606
- // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
607
- if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
608
- this.log.trace(`Not attempting to vote since there is still time for block building`, {
609
- secondsIntoSlot,
610
- maxAllowedTime,
611
- });
612
- return;
613
- }
1026
+ // Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
1027
+ // Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
1028
+ // build-start deadline can miss the whole fallback window when the target advances with the clock.
1029
+ const nowSeconds = this.dateProvider.now() / 1000;
1030
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
614
1031
 
615
- this.log.trace(`Sync for slot ${slot} failed, checking for voting opportunities`, {
616
- secondsIntoSlot,
617
- maxAllowedTime,
1032
+ this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
1033
+ nowSeconds,
1034
+ startDeadline,
618
1035
  });
619
1036
 
620
1037
  // Check if we're a proposer or proposal is open
621
- const [canPropose, proposer] = await this.checkCanPropose(slot);
1038
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
622
1039
  if (!canPropose) {
623
1040
  this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
624
1041
  return;
625
1042
  }
626
1043
 
627
1044
  // Mark this slot as attempted
628
- this.lastSlotForFallbackVote = slot;
1045
+ this.lastSlotForFallbackAction = slot;
629
1046
 
630
1047
  // Get a publisher for voting
631
1048
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
@@ -635,9 +1052,9 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
635
1052
  slot,
636
1053
  });
637
1054
 
638
- // Enqueue governance and slashing votes
1055
+ // Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
639
1056
  const voter = new CheckpointVoter(
640
- slot,
1057
+ targetSlot,
641
1058
  publisher,
642
1059
  attestorAddress,
643
1060
  this.validatorClient,
@@ -650,13 +1067,41 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
650
1067
  const votesPromises = voter.enqueueVotes();
651
1068
  const votes = await Promise.all(votesPromises);
652
1069
 
653
- if (votes.every(p => !p)) {
654
- this.log.debug(`No votes to enqueue for slot ${slot}`);
1070
+ // Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
1071
+ // recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
1072
+ const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
1073
+
1074
+ // Bail if nothing to do
1075
+ if (votes.every(p => !p) && !pruneEnqueued) {
1076
+ this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
655
1077
  return;
656
1078
  }
657
1079
 
658
- this.log.info(`Voting in slot ${slot} despite sync failure`, { slot });
659
- await publisher.sendRequests();
1080
+ const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
1081
+ this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
1082
+ slot,
1083
+ pruneEnqueued,
1084
+ governanceVoteEnqueued: !!governanceVoteEnqueued,
1085
+ slashingVoteEnqueued: !!slashingVoteEnqueued,
1086
+ });
1087
+
1088
+ // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
1089
+ // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
1090
+ // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
1091
+ // work loop while waiting for the target slot to start, but track it so stop() can drain it.
1092
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1093
+ this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, { slot });
1094
+ });
1095
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
1096
+ }
1097
+
1098
+ private async tryEnqueuePruneIfPrunable(targetSlot: SlotNumber, publisher: SequencerPublisher): Promise<boolean> {
1099
+ try {
1100
+ return await publisher.enqueuePruneIfPrunable(targetSlot);
1101
+ } catch (err) {
1102
+ this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, { targetSlot });
1103
+ return false;
1104
+ }
660
1105
  }
661
1106
 
662
1107
  /**
@@ -666,25 +1111,34 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
666
1111
  @trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
667
1112
  protected async tryVoteWhenEscapeHatchOpen(args: {
668
1113
  slot: SlotNumber;
1114
+ targetSlot: SlotNumber;
669
1115
  proposer: EthAddress | undefined;
670
1116
  }): Promise<void> {
671
- const { slot, proposer } = args;
1117
+ const { slot, targetSlot, proposer } = args;
672
1118
 
673
1119
  // Prevent duplicate attempts in the same slot
674
- if (this.lastSlotForFallbackVote === slot) {
1120
+ if (this.lastSlotForFallbackAction === slot) {
675
1121
  this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
676
1122
  return;
677
1123
  }
678
1124
 
679
1125
  // Mark this slot as attempted
680
- this.lastSlotForFallbackVote = slot;
1126
+ this.lastSlotForFallbackAction = slot;
681
1127
 
682
1128
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
683
1129
 
684
- this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, { slot, attestorAddress });
1130
+ this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
1131
+ slot,
1132
+ targetSlot,
1133
+ attestorAddress,
1134
+ });
685
1135
 
1136
+ // Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
1137
+ // Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
1138
+ // L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
1139
+ // sign for `targetSlot` and delay submission to the start of `targetSlot`.
686
1140
  const voter = new CheckpointVoter(
687
- slot,
1141
+ targetSlot,
688
1142
  publisher,
689
1143
  attestorAddress,
690
1144
  this.validatorClient,
@@ -703,8 +1157,17 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
703
1157
  return;
704
1158
  }
705
1159
 
706
- this.log.info(`Voting in slot ${slot} (escape hatch open)`, { slot });
707
- await publisher.sendRequests();
1160
+ this.log.info(`Voting in slot ${slot} (escape hatch open)`, { slot, targetSlot });
1161
+ // Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
1162
+ // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1163
+ // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1164
+ // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1165
+ // waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
1166
+ // stop() can drain it.
1167
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1168
+ this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, { slot, targetSlot });
1169
+ });
1170
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
708
1171
  }
709
1172
 
710
1173
  /**
@@ -712,17 +1175,34 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
712
1175
  * has been there without being invalidated and whether the sequencer is in the committee or not. We always
713
1176
  * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
714
1177
  * and if they fail, any sequencer will try as well.
1178
+ * @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
1179
+ * @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
715
1180
  */
716
1181
  protected async considerInvalidatingCheckpoint(
717
- syncedTo: SequencerSyncCheckResult,
1182
+ pendingChainValidationStatus: ValidateCheckpointResult,
718
1183
  currentSlot: SlotNumber,
719
1184
  ): Promise<void> {
720
- const { pendingChainValidationStatus, l1Timestamp } = syncedTo;
721
1185
  if (pendingChainValidationStatus.valid) {
722
1186
  return;
723
1187
  }
724
1188
 
725
1189
  const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1190
+
1191
+ // Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
1192
+ // The guard is keyed by (checkpoint, slot) — so a different invalid checkpoint surfacing later in
1193
+ // the same slot is not suppressed — and is set only after a request is successfully simulated below,
1194
+ // so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
1195
+ if (
1196
+ this.lastInvalidationAttempt?.slot === currentSlot &&
1197
+ this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber
1198
+ ) {
1199
+ this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
1200
+ currentSlot,
1201
+ invalidCheckpointNumber,
1202
+ });
1203
+ return;
1204
+ }
1205
+
726
1206
  const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
727
1207
  const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
728
1208
  const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
@@ -732,7 +1212,6 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
732
1212
 
733
1213
  const logData = {
734
1214
  invalidL1Timestamp: invalidCheckpointTimestamp,
735
- l1Timestamp,
736
1215
  invalidCheckpoint: pendingChainValidationStatus.checkpoint,
737
1216
  secondsBeforeInvalidatingBlockAsCommitteeMember,
738
1217
  secondsBeforeInvalidatingBlockAsNonCommitteeMember,
@@ -785,6 +1264,10 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
785
1264
  return;
786
1265
  }
787
1266
 
1267
+ // We produced a valid invalidation request; record it so further ticks within this slot skip the
1268
+ // committee lookup, simulation, and submission above for this same invalid checkpoint.
1269
+ this.lastInvalidationAttempt = { slot: currentSlot, checkpointNumber: invalidCheckpointNumber };
1270
+
788
1271
  this.log.info(
789
1272
  invalidateAsCommitteeMember
790
1273
  ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member`
@@ -831,13 +1314,13 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
831
1314
  });
832
1315
  }
833
1316
 
834
- private getSlotStartBuildTimestamp(slotNumber: SlotNumber): number {
835
- return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
836
- }
837
-
838
- private getSecondsIntoSlot(slotNumber: SlotNumber): number {
839
- const slotStartTimestamp = this.getSlotStartBuildTimestamp(slotNumber);
840
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1317
+ /**
1318
+ * Wall-clock seconds elapsed since the build-frame start of the given target slot
1319
+ * (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
1320
+ */
1321
+ private getSecondsIntoBuildFrame(targetSlot: SlotNumber): number {
1322
+ const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
1323
+ return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
841
1324
  }
842
1325
 
843
1326
  public get aztecSlotDuration() {
@@ -860,20 +1343,24 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
860
1343
  return this.validatorClient?.getValidatorAddresses();
861
1344
  }
862
1345
 
863
- public getConfig() {
864
- return this.config;
1346
+ /** Updates the publisher factory's node keystore adapter after a keystore reload. */
1347
+ public updatePublisherNodeKeyStore(adapter: NodeKeystoreAdapter): void {
1348
+ this.publisherFactory.updateNodeKeyStore(adapter);
865
1349
  }
866
1350
 
867
- private get l1PublishingTime(): number {
868
- return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
1351
+ public getConfig() {
1352
+ return this.config;
869
1353
  }
870
1354
  }
871
1355
 
872
1356
  type SequencerSyncCheckResult = {
873
- block?: L2Block;
1357
+ blockData?: BlockData;
874
1358
  checkpointNumber: CheckpointNumber;
1359
+ checkpointedCheckpointNumber: CheckpointNumber;
875
1360
  blockNumber: BlockNumber;
876
1361
  archive: Fr;
877
- l1Timestamp: bigint;
1362
+ hasProposedCheckpoint: boolean;
1363
+ proposedCheckpointData?: ProposedCheckpointData;
1364
+ syncedL2Slot: SlotNumber;
878
1365
  pendingChainValidationStatus: ValidateCheckpointResult;
879
1366
  };