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

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 (101) 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 +49 -25
  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 +13 -26
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +9 -67
  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 +19 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +30 -5
  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 +84 -65
  32. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher.js +403 -531
  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 +189 -0
  38. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  39. package/dest/sequencer/automine/automine_sequencer.js +689 -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/checkpoint_proposal_job.d.ts +73 -21
  44. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  45. package/dest/sequencer/checkpoint_proposal_job.js +709 -200
  46. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  47. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  48. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  49. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  50. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  51. package/dest/sequencer/checkpoint_voter.js +2 -5
  52. package/dest/sequencer/errors.d.ts +1 -8
  53. package/dest/sequencer/errors.d.ts.map +1 -1
  54. package/dest/sequencer/errors.js +0 -9
  55. package/dest/sequencer/events.d.ts +61 -4
  56. package/dest/sequencer/events.d.ts.map +1 -1
  57. package/dest/sequencer/metrics.d.ts +9 -10
  58. package/dest/sequencer/metrics.d.ts.map +1 -1
  59. package/dest/sequencer/metrics.js +34 -20
  60. package/dest/sequencer/sequencer.d.ts +117 -30
  61. package/dest/sequencer/sequencer.d.ts.map +1 -1
  62. package/dest/sequencer/sequencer.js +483 -158
  63. package/dest/sequencer/types.d.ts +2 -2
  64. package/dest/sequencer/types.d.ts.map +1 -1
  65. package/dest/test/index.d.ts +3 -3
  66. package/dest/test/index.d.ts.map +1 -1
  67. package/dest/test/utils.d.ts +15 -1
  68. package/dest/test/utils.d.ts.map +1 -1
  69. package/dest/test/utils.js +24 -7
  70. package/package.json +28 -27
  71. package/src/client/sequencer-client.ts +29 -41
  72. package/src/config.ts +58 -25
  73. package/src/global_variable_builder/README.md +44 -0
  74. package/src/global_variable_builder/fee_predictor.ts +172 -0
  75. package/src/global_variable_builder/fee_provider.ts +80 -0
  76. package/src/global_variable_builder/global_builder.ts +19 -89
  77. package/src/global_variable_builder/index.ts +3 -1
  78. package/src/publisher/config.ts +62 -7
  79. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  80. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  81. package/src/publisher/sequencer-publisher-factory.ts +3 -6
  82. package/src/publisher/sequencer-publisher.ts +456 -578
  83. package/src/sequencer/automine/README.md +60 -0
  84. package/src/sequencer/automine/automine_factory.ts +152 -0
  85. package/src/sequencer/automine/automine_sequencer.ts +795 -0
  86. package/src/sequencer/automine/index.ts +6 -0
  87. package/src/sequencer/checkpoint_proposal_job.ts +817 -225
  88. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  89. package/src/sequencer/checkpoint_voter.ts +1 -12
  90. package/src/sequencer/errors.ts +0 -15
  91. package/src/sequencer/events.ts +65 -4
  92. package/src/sequencer/metrics.ts +43 -24
  93. package/src/sequencer/sequencer.ts +557 -175
  94. package/src/sequencer/types.ts +1 -1
  95. package/src/test/index.ts +2 -2
  96. package/src/test/utils.ts +60 -10
  97. package/dest/sequencer/timetable.d.ts +0 -88
  98. package/dest/sequencer/timetable.d.ts.map +0 -1
  99. package/dest/sequencer/timetable.js +0 -222
  100. package/src/sequencer/README.md +0 -531
  101. 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,17 @@ 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
+ buildCheckpointSimulationOverridesPlan,
41
+ getPreviousCheckpointOutHashes,
42
+ validateCheckpoint,
43
+ } from '@aztec/stdlib/checkpoint';
44
+ import { computeQuorum, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
35
45
  import { Gas } from '@aztec/stdlib/gas';
36
46
  import {
37
47
  type BlockBuilderOptions,
@@ -43,11 +53,14 @@ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@azte
43
53
  import type {
44
54
  BlockProposal,
45
55
  BlockProposalOptions,
56
+ CheckpointAttestation,
46
57
  CheckpointProposal,
47
58
  CheckpointProposalOptions,
59
+ CoordinationSignatureContext,
48
60
  } from '@aztec/stdlib/p2p';
49
61
  import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
50
62
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
63
+ import type { ProposerTimetable } from '@aztec/stdlib/timetable';
51
64
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
52
65
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
53
66
  import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
@@ -56,16 +69,31 @@ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validato
56
69
 
57
70
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
58
71
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.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,307 @@ 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, { txTimeoutAt });
402
+ }
403
+
404
+ /**
405
+ * Wait until the archiver syncs past the given L2 slot number.
406
+ * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
407
+ * L1 submission window and is no longer useful.
408
+ */
409
+ private async waitForSyncedL2SlotNumber(waitForSlot: SlotNumber): Promise<boolean> {
410
+ const targetSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
411
+ const targetSlotEndMs = (targetSlotStart + this.l1Constants.slotDuration) * 1000;
412
+ const syncDelayTolerance = this.l1Constants.ethereumSlotDuration * 2 * 1000;
413
+ const timeoutSeconds = Math.max(0.1, (targetSlotEndMs + syncDelayTolerance - this.dateProvider.now()) / 1000);
414
+
415
+ try {
416
+ const timer = new Timer();
417
+ while (true) {
418
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
419
+ if (syncedSlot !== undefined && syncedSlot >= waitForSlot) {
420
+ return true;
421
+ }
422
+ if (timeoutSeconds && timer.s() > timeoutSeconds) {
423
+ throw new TimeoutError(`Timeout awaiting archiver sync past slot ${waitForSlot}`);
424
+ }
425
+ await this.awaitInterruptibleSleep(ARCHIVER_SYNC_POLLING_MS);
426
+ }
427
+ } catch (err) {
428
+ if (err instanceof SequencerInterruptedError) {
429
+ throw err;
430
+ }
431
+ this.log.warn(
432
+ `Archiver did not sync L1 past slot ${waitForSlot} before slot ${this.targetSlot} expired, discarding pipelined work`,
433
+ { checkpointNumber: this.checkpointNumber },
434
+ );
435
+ this.emitPipelinedCheckpointDiscarded('archiver-sync-timeout');
436
+ return false;
437
+ }
438
+ }
439
+
440
+ /**
441
+ * Waits for the parent checkpoint to land on L1 before submitting a pipelined checkpoint.
442
+ * Polls until the archiver has synced L1 past the parent's slot, then verifies:
443
+ * - If we built on a proposed parent: it must have landed on L1 with matching hash and valid attestations.
444
+ * - If we built without a proposed parent: no new checkpoint must have appeared for that slot.
445
+ * If the parent has invalid attestations, enqueues an invalidation. Returns whether to proceed with the proposal.
446
+ */
447
+ protected async waitForValidParentCheckpointOnL1(): Promise<boolean> {
448
+ if (this.config.skipWaitForValidParentCheckpointOnL1) {
449
+ this.log.warn(`Skipping waitForValidParentCheckpointOnL1 due to test configuration`, {
450
+ checkpointNumber: this.checkpointNumber,
172
451
  });
173
- await sleepUntil(new Date(Number(submissionSlotTimestamp) * 1000), this.dateProvider.nowAsDate());
452
+ return true;
453
+ }
454
+
455
+ const parentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 1);
456
+
457
+ // Wait until archiver has synced L1 past the parent's slot (the build slot, one before targetSlot)
458
+ if (!(await this.waitForSyncedL2SlotNumber(this.getBuildSlot()))) {
459
+ return false;
460
+ }
174
461
 
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) {
462
+ const tips = await this.l2BlockSource.getL2Tips();
463
+ const checkpointedNumber = tips.checkpointed.checkpoint.number;
464
+
465
+ // We built on top of a proposed checkpoint. Verify it landed on L1 as expected.
466
+ if (this.proposedCheckpointData) {
467
+ // After syncing from L1 we see the chain tip has invalid attestations. This means the parent checkpoint was posted
468
+ // with invalid attestations, or it built on top of something with invalid attestations and didnt invalidate them.
469
+ // Either way, we thought our parent would be valid, so we have to throw away our work. But at least we'll try and
470
+ // invalidate on L1 so we clean up the chain for the next proposer. And we'll slash them, but that's handled elsewhere.
471
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
472
+ if (!validationStatus.valid) {
180
473
  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}`,
474
+ `Parent checkpoint ${parentCheckpointNumber} has invalid attestations, discarding pipelined work`,
475
+ { checkpointNumber: this.checkpointNumber, reason: validationStatus.reason },
182
476
  );
183
- return undefined;
477
+ this.emitPipelinedCheckpointDiscarded('parent-invalid-attestations');
478
+ await this.enqueueInvalidation(validationStatus);
479
+ return false;
184
480
  }
481
+
482
+ // The pending chain is valid. But did the parent checkpoint land on L1 at all?
483
+ if (checkpointedNumber < parentCheckpointNumber) {
484
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} did not land on L1, discarding pipelined work`, {
485
+ checkpointNumber: this.checkpointNumber,
486
+ checkpointedNumber,
487
+ });
488
+ this.emitPipelinedCheckpointDiscarded('parent-not-on-l1');
489
+ return false;
490
+ }
491
+
492
+ // It landed. But is it the one we were expecting?
493
+ const expectedHash = this.proposedCheckpointData.header.hash().toString();
494
+ if (tips.checkpointed.checkpoint.hash !== expectedHash) {
495
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} hash mismatch on L1, discarding pipelined work`, {
496
+ checkpointNumber: this.checkpointNumber,
497
+ expectedHash,
498
+ actualHash: tips.checkpointed.checkpoint.hash,
499
+ });
500
+ this.emitPipelinedCheckpointDiscarded('parent-hash-mismatch');
501
+ return false;
502
+ }
503
+
504
+ return true;
505
+ } else {
506
+ // We didn't see a proposed checkpoint at build time, so we built on checkpointed parent from two slots ago.
507
+ // But if a new checkpoint for the previous slot appeared on L1 in the meantime, our checkpoint assumed the wrong parent,
508
+ // so we have to discard our work. This can happen if we're somehow cut off from p2p and fail to see the checkpoint
509
+ // proposal for the previous slot.
510
+ if (checkpointedNumber > parentCheckpointNumber) {
511
+ this.log.warn(
512
+ `Unexpected checkpoint ${checkpointedNumber} landed on L1 after we built on top of parent ${parentCheckpointNumber}, discarding pipelined work`,
513
+ { checkpointNumber: this.checkpointNumber, checkpointedNumber },
514
+ );
515
+ this.emitPipelinedCheckpointDiscarded('unexpected-parent-appeared');
516
+ return false;
517
+ }
518
+
519
+ return true;
185
520
  }
521
+ }
186
522
 
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;
523
+ /** Emits the pipelined-checkpoint-discarded event and records the metric. */
524
+ private emitPipelinedCheckpointDiscarded(reason: string): void {
525
+ this.metrics.recordPipelineParentCheckpointMismatch(reason);
526
+ this.eventEmitter.emit('pipelined-checkpoint-discarded', {
527
+ slot: this.targetSlot,
528
+ checkpointNumber: this.checkpointNumber,
529
+ reason,
530
+ });
531
+ }
532
+
533
+ /** Simulates and enqueues an invalidation request for the invalid parent checkpoint. */
534
+ private async enqueueInvalidation(validationStatus: ValidateCheckpointResult): Promise<void> {
535
+ if (this.config.skipInvalidateBlockAsProposer) {
536
+ this.log.warn(`Skipping checkpoint invalidation as proposer due to test configuration`);
537
+ return;
538
+ }
539
+ const invalidateRequest = await this.publisher.simulateInvalidateCheckpoint(validationStatus);
540
+ if (invalidateRequest) {
541
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
542
+ const txTimeoutAt = new Date((submissionSlotStart + this.l1Constants.slotDuration) * 1000);
543
+ this.publisher.enqueueInvalidateCheckpoint(invalidateRequest, { txTimeoutAt });
544
+ } else {
545
+ this.log.info(`Invalidation simulation returned undefined, checkpoint may have been removed already`, {
546
+ checkpointNumber: this.checkpointNumber,
547
+ });
198
548
  }
199
549
  }
200
550
 
@@ -205,19 +555,32 @@ export class CheckpointProposalJob implements Traceable {
205
555
  [Attributes.SLOT_NUMBER]: this.targetSlot,
206
556
  };
207
557
  })
208
- private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
558
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
209
559
  try {
560
+ const now = this.dateProvider.now();
561
+ if (this.proposedCheckpointData) {
562
+ // Measure against the wall-clock slot whose build window we are currently using.
563
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
564
+ // target-slot boundary a full slot away from the actual build start time.
565
+ const slotBoundaryMs = Number(getTimestampForSlot(this.getBuildSlot(), this.l1Constants)) * 1000;
566
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
567
+ }
568
+ this.checkpointMetrics.startCheckpointTiming(now);
569
+
210
570
  // Get operator configured coinbase and fee recipient for this attestor
211
571
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
212
572
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
213
573
 
214
574
  // Start the checkpoint
215
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
216
- this.log.info(`Starting checkpoint proposal`, {
217
- buildSlot: this.slot,
575
+ this.setState(SequencerState.INITIALIZING_CHECKPOINT);
576
+ this.logCheckpointEvent('slot-started', `Starting checkpoint proposal for slot ${this.targetSlot}`, {
577
+ buildSlot: this.getBuildSlot(),
218
578
  submissionSlot: this.targetSlot,
219
- pipelining: this.epochCache.isProposerPipeliningEnabled(),
579
+ slot: this.targetSlot,
580
+ checkpointNumber: this.checkpointNumber,
220
581
  proposer: this.proposer?.toString(),
582
+ attestorAddress: this.attestorAddress.toString(),
583
+ publisherAddress: this.publisher.getSenderAddress().toString(),
221
584
  coinbase: coinbase.toString(),
222
585
  });
223
586
  this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
@@ -227,24 +590,51 @@ export class CheckpointProposalJob implements Traceable {
227
590
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
228
591
  }
229
592
 
230
- // Create checkpoint builder for the slot
593
+ // Build the simulation plan for this slot. When pipelining, this overrides L1's view of
594
+ // pending/archive/fee-header to "as if the proposed parent had landed", so both the
595
+ // mana-min-fee simulation (in the globals builder) and the pre-broadcast
596
+ // validateBlockHeader see the chain tip the eventual L1 send will see.
597
+ this.checkpointSimulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
598
+ checkpointNumber: this.checkpointNumber,
599
+ proposedCheckpointData: this.proposedCheckpointData,
600
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
601
+ checkpointedCheckpointNumber: this.checkpointedCheckpointNumber,
602
+ rollup: this.publisher.rollupContract,
603
+ signatureContext: this.signatureContext,
604
+ log: this.log,
605
+ });
606
+
231
607
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
232
608
  coinbase,
233
609
  feeRecipient,
234
610
  this.targetSlot,
611
+ this.checkpointSimulationOverridesPlan,
235
612
  );
236
613
 
237
614
  // Collect L1 to L2 messages for the checkpoint and compute their hash
238
615
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
239
616
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
240
617
 
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);
618
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
619
+ // Under pipelining the parent checkpoint may not be on L1 yet at build time, so the helper
620
+ // splices in the parent's checkpointOutHash from the locally-known proposed checkpoint so
621
+ // the resulting `epochOutHash` matches what validators (and L1) compute once the parent
622
+ // lands on L1.
623
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
624
+ blockSource: this.l2BlockSource,
625
+ epoch: this.targetEpoch,
626
+ checkpointNumber: this.checkpointNumber,
627
+ l1Constants: this.epochCache.getL1Constants(),
628
+ pipeliningEnabled: true,
629
+ proposedCheckpointData: this.proposedCheckpointData,
630
+ log: this.log,
631
+ });
245
632
 
246
- // Get the fee asset price modifier from the oracle
247
- const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
633
+ // Anchor the modifier to the predicted parent fee header: L1 will apply it against
634
+ // that, not against the latest published checkpoint (which lags by one under pipelining).
635
+ const predictedParentEthPerFeeAssetE12 =
636
+ this.checkpointSimulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
637
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12);
248
638
 
249
639
  // Create a long-lived forked world state for the checkpoint builder
250
640
  await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
@@ -268,11 +658,12 @@ export class CheckpointProposalJob implements Traceable {
268
658
 
269
659
  const checkpointProposalOptions: CheckpointProposalOptions = {
270
660
  publishFullTxs: !!this.config.publishTxsWithProposals,
271
- broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
661
+ broadcastInvalidCheckpointProposal:
662
+ this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal,
272
663
  };
273
664
 
274
665
  let blocksInCheckpoint: L2Block[] = [];
275
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
666
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
276
667
  const checkpointBuildTimer = new Timer();
277
668
 
278
669
  try {
@@ -296,23 +687,45 @@ export class CheckpointProposalJob implements Traceable {
296
687
  }
297
688
 
298
689
  if (blocksInCheckpoint.length === 0) {
299
- this.log.warn(`No blocks were built for slot ${this.targetSlot}`, { slot: this.targetSlot });
690
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
691
+ slot: this.targetSlot,
692
+ checkpointNumber: this.checkpointNumber,
693
+ reason: 'no_blocks_built',
694
+ });
695
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
696
+ slot: this.targetSlot,
697
+ checkpointNumber: this.checkpointNumber,
698
+ reason: 'no_blocks_built',
699
+ });
300
700
  this.eventEmitter.emit('checkpoint-empty', { slot: this.targetSlot });
301
701
  return undefined;
302
702
  }
303
703
 
304
704
  const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
305
705
  if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
706
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
707
+ slot: this.targetSlot,
708
+ checkpointNumber: this.checkpointNumber,
709
+ blocksBuilt: blocksInCheckpoint.length,
710
+ minBlocksForCheckpoint,
711
+ reason: 'min_blocks_not_met',
712
+ });
306
713
  this.log.warn(
307
714
  `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
308
- { slot: this.targetSlot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
715
+ {
716
+ slot: this.targetSlot,
717
+ checkpointNumber: this.checkpointNumber,
718
+ blocksBuilt: blocksInCheckpoint.length,
719
+ minBlocksForCheckpoint,
720
+ reason: 'min_blocks_not_met',
721
+ },
309
722
  );
310
723
  return undefined;
311
724
  }
312
725
 
313
726
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
314
727
  // broadcasted yet, and wait to collect the committee attestations.
315
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
728
+ this.setState(SequencerState.ASSEMBLING_CHECKPOINT);
316
729
  const checkpoint = await checkpointBuilder.completeCheckpoint();
317
730
 
318
731
  // Final validation: per-block limits are only checked if the operator set them explicitly.
@@ -326,21 +739,43 @@ export class CheckpointProposalJob implements Traceable {
326
739
  maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
327
740
  });
328
741
  } catch (err) {
329
- this.log.error(`Built an invalid checkpoint at slot ${this.slot} (skipping proposal)`, err, {
742
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
743
+ slot: this.targetSlot,
744
+ checkpointNumber: this.checkpointNumber,
745
+ blocksBuilt: blocksInCheckpoint.length,
746
+ reason: 'invalid_checkpoint',
747
+ checkpoint: checkpoint.header.toInspect(),
748
+ });
749
+ this.log.error(`Built an invalid checkpoint at slot ${this.targetSlot} (skipping proposal)`, err, {
750
+ slot: this.targetSlot,
751
+ checkpointNumber: this.checkpointNumber,
752
+ blocksBuilt: blocksInCheckpoint.length,
753
+ reason: 'invalid_checkpoint',
330
754
  checkpoint: checkpoint.header.toInspect(),
331
755
  });
332
756
  return undefined;
333
757
  }
334
758
 
335
759
  // Record checkpoint-level build metrics
336
- this.metrics.recordCheckpointBuild(
760
+ this.checkpointMetrics.recordCheckpointBuild(
337
761
  checkpointBuildTimer.ms(),
338
762
  blocksInCheckpoint.length,
339
763
  checkpoint.getStats().txCount,
340
764
  Number(checkpoint.header.totalManaUsed.toBigInt()),
341
765
  );
766
+ this.logCheckpointEvent('built', `Checkpoint built for slot ${this.targetSlot}`, {
767
+ slot: this.targetSlot,
768
+ buildSlot: this.getBuildSlot(),
769
+ checkpointNumber: this.checkpointNumber,
770
+ proposer: this.proposer?.toString(),
771
+ attestorAddress: this.attestorAddress.toString(),
772
+ publisherAddress: this.publisher.getSenderAddress().toString(),
773
+ blocksBuilt: blocksInCheckpoint.length,
774
+ txCount: checkpoint.getStats().txCount,
775
+ totalMana: Number(checkpoint.header.totalManaUsed.toBigInt()),
776
+ });
342
777
 
343
- // Do not collect attestations nor publish to L1 in fisherman mode
778
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
344
779
  if (this.config.fishermanMode) {
345
780
  this.log.info(
346
781
  `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
@@ -352,87 +787,70 @@ export class CheckpointProposalJob implements Traceable {
352
787
  },
353
788
  );
354
789
  this.metrics.recordCheckpointSuccess();
355
- return checkpoint;
790
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
791
+ return { checkpoint, proposal: undefined!, blockProposedAt: this.dateProvider.now() };
356
792
  }
357
793
 
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
- };
794
+ // Validate the header against L1 state before broadcasting.
795
+ // If this fails the slot is aborted before any gossip work; state drift between here
796
+ // and the eventual L1 send is caught by the bundle simulate at send time.
797
+ try {
798
+ await this.publisher.validateBlockHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
799
+ } catch (err) {
800
+ this.log.error(`Pre-broadcast header validation failed for slot ${this.targetSlot}; aborting`, err, {
801
+ slot: this.targetSlot,
802
+ checkpointNumber: this.checkpointNumber,
803
+ });
804
+ this.metrics.recordCheckpointProposalFailed('header_validation_failed');
805
+ this.eventEmitter.emit('header-validation-failed', {
806
+ slot: this.targetSlot,
807
+ checkpointNumber: this.checkpointNumber,
808
+ reason: err instanceof Error ? err.message : String(err),
809
+ });
810
+ return undefined;
811
+ }
364
812
 
365
813
  // Create the checkpoint proposal and broadcast it
366
814
  const proposal = await this.validatorClient.createCheckpointProposal(
367
815
  checkpoint.header,
368
816
  checkpoint.archive.root,
817
+ this.checkpointNumber,
369
818
  feeAssetPriceModifier,
370
- lastBlock,
819
+ blockPendingBroadcast,
371
820
  this.proposer,
372
821
  checkpointProposalOptions,
373
822
  );
374
823
 
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();
824
+ // Advance our own optimistic proposed-checkpoint tip locally before gossiping. Gossipsub
825
+ // doesn't echo our own messages back, so this is how the proposer makes its own proposed
826
+ // checkpoint visible for pipelining the next slot. Built from local checkpoint data — never
827
+ // from the broadcast proposal archive, which may be deliberately corrupted under test flags.
828
+ // Fail closed: if this throws, the outer catch aborts the slot before gossiping.
829
+ await this.syncProposedCheckpointToArchiver(checkpoint, blocksInCheckpoint.length, feeAssetPriceModifier);
381
830
 
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
- }
402
-
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;
831
+ const blockProposedAt = this.dateProvider.now();
832
+ if (this.config.skipBroadcastCheckpointProposal) {
833
+ // Test-only: suppress the CheckpointProposal so peers never see a proposed checkpoint for
834
+ // this slot, but still broadcast the held last block standalone so peers' archivers ingest
835
+ // it as a proposed-but-uncheckpointed tip — the exact orphan-block state that
836
+ // pruneOrphanProposedBlocks / checkSync must handle.
837
+ if (blockPendingBroadcast && !this.config.skipBroadcastProposals) {
838
+ await this.p2pClient.broadcastProposal(blockPendingBroadcast);
420
839
  }
840
+ } else if (!this.config.skipBroadcastProposals) {
841
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
842
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
421
843
  }
422
844
 
423
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
424
- txTimeoutAt,
425
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
426
- });
427
-
428
- return checkpoint;
845
+ // Return immediately after broadcast — attestation collection happens in the background
846
+ return { checkpoint, proposal, blockProposedAt };
429
847
  } catch (err) {
430
848
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
431
849
  // swallow this error. It's already been logged by a function deeper in the stack
432
850
  return undefined;
433
851
  }
434
852
 
435
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
853
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
436
854
  return undefined;
437
855
  }
438
856
  }
@@ -448,28 +866,37 @@ export class CheckpointProposalJob implements Traceable {
448
866
  blockProposalOptions: BlockProposalOptions,
449
867
  ): Promise<{
450
868
  blocksInCheckpoint: L2Block[];
451
- blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
869
+ blockPendingBroadcast: BlockProposal | undefined;
452
870
  }> {
453
871
  const blocksInCheckpoint: L2Block[] = [];
454
872
  const txHashesAlreadyIncluded = new Set<string>();
455
873
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
456
874
 
457
875
  // 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;
876
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
459
877
 
460
878
  while (true) {
461
879
  const blocksBuilt = blocksInCheckpoint.length;
462
880
  const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
463
881
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
464
882
 
465
- const secondsIntoSlot = this.getSecondsIntoSlot();
466
- const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
883
+ if (blocksBuilt >= this.config.maxBlocksPerCheckpoint) {
884
+ this.log.debug(`Reached max blocks per checkpoint`, {
885
+ slot: this.targetSlot,
886
+ blocksBuilt,
887
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint,
888
+ });
889
+ break;
890
+ }
891
+
892
+ const nowSeconds = this.dateProvider.now() / 1000;
893
+ const timingInfo = this.timetable.selectNextSubslot(this.targetSlot, nowSeconds);
467
894
 
468
895
  if (!timingInfo.canStart) {
469
896
  this.log.debug(`Not enough time left in slot to start another block`, {
470
897
  slot: this.targetSlot,
471
898
  blocksBuilt,
472
- secondsIntoSlot,
899
+ nowSeconds,
473
900
  });
474
901
  break;
475
902
  }
@@ -479,28 +906,26 @@ export class CheckpointProposalJob implements Traceable {
479
906
  blockTimestamp: timestamp,
480
907
  // Create an empty block if we haven't already and this is the last one
481
908
  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,
909
+ buildDeadline: new Date(timingInfo.deadline * 1000),
486
910
  blockNumber,
487
911
  indexWithinCheckpoint,
488
912
  txHashesAlreadyIncluded,
489
913
  });
490
914
 
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
915
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
916
+ if ('failure' in buildResult) {
917
+ // If this was the last subslot, we're done.
918
+ if (timingInfo.isLastBlock) {
919
+ break;
920
+ }
921
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
497
922
  await this.waitUntilNextSubslot(timingInfo.deadline);
498
923
  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
924
+ }
925
+
926
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
927
+ // We don't want to risk building more blocks if something went wrong.
928
+ if ('error' in buildResult) {
504
929
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
505
930
  this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
506
931
  slot: this.targetSlot,
@@ -512,35 +937,44 @@ export class CheckpointProposalJob implements Traceable {
512
937
  }
513
938
 
514
939
  const { block, usedTxs } = buildResult;
940
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
941
+ isFirstBlock: blocksBuilt === 0,
942
+ isLastBlock: timingInfo.isLastBlock,
943
+ });
944
+
515
945
  blocksInCheckpoint.push(block);
516
946
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
517
947
 
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.
948
+ // Sign the block proposal. This will throw if HA signing fails.
949
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, {
950
+ ...blockProposalOptions,
951
+ broadcastInvalidBlockProposal:
952
+ blockProposalOptions.broadcastInvalidBlockProposal ||
953
+ block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint,
954
+ });
955
+
956
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
957
+ // so we avoid polluting our archive with a block that would fail.
958
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
959
+ // If this throws, we abort the entire checkpoint.
960
+ await this.syncProposedBlockToArchiver(block);
961
+
962
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
520
963
  if (timingInfo.isLastBlock) {
521
- await this.syncProposedBlockToArchiver(block);
522
964
  this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
523
965
  slot: this.targetSlot,
524
966
  blockNumber,
525
967
  blocksBuilt,
526
968
  });
527
- blockPendingBroadcast = { block, txs: usedTxs };
969
+
970
+ blockPendingBroadcast = proposal;
528
971
  break;
529
972
  }
530
973
 
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
974
  // 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));
975
+ if (proposal && !this.config.skipBroadcastProposals) {
976
+ await this.p2pClient.broadcastProposal(proposal);
977
+ }
544
978
 
545
979
  // Wait until the next block's start time
546
980
  await this.waitUntilNextSubslot(timingInfo.deadline);
@@ -567,6 +1001,7 @@ export class CheckpointProposalJob implements Traceable {
567
1001
  }
568
1002
  return this.validatorClient.createBlockProposal(
569
1003
  block.header,
1004
+ this.checkpointNumber,
570
1005
  block.indexWithinCheckpoint,
571
1006
  inHash,
572
1007
  block.archive.root,
@@ -576,14 +1011,17 @@ export class CheckpointProposalJob implements Traceable {
576
1011
  );
577
1012
  }
578
1013
 
579
- /** Sleeps until it is time to produce the next block in the slot */
1014
+ /**
1015
+ * Sleeps until it is time to produce the next block in the slot.
1016
+ * @param nextSubslotStart - Absolute wall-clock timestamp in seconds of the previous sub-slot deadline.
1017
+ */
580
1018
  @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`, {
1019
+ protected async waitUntilNextSubslot(nextSubslotStart: number) {
1020
+ this.setState(SequencerState.WAITING_UNTIL_NEXT_BLOCK);
1021
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s`, {
584
1022
  slot: this.targetSlot,
585
1023
  });
586
- await this.waitUntilTimeInSlot(nextSubslotStart);
1024
+ await this.awaitInterruptibleSleep(Math.max(0, nextSubslotStart * 1000 - this.dateProvider.now()));
587
1025
  }
588
1026
 
589
1027
  /** Builds a single block. Called from the main block building loop. */
@@ -598,7 +1036,9 @@ export class CheckpointProposalJob implements Traceable {
598
1036
  buildDeadline: Date | undefined;
599
1037
  txHashesAlreadyIncluded: Set<string>;
600
1038
  },
601
- ): Promise<{ block: L2Block; usedTxs: Tx[] } | { error: Error } | undefined> {
1039
+ ): Promise<
1040
+ { block: L2Block; usedTxs: Tx[] } | { failure: 'insufficient-txs' | 'insufficient-valid-txs' } | { error: Error }
1041
+ > {
602
1042
  const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
603
1043
  opts;
604
1044
 
@@ -611,19 +1051,38 @@ export class CheckpointProposalJob implements Traceable {
611
1051
  // Wait until we have enough txs to build the block
612
1052
  const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
613
1053
  if (!canStartBuilding) {
614
- this.log.warn(
1054
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1055
+ reason: 'insufficient_txs',
1056
+ blockNumber,
1057
+ slot: this.targetSlot,
1058
+ checkpointNumber: this.checkpointNumber,
1059
+ indexWithinCheckpoint,
1060
+ availableTxs,
1061
+ minTxs,
1062
+ });
1063
+ this.log.verbose(
615
1064
  `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 },
1065
+ {
1066
+ reason: 'insufficient_txs',
1067
+ blockNumber,
1068
+ slot: this.targetSlot,
1069
+ checkpointNumber: this.checkpointNumber,
1070
+ indexWithinCheckpoint,
1071
+ availableTxs,
1072
+ minTxs,
1073
+ },
617
1074
  );
618
1075
  this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.targetSlot });
619
1076
  this.metrics.recordBlockProposalFailed('insufficient_txs');
620
- return undefined;
1077
+ return { failure: 'insufficient-txs' };
621
1078
  }
622
1079
 
623
1080
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
624
1081
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
1082
+ // Block building only executes txs, so we skip loading their proofs unless these same tx objects get attached
1083
+ // to the broadcasted proposals via publishTxsWithProposals.
625
1084
  const pendingTxs = filter(
626
- this.p2pClient.iterateEligiblePendingTxs(),
1085
+ this.p2pClient.iterateEligiblePendingTxs({ includeProof: !!this.config.publishTxsWithProposals }),
627
1086
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
628
1087
  );
629
1088
 
@@ -631,7 +1090,7 @@ export class CheckpointProposalJob implements Traceable {
631
1090
  `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`,
632
1091
  { slot: this.targetSlot, blockNumber, indexWithinCheckpoint },
633
1092
  );
634
- this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
1093
+ this.setState(SequencerState.CREATING_BLOCK);
635
1094
 
636
1095
  // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
637
1096
  // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
@@ -646,8 +1105,9 @@ export class CheckpointProposalJob implements Traceable {
646
1105
  deadline: buildDeadline,
647
1106
  isBuildingProposal: true,
648
1107
  minValidTxs,
649
- maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
1108
+ maxBlocksPerCheckpoint: this.timetable.getMaxBlocksPerCheckpoint(),
650
1109
  perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
1110
+ perBlockDAAllocationMultiplier: this.config.perBlockDAAllocationMultiplier,
651
1111
  };
652
1112
 
653
1113
  // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
@@ -665,10 +1125,21 @@ export class CheckpointProposalJob implements Traceable {
665
1125
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
666
1126
 
667
1127
  if (buildResult.status === 'insufficient-valid-txs') {
1128
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1129
+ reason: 'insufficient_valid_txs',
1130
+ slot: this.targetSlot,
1131
+ checkpointNumber: this.checkpointNumber,
1132
+ blockNumber,
1133
+ numTxs: buildResult.processedCount,
1134
+ indexWithinCheckpoint,
1135
+ minValidTxs,
1136
+ });
668
1137
  this.log.warn(
669
1138
  `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`,
670
1139
  {
1140
+ reason: 'insufficient_valid_txs',
671
1141
  slot: this.targetSlot,
1142
+ checkpointNumber: this.checkpointNumber,
672
1143
  blockNumber,
673
1144
  numTxs: buildResult.processedCount,
674
1145
  indexWithinCheckpoint,
@@ -680,7 +1151,7 @@ export class CheckpointProposalJob implements Traceable {
680
1151
  slot: this.targetSlot,
681
1152
  });
682
1153
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
683
- return undefined;
1154
+ return { failure: 'insufficient-valid-txs' };
684
1155
  }
685
1156
 
686
1157
  // Block creation succeeded, emit stats and metrics
@@ -702,12 +1173,17 @@ export class CheckpointProposalJob implements Traceable {
702
1173
  { blockHash, txHashes, manaPerSec, ...blockStats },
703
1174
  );
704
1175
 
1176
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
1177
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
705
1178
  this.eventEmitter.emit('block-proposed', {
706
1179
  blockNumber: block.number,
1180
+ blockHash,
1181
+ checkpointNumber: this.checkpointNumber,
1182
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
707
1183
  slot: this.targetSlot,
708
- buildSlot: this.slotNow,
1184
+ buildSlot: this.getBuildSlot(),
709
1185
  });
710
- this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
1186
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
711
1187
 
712
1188
  return { block, usedTxs };
713
1189
  } catch (err: any) {
@@ -715,7 +1191,18 @@ export class CheckpointProposalJob implements Traceable {
715
1191
  reason: err.message,
716
1192
  slot: this.targetSlot,
717
1193
  });
718
- this.log.error(`Error building block`, err, { blockNumber, slot: this.targetSlot });
1194
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1195
+ reason: err instanceof Error ? err.message : String(err),
1196
+ slot: this.targetSlot,
1197
+ checkpointNumber: this.checkpointNumber,
1198
+ blockNumber,
1199
+ });
1200
+ this.log.error(`Error building block`, err, {
1201
+ reason: err instanceof Error ? err.message : String(err),
1202
+ slot: this.targetSlot,
1203
+ checkpointNumber: this.checkpointNumber,
1204
+ blockNumber,
1205
+ });
719
1206
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
720
1207
  this.metrics.recordFailedBlock();
721
1208
  return { error: err };
@@ -760,9 +1247,9 @@ export class CheckpointProposalJob implements Traceable {
760
1247
  // We only allow a block with 0 txs in the first block of the checkpoint
761
1248
  const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
762
1249
 
763
- // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
1250
+ // Latest time to keep waiting for txs: wait_for_txs_deadline = block_build_deadline(k) - min_block_duration.
764
1251
  const startBuildingDeadline = buildDeadline
765
- ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
1252
+ ? new Date(buildDeadline.getTime() - this.timetable.minBlockDuration * 1000)
766
1253
  : undefined;
767
1254
 
768
1255
  let availableTxs = await this.p2pClient.getPendingTxCount();
@@ -775,7 +1262,7 @@ export class CheckpointProposalJob implements Traceable {
775
1262
  }
776
1263
 
777
1264
  // Wait a bit before checking again
778
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
1265
+ this.setState(SequencerState.WAITING_FOR_TXS);
779
1266
  this.log.verbose(
780
1267
  `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`,
781
1268
  { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
@@ -787,15 +1274,47 @@ export class CheckpointProposalJob implements Traceable {
787
1274
  return { canStartBuilding: true, availableTxs, minTxs };
788
1275
  }
789
1276
 
1277
+ private async getSignedCommitteeAttestations(
1278
+ broadcast: CheckpointProposalBroadcast,
1279
+ ): Promise<{ attestations: CommitteeAttestationsAndSigners; attestationsSignature: Signature } | undefined> {
1280
+ const { proposal, blockProposedAt } = broadcast;
1281
+ this.setState(SequencerState.COLLECTING_ATTESTATIONS);
1282
+ const attestations = await this.waitForAttestations(proposal);
1283
+ if (!attestations) {
1284
+ return undefined;
1285
+ }
1286
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
1287
+
1288
+ // Proposer must sign over the attestations before pushing them to L1
1289
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1290
+ try {
1291
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
1292
+ attestations,
1293
+ signer,
1294
+ this.targetSlot,
1295
+ this.checkpointNumber,
1296
+ );
1297
+ return { attestations, attestationsSignature };
1298
+ } catch (err) {
1299
+ if (this.handleHASigningError(err, 'Attestations signature')) {
1300
+ return;
1301
+ }
1302
+ this.log.error(`Error signing attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1303
+ return undefined;
1304
+ }
1305
+ }
1306
+
790
1307
  /**
791
1308
  * Waits for enough attestations to be collected via p2p.
792
1309
  * This is run after all blocks for the checkpoint have been built.
793
1310
  */
794
1311
  @trackSpan('CheckpointProposalJob.waitForAttestations')
795
- private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
1312
+ private async waitForAttestations(
1313
+ proposal: CheckpointProposal,
1314
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
796
1315
  if (this.config.fishermanMode) {
797
1316
  this.log.debug('Skipping attestation collection in fisherman mode');
798
- return CommitteeAttestationsAndSigners.empty();
1317
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
799
1318
  }
800
1319
 
801
1320
  const slotNumber = proposal.slotNumber;
@@ -805,25 +1324,33 @@ export class CheckpointProposalJob implements Traceable {
805
1324
  throw new Error('No committee when collecting attestations');
806
1325
  } else if (committee.length === 0) {
807
1326
  this.log.verbose(`Attesting committee is empty`);
808
- return CommitteeAttestationsAndSigners.empty();
1327
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
809
1328
  } else {
810
1329
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
811
1330
  }
812
1331
 
813
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
1332
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
814
1333
 
815
1334
  if (this.config.skipCollectingAttestations) {
816
1335
  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));
1336
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
1337
+ this.logCheckpointAttestations('collected', committee, attestations ?? [], numberOfRequiredAttestations, {
1338
+ reason: 'collect_own_only',
1339
+ });
1340
+ return new CommitteeAttestationsAndSigners(
1341
+ orderAttestations(attestations ?? [], committee),
1342
+ this.getSignatureContext(),
1343
+ );
819
1344
  }
820
1345
 
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);
1346
+ // Hard attestation-collection cutoff = the single consensus attestation_deadline (target_slot_start + S - 2E).
1347
+ const attestationDeadlineSeconds = this.timetable.getAttestationDeadline(this.targetSlot);
1348
+ const attestationDeadline = new Date(attestationDeadlineSeconds * 1000);
825
1349
 
826
- this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
1350
+ this.metrics.recordRequiredAttestations(
1351
+ numberOfRequiredAttestations,
1352
+ Math.max(0, attestationDeadline.getTime() - this.dateProvider.now()),
1353
+ );
827
1354
 
828
1355
  const collectAttestationsTimer = new Timer();
829
1356
  let collectedAttestationsCount: number = 0;
@@ -832,6 +1359,7 @@ export class CheckpointProposalJob implements Traceable {
832
1359
  proposal,
833
1360
  numberOfRequiredAttestations,
834
1361
  attestationDeadline,
1362
+ this.checkpointNumber,
835
1363
  );
836
1364
 
837
1365
  collectedAttestationsCount = attestations.length;
@@ -850,6 +1378,9 @@ export class CheckpointProposalJob implements Traceable {
850
1378
 
851
1379
  // Rollup contract requires that the signatures are provided in the order of the committee
852
1380
  const sorted = orderAttestations(trimmed, committee);
1381
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1382
+ submittedCount: trimmed.length,
1383
+ });
853
1384
 
854
1385
  // Manipulate the attestations if we've been configured to do so
855
1386
  if (
@@ -861,17 +1392,56 @@ export class CheckpointProposalJob implements Traceable {
861
1392
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
862
1393
  }
863
1394
 
864
- return new CommitteeAttestationsAndSigners(sorted);
1395
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
865
1396
  } catch (err) {
866
1397
  if (err && err instanceof AttestationTimeoutError) {
867
1398
  collectedAttestationsCount = err.collectedCount;
1399
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1400
+ collectedCount: collectedAttestationsCount,
1401
+ reason: 'timeout',
1402
+ });
1403
+ this.log.error(
1404
+ `Timeout while waiting for attestations for checkpoint proposal at slot ${proposal.slotNumber} (collected ${collectedAttestationsCount}/${numberOfRequiredAttestations})`,
1405
+ err,
1406
+ );
1407
+ } else {
1408
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1409
+ collectedCount: collectedAttestationsCount,
1410
+ reason: err instanceof Error ? err.message : String(err),
1411
+ });
1412
+ this.log.error(`Error collecting attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
868
1413
  }
869
- throw err;
1414
+ return undefined;
870
1415
  } finally {
871
1416
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
872
1417
  }
873
1418
  }
874
1419
 
1420
+ private logCheckpointAttestations(
1421
+ status: 'collected' | 'failed',
1422
+ committee: EthAddress[],
1423
+ attestations: CheckpointAttestation[] | undefined,
1424
+ requiredAttestations: number,
1425
+ opts: { collectedCount?: number; submittedCount?: number; reason?: string } = {},
1426
+ ) {
1427
+ const signedValidators =
1428
+ attestations
1429
+ ?.map(attestation => attestation.getSender()?.toString())
1430
+ .filter((address): address is `0x${string}` => address !== undefined) ?? [];
1431
+ const collectedCount = opts.collectedCount ?? new Set(signedValidators).size;
1432
+ const missingValidatorCount = status === 'failed' ? Math.max(0, requiredAttestations - collectedCount) : undefined;
1433
+ this.logCheckpointEvent(`attestations-${status}`, `Checkpoint attestations ${status} for slot ${this.targetSlot}`, {
1434
+ slot: this.targetSlot,
1435
+ checkpointNumber: this.checkpointNumber,
1436
+ committeeSize: committee.length,
1437
+ requiredAttestations,
1438
+ collectedAttestations: collectedCount,
1439
+ ...(opts.submittedCount !== undefined && { submittedAttestations: opts.submittedCount }),
1440
+ ...(missingValidatorCount !== undefined && { missingValidatorCount }),
1441
+ ...(opts.reason !== undefined && { reason: opts.reason }),
1442
+ });
1443
+ }
1444
+
875
1445
  /** Breaks the attestations before publishing based on attack configs */
876
1446
  private manipulateAttestations(
877
1447
  slotNumber: SlotNumber,
@@ -915,7 +1485,7 @@ export class CheckpointProposalJob implements Traceable {
915
1485
  unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
916
1486
  }
917
1487
  }
918
- return new CommitteeAttestationsAndSigners(attestations);
1488
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
919
1489
  }
920
1490
 
921
1491
  if (this.config.shuffleAttestationOrdering) {
@@ -937,11 +1507,11 @@ export class CheckpointProposalJob implements Traceable {
937
1507
  [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
938
1508
  }
939
1509
 
940
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
941
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
1510
+ const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
1511
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
942
1512
  }
943
1513
 
944
- return new CommitteeAttestationsAndSigners(attestations);
1514
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
945
1515
  }
946
1516
 
947
1517
  private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
@@ -958,9 +1528,13 @@ export class CheckpointProposalJob implements Traceable {
958
1528
  * Adds the proposed block to the archiver so it's available via P2P.
959
1529
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
960
1530
  * would never receive its own block without this explicit sync.
1531
+ *
1532
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1533
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1534
+ * whenever the real proposer's block arrives from L1.
961
1535
  */
962
1536
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
963
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1537
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
964
1538
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
965
1539
  blockNumber: block.number,
966
1540
  slot: block.header.globalVariables.slotNumber,
@@ -974,6 +1548,41 @@ export class CheckpointProposalJob implements Traceable {
974
1548
  await this.blockSink.addBlock(block);
975
1549
  }
976
1550
 
1551
+ /**
1552
+ * Adds the proposed checkpoint to the archiver so the proposer's optimistic proposed-checkpoint
1553
+ * tip advances locally. Gossip doesn't echo our own messages back, so without this the proposer
1554
+ * would never see its own proposed checkpoint and couldn't pipeline the next slot.
1555
+ *
1556
+ * Skipped whenever proposed blocks aren't pushed (`skipPushProposedBlocksToArchiver`, fisherman
1557
+ * mode): the archiver derives the checkpoint archive from its stored blocks, so without them the
1558
+ * push would fail. All blocks were already added (and awaited) during block building, so this
1559
+ * needs no retry — they are guaranteed present by the time we get here.
1560
+ */
1561
+ private async syncProposedCheckpointToArchiver(
1562
+ checkpoint: Checkpoint,
1563
+ blockCount: number,
1564
+ feeAssetPriceModifier: bigint,
1565
+ ): Promise<void> {
1566
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1567
+ return;
1568
+ }
1569
+ const startBlock = BlockNumber(this.syncedToBlockNumber + 1);
1570
+ this.log.debug(`Syncing proposed checkpoint ${this.checkpointNumber} to archiver`, {
1571
+ checkpointNumber: this.checkpointNumber,
1572
+ slot: this.targetSlot,
1573
+ startBlock,
1574
+ blockCount,
1575
+ });
1576
+ await this.blockSink.addProposedCheckpoint({
1577
+ header: checkpoint.header,
1578
+ checkpointNumber: this.checkpointNumber,
1579
+ startBlock,
1580
+ blockCount,
1581
+ totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
1582
+ feeAssetPriceModifier,
1583
+ });
1584
+ }
1585
+
977
1586
  /** Runs fee analysis and logs checkpoint outcome as fisherman */
978
1587
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
979
1588
  // Perform L1 fee analysis before clearing requests
@@ -1021,26 +1630,9 @@ export class CheckpointProposalJob implements Traceable {
1021
1630
  return false;
1022
1631
  }
1023
1632
 
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
1633
  /** Waits the polling interval for transactions. Extracted for test overriding. */
1033
1634
  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));
1635
+ await this.awaitInterruptibleSleep(TXS_POLLING_MS);
1044
1636
  }
1045
1637
 
1046
1638
  public getPublisher() {