@aztec/sequencer-client 5.0.0-private.20260319 → 5.0.0-rc.1

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 (105) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +8 -3
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +17 -32
  5. package/dest/config.d.ts +10 -4
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +48 -24
  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 +128 -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 +67 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +14 -14
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +16 -51
  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 +15 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +19 -4
  23. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +3 -4
  24. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  25. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  26. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  27. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  28. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -5
  29. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  30. package/dest/publisher/sequencer-publisher-factory.js +2 -3
  31. package/dest/publisher/sequencer-publisher.d.ts +70 -64
  32. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher.js +312 -533
  34. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  35. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  36. package/dest/sequencer/automine/automine_factory.js +85 -0
  37. package/dest/sequencer/automine/automine_sequencer.d.ts +184 -0
  38. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  39. package/dest/sequencer/automine/automine_sequencer.js +677 -0
  40. package/dest/sequencer/automine/index.d.ts +3 -0
  41. package/dest/sequencer/automine/index.d.ts.map +1 -0
  42. package/dest/sequencer/automine/index.js +2 -0
  43. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  44. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  45. package/dest/sequencer/chain_state_overrides.js +98 -0
  46. package/dest/sequencer/checkpoint_proposal_job.d.ts +73 -21
  47. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  48. package/dest/sequencer/checkpoint_proposal_job.js +709 -199
  49. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  50. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  51. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  52. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  53. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  54. package/dest/sequencer/checkpoint_voter.js +2 -5
  55. package/dest/sequencer/errors.d.ts +1 -8
  56. package/dest/sequencer/errors.d.ts.map +1 -1
  57. package/dest/sequencer/errors.js +0 -9
  58. package/dest/sequencer/events.d.ts +61 -4
  59. package/dest/sequencer/events.d.ts.map +1 -1
  60. package/dest/sequencer/metrics.d.ts +9 -10
  61. package/dest/sequencer/metrics.d.ts.map +1 -1
  62. package/dest/sequencer/metrics.js +34 -20
  63. package/dest/sequencer/sequencer.d.ts +112 -27
  64. package/dest/sequencer/sequencer.d.ts.map +1 -1
  65. package/dest/sequencer/sequencer.js +467 -147
  66. package/dest/sequencer/types.d.ts +2 -2
  67. package/dest/sequencer/types.d.ts.map +1 -1
  68. package/dest/test/index.d.ts +3 -3
  69. package/dest/test/index.d.ts.map +1 -1
  70. package/dest/test/utils.d.ts +15 -1
  71. package/dest/test/utils.d.ts.map +1 -1
  72. package/dest/test/utils.js +23 -6
  73. package/package.json +28 -27
  74. package/src/client/sequencer-client.ts +29 -41
  75. package/src/config.ts +57 -24
  76. package/src/global_variable_builder/README.md +44 -0
  77. package/src/global_variable_builder/fee_predictor.ts +172 -0
  78. package/src/global_variable_builder/fee_provider.ts +80 -0
  79. package/src/global_variable_builder/global_builder.ts +25 -63
  80. package/src/global_variable_builder/index.ts +3 -1
  81. package/src/publisher/config.ts +40 -6
  82. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  83. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  84. package/src/publisher/sequencer-publisher-factory.ts +3 -6
  85. package/src/publisher/sequencer-publisher.ts +368 -577
  86. package/src/sequencer/automine/README.md +60 -0
  87. package/src/sequencer/automine/automine_factory.ts +152 -0
  88. package/src/sequencer/automine/automine_sequencer.ts +783 -0
  89. package/src/sequencer/automine/index.ts +6 -0
  90. package/src/sequencer/chain_state_overrides.ts +169 -0
  91. package/src/sequencer/checkpoint_proposal_job.ts +818 -224
  92. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  93. package/src/sequencer/checkpoint_voter.ts +1 -12
  94. package/src/sequencer/errors.ts +0 -15
  95. package/src/sequencer/events.ts +65 -4
  96. package/src/sequencer/metrics.ts +43 -24
  97. package/src/sequencer/sequencer.ts +542 -164
  98. package/src/sequencer/types.ts +1 -1
  99. package/src/test/index.ts +2 -2
  100. package/src/test/utils.ts +59 -10
  101. package/dest/sequencer/timetable.d.ts +0 -88
  102. package/dest/sequencer/timetable.d.ts.map +0 -1
  103. package/dest/sequencer/timetable.js +0 -222
  104. package/src/sequencer/README.md +0 -531
  105. package/src/sequencer/timetable.ts +0 -283
@@ -1,4 +1,5 @@
1
- import type { EpochCache } from '@aztec/epoch-cache';
1
+ import { type EpochCache, PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
2
+ import type { SimulationOverridesPlan } from '@aztec/ethereum/contracts';
2
3
  import {
3
4
  BlockNumber,
4
5
  CheckpointNumber,
@@ -13,11 +14,12 @@ import {
13
14
  generateUnrecoverableSignature,
14
15
  } from '@aztec/foundation/crypto/secp256k1-signer';
15
16
  import { Fr } from '@aztec/foundation/curves/bn254';
17
+ import { InterruptError, TimeoutError } from '@aztec/foundation/error';
16
18
  import { EthAddress } from '@aztec/foundation/eth-address';
17
19
  import { Signature } from '@aztec/foundation/eth-signature';
18
20
  import { filter } from '@aztec/foundation/iterator';
19
21
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
20
- import { sleep, sleepUntil } from '@aztec/foundation/sleep';
22
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
21
23
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
22
24
  import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
23
25
  import type { P2P } from '@aztec/p2p';
@@ -29,9 +31,16 @@ import {
29
31
  type L2BlockSink,
30
32
  type L2BlockSource,
31
33
  MaliciousCommitteeAttestationsAndSigners,
34
+ type ProposedCheckpointSink,
35
+ type ValidateCheckpointResult,
32
36
  } from '@aztec/stdlib/block';
33
- import { type Checkpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
34
- import { getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
37
+ import {
38
+ type Checkpoint,
39
+ type ProposedCheckpointData,
40
+ getPreviousCheckpointOutHashes,
41
+ validateCheckpoint,
42
+ } from '@aztec/stdlib/checkpoint';
43
+ import { computeQuorum, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
35
44
  import { Gas } from '@aztec/stdlib/gas';
36
45
  import {
37
46
  type BlockBuilderOptions,
@@ -43,11 +52,14 @@ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@azte
43
52
  import type {
44
53
  BlockProposal,
45
54
  BlockProposalOptions,
55
+ CheckpointAttestation,
46
56
  CheckpointProposal,
47
57
  CheckpointProposalOptions,
58
+ CoordinationSignatureContext,
48
59
  } from '@aztec/stdlib/p2p';
49
60
  import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
50
61
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
62
+ import type { ProposerTimetable } from '@aztec/stdlib/timetable';
51
63
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
52
64
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
53
65
  import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
@@ -56,16 +68,32 @@ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validato
56
68
 
57
69
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
58
70
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
71
+ import { buildCheckpointSimulationOverridesPlan } from './chain_state_overrides.js';
72
+ import type { CheckpointProposalJobMetricsRecorder } from './checkpoint_proposal_job_metrics.js';
59
73
  import { CheckpointVoter } from './checkpoint_voter.js';
60
74
  import { SequencerInterruptedError } from './errors.js';
61
75
  import type { SequencerEvents } from './events.js';
62
76
  import type { SequencerMetrics } from './metrics.js';
63
- import type { SequencerTimetable } from './timetable.js';
64
77
  import type { SequencerRollupConstants } from './types.js';
65
78
  import { SequencerState } from './utils.js';
66
79
 
67
80
  /** How much time to sleep while waiting for min transactions to accumulate for a block */
68
81
  const TXS_POLLING_MS = 500;
82
+ const ARCHIVER_SYNC_POLLING_MS = 200;
83
+
84
+ /** Result from proposeCheckpoint when a checkpoint was successfully built and broadcast. */
85
+ type CheckpointProposalBroadcast = {
86
+ checkpoint: Checkpoint;
87
+ proposal: CheckpointProposal;
88
+ blockProposedAt: number;
89
+ };
90
+
91
+ /** Result after attestation collection and signing, ready for L1 submission. */
92
+ type CheckpointProposalResult = {
93
+ checkpoint: Checkpoint;
94
+ attestations: CommitteeAttestationsAndSigners;
95
+ attestationsSignature: Signature;
96
+ };
69
97
 
70
98
  /**
71
99
  * Handles the execution of a checkpoint proposal after the initial preparation phase.
@@ -75,14 +103,31 @@ const TXS_POLLING_MS = 500;
75
103
  */
76
104
  export class CheckpointProposalJob implements Traceable {
77
105
  protected readonly log: Logger;
106
+ private readonly checkpointEventLog: Logger;
107
+
108
+ /** Tracks the fire-and-forget L1 submission promise so it can be awaited during shutdown. */
109
+ private pendingL1Submission: Promise<void> | undefined;
110
+ private readonly interruptibleSleep = new InterruptibleSleep();
111
+ private interrupted = false;
112
+
113
+ /**
114
+ * Chain state overrides built once per slot in proposeCheckpoint after the checkpoint is
115
+ * complete. Carries the pending parent override (archive + slot + fee header) for pipelining,
116
+ * or the invalidation pending override when rolling back. Consumed by
117
+ * publisher.validateBlockHeader before broadcast.
118
+ */
119
+ private checkpointSimulationOverridesPlan?: SimulationOverridesPlan;
120
+
121
+ private getSignatureContext(): CoordinationSignatureContext {
122
+ return this.signatureContext;
123
+ }
78
124
 
79
125
  constructor(
80
- private readonly slotNow: SlotNumber,
81
126
  private readonly targetSlot: SlotNumber,
82
- private readonly epochNow: EpochNumber,
83
127
  private readonly targetEpoch: EpochNumber,
84
128
  private readonly checkpointNumber: CheckpointNumber,
85
129
  private readonly syncedToBlockNumber: BlockNumber,
130
+ private readonly checkpointedCheckpointNumber: CheckpointNumber,
86
131
  // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
87
132
  private readonly proposer: EthAddress | undefined,
88
133
  private readonly publisher: SequencerPublisher,
@@ -95,38 +140,92 @@ export class CheckpointProposalJob implements Traceable {
95
140
  private readonly l1ToL2MessageSource: L1ToL2MessageSource,
96
141
  private readonly l2BlockSource: L2BlockSource,
97
142
  private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
98
- private readonly blockSink: L2BlockSink,
143
+ private readonly blockSink: L2BlockSink & ProposedCheckpointSink,
99
144
  private readonly l1Constants: SequencerRollupConstants,
145
+ private readonly signatureContext: CoordinationSignatureContext,
100
146
  protected config: ResolvedSequencerConfig,
101
- protected timetable: SequencerTimetable,
147
+ protected timetable: ProposerTimetable,
102
148
  private readonly slasherClient: SlasherClientInterface | undefined,
103
149
  private readonly epochCache: EpochCache,
104
150
  private readonly dateProvider: DateProvider,
105
151
  private readonly metrics: SequencerMetrics,
106
- private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
107
- private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
152
+ private readonly checkpointMetrics: CheckpointProposalJobMetricsRecorder,
153
+ protected readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
154
+ private readonly setStateFn: (state: SequencerState, slot: SlotNumber) => void,
108
155
  public readonly tracer: Tracer,
109
156
  bindings?: LoggerBindings,
157
+ private readonly proposedCheckpointData?: ProposedCheckpointData,
110
158
  ) {
111
159
  this.log = createLogger('sequencer:checkpoint-proposal', {
112
160
  ...bindings,
113
- instanceId: `slot-${this.slotNow}`,
161
+ instanceId: `slot-${this.getBuildSlot()}`,
162
+ });
163
+ this.checkpointEventLog = createLogger('sequencer:checkpoint-events', {
164
+ ...bindings,
165
+ instanceId: `slot-${this.getBuildSlot()}`,
114
166
  });
115
167
  }
116
168
 
117
- /** The wall-clock slot during which the proposer builds. */
118
- private get slot(): SlotNumber {
119
- return this.slotNow;
169
+ /**
170
+ * The wall-clock slot during which this job builds, i.e. the slot one before {@link targetSlot} under
171
+ * proposer pipelining. Also the slot of the parent checkpoint this job builds on top of.
172
+ */
173
+ private getBuildSlot(): SlotNumber {
174
+ return SlotNumber(this.targetSlot - PROPOSER_PIPELINING_SLOT_OFFSET);
120
175
  }
121
176
 
122
- /** The wall-clock epoch. */
123
- private get epoch(): EpochNumber {
124
- return this.epochNow;
177
+ /**
178
+ * Sets the sequencer state for this job, reporting the target slot the checkpoint is being proposed for
179
+ * (not the wall-clock build slot). The slot is informational on the event payload/metrics; the job knows
180
+ * its own target slot, so callers only pass the state.
181
+ */
182
+ private setState(state: SequencerState): void {
183
+ this.setStateFn(state, this.targetSlot);
184
+ }
185
+
186
+ /** Awaits the pending L1 submission if one is in progress. Call during shutdown. */
187
+ public async awaitPendingSubmission(): Promise<void> {
188
+ this.log.info('Awaiting pending L1 payload submission');
189
+ await this.pendingL1Submission;
190
+ }
191
+
192
+ /** Interrupts job-owned waits, including the publisher's send-at-slot sleep, so shutdown can finish. */
193
+ public interrupt(): void {
194
+ this.interrupted = true;
195
+ this.interruptibleSleep.interrupt(true);
196
+ this.publisher.interrupt();
197
+ }
198
+
199
+ private async awaitInterruptibleSleep(ms: number): Promise<void> {
200
+ if (this.interrupted) {
201
+ throw new SequencerInterruptedError();
202
+ }
203
+ if (ms <= 0) {
204
+ return;
205
+ }
206
+ try {
207
+ await this.interruptibleSleep.sleep(ms);
208
+ } catch (err) {
209
+ if (err instanceof InterruptError) {
210
+ throw new SequencerInterruptedError();
211
+ }
212
+ throw err;
213
+ }
214
+ }
215
+
216
+ private logCheckpointEvent(eventName: string, message: string, fields: Record<string, unknown>): void {
217
+ this.checkpointEventLog.debug(message, {
218
+ eventName: `sequencer-checkpoint-${eventName}`,
219
+ ...fields,
220
+ });
125
221
  }
126
222
 
127
223
  /**
128
224
  * Executes the checkpoint proposal job.
129
- * Returns the published checkpoint if successful, undefined otherwise.
225
+ * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
226
+ * Attestation collection, signing, and L1 submission are backgrounded so the
227
+ * work loop can return to IDLE immediately for consecutive slot proposals.
228
+ * Returns the built checkpoint if successful, undefined otherwise.
130
229
  */
131
230
  @trackSpan('CheckpointProposalJob.execute')
132
231
  public async execute(): Promise<Checkpoint | undefined> {
@@ -145,56 +244,309 @@ export class CheckpointProposalJob implements Traceable {
145
244
  this.log,
146
245
  ).enqueueVotes();
147
246
 
148
- // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
149
- const checkpoint = await this.proposeCheckpoint();
150
-
151
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
152
- await Promise.all(votesPromises);
153
-
154
- if (checkpoint) {
155
- this.metrics.recordCheckpointProposalSuccess();
247
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
248
+ // Returns after broadcast — attestation collection is deferred.
249
+ const broadcast = await this.proposeCheckpoint();
250
+
251
+ if (!broadcast) {
252
+ await Promise.all(votesPromises);
253
+ // Still submit votes even without a checkpoint.
254
+ // Under proposer pipelining, vote-offenses signatures are EIP-712-bound to `targetSlot`
255
+ // (the pipelined slot in which the multicall is expected to mine). Submitting at the
256
+ // wall-clock time would let the multicall mine in a different L2 slot, causing
257
+ // signature verification to fail silently inside Multicall3. Delay submission to the
258
+ // start of `targetSlot` so the tx mines in the slot the vote was signed for.
259
+ if (!this.config.fishermanMode) {
260
+ this.pendingL1Submission = this.publisher.sendRequestsAt(this.targetSlot).then(() => {});
261
+ }
262
+ return undefined;
156
263
  }
157
264
 
265
+ const { checkpoint } = broadcast;
266
+ this.metrics.recordCheckpointProposalSuccess();
267
+
158
268
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
159
269
  if (this.config.fishermanMode) {
160
270
  await this.handleCheckpointEndAsFisherman(checkpoint);
161
- return;
271
+ return checkpoint;
162
272
  }
163
273
 
164
- // If pipelining, wait until the submission slot so L1 recognizes the pipelined proposer
165
- if (this.epochCache.isProposerPipeliningEnabled()) {
166
- const submissionSlotTimestamp =
167
- getTimestampForSlot(this.targetSlot, this.l1Constants) - BigInt(this.l1Constants.ethereumSlotDuration);
168
- this.log.info(`Waiting until submission slot ${this.targetSlot} for L1 submission`, {
169
- slot: this.slot,
170
- submissionSlot: this.targetSlot,
171
- submissionSlotTimestamp,
274
+ // Background the attestation signing L1 pipeline so the work loop is unblocked
275
+ this.pendingL1Submission = this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises);
276
+
277
+ // Return the built checkpoint immediately — the work loop is now unblocked
278
+ return checkpoint;
279
+ }
280
+
281
+ /**
282
+ * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
283
+ * Runs as a fire-and-forget task stored in `pendingL1Submission` so the work loop is unblocked.
284
+ */
285
+ private async waitForAttestationsAndEnqueueSubmissionAsync(
286
+ broadcast: CheckpointProposalBroadcast,
287
+ votesPromises: Promise<unknown>[],
288
+ ): Promise<void> {
289
+ const { checkpoint } = broadcast;
290
+
291
+ try {
292
+ // Wait for all votes actions, enqueued at the beginning, to resolve
293
+ await Promise.all(votesPromises);
294
+
295
+ // Try to collect attestations from the committee
296
+ const signedAttestations = await this.getSignedCommitteeAttestations(broadcast);
297
+
298
+ // Wait for the previous checkpoint to land on L1 before submitting, so we can check it
299
+ // matches the proposed checkpoint we used as parent, and has valid attestations.
300
+ if (signedAttestations && (await this.waitForValidParentCheckpointOnL1())) {
301
+ await this.enqueueCheckpointForSubmission({ checkpoint, ...signedAttestations });
302
+ }
303
+
304
+ // If we failed to collect attestations, at least check if we need to issue an invalidation
305
+ if (!signedAttestations && (await this.waitForSyncedL2SlotNumber(this.getBuildSlot()))) {
306
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
307
+ if (!validationStatus.valid) {
308
+ this.log.warn(
309
+ `Checkpoint ${validationStatus.checkpoint.checkpointNumber} has invalid attestations, enqueuing invalidation in spite of attestation collection failure`,
310
+ { checkpoint: validationStatus.checkpoint, reason: validationStatus.reason },
311
+ );
312
+ await this.enqueueInvalidation(validationStatus);
313
+ }
314
+ }
315
+
316
+ // Send whatever was enqueued: votes + (propose | invalidation | nothing).
317
+ const l1Response = await this.publisher.sendRequestsAt(this.targetSlot);
318
+ const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
319
+ if (proposedAction) {
320
+ this.logCheckpointEvent('published', `Checkpoint published for slot ${this.targetSlot}`, {
321
+ slot: this.targetSlot,
322
+ checkpointNumber: this.checkpointNumber,
323
+ successfulActions: l1Response?.successfulActions,
324
+ sentActions: l1Response?.sentActions,
325
+ });
326
+ this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
327
+ const coinbase = checkpoint.header.coinbase;
328
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
329
+ } else {
330
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
331
+ slot: this.targetSlot,
332
+ checkpointNumber: this.checkpointNumber,
333
+ successfulActions: l1Response?.successfulActions,
334
+ failedActions: l1Response?.failedActions,
335
+ sentActions: l1Response?.sentActions,
336
+ expiredActions: l1Response?.expiredActions,
337
+ reason: 'propose_action_not_successful',
338
+ });
339
+ this.log.warn(`Checkpoint publish failed for slot ${this.targetSlot}`, {
340
+ slot: this.targetSlot,
341
+ checkpointNumber: this.checkpointNumber,
342
+ successfulActions: l1Response?.successfulActions,
343
+ failedActions: l1Response?.failedActions,
344
+ sentActions: l1Response?.sentActions,
345
+ expiredActions: l1Response?.expiredActions,
346
+ reason: 'propose_action_not_successful',
347
+ });
348
+ this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
349
+ this.metrics.recordPipelineDiscard();
350
+ }
351
+ } catch (err) {
352
+ if (err instanceof SequencerInterruptedError) {
353
+ return;
354
+ }
355
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
356
+ slot: this.targetSlot,
357
+ checkpointNumber: this.checkpointNumber,
358
+ reason: err instanceof Error ? err.message : String(err),
359
+ });
360
+ this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err, {
361
+ slot: this.targetSlot,
362
+ checkpointNumber: this.checkpointNumber,
363
+ reason: err instanceof Error ? err.message : String(err),
364
+ });
365
+ this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
366
+ this.metrics.recordPipelineDiscard();
367
+ }
368
+ }
369
+
370
+ /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */
371
+ private async enqueueCheckpointForSubmission(result: CheckpointProposalResult): Promise<void> {
372
+ const { checkpoint, attestations, attestationsSignature } = result;
373
+
374
+ this.setState(SequencerState.PUBLISHING_CHECKPOINT);
375
+ // Latest L1 block the propose can still land in for the target slot: the last Ethereum block inside
376
+ // the target slot (`target_slot_start + S - E`). This is one ethereum slot later than
377
+ // `attestation_deadline` (= last_ethereum_block_in_target_slot - E), which bounds when validators must
378
+ // have signed, not when the proposer must have sent. Using the attestation deadline here is too tight:
379
+ // attestations are collected up to (and, when not enforcing, past) it, so the propose tx would be
380
+ // enqueued already expired and time out before it can mine.
381
+ const lastL1BlockInTargetSlot =
382
+ Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) +
383
+ this.l1Constants.slotDuration -
384
+ this.l1Constants.ethereumSlotDuration;
385
+ const txTimeoutAt = new Date(lastL1BlockInTargetSlot * 1000);
386
+
387
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
388
+ if (
389
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
390
+ this.config.skipPublishingCheckpointsPercent > 0
391
+ ) {
392
+ const roll = Math.max(0, randomInt(100));
393
+ if (roll < this.config.skipPublishingCheckpointsPercent) {
394
+ this.log.warn(
395
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${roll}`,
396
+ );
397
+ return;
398
+ }
399
+ }
400
+
401
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
402
+ txTimeoutAt,
403
+ });
404
+ }
405
+
406
+ /**
407
+ * Wait until the archiver syncs past the given L2 slot number.
408
+ * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
409
+ * L1 submission window and is no longer useful.
410
+ */
411
+ private async waitForSyncedL2SlotNumber(waitForSlot: SlotNumber): Promise<boolean> {
412
+ const targetSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
413
+ const targetSlotEndMs = (targetSlotStart + this.l1Constants.slotDuration) * 1000;
414
+ const syncDelayTolerance = this.l1Constants.ethereumSlotDuration * 2 * 1000;
415
+ const timeoutSeconds = Math.max(0.1, (targetSlotEndMs + syncDelayTolerance - this.dateProvider.now()) / 1000);
416
+
417
+ try {
418
+ const timer = new Timer();
419
+ while (true) {
420
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
421
+ if (syncedSlot !== undefined && syncedSlot >= waitForSlot) {
422
+ return true;
423
+ }
424
+ if (timeoutSeconds && timer.s() > timeoutSeconds) {
425
+ throw new TimeoutError(`Timeout awaiting archiver sync past slot ${waitForSlot}`);
426
+ }
427
+ await this.awaitInterruptibleSleep(ARCHIVER_SYNC_POLLING_MS);
428
+ }
429
+ } catch (err) {
430
+ if (err instanceof SequencerInterruptedError) {
431
+ throw err;
432
+ }
433
+ this.log.warn(
434
+ `Archiver did not sync L1 past slot ${waitForSlot} before slot ${this.targetSlot} expired, discarding pipelined work`,
435
+ { checkpointNumber: this.checkpointNumber },
436
+ );
437
+ this.emitPipelinedCheckpointDiscarded('archiver-sync-timeout');
438
+ return false;
439
+ }
440
+ }
441
+
442
+ /**
443
+ * Waits for the parent checkpoint to land on L1 before submitting a pipelined checkpoint.
444
+ * Polls until the archiver has synced L1 past the parent's slot, then verifies:
445
+ * - If we built on a proposed parent: it must have landed on L1 with matching hash and valid attestations.
446
+ * - If we built without a proposed parent: no new checkpoint must have appeared for that slot.
447
+ * If the parent has invalid attestations, enqueues an invalidation. Returns whether to proceed with the proposal.
448
+ */
449
+ protected async waitForValidParentCheckpointOnL1(): Promise<boolean> {
450
+ if (this.config.skipWaitForValidParentCheckpointOnL1) {
451
+ this.log.warn(`Skipping waitForValidParentCheckpointOnL1 due to test configuration`, {
452
+ checkpointNumber: this.checkpointNumber,
172
453
  });
173
- await sleepUntil(new Date(Number(submissionSlotTimestamp) * 1000), this.dateProvider.nowAsDate());
454
+ return true;
455
+ }
456
+
457
+ const parentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 1);
174
458
 
175
- // After waking, verify the parent checkpoint wasn't pruned during the sleep.
176
- // We check L1's pending tip directly instead of canProposeAt, which also validates the proposer
177
- // identity and would fail because the timestamp resolves to a different slot's proposer.
178
- const l1Tips = await this.publisher.rollupContract.getTips();
179
- if (l1Tips.pending < this.checkpointNumber - 1) {
459
+ // Wait until archiver has synced L1 past the parent's slot (the build slot, one before targetSlot)
460
+ if (!(await this.waitForSyncedL2SlotNumber(this.getBuildSlot()))) {
461
+ return false;
462
+ }
463
+
464
+ const tips = await this.l2BlockSource.getL2Tips();
465
+ const checkpointedNumber = tips.checkpointed.checkpoint.number;
466
+
467
+ // We built on top of a proposed checkpoint. Verify it landed on L1 as expected.
468
+ if (this.proposedCheckpointData) {
469
+ // After syncing from L1 we see the chain tip has invalid attestations. This means the parent checkpoint was posted
470
+ // with invalid attestations, or it built on top of something with invalid attestations and didnt invalidate them.
471
+ // Either way, we thought our parent would be valid, so we have to throw away our work. But at least we'll try and
472
+ // invalidate on L1 so we clean up the chain for the next proposer. And we'll slash them, but that's handled elsewhere.
473
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
474
+ if (!validationStatus.valid) {
180
475
  this.log.warn(
181
- `Parent checkpoint was pruned during pipelining sleep (L1 pending=${l1Tips.pending}, expected>=${this.checkpointNumber - 1}), skipping L1 submission for checkpoint ${this.checkpointNumber}`,
476
+ `Parent checkpoint ${parentCheckpointNumber} has invalid attestations, discarding pipelined work`,
477
+ { checkpointNumber: this.checkpointNumber, reason: validationStatus.reason },
182
478
  );
183
- return undefined;
479
+ this.emitPipelinedCheckpointDiscarded('parent-invalid-attestations');
480
+ await this.enqueueInvalidation(validationStatus);
481
+ return false;
184
482
  }
483
+
484
+ // The pending chain is valid. But did the parent checkpoint land on L1 at all?
485
+ if (checkpointedNumber < parentCheckpointNumber) {
486
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} did not land on L1, discarding pipelined work`, {
487
+ checkpointNumber: this.checkpointNumber,
488
+ checkpointedNumber,
489
+ });
490
+ this.emitPipelinedCheckpointDiscarded('parent-not-on-l1');
491
+ return false;
492
+ }
493
+
494
+ // It landed. But is it the one we were expecting?
495
+ const expectedHash = this.proposedCheckpointData.header.hash().toString();
496
+ if (tips.checkpointed.checkpoint.hash !== expectedHash) {
497
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} hash mismatch on L1, discarding pipelined work`, {
498
+ checkpointNumber: this.checkpointNumber,
499
+ expectedHash,
500
+ actualHash: tips.checkpointed.checkpoint.hash,
501
+ });
502
+ this.emitPipelinedCheckpointDiscarded('parent-hash-mismatch');
503
+ return false;
504
+ }
505
+
506
+ return true;
507
+ } else {
508
+ // We didn't see a proposed checkpoint at build time, so we built on checkpointed parent from two slots ago.
509
+ // But if a new checkpoint for the previous slot appeared on L1 in the meantime, our checkpoint assumed the wrong parent,
510
+ // so we have to discard our work. This can happen if we're somehow cut off from p2p and fail to see the checkpoint
511
+ // proposal for the previous slot.
512
+ if (checkpointedNumber > parentCheckpointNumber) {
513
+ this.log.warn(
514
+ `Unexpected checkpoint ${checkpointedNumber} landed on L1 after we built on top of parent ${parentCheckpointNumber}, discarding pipelined work`,
515
+ { checkpointNumber: this.checkpointNumber, checkpointedNumber },
516
+ );
517
+ this.emitPipelinedCheckpointDiscarded('unexpected-parent-appeared');
518
+ return false;
519
+ }
520
+
521
+ return true;
185
522
  }
523
+ }
186
524
 
187
- // Then send everything to L1
188
- const l1Response = await this.publisher.sendRequests();
189
- const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
190
- if (proposedAction) {
191
- this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.slot });
192
- const coinbase = checkpoint?.header.coinbase;
193
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
194
- return checkpoint;
195
- } else if (checkpoint) {
196
- this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.slot });
197
- return undefined;
525
+ /** Emits the pipelined-checkpoint-discarded event and records the metric. */
526
+ private emitPipelinedCheckpointDiscarded(reason: string): void {
527
+ this.metrics.recordPipelineParentCheckpointMismatch(reason);
528
+ this.eventEmitter.emit('pipelined-checkpoint-discarded', {
529
+ slot: this.targetSlot,
530
+ checkpointNumber: this.checkpointNumber,
531
+ reason,
532
+ });
533
+ }
534
+
535
+ /** Simulates and enqueues an invalidation request for the invalid parent checkpoint. */
536
+ private async enqueueInvalidation(validationStatus: ValidateCheckpointResult): Promise<void> {
537
+ if (this.config.skipInvalidateBlockAsProposer) {
538
+ this.log.warn(`Skipping checkpoint invalidation as proposer due to test configuration`);
539
+ return;
540
+ }
541
+ const invalidateRequest = await this.publisher.simulateInvalidateCheckpoint(validationStatus);
542
+ if (invalidateRequest) {
543
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
544
+ const txTimeoutAt = new Date((submissionSlotStart + this.l1Constants.slotDuration) * 1000);
545
+ this.publisher.enqueueInvalidateCheckpoint(invalidateRequest, { txTimeoutAt });
546
+ } else {
547
+ this.log.info(`Invalidation simulation returned undefined, checkpoint may have been removed already`, {
548
+ checkpointNumber: this.checkpointNumber,
549
+ });
198
550
  }
199
551
  }
200
552
 
@@ -205,19 +557,32 @@ export class CheckpointProposalJob implements Traceable {
205
557
  [Attributes.SLOT_NUMBER]: this.targetSlot,
206
558
  };
207
559
  })
208
- private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
560
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
209
561
  try {
562
+ const now = this.dateProvider.now();
563
+ if (this.proposedCheckpointData) {
564
+ // Measure against the wall-clock slot whose build window we are currently using.
565
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
566
+ // target-slot boundary a full slot away from the actual build start time.
567
+ const slotBoundaryMs = Number(getTimestampForSlot(this.getBuildSlot(), this.l1Constants)) * 1000;
568
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
569
+ }
570
+ this.checkpointMetrics.startCheckpointTiming(now);
571
+
210
572
  // Get operator configured coinbase and fee recipient for this attestor
211
573
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
212
574
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
213
575
 
214
576
  // Start the checkpoint
215
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
216
- this.log.info(`Starting checkpoint proposal`, {
217
- buildSlot: this.slot,
577
+ this.setState(SequencerState.INITIALIZING_CHECKPOINT);
578
+ this.logCheckpointEvent('slot-started', `Starting checkpoint proposal for slot ${this.targetSlot}`, {
579
+ buildSlot: this.getBuildSlot(),
218
580
  submissionSlot: this.targetSlot,
219
- pipelining: this.epochCache.isProposerPipeliningEnabled(),
581
+ slot: this.targetSlot,
582
+ checkpointNumber: this.checkpointNumber,
220
583
  proposer: this.proposer?.toString(),
584
+ attestorAddress: this.attestorAddress.toString(),
585
+ publisherAddress: this.publisher.getSenderAddress().toString(),
221
586
  coinbase: coinbase.toString(),
222
587
  });
223
588
  this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
@@ -227,24 +592,51 @@ export class CheckpointProposalJob implements Traceable {
227
592
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
228
593
  }
229
594
 
230
- // Create checkpoint builder for the slot
595
+ // Build the simulation plan for this slot. When pipelining, this overrides L1's view of
596
+ // pending/archive/fee-header to "as if the proposed parent had landed", so both the
597
+ // mana-min-fee simulation (in the globals builder) and the pre-broadcast
598
+ // validateBlockHeader see the chain tip the eventual L1 send will see.
599
+ this.checkpointSimulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
600
+ checkpointNumber: this.checkpointNumber,
601
+ proposedCheckpointData: this.proposedCheckpointData,
602
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
603
+ checkpointedCheckpointNumber: this.checkpointedCheckpointNumber,
604
+ rollup: this.publisher.rollupContract,
605
+ signatureContext: this.signatureContext,
606
+ log: this.log,
607
+ });
608
+
231
609
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
232
610
  coinbase,
233
611
  feeRecipient,
234
612
  this.targetSlot,
613
+ this.checkpointSimulationOverridesPlan,
235
614
  );
236
615
 
237
616
  // Collect L1 to L2 messages for the checkpoint and compute their hash
238
617
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
239
618
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
240
619
 
241
- // Collect the out hashes of all the checkpoints before this one in the same epoch
242
- const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.targetEpoch))
243
- .filter(c => c.checkpointNumber < this.checkpointNumber)
244
- .map(c => c.checkpointOutHash);
620
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
621
+ // Under pipelining the parent checkpoint may not be on L1 yet at build time, so the helper
622
+ // splices in the parent's checkpointOutHash from the locally-known proposed checkpoint so
623
+ // the resulting `epochOutHash` matches what validators (and L1) compute once the parent
624
+ // lands on L1.
625
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
626
+ blockSource: this.l2BlockSource,
627
+ epoch: this.targetEpoch,
628
+ checkpointNumber: this.checkpointNumber,
629
+ l1Constants: this.epochCache.getL1Constants(),
630
+ pipeliningEnabled: true,
631
+ proposedCheckpointData: this.proposedCheckpointData,
632
+ log: this.log,
633
+ });
245
634
 
246
- // Get the fee asset price modifier from the oracle
247
- const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
635
+ // Anchor the modifier to the predicted parent fee header: L1 will apply it against
636
+ // that, not against the latest published checkpoint (which lags by one under pipelining).
637
+ const predictedParentEthPerFeeAssetE12 =
638
+ this.checkpointSimulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
639
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12);
248
640
 
249
641
  // Create a long-lived forked world state for the checkpoint builder
250
642
  await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
@@ -268,11 +660,12 @@ export class CheckpointProposalJob implements Traceable {
268
660
 
269
661
  const checkpointProposalOptions: CheckpointProposalOptions = {
270
662
  publishFullTxs: !!this.config.publishTxsWithProposals,
271
- broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
663
+ broadcastInvalidCheckpointProposal:
664
+ this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal,
272
665
  };
273
666
 
274
667
  let blocksInCheckpoint: L2Block[] = [];
275
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
668
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
276
669
  const checkpointBuildTimer = new Timer();
277
670
 
278
671
  try {
@@ -296,23 +689,45 @@ export class CheckpointProposalJob implements Traceable {
296
689
  }
297
690
 
298
691
  if (blocksInCheckpoint.length === 0) {
299
- this.log.warn(`No blocks were built for slot ${this.targetSlot}`, { slot: this.targetSlot });
692
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
693
+ slot: this.targetSlot,
694
+ checkpointNumber: this.checkpointNumber,
695
+ reason: 'no_blocks_built',
696
+ });
697
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
698
+ slot: this.targetSlot,
699
+ checkpointNumber: this.checkpointNumber,
700
+ reason: 'no_blocks_built',
701
+ });
300
702
  this.eventEmitter.emit('checkpoint-empty', { slot: this.targetSlot });
301
703
  return undefined;
302
704
  }
303
705
 
304
706
  const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
305
707
  if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
708
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
709
+ slot: this.targetSlot,
710
+ checkpointNumber: this.checkpointNumber,
711
+ blocksBuilt: blocksInCheckpoint.length,
712
+ minBlocksForCheckpoint,
713
+ reason: 'min_blocks_not_met',
714
+ });
306
715
  this.log.warn(
307
716
  `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
308
- { slot: this.targetSlot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
717
+ {
718
+ slot: this.targetSlot,
719
+ checkpointNumber: this.checkpointNumber,
720
+ blocksBuilt: blocksInCheckpoint.length,
721
+ minBlocksForCheckpoint,
722
+ reason: 'min_blocks_not_met',
723
+ },
309
724
  );
310
725
  return undefined;
311
726
  }
312
727
 
313
728
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
314
729
  // broadcasted yet, and wait to collect the committee attestations.
315
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
730
+ this.setState(SequencerState.ASSEMBLING_CHECKPOINT);
316
731
  const checkpoint = await checkpointBuilder.completeCheckpoint();
317
732
 
318
733
  // Final validation: per-block limits are only checked if the operator set them explicitly.
@@ -326,21 +741,43 @@ export class CheckpointProposalJob implements Traceable {
326
741
  maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
327
742
  });
328
743
  } catch (err) {
329
- this.log.error(`Built an invalid checkpoint at slot ${this.slot} (skipping proposal)`, err, {
744
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
745
+ slot: this.targetSlot,
746
+ checkpointNumber: this.checkpointNumber,
747
+ blocksBuilt: blocksInCheckpoint.length,
748
+ reason: 'invalid_checkpoint',
749
+ checkpoint: checkpoint.header.toInspect(),
750
+ });
751
+ this.log.error(`Built an invalid checkpoint at slot ${this.targetSlot} (skipping proposal)`, err, {
752
+ slot: this.targetSlot,
753
+ checkpointNumber: this.checkpointNumber,
754
+ blocksBuilt: blocksInCheckpoint.length,
755
+ reason: 'invalid_checkpoint',
330
756
  checkpoint: checkpoint.header.toInspect(),
331
757
  });
332
758
  return undefined;
333
759
  }
334
760
 
335
761
  // Record checkpoint-level build metrics
336
- this.metrics.recordCheckpointBuild(
762
+ this.checkpointMetrics.recordCheckpointBuild(
337
763
  checkpointBuildTimer.ms(),
338
764
  blocksInCheckpoint.length,
339
765
  checkpoint.getStats().txCount,
340
766
  Number(checkpoint.header.totalManaUsed.toBigInt()),
341
767
  );
768
+ this.logCheckpointEvent('built', `Checkpoint built for slot ${this.targetSlot}`, {
769
+ slot: this.targetSlot,
770
+ buildSlot: this.getBuildSlot(),
771
+ checkpointNumber: this.checkpointNumber,
772
+ proposer: this.proposer?.toString(),
773
+ attestorAddress: this.attestorAddress.toString(),
774
+ publisherAddress: this.publisher.getSenderAddress().toString(),
775
+ blocksBuilt: blocksInCheckpoint.length,
776
+ txCount: checkpoint.getStats().txCount,
777
+ totalMana: Number(checkpoint.header.totalManaUsed.toBigInt()),
778
+ });
342
779
 
343
- // Do not collect attestations nor publish to L1 in fisherman mode
780
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
344
781
  if (this.config.fishermanMode) {
345
782
  this.log.info(
346
783
  `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
@@ -352,87 +789,70 @@ export class CheckpointProposalJob implements Traceable {
352
789
  },
353
790
  );
354
791
  this.metrics.recordCheckpointSuccess();
355
- return checkpoint;
792
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
793
+ return { checkpoint, proposal: undefined!, blockProposedAt: this.dateProvider.now() };
356
794
  }
357
795
 
358
- // Include the block pending broadcast in the checkpoint proposal if any
359
- const lastBlock = blockPendingBroadcast && {
360
- blockHeader: blockPendingBroadcast.block.header,
361
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
362
- txs: blockPendingBroadcast.txs,
363
- };
796
+ // Validate the header against L1 state before broadcasting.
797
+ // If this fails the slot is aborted before any gossip work; state drift between here
798
+ // and the eventual L1 send is caught by the bundle simulate at send time.
799
+ try {
800
+ await this.publisher.validateBlockHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
801
+ } catch (err) {
802
+ this.log.error(`Pre-broadcast header validation failed for slot ${this.targetSlot}; aborting`, err, {
803
+ slot: this.targetSlot,
804
+ checkpointNumber: this.checkpointNumber,
805
+ });
806
+ this.metrics.recordCheckpointProposalFailed('header_validation_failed');
807
+ this.eventEmitter.emit('header-validation-failed', {
808
+ slot: this.targetSlot,
809
+ checkpointNumber: this.checkpointNumber,
810
+ reason: err instanceof Error ? err.message : String(err),
811
+ });
812
+ return undefined;
813
+ }
364
814
 
365
815
  // Create the checkpoint proposal and broadcast it
366
816
  const proposal = await this.validatorClient.createCheckpointProposal(
367
817
  checkpoint.header,
368
818
  checkpoint.archive.root,
819
+ this.checkpointNumber,
369
820
  feeAssetPriceModifier,
370
- lastBlock,
821
+ blockPendingBroadcast,
371
822
  this.proposer,
372
823
  checkpointProposalOptions,
373
824
  );
374
825
 
375
- const blockProposedAt = this.dateProvider.now();
376
- await this.p2pClient.broadcastCheckpointProposal(proposal);
377
-
378
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.targetSlot);
379
- const attestations = await this.waitForAttestations(proposal);
380
- const blockAttestedAt = this.dateProvider.now();
381
-
382
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
383
-
384
- // Proposer must sign over the attestations before pushing them to L1
385
- const signer = this.proposer ?? this.publisher.getSenderAddress();
386
- let attestationsSignature: Signature;
387
- try {
388
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
389
- attestations,
390
- signer,
391
- this.targetSlot,
392
- this.checkpointNumber,
393
- );
394
- } catch (err) {
395
- // We shouldn't really get here since we yield to another HA node
396
- // as soon as we see these errors when creating block or checkpoint proposals.
397
- if (this.handleHASigningError(err, 'Attestations signature')) {
398
- return undefined;
399
- }
400
- throw err;
401
- }
826
+ // Advance our own optimistic proposed-checkpoint tip locally before gossiping. Gossipsub
827
+ // doesn't echo our own messages back, so this is how the proposer makes its own proposed
828
+ // checkpoint visible for pipelining the next slot. Built from local checkpoint data — never
829
+ // from the broadcast proposal archive, which may be deliberately corrupted under test flags.
830
+ // Fail closed: if this throws, the outer catch aborts the slot before gossiping.
831
+ await this.syncProposedCheckpointToArchiver(checkpoint, blocksInCheckpoint.length, feeAssetPriceModifier);
402
832
 
403
- // Enqueue publishing the checkpoint to L1
404
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.targetSlot);
405
- const aztecSlotDuration = this.l1Constants.slotDuration;
406
- const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
407
- const txTimeoutAt = new Date((submissionSlotStart + aztecSlotDuration) * 1000);
408
-
409
- // If we have been configured to potentially skip publishing checkpoint then roll the dice here
410
- if (
411
- this.config.skipPublishingCheckpointsPercent !== undefined &&
412
- this.config.skipPublishingCheckpointsPercent > 0
413
- ) {
414
- const result = Math.max(0, randomInt(100));
415
- if (result < this.config.skipPublishingCheckpointsPercent) {
416
- this.log.warn(
417
- `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${result}`,
418
- );
419
- return checkpoint;
833
+ const blockProposedAt = this.dateProvider.now();
834
+ if (this.config.skipBroadcastCheckpointProposal) {
835
+ // Test-only: suppress the CheckpointProposal so peers never see a proposed checkpoint for
836
+ // this slot, but still broadcast the held last block standalone so peers' archivers ingest
837
+ // it as a proposed-but-uncheckpointed tip the exact orphan-block state that
838
+ // pruneOrphanProposedBlocks / checkSync must handle.
839
+ if (blockPendingBroadcast && !this.config.skipBroadcastProposals) {
840
+ await this.p2pClient.broadcastProposal(blockPendingBroadcast);
420
841
  }
842
+ } else if (!this.config.skipBroadcastProposals) {
843
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
844
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
421
845
  }
422
846
 
423
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
424
- txTimeoutAt,
425
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
426
- });
427
-
428
- return checkpoint;
847
+ // Return immediately after broadcast — attestation collection happens in the background
848
+ return { checkpoint, proposal, blockProposedAt };
429
849
  } catch (err) {
430
850
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
431
851
  // swallow this error. It's already been logged by a function deeper in the stack
432
852
  return undefined;
433
853
  }
434
854
 
435
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
855
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
436
856
  return undefined;
437
857
  }
438
858
  }
@@ -448,28 +868,37 @@ export class CheckpointProposalJob implements Traceable {
448
868
  blockProposalOptions: BlockProposalOptions,
449
869
  ): Promise<{
450
870
  blocksInCheckpoint: L2Block[];
451
- blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
871
+ blockPendingBroadcast: BlockProposal | undefined;
452
872
  }> {
453
873
  const blocksInCheckpoint: L2Block[] = [];
454
874
  const txHashesAlreadyIncluded = new Set<string>();
455
875
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
456
876
 
457
877
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
458
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
878
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
459
879
 
460
880
  while (true) {
461
881
  const blocksBuilt = blocksInCheckpoint.length;
462
882
  const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
463
883
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
464
884
 
465
- const secondsIntoSlot = this.getSecondsIntoSlot();
466
- const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
885
+ if (blocksBuilt >= this.config.maxBlocksPerCheckpoint) {
886
+ this.log.debug(`Reached max blocks per checkpoint`, {
887
+ slot: this.targetSlot,
888
+ blocksBuilt,
889
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint,
890
+ });
891
+ break;
892
+ }
893
+
894
+ const nowSeconds = this.dateProvider.now() / 1000;
895
+ const timingInfo = this.timetable.selectNextSubslot(this.targetSlot, nowSeconds);
467
896
 
468
897
  if (!timingInfo.canStart) {
469
898
  this.log.debug(`Not enough time left in slot to start another block`, {
470
899
  slot: this.targetSlot,
471
900
  blocksBuilt,
472
- secondsIntoSlot,
901
+ nowSeconds,
473
902
  });
474
903
  break;
475
904
  }
@@ -479,28 +908,26 @@ export class CheckpointProposalJob implements Traceable {
479
908
  blockTimestamp: timestamp,
480
909
  // Create an empty block if we haven't already and this is the last one
481
910
  forceCreate: timingInfo.isLastBlock && blocksBuilt === 0 && this.config.buildCheckpointIfEmpty,
482
- // Build deadline is only set if we are enforcing the timetable
483
- buildDeadline: timingInfo.deadline
484
- ? new Date((this.getSlotStartBuildTimestamp() + timingInfo.deadline) * 1000)
485
- : undefined,
911
+ buildDeadline: new Date(timingInfo.deadline * 1000),
486
912
  blockNumber,
487
913
  indexWithinCheckpoint,
488
914
  txHashesAlreadyIncluded,
489
915
  });
490
916
 
491
- // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
492
- if (!buildResult && timingInfo.isLastBlock) {
493
- // If no block was produced due to not enough txs and this was the last subslot, exit
494
- break;
495
- } else if (!buildResult && timingInfo.deadline !== undefined) {
496
- // But if there is still time for more blocks, wait until the next subslot and try again
917
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
918
+ if ('failure' in buildResult) {
919
+ // If this was the last subslot, we're done.
920
+ if (timingInfo.isLastBlock) {
921
+ break;
922
+ }
923
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
497
924
  await this.waitUntilNextSubslot(timingInfo.deadline);
498
925
  continue;
499
- } else if (!buildResult) {
500
- // Exit if there is no possibility of building more blocks
501
- break;
502
- } else if ('error' in buildResult) {
503
- // If there was an error building the block, just exit the loop and give up the rest of the slot
926
+ }
927
+
928
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
929
+ // We don't want to risk building more blocks if something went wrong.
930
+ if ('error' in buildResult) {
504
931
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
505
932
  this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
506
933
  slot: this.targetSlot,
@@ -512,35 +939,44 @@ export class CheckpointProposalJob implements Traceable {
512
939
  }
513
940
 
514
941
  const { block, usedTxs } = buildResult;
942
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
943
+ isFirstBlock: blocksBuilt === 0,
944
+ isLastBlock: timingInfo.isLastBlock,
945
+ });
946
+
515
947
  blocksInCheckpoint.push(block);
516
948
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
517
949
 
518
- // If this is the last block, sync it to the archiver and exit the loop
519
- // so we can build the checkpoint and start collecting attestations.
950
+ // Sign the block proposal. This will throw if HA signing fails.
951
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, {
952
+ ...blockProposalOptions,
953
+ broadcastInvalidBlockProposal:
954
+ blockProposalOptions.broadcastInvalidBlockProposal ||
955
+ block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint,
956
+ });
957
+
958
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
959
+ // so we avoid polluting our archive with a block that would fail.
960
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
961
+ // If this throws, we abort the entire checkpoint.
962
+ await this.syncProposedBlockToArchiver(block);
963
+
964
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
520
965
  if (timingInfo.isLastBlock) {
521
- await this.syncProposedBlockToArchiver(block);
522
966
  this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
523
967
  slot: this.targetSlot,
524
968
  blockNumber,
525
969
  blocksBuilt,
526
970
  });
527
- blockPendingBroadcast = { block, txs: usedTxs };
971
+
972
+ blockPendingBroadcast = proposal;
528
973
  break;
529
974
  }
530
975
 
531
- // Broadcast the block proposal (unless we're in fisherman mode) unless the block is the last one,
532
- // in which case we'll broadcast it along with the checkpoint at the end of the loop.
533
- // Note that we only send the block to the archiver if we manage to create the proposal, so if there's
534
- // a HA error we don't pollute our archiver with a block that won't make it to the chain.
535
- const proposal = await this.createBlockProposal(block, inHash, usedTxs, blockProposalOptions);
536
-
537
- // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal.
538
- // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
539
- // If this throws, we abort the entire checkpoint.
540
- await this.syncProposedBlockToArchiver(block);
541
-
542
976
  // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
543
- proposal && (await this.p2pClient.broadcastProposal(proposal));
977
+ if (proposal && !this.config.skipBroadcastProposals) {
978
+ await this.p2pClient.broadcastProposal(proposal);
979
+ }
544
980
 
545
981
  // Wait until the next block's start time
546
982
  await this.waitUntilNextSubslot(timingInfo.deadline);
@@ -567,6 +1003,7 @@ export class CheckpointProposalJob implements Traceable {
567
1003
  }
568
1004
  return this.validatorClient.createBlockProposal(
569
1005
  block.header,
1006
+ this.checkpointNumber,
570
1007
  block.indexWithinCheckpoint,
571
1008
  inHash,
572
1009
  block.archive.root,
@@ -576,14 +1013,17 @@ export class CheckpointProposalJob implements Traceable {
576
1013
  );
577
1014
  }
578
1015
 
579
- /** Sleeps until it is time to produce the next block in the slot */
1016
+ /**
1017
+ * Sleeps until it is time to produce the next block in the slot.
1018
+ * @param nextSubslotStart - Absolute wall-clock timestamp in seconds of the previous sub-slot deadline.
1019
+ */
580
1020
  @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
581
- private async waitUntilNextSubslot(nextSubslotStart: number) {
582
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
583
- this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
1021
+ protected async waitUntilNextSubslot(nextSubslotStart: number) {
1022
+ this.setState(SequencerState.WAITING_UNTIL_NEXT_BLOCK);
1023
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s`, {
584
1024
  slot: this.targetSlot,
585
1025
  });
586
- await this.waitUntilTimeInSlot(nextSubslotStart);
1026
+ await this.awaitInterruptibleSleep(Math.max(0, nextSubslotStart * 1000 - this.dateProvider.now()));
587
1027
  }
588
1028
 
589
1029
  /** Builds a single block. Called from the main block building loop. */
@@ -598,7 +1038,9 @@ export class CheckpointProposalJob implements Traceable {
598
1038
  buildDeadline: Date | undefined;
599
1039
  txHashesAlreadyIncluded: Set<string>;
600
1040
  },
601
- ): Promise<{ block: L2Block; usedTxs: Tx[] } | { error: Error } | undefined> {
1041
+ ): Promise<
1042
+ { block: L2Block; usedTxs: Tx[] } | { failure: 'insufficient-txs' | 'insufficient-valid-txs' } | { error: Error }
1043
+ > {
602
1044
  const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
603
1045
  opts;
604
1046
 
@@ -611,19 +1053,38 @@ export class CheckpointProposalJob implements Traceable {
611
1053
  // Wait until we have enough txs to build the block
612
1054
  const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
613
1055
  if (!canStartBuilding) {
1056
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1057
+ reason: 'insufficient_txs',
1058
+ blockNumber,
1059
+ slot: this.targetSlot,
1060
+ checkpointNumber: this.checkpointNumber,
1061
+ indexWithinCheckpoint,
1062
+ availableTxs,
1063
+ minTxs,
1064
+ });
614
1065
  this.log.warn(
615
1066
  `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (got ${availableTxs} txs but needs ${minTxs})`,
616
- { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
1067
+ {
1068
+ reason: 'insufficient_txs',
1069
+ blockNumber,
1070
+ slot: this.targetSlot,
1071
+ checkpointNumber: this.checkpointNumber,
1072
+ indexWithinCheckpoint,
1073
+ availableTxs,
1074
+ minTxs,
1075
+ },
617
1076
  );
618
1077
  this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.targetSlot });
619
1078
  this.metrics.recordBlockProposalFailed('insufficient_txs');
620
- return undefined;
1079
+ return { failure: 'insufficient-txs' };
621
1080
  }
622
1081
 
623
1082
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
624
1083
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
1084
+ // Block building only executes txs, so we skip loading their proofs unless these same tx objects get attached
1085
+ // to the broadcasted proposals via publishTxsWithProposals.
625
1086
  const pendingTxs = filter(
626
- this.p2pClient.iterateEligiblePendingTxs(),
1087
+ this.p2pClient.iterateEligiblePendingTxs({ includeProof: !!this.config.publishTxsWithProposals }),
627
1088
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
628
1089
  );
629
1090
 
@@ -631,7 +1092,7 @@ export class CheckpointProposalJob implements Traceable {
631
1092
  `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`,
632
1093
  { slot: this.targetSlot, blockNumber, indexWithinCheckpoint },
633
1094
  );
634
- this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
1095
+ this.setState(SequencerState.CREATING_BLOCK);
635
1096
 
636
1097
  // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
637
1098
  // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
@@ -646,8 +1107,9 @@ export class CheckpointProposalJob implements Traceable {
646
1107
  deadline: buildDeadline,
647
1108
  isBuildingProposal: true,
648
1109
  minValidTxs,
649
- maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
1110
+ maxBlocksPerCheckpoint: this.timetable.getMaxBlocksPerCheckpoint(),
650
1111
  perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
1112
+ perBlockDAAllocationMultiplier: this.config.perBlockDAAllocationMultiplier,
651
1113
  };
652
1114
 
653
1115
  // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
@@ -665,10 +1127,21 @@ export class CheckpointProposalJob implements Traceable {
665
1127
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
666
1128
 
667
1129
  if (buildResult.status === 'insufficient-valid-txs') {
1130
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1131
+ reason: 'insufficient_valid_txs',
1132
+ slot: this.targetSlot,
1133
+ checkpointNumber: this.checkpointNumber,
1134
+ blockNumber,
1135
+ numTxs: buildResult.processedCount,
1136
+ indexWithinCheckpoint,
1137
+ minValidTxs,
1138
+ });
668
1139
  this.log.warn(
669
1140
  `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`,
670
1141
  {
1142
+ reason: 'insufficient_valid_txs',
671
1143
  slot: this.targetSlot,
1144
+ checkpointNumber: this.checkpointNumber,
672
1145
  blockNumber,
673
1146
  numTxs: buildResult.processedCount,
674
1147
  indexWithinCheckpoint,
@@ -680,7 +1153,7 @@ export class CheckpointProposalJob implements Traceable {
680
1153
  slot: this.targetSlot,
681
1154
  });
682
1155
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
683
- return undefined;
1156
+ return { failure: 'insufficient-valid-txs' };
684
1157
  }
685
1158
 
686
1159
  // Block creation succeeded, emit stats and metrics
@@ -702,12 +1175,17 @@ export class CheckpointProposalJob implements Traceable {
702
1175
  { blockHash, txHashes, manaPerSec, ...blockStats },
703
1176
  );
704
1177
 
1178
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
1179
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
705
1180
  this.eventEmitter.emit('block-proposed', {
706
1181
  blockNumber: block.number,
1182
+ blockHash,
1183
+ checkpointNumber: this.checkpointNumber,
1184
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
707
1185
  slot: this.targetSlot,
708
- buildSlot: this.slotNow,
1186
+ buildSlot: this.getBuildSlot(),
709
1187
  });
710
- this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
1188
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
711
1189
 
712
1190
  return { block, usedTxs };
713
1191
  } catch (err: any) {
@@ -715,7 +1193,18 @@ export class CheckpointProposalJob implements Traceable {
715
1193
  reason: err.message,
716
1194
  slot: this.targetSlot,
717
1195
  });
718
- this.log.error(`Error building block`, err, { blockNumber, slot: this.targetSlot });
1196
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1197
+ reason: err instanceof Error ? err.message : String(err),
1198
+ slot: this.targetSlot,
1199
+ checkpointNumber: this.checkpointNumber,
1200
+ blockNumber,
1201
+ });
1202
+ this.log.error(`Error building block`, err, {
1203
+ reason: err instanceof Error ? err.message : String(err),
1204
+ slot: this.targetSlot,
1205
+ checkpointNumber: this.checkpointNumber,
1206
+ blockNumber,
1207
+ });
719
1208
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
720
1209
  this.metrics.recordFailedBlock();
721
1210
  return { error: err };
@@ -760,9 +1249,9 @@ export class CheckpointProposalJob implements Traceable {
760
1249
  // We only allow a block with 0 txs in the first block of the checkpoint
761
1250
  const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
762
1251
 
763
- // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
1252
+ // Latest time to keep waiting for txs: wait_for_txs_deadline = block_build_deadline(k) - min_block_duration.
764
1253
  const startBuildingDeadline = buildDeadline
765
- ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
1254
+ ? new Date(buildDeadline.getTime() - this.timetable.minBlockDuration * 1000)
766
1255
  : undefined;
767
1256
 
768
1257
  let availableTxs = await this.p2pClient.getPendingTxCount();
@@ -775,7 +1264,7 @@ export class CheckpointProposalJob implements Traceable {
775
1264
  }
776
1265
 
777
1266
  // Wait a bit before checking again
778
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
1267
+ this.setState(SequencerState.WAITING_FOR_TXS);
779
1268
  this.log.verbose(
780
1269
  `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`,
781
1270
  { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
@@ -787,15 +1276,47 @@ export class CheckpointProposalJob implements Traceable {
787
1276
  return { canStartBuilding: true, availableTxs, minTxs };
788
1277
  }
789
1278
 
1279
+ private async getSignedCommitteeAttestations(
1280
+ broadcast: CheckpointProposalBroadcast,
1281
+ ): Promise<{ attestations: CommitteeAttestationsAndSigners; attestationsSignature: Signature } | undefined> {
1282
+ const { proposal, blockProposedAt } = broadcast;
1283
+ this.setState(SequencerState.COLLECTING_ATTESTATIONS);
1284
+ const attestations = await this.waitForAttestations(proposal);
1285
+ if (!attestations) {
1286
+ return undefined;
1287
+ }
1288
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
1289
+
1290
+ // Proposer must sign over the attestations before pushing them to L1
1291
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1292
+ try {
1293
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
1294
+ attestations,
1295
+ signer,
1296
+ this.targetSlot,
1297
+ this.checkpointNumber,
1298
+ );
1299
+ return { attestations, attestationsSignature };
1300
+ } catch (err) {
1301
+ if (this.handleHASigningError(err, 'Attestations signature')) {
1302
+ return;
1303
+ }
1304
+ this.log.error(`Error signing attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1305
+ return undefined;
1306
+ }
1307
+ }
1308
+
790
1309
  /**
791
1310
  * Waits for enough attestations to be collected via p2p.
792
1311
  * This is run after all blocks for the checkpoint have been built.
793
1312
  */
794
1313
  @trackSpan('CheckpointProposalJob.waitForAttestations')
795
- private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
1314
+ private async waitForAttestations(
1315
+ proposal: CheckpointProposal,
1316
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
796
1317
  if (this.config.fishermanMode) {
797
1318
  this.log.debug('Skipping attestation collection in fisherman mode');
798
- return CommitteeAttestationsAndSigners.empty();
1319
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
799
1320
  }
800
1321
 
801
1322
  const slotNumber = proposal.slotNumber;
@@ -805,25 +1326,33 @@ export class CheckpointProposalJob implements Traceable {
805
1326
  throw new Error('No committee when collecting attestations');
806
1327
  } else if (committee.length === 0) {
807
1328
  this.log.verbose(`Attesting committee is empty`);
808
- return CommitteeAttestationsAndSigners.empty();
1329
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
809
1330
  } else {
810
1331
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
811
1332
  }
812
1333
 
813
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
1334
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
814
1335
 
815
1336
  if (this.config.skipCollectingAttestations) {
816
1337
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
817
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
818
- return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
1338
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
1339
+ this.logCheckpointAttestations('collected', committee, attestations ?? [], numberOfRequiredAttestations, {
1340
+ reason: 'collect_own_only',
1341
+ });
1342
+ return new CommitteeAttestationsAndSigners(
1343
+ orderAttestations(attestations ?? [], committee),
1344
+ this.getSignatureContext(),
1345
+ );
819
1346
  }
820
1347
 
821
- const attestationTimeAllowed = this.config.enforceTimeTable
822
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
823
- : this.l1Constants.slotDuration;
824
- const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
1348
+ // Hard attestation-collection cutoff = the single consensus attestation_deadline (target_slot_start + S - 2E).
1349
+ const attestationDeadlineSeconds = this.timetable.getAttestationDeadline(this.targetSlot);
1350
+ const attestationDeadline = new Date(attestationDeadlineSeconds * 1000);
825
1351
 
826
- this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
1352
+ this.metrics.recordRequiredAttestations(
1353
+ numberOfRequiredAttestations,
1354
+ Math.max(0, attestationDeadline.getTime() - this.dateProvider.now()),
1355
+ );
827
1356
 
828
1357
  const collectAttestationsTimer = new Timer();
829
1358
  let collectedAttestationsCount: number = 0;
@@ -832,6 +1361,7 @@ export class CheckpointProposalJob implements Traceable {
832
1361
  proposal,
833
1362
  numberOfRequiredAttestations,
834
1363
  attestationDeadline,
1364
+ this.checkpointNumber,
835
1365
  );
836
1366
 
837
1367
  collectedAttestationsCount = attestations.length;
@@ -850,6 +1380,9 @@ export class CheckpointProposalJob implements Traceable {
850
1380
 
851
1381
  // Rollup contract requires that the signatures are provided in the order of the committee
852
1382
  const sorted = orderAttestations(trimmed, committee);
1383
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1384
+ submittedCount: trimmed.length,
1385
+ });
853
1386
 
854
1387
  // Manipulate the attestations if we've been configured to do so
855
1388
  if (
@@ -861,17 +1394,56 @@ export class CheckpointProposalJob implements Traceable {
861
1394
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
862
1395
  }
863
1396
 
864
- return new CommitteeAttestationsAndSigners(sorted);
1397
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
865
1398
  } catch (err) {
866
1399
  if (err && err instanceof AttestationTimeoutError) {
867
1400
  collectedAttestationsCount = err.collectedCount;
1401
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1402
+ collectedCount: collectedAttestationsCount,
1403
+ reason: 'timeout',
1404
+ });
1405
+ this.log.error(
1406
+ `Timeout while waiting for attestations for checkpoint proposal at slot ${proposal.slotNumber} (collected ${collectedAttestationsCount}/${numberOfRequiredAttestations})`,
1407
+ err,
1408
+ );
1409
+ } else {
1410
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1411
+ collectedCount: collectedAttestationsCount,
1412
+ reason: err instanceof Error ? err.message : String(err),
1413
+ });
1414
+ this.log.error(`Error collecting attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
868
1415
  }
869
- throw err;
1416
+ return undefined;
870
1417
  } finally {
871
1418
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
872
1419
  }
873
1420
  }
874
1421
 
1422
+ private logCheckpointAttestations(
1423
+ status: 'collected' | 'failed',
1424
+ committee: EthAddress[],
1425
+ attestations: CheckpointAttestation[] | undefined,
1426
+ requiredAttestations: number,
1427
+ opts: { collectedCount?: number; submittedCount?: number; reason?: string } = {},
1428
+ ) {
1429
+ const signedValidators =
1430
+ attestations
1431
+ ?.map(attestation => attestation.getSender()?.toString())
1432
+ .filter((address): address is `0x${string}` => address !== undefined) ?? [];
1433
+ const collectedCount = opts.collectedCount ?? new Set(signedValidators).size;
1434
+ const missingValidatorCount = status === 'failed' ? Math.max(0, requiredAttestations - collectedCount) : undefined;
1435
+ this.logCheckpointEvent(`attestations-${status}`, `Checkpoint attestations ${status} for slot ${this.targetSlot}`, {
1436
+ slot: this.targetSlot,
1437
+ checkpointNumber: this.checkpointNumber,
1438
+ committeeSize: committee.length,
1439
+ requiredAttestations,
1440
+ collectedAttestations: collectedCount,
1441
+ ...(opts.submittedCount !== undefined && { submittedAttestations: opts.submittedCount }),
1442
+ ...(missingValidatorCount !== undefined && { missingValidatorCount }),
1443
+ ...(opts.reason !== undefined && { reason: opts.reason }),
1444
+ });
1445
+ }
1446
+
875
1447
  /** Breaks the attestations before publishing based on attack configs */
876
1448
  private manipulateAttestations(
877
1449
  slotNumber: SlotNumber,
@@ -915,7 +1487,7 @@ export class CheckpointProposalJob implements Traceable {
915
1487
  unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
916
1488
  }
917
1489
  }
918
- return new CommitteeAttestationsAndSigners(attestations);
1490
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
919
1491
  }
920
1492
 
921
1493
  if (this.config.shuffleAttestationOrdering) {
@@ -937,11 +1509,11 @@ export class CheckpointProposalJob implements Traceable {
937
1509
  [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
938
1510
  }
939
1511
 
940
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
941
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
1512
+ const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
1513
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
942
1514
  }
943
1515
 
944
- return new CommitteeAttestationsAndSigners(attestations);
1516
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
945
1517
  }
946
1518
 
947
1519
  private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
@@ -958,9 +1530,13 @@ export class CheckpointProposalJob implements Traceable {
958
1530
  * Adds the proposed block to the archiver so it's available via P2P.
959
1531
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
960
1532
  * would never receive its own block without this explicit sync.
1533
+ *
1534
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1535
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1536
+ * whenever the real proposer's block arrives from L1.
961
1537
  */
962
1538
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
963
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1539
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
964
1540
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
965
1541
  blockNumber: block.number,
966
1542
  slot: block.header.globalVariables.slotNumber,
@@ -974,6 +1550,41 @@ export class CheckpointProposalJob implements Traceable {
974
1550
  await this.blockSink.addBlock(block);
975
1551
  }
976
1552
 
1553
+ /**
1554
+ * Adds the proposed checkpoint to the archiver so the proposer's optimistic proposed-checkpoint
1555
+ * tip advances locally. Gossip doesn't echo our own messages back, so without this the proposer
1556
+ * would never see its own proposed checkpoint and couldn't pipeline the next slot.
1557
+ *
1558
+ * Skipped whenever proposed blocks aren't pushed (`skipPushProposedBlocksToArchiver`, fisherman
1559
+ * mode): the archiver derives the checkpoint archive from its stored blocks, so without them the
1560
+ * push would fail. All blocks were already added (and awaited) during block building, so this
1561
+ * needs no retry — they are guaranteed present by the time we get here.
1562
+ */
1563
+ private async syncProposedCheckpointToArchiver(
1564
+ checkpoint: Checkpoint,
1565
+ blockCount: number,
1566
+ feeAssetPriceModifier: bigint,
1567
+ ): Promise<void> {
1568
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1569
+ return;
1570
+ }
1571
+ const startBlock = BlockNumber(this.syncedToBlockNumber + 1);
1572
+ this.log.debug(`Syncing proposed checkpoint ${this.checkpointNumber} to archiver`, {
1573
+ checkpointNumber: this.checkpointNumber,
1574
+ slot: this.targetSlot,
1575
+ startBlock,
1576
+ blockCount,
1577
+ });
1578
+ await this.blockSink.addProposedCheckpoint({
1579
+ header: checkpoint.header,
1580
+ checkpointNumber: this.checkpointNumber,
1581
+ startBlock,
1582
+ blockCount,
1583
+ totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
1584
+ feeAssetPriceModifier,
1585
+ });
1586
+ }
1587
+
977
1588
  /** Runs fee analysis and logs checkpoint outcome as fisherman */
978
1589
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
979
1590
  // Perform L1 fee analysis before clearing requests
@@ -1021,26 +1632,9 @@ export class CheckpointProposalJob implements Traceable {
1021
1632
  return false;
1022
1633
  }
1023
1634
 
1024
- /** Waits until a specific time within the current slot */
1025
- @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
1026
- protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
1027
- const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1028
- const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
1029
- await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
1030
- }
1031
-
1032
1635
  /** Waits the polling interval for transactions. Extracted for test overriding. */
1033
1636
  protected async waitForTxsPollingInterval(): Promise<void> {
1034
- await sleep(TXS_POLLING_MS);
1035
- }
1036
-
1037
- private getSlotStartBuildTimestamp(): number {
1038
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1039
- }
1040
-
1041
- private getSecondsIntoSlot(): number {
1042
- const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1043
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1637
+ await this.awaitInterruptibleSleep(TXS_POLLING_MS);
1044
1638
  }
1045
1639
 
1046
1640
  public getPublisher() {