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

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