@aztec/sequencer-client 0.0.1-commit.d1f2d6c → 0.0.1-commit.d20b825a7

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 (107) hide show
  1. package/dest/client/sequencer-client.d.ts +17 -7
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +63 -30
  4. package/dest/config.d.ts +26 -7
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +52 -36
  7. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  8. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  9. package/dest/global_variable_builder/fee_predictor.js +128 -0
  10. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  12. package/dest/global_variable_builder/fee_provider.js +58 -0
  13. package/dest/global_variable_builder/global_builder.d.ts +15 -16
  14. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  15. package/dest/global_variable_builder/global_builder.js +16 -50
  16. package/dest/global_variable_builder/index.d.ts +4 -2
  17. package/dest/global_variable_builder/index.d.ts.map +1 -1
  18. package/dest/global_variable_builder/index.js +2 -0
  19. package/dest/publisher/config.d.ts +47 -17
  20. package/dest/publisher/config.d.ts.map +1 -1
  21. package/dest/publisher/config.js +121 -42
  22. package/dest/publisher/index.d.ts +2 -1
  23. package/dest/publisher/index.d.ts.map +1 -1
  24. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  25. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  26. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  27. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  28. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  29. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  30. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  31. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  32. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  33. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  34. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  35. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  36. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -5
  37. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  38. package/dest/publisher/sequencer-publisher-factory.js +27 -3
  39. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  40. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  41. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  42. package/dest/publisher/sequencer-publisher.d.ts +75 -49
  43. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  44. package/dest/publisher/sequencer-publisher.js +470 -156
  45. package/dest/sequencer/chain_state_overrides.d.ts +25 -0
  46. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  47. package/dest/sequencer/chain_state_overrides.js +39 -0
  48. package/dest/sequencer/checkpoint_proposal_job.d.ts +67 -14
  49. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  50. package/dest/sequencer/checkpoint_proposal_job.js +581 -242
  51. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  52. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  53. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  54. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  55. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  56. package/dest/sequencer/checkpoint_voter.js +2 -5
  57. package/dest/sequencer/events.d.ts +7 -1
  58. package/dest/sequencer/events.d.ts.map +1 -1
  59. package/dest/sequencer/metrics.d.ts +21 -8
  60. package/dest/sequencer/metrics.d.ts.map +1 -1
  61. package/dest/sequencer/metrics.js +135 -36
  62. package/dest/sequencer/sequencer.d.ts +45 -17
  63. package/dest/sequencer/sequencer.d.ts.map +1 -1
  64. package/dest/sequencer/sequencer.js +160 -94
  65. package/dest/sequencer/timetable.d.ts +17 -6
  66. package/dest/sequencer/timetable.d.ts.map +1 -1
  67. package/dest/sequencer/timetable.js +51 -46
  68. package/dest/sequencer/types.d.ts +2 -2
  69. package/dest/sequencer/types.d.ts.map +1 -1
  70. package/dest/test/index.d.ts +3 -5
  71. package/dest/test/index.d.ts.map +1 -1
  72. package/dest/test/mock_checkpoint_builder.d.ts +14 -11
  73. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  74. package/dest/test/mock_checkpoint_builder.js +63 -40
  75. package/dest/test/utils.d.ts +3 -3
  76. package/dest/test/utils.d.ts.map +1 -1
  77. package/dest/test/utils.js +5 -4
  78. package/package.json +27 -28
  79. package/src/client/sequencer-client.ts +81 -30
  80. package/src/config.ts +70 -46
  81. package/src/global_variable_builder/README.md +44 -0
  82. package/src/global_variable_builder/fee_predictor.ts +172 -0
  83. package/src/global_variable_builder/fee_provider.ts +75 -0
  84. package/src/global_variable_builder/global_builder.ts +27 -63
  85. package/src/global_variable_builder/index.ts +3 -1
  86. package/src/publisher/config.ts +157 -45
  87. package/src/publisher/index.ts +3 -0
  88. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  89. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  90. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  91. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  92. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  93. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  94. package/src/publisher/sequencer-publisher.ts +531 -214
  95. package/src/sequencer/README.md +83 -13
  96. package/src/sequencer/chain_state_overrides.ts +87 -0
  97. package/src/sequencer/checkpoint_proposal_job.ts +748 -278
  98. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  99. package/src/sequencer/checkpoint_voter.ts +1 -12
  100. package/src/sequencer/events.ts +6 -1
  101. package/src/sequencer/metrics.ts +156 -40
  102. package/src/sequencer/sequencer.ts +232 -107
  103. package/src/sequencer/timetable.ts +70 -57
  104. package/src/sequencer/types.ts +1 -1
  105. package/src/test/index.ts +2 -4
  106. package/src/test/mock_checkpoint_builder.ts +84 -56
  107. package/src/test/utils.ts +5 -2
@@ -1,16 +1,27 @@
1
- import { NUM_CHECKPOINT_END_MARKER_FIELDS, getNumBlockEndBlobFields } from '@aztec/blob-lib/encoding';
2
- import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
3
1
  import type { EpochCache } from '@aztec/epoch-cache';
4
- import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { SimulationOverridesPlan } from '@aztec/ethereum/contracts';
3
+ import {
4
+ BlockNumber,
5
+ CheckpointNumber,
6
+ EpochNumber,
7
+ IndexWithinCheckpoint,
8
+ SlotNumber,
9
+ } from '@aztec/foundation/branded-types';
5
10
  import { randomInt } from '@aztec/foundation/crypto/random';
11
+ import {
12
+ flipSignature,
13
+ generateRecoverableSignature,
14
+ generateUnrecoverableSignature,
15
+ } from '@aztec/foundation/crypto/secp256k1-signer';
6
16
  import { Fr } from '@aztec/foundation/curves/bn254';
7
17
  import { EthAddress } from '@aztec/foundation/eth-address';
8
18
  import { Signature } from '@aztec/foundation/eth-signature';
9
19
  import { filter } from '@aztec/foundation/iterator';
10
- import type { Logger } from '@aztec/foundation/log';
20
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
21
+ import { retryUntil } from '@aztec/foundation/retry';
11
22
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
12
23
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
13
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
24
+ import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
14
25
  import type { P2P } from '@aztec/p2p';
15
26
  import type { SlasherClientInterface } from '@aztec/slasher';
16
27
  import {
@@ -20,18 +31,25 @@ import {
20
31
  type L2BlockSink,
21
32
  type L2BlockSource,
22
33
  MaliciousCommitteeAttestationsAndSigners,
34
+ type ValidateCheckpointResult,
23
35
  } from '@aztec/stdlib/block';
24
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
25
- import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
36
+ import { type Checkpoint, type ProposedCheckpointData, validateCheckpoint } from '@aztec/stdlib/checkpoint';
37
+ import { computeQuorum, getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
26
38
  import { Gas } from '@aztec/stdlib/gas';
27
- import type {
28
- PublicProcessorLimits,
29
- ResolvedSequencerConfig,
30
- WorldStateSynchronizer,
39
+ import {
40
+ type BlockBuilderOptions,
41
+ InsufficientValidTxsError,
42
+ type ResolvedSequencerConfig,
43
+ type WorldStateSynchronizer,
31
44
  } from '@aztec/stdlib/interfaces/server';
32
45
  import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
33
- import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
34
- import { orderAttestations } from '@aztec/stdlib/p2p';
46
+ import type {
47
+ BlockProposal,
48
+ BlockProposalOptions,
49
+ CheckpointProposal,
50
+ CheckpointProposalOptions,
51
+ } from '@aztec/stdlib/p2p';
52
+ import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
35
53
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
36
54
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
37
55
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
@@ -41,6 +59,11 @@ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validato
41
59
 
42
60
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
43
61
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
62
+ import {
63
+ buildPipelinedParentSimulationOverridesPlan,
64
+ buildSubmissionSimulationOverridesPlan,
65
+ } from './chain_state_overrides.js';
66
+ import type { CheckpointProposalJobMetricsRecorder } from './checkpoint_proposal_job_metrics.js';
44
67
  import { CheckpointVoter } from './checkpoint_voter.js';
45
68
  import { SequencerInterruptedError } from './errors.js';
46
69
  import type { SequencerEvents } from './events.js';
@@ -52,6 +75,20 @@ import { SequencerState } from './utils.js';
52
75
  /** How much time to sleep while waiting for min transactions to accumulate for a block */
53
76
  const TXS_POLLING_MS = 500;
54
77
 
78
+ /** Result from proposeCheckpoint when a checkpoint was successfully built and broadcast. */
79
+ type CheckpointProposalBroadcast = {
80
+ checkpoint: Checkpoint;
81
+ proposal: CheckpointProposal;
82
+ blockProposedAt: number;
83
+ };
84
+
85
+ /** Result after attestation collection and signing, ready for L1 submission. */
86
+ type CheckpointProposalResult = {
87
+ checkpoint: Checkpoint;
88
+ attestations: CommitteeAttestationsAndSigners;
89
+ attestationsSignature: Signature;
90
+ };
91
+
55
92
  /**
56
93
  * Handles the execution of a checkpoint proposal after the initial preparation phase.
57
94
  * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
@@ -59,9 +96,18 @@ const TXS_POLLING_MS = 500;
59
96
  * the Sequencer once the check for being the proposer for the slot has succeeded.
60
97
  */
61
98
  export class CheckpointProposalJob implements Traceable {
99
+ protected readonly log: Logger;
100
+
101
+ /** Tracks the fire-and-forget L1 submission promise so it can be awaited during shutdown. */
102
+ private pendingL1Submission: Promise<void> | undefined;
103
+
104
+ /** Pipelined parent chain state used while building and later submitting this checkpoint. */
105
+ private pipelinedParentSimulationOverridesPlan?: SimulationOverridesPlan;
106
+
62
107
  constructor(
63
- private readonly epoch: EpochNumber,
64
- private readonly slot: SlotNumber,
108
+ private readonly slotNow: SlotNumber,
109
+ private readonly targetSlot: SlotNumber,
110
+ private readonly targetEpoch: EpochNumber,
65
111
  private readonly checkpointNumber: CheckpointNumber,
66
112
  private readonly syncedToBlockNumber: BlockNumber,
67
113
  // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
@@ -84,15 +130,31 @@ export class CheckpointProposalJob implements Traceable {
84
130
  private readonly epochCache: EpochCache,
85
131
  private readonly dateProvider: DateProvider,
86
132
  private readonly metrics: SequencerMetrics,
87
- private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
133
+ private readonly checkpointMetrics: CheckpointProposalJobMetricsRecorder,
134
+ protected readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
88
135
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
89
- protected readonly log: Logger,
90
136
  public readonly tracer: Tracer,
91
- ) {}
137
+ bindings?: LoggerBindings,
138
+ private readonly proposedCheckpointData?: ProposedCheckpointData,
139
+ ) {
140
+ this.log = createLogger('sequencer:checkpoint-proposal', {
141
+ ...bindings,
142
+ instanceId: `slot-${this.slotNow}`,
143
+ });
144
+ }
145
+
146
+ /** Awaits the pending L1 submission if one is in progress. Call during shutdown. */
147
+ public async awaitPendingSubmission(): Promise<void> {
148
+ this.log.info('Awaiting pending L1 payload submission');
149
+ await this.pendingL1Submission;
150
+ }
92
151
 
93
152
  /**
94
153
  * Executes the checkpoint proposal job.
95
- * Returns the published checkpoint if successful, undefined otherwise.
154
+ * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
155
+ * Attestation collection, signing, and L1 submission are backgrounded so the
156
+ * work loop can return to IDLE immediately for consecutive slot proposals.
157
+ * Returns the built checkpoint if successful, undefined otherwise.
96
158
  */
97
159
  @trackSpan('CheckpointProposalJob.execute')
98
160
  public async execute(): Promise<Checkpoint | undefined> {
@@ -100,7 +162,7 @@ export class CheckpointProposalJob implements Traceable {
100
162
  // In fisherman mode, we simulate slashing but don't actually publish to L1
101
163
  // These are constant for the whole slot, so we only enqueue them once
102
164
  const votesPromises = new CheckpointVoter(
103
- this.slot,
165
+ this.targetSlot,
104
166
  this.publisher,
105
167
  this.attestorAddress,
106
168
  this.validatorClient,
@@ -111,33 +173,271 @@ export class CheckpointProposalJob implements Traceable {
111
173
  this.log,
112
174
  ).enqueueVotes();
113
175
 
114
- // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
115
- const checkpoint = await this.proposeCheckpoint();
176
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
177
+ // Returns after broadcast — attestation collection is deferred.
178
+ const broadcast = await this.proposeCheckpoint();
116
179
 
117
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
118
- await Promise.all(votesPromises);
119
-
120
- if (checkpoint) {
121
- this.metrics.recordBlockProposalSuccess();
180
+ if (!broadcast) {
181
+ await Promise.all(votesPromises);
182
+ // Still submit votes even without a checkpoint
183
+ if (!this.config.fishermanMode) {
184
+ this.pendingL1Submission = this.publisher.sendRequestsAt(this.dateProvider.nowAsDate()).then(() => {});
185
+ }
186
+ return undefined;
122
187
  }
123
188
 
189
+ const { checkpoint } = broadcast;
190
+ this.metrics.recordCheckpointProposalSuccess();
191
+
124
192
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
125
193
  if (this.config.fishermanMode) {
126
194
  await this.handleCheckpointEndAsFisherman(checkpoint);
127
- return;
195
+ return checkpoint;
128
196
  }
129
197
 
130
- // Then send everything to L1
131
- const l1Response = await this.publisher.sendRequests();
132
- const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
133
- if (proposedAction) {
134
- this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.slot });
135
- const coinbase = checkpoint?.header.coinbase;
136
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
137
- return checkpoint;
138
- } else if (checkpoint) {
139
- this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.slot });
140
- return undefined;
198
+ // Background the attestation signing → L1 pipeline so the work loop is unblocked
199
+ this.pendingL1Submission = this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises);
200
+
201
+ // Return the built checkpoint immediately — the work loop is now unblocked
202
+ return checkpoint;
203
+ }
204
+
205
+ /**
206
+ * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
207
+ * Runs as a fire-and-forget task stored in `pendingL1Submission` so the work loop is unblocked.
208
+ */
209
+ private async waitForAttestationsAndEnqueueSubmissionAsync(
210
+ broadcast: CheckpointProposalBroadcast,
211
+ votesPromises: Promise<unknown>[],
212
+ ): Promise<void> {
213
+ const { checkpoint } = broadcast;
214
+ const isPipelining = this.epochCache.isProposerPipeliningEnabled();
215
+
216
+ try {
217
+ // Wait for all votes actions, enqueued at the beginning, to resolve
218
+ await Promise.all(votesPromises);
219
+
220
+ // Try to collect attestations from the committee
221
+ const signedAttestations = await this.getSignedCommitteeAttestations(broadcast);
222
+
223
+ // If pipelining, wait for the previous checkpoint to land on L1 before submitting,
224
+ // so we can check it matches the proposed checkpoint we used as parent, and has valid attestations.
225
+ if (signedAttestations && (!isPipelining || (await this.waitForValidParentCheckpointOnL1()))) {
226
+ await this.enqueueCheckpointForSubmission({ checkpoint, ...signedAttestations });
227
+ }
228
+
229
+ // If we failed to collect attestations, at least check if we need to issue an invalidation
230
+ // Note that if we are not pipelining, we enqueued the invalidation at the beginning
231
+ if (!signedAttestations && isPipelining && (await this.waitForSyncedL2SlotNumber(this.slotNow))) {
232
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
233
+ if (!validationStatus.valid) {
234
+ this.log.warn(
235
+ `Checkpoint ${validationStatus.checkpoint.checkpointNumber} has invalid attestations, enqueuing invalidation in spite of attestation collection failure`,
236
+ { checkpoint: validationStatus.checkpoint, reason: validationStatus.reason },
237
+ );
238
+ await this.enqueueInvalidation(validationStatus);
239
+ }
240
+ }
241
+
242
+ // Send whatever was enqueued: votes + (propose | invalidation | nothing).
243
+ // Compute the earliest time to submit: pipeline slot start when pipelining, now otherwise.
244
+ const submitAfter = isPipelining
245
+ ? new Date(Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) * 1000)
246
+ : new Date(this.dateProvider.now());
247
+
248
+ const l1Response = await this.publisher.sendRequestsAt(submitAfter);
249
+ const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
250
+ if (proposedAction) {
251
+ this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
252
+ const coinbase = checkpoint.header.coinbase;
253
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
254
+ } else {
255
+ this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
256
+ if (isPipelining) {
257
+ this.metrics.recordPipelineDiscard();
258
+ }
259
+ }
260
+ } catch (err) {
261
+ if (err instanceof SequencerInterruptedError) {
262
+ return;
263
+ }
264
+ this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err);
265
+ this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
266
+ if (isPipelining) {
267
+ this.metrics.recordPipelineDiscard();
268
+ }
269
+ }
270
+ }
271
+
272
+ /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */
273
+ private async enqueueCheckpointForSubmission(result: CheckpointProposalResult): Promise<void> {
274
+ const { checkpoint, attestations, attestationsSignature } = result;
275
+
276
+ this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.targetSlot);
277
+ const aztecSlotDuration = this.l1Constants.slotDuration;
278
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
279
+ const txTimeoutAt = new Date((submissionSlotStart + aztecSlotDuration) * 1000);
280
+
281
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
282
+ if (
283
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
284
+ this.config.skipPublishingCheckpointsPercent > 0
285
+ ) {
286
+ const roll = Math.max(0, randomInt(100));
287
+ if (roll < this.config.skipPublishingCheckpointsPercent) {
288
+ this.log.warn(
289
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${roll}`,
290
+ );
291
+ return;
292
+ }
293
+ }
294
+
295
+ const isPipelining = this.epochCache.isProposerPipeliningEnabled();
296
+ const submissionSimulationOverridesPlan = buildSubmissionSimulationOverridesPlan({
297
+ pipelinedParentPlan: this.pipelinedParentSimulationOverridesPlan,
298
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
299
+ lastArchiveRoot: checkpoint.header.lastArchiveRoot,
300
+ pipeliningEnabled: isPipelining,
301
+ });
302
+
303
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
304
+ txTimeoutAt,
305
+ ...(submissionSimulationOverridesPlan ? { simulationOverridesPlan: submissionSimulationOverridesPlan } : {}),
306
+ });
307
+ }
308
+
309
+ /**
310
+ * Wait until the archiver syncs past the given L2 slot number.
311
+ * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
312
+ * L1 submission window and is no longer useful.
313
+ */
314
+ private async waitForSyncedL2SlotNumber(waitForSlot: SlotNumber): Promise<boolean> {
315
+ const targetSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
316
+ const targetSlotEndMs = (targetSlotStart + this.l1Constants.slotDuration) * 1000;
317
+ const syncDelayTolerance = this.l1Constants.ethereumSlotDuration * 2 * 1000;
318
+ const timeoutSeconds = Math.max(0.1, (targetSlotEndMs + syncDelayTolerance - this.dateProvider.now()) / 1000);
319
+
320
+ try {
321
+ return await retryUntil(
322
+ async () => {
323
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
324
+ return syncedSlot !== undefined && syncedSlot >= waitForSlot;
325
+ },
326
+ `archiver sync past slot ${waitForSlot}`,
327
+ timeoutSeconds,
328
+ 0.2,
329
+ );
330
+ } catch {
331
+ this.log.warn(
332
+ `Archiver did not sync L1 past slot ${waitForSlot} before slot ${this.targetSlot} expired, discarding pipelined work`,
333
+ { checkpointNumber: this.checkpointNumber },
334
+ );
335
+ this.emitPipelinedCheckpointDiscarded('archiver-sync-timeout');
336
+ return false;
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Waits for the parent checkpoint to land on L1 before submitting a pipelined checkpoint.
342
+ * Polls until the archiver has synced L1 past the parent's slot, then verifies:
343
+ * - If we built on a proposed parent: it must have landed on L1 with matching hash and valid attestations.
344
+ * - If we built without a proposed parent: no new checkpoint must have appeared for that slot.
345
+ * If the parent has invalid attestations, enqueues an invalidation. Returns whether to proceed with the proposal.
346
+ */
347
+ protected async waitForValidParentCheckpointOnL1(): Promise<boolean> {
348
+ const parentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 1);
349
+
350
+ // Wait until archiver has synced L1 past the parent's slot (slotNow)
351
+ if (!(await this.waitForSyncedL2SlotNumber(this.slotNow))) {
352
+ return false;
353
+ }
354
+
355
+ const tips = await this.l2BlockSource.getL2Tips();
356
+ const checkpointedNumber = tips.checkpointed.checkpoint.number;
357
+
358
+ // We built on top of a proposed checkpoint. Verify it landed on L1 as expected.
359
+ if (this.proposedCheckpointData) {
360
+ // After syncing from L1 we see the chain tip has invalid attestations. This means the parent checkpoint was posted
361
+ // with invalid attestations, or it built on top of something with invalid attestations and didnt invalidate them.
362
+ // Either way, we thought our parent would be valid, so we have to throw away our work. But at least we'll try and
363
+ // invalidate on L1 so we clean up the chain for the next proposer. And we'll slash them, but that's handled elsewhere.
364
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
365
+ if (!validationStatus.valid) {
366
+ this.log.warn(
367
+ `Parent checkpoint ${parentCheckpointNumber} has invalid attestations, discarding pipelined work`,
368
+ { checkpointNumber: this.checkpointNumber, reason: validationStatus.reason },
369
+ );
370
+ this.emitPipelinedCheckpointDiscarded('parent-invalid-attestations');
371
+ await this.enqueueInvalidation(validationStatus);
372
+ return false;
373
+ }
374
+
375
+ // The pending chain is valid. But did the parent checkpoint land on L1 at all?
376
+ if (checkpointedNumber < parentCheckpointNumber) {
377
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} did not land on L1, discarding pipelined work`, {
378
+ checkpointNumber: this.checkpointNumber,
379
+ checkpointedNumber,
380
+ });
381
+ this.emitPipelinedCheckpointDiscarded('parent-not-on-l1');
382
+ return false;
383
+ }
384
+
385
+ // It landed. But is it the one we were expecting?
386
+ const expectedHash = this.proposedCheckpointData.header.hash().toString();
387
+ if (tips.checkpointed.checkpoint.hash !== expectedHash) {
388
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} hash mismatch on L1, discarding pipelined work`, {
389
+ checkpointNumber: this.checkpointNumber,
390
+ expectedHash,
391
+ actualHash: tips.checkpointed.checkpoint.hash,
392
+ });
393
+ this.emitPipelinedCheckpointDiscarded('parent-hash-mismatch');
394
+ return false;
395
+ }
396
+
397
+ return true;
398
+ } else {
399
+ // We didn't see a proposed checkpoint at build time, so we built on checkpointed parent from two slots ago.
400
+ // But if a new checkpoint for the previous slot appeared on L1 in the meantime, our checkpoint assumed the wrong parent,
401
+ // so we have to discard our work. This can happen if we're somehow cut off from p2p and fail to see the checkpoint
402
+ // proposal for the previous slot.
403
+ if (checkpointedNumber > parentCheckpointNumber) {
404
+ this.log.warn(
405
+ `Unexpected checkpoint ${checkpointedNumber} landed on L1 after we built on top of parent ${parentCheckpointNumber}, discarding pipelined work`,
406
+ { checkpointNumber: this.checkpointNumber, checkpointedNumber },
407
+ );
408
+ this.emitPipelinedCheckpointDiscarded('unexpected-parent-appeared');
409
+ return false;
410
+ }
411
+
412
+ return true;
413
+ }
414
+ }
415
+
416
+ /** Emits the pipelined-checkpoint-discarded event and records the metric. */
417
+ private emitPipelinedCheckpointDiscarded(reason: string): void {
418
+ this.metrics.recordPipelineParentCheckpointMismatch(reason);
419
+ this.eventEmitter.emit('pipelined-checkpoint-discarded', {
420
+ slot: this.targetSlot,
421
+ checkpointNumber: this.checkpointNumber,
422
+ reason,
423
+ });
424
+ }
425
+
426
+ /** Simulates and enqueues an invalidation request for the invalid parent checkpoint. */
427
+ private async enqueueInvalidation(validationStatus: ValidateCheckpointResult): Promise<void> {
428
+ if (this.config.skipInvalidateBlockAsProposer) {
429
+ this.log.warn(`Skipping checkpoint invalidation as proposer due to test configuration`);
430
+ return;
431
+ }
432
+ const invalidateRequest = await this.publisher.simulateInvalidateCheckpoint(validationStatus);
433
+ if (invalidateRequest) {
434
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
435
+ const txTimeoutAt = new Date((submissionSlotStart + this.l1Constants.slotDuration) * 1000);
436
+ this.publisher.enqueueInvalidateCheckpoint(invalidateRequest, { txTimeoutAt });
437
+ } else {
438
+ this.log.info(`Invalidation simulation returned undefined, checkpoint may have been removed already`, {
439
+ checkpointNumber: this.checkpointNumber,
440
+ });
141
441
  }
142
442
  }
143
443
 
@@ -145,29 +445,59 @@ export class CheckpointProposalJob implements Traceable {
145
445
  return {
146
446
  // nullish operator needed for tests
147
447
  [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
148
- [Attributes.SLOT_NUMBER]: this.slot,
448
+ [Attributes.SLOT_NUMBER]: this.targetSlot,
149
449
  };
150
450
  })
151
- private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
451
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
152
452
  try {
453
+ const now = this.dateProvider.now();
454
+ if (this.epochCache.isProposerPipeliningEnabled() && this.proposedCheckpointData) {
455
+ // Measure against the wall-clock slot whose build window we are currently using.
456
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
457
+ // target-slot boundary a full slot away from the actual build start time.
458
+ const slotBoundaryMs = Number(getTimestampForSlot(this.slotNow, this.l1Constants)) * 1000;
459
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
460
+ }
461
+ this.checkpointMetrics.startCheckpointTiming(now);
462
+
153
463
  // Get operator configured coinbase and fee recipient for this attestor
154
464
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
155
465
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
156
466
 
157
467
  // Start the checkpoint
158
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
159
- this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
468
+ this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
469
+ this.log.info(`Starting checkpoint proposal`, {
470
+ buildSlot: this.slotNow,
471
+ submissionSlot: this.targetSlot,
472
+ pipelining: this.epochCache.isProposerPipeliningEnabled(),
473
+ proposer: this.proposer?.toString(),
474
+ coinbase: coinbase.toString(),
475
+ });
476
+ this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
160
477
 
161
478
  // Enqueues checkpoint invalidation (constant for the whole slot)
162
479
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
163
480
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
164
481
  }
165
482
 
166
- // Create checkpoint builder for the slot
483
+ // Create checkpoint builder for the slot.
484
+ // When pipelining, force the proposed checkpoint number and fee header to our parent so the
485
+ // fee computation sees the same chain tip that L1 will see once the previous pipelined checkpoint lands.
486
+ const isPipelining = this.epochCache.isProposerPipeliningEnabled();
487
+ this.pipelinedParentSimulationOverridesPlan = isPipelining
488
+ ? await buildPipelinedParentSimulationOverridesPlan({
489
+ checkpointNumber: this.checkpointNumber,
490
+ proposedCheckpointData: this.proposedCheckpointData,
491
+ rollup: this.publisher.rollupContract,
492
+ log: this.log,
493
+ })
494
+ : undefined;
495
+
167
496
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
168
497
  coinbase,
169
498
  feeRecipient,
170
- this.slot,
499
+ this.targetSlot,
500
+ this.pipelinedParentSimulationOverridesPlan,
171
501
  );
172
502
 
173
503
  // Collect L1 to L2 messages for the checkpoint and compute their hash
@@ -175,21 +505,25 @@ export class CheckpointProposalJob implements Traceable {
175
505
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
176
506
 
177
507
  // Collect the out hashes of all the checkpoints before this one in the same epoch
178
- const previousCheckpoints = (await this.l2BlockSource.getCheckpointsForEpoch(this.epoch)).filter(
179
- c => c.number < this.checkpointNumber,
180
- );
181
- const previousCheckpointOutHashes = previousCheckpoints.map(c => c.getCheckpointOutHash());
508
+ const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.targetEpoch))
509
+ .filter(c => c.checkpointNumber < this.checkpointNumber)
510
+ .map(c => c.checkpointOutHash);
511
+
512
+ // Get the fee asset price modifier from the oracle
513
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
182
514
 
183
515
  // Create a long-lived forked world state for the checkpoint builder
184
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
516
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
185
517
 
186
518
  // Create checkpoint builder for the entire slot
187
519
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
188
520
  this.checkpointNumber,
189
521
  checkpointGlobalVariables,
522
+ feeAssetPriceModifier,
190
523
  l1ToL2Messages,
191
524
  previousCheckpointOutHashes,
192
525
  fork,
526
+ this.log.getBindings(),
193
527
  );
194
528
 
195
529
  // Options for the validator client when creating block and checkpoint proposals
@@ -204,7 +538,8 @@ export class CheckpointProposalJob implements Traceable {
204
538
  };
205
539
 
206
540
  let blocksInCheckpoint: L2Block[] = [];
207
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
541
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
542
+ const checkpointBuildTimer = new Timer();
208
543
 
209
544
  try {
210
545
  // Main loop: build blocks for the checkpoint
@@ -220,124 +555,97 @@ export class CheckpointProposalJob implements Traceable {
220
555
  // These errors are expected in HA mode, so we yield and let another HA node handle the slot
221
556
  // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
222
557
  // which is normal for block building (may have picked different txs)
223
- if (err instanceof DutyAlreadySignedError) {
224
- this.log.info(`Checkpoint proposal for slot ${this.slot} already signed by another HA node, yielding`, {
225
- slot: this.slot,
226
- signedByNode: err.signedByNode,
227
- });
228
- return undefined;
229
- }
230
- if (err instanceof SlashingProtectionError) {
231
- this.log.info(`Checkpoint proposal for slot ${this.slot} blocked by slashing protection, yielding`, {
232
- slot: this.slot,
233
- existingMessageHash: err.existingMessageHash,
234
- attemptedMessageHash: err.attemptedMessageHash,
235
- });
558
+ if (this.handleHASigningError(err, 'Block proposal')) {
236
559
  return undefined;
237
560
  }
238
561
  throw err;
239
562
  }
240
563
 
241
564
  if (blocksInCheckpoint.length === 0) {
242
- this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
243
- this.eventEmitter.emit('checkpoint-empty', { slot: this.slot });
565
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, { slot: this.targetSlot });
566
+ this.eventEmitter.emit('checkpoint-empty', { slot: this.targetSlot });
567
+ return undefined;
568
+ }
569
+
570
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
571
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
572
+ this.log.warn(
573
+ `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
574
+ { slot: this.targetSlot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
575
+ );
244
576
  return undefined;
245
577
  }
246
578
 
247
579
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
248
580
  // broadcasted yet, and wait to collect the committee attestations.
249
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
581
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
250
582
  const checkpoint = await checkpointBuilder.completeCheckpoint();
251
583
 
252
- // Do not collect attestations nor publish to L1 in fisherman mode
584
+ // Final validation: per-block limits are only checked if the operator set them explicitly.
585
+ // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
586
+ try {
587
+ validateCheckpoint(checkpoint, {
588
+ rollupManaLimit: this.l1Constants.rollupManaLimit,
589
+ maxL2BlockGas: this.config.maxL2BlockGas,
590
+ maxDABlockGas: this.config.maxDABlockGas,
591
+ maxTxsPerBlock: this.config.maxTxsPerBlock,
592
+ maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
593
+ });
594
+ } catch (err) {
595
+ this.log.error(`Built an invalid checkpoint at slot ${this.slotNow} (skipping proposal)`, err, {
596
+ checkpoint: checkpoint.header.toInspect(),
597
+ });
598
+ return undefined;
599
+ }
600
+
601
+ // Record checkpoint-level build metrics
602
+ this.checkpointMetrics.recordCheckpointBuild(
603
+ checkpointBuildTimer.ms(),
604
+ blocksInCheckpoint.length,
605
+ checkpoint.getStats().txCount,
606
+ Number(checkpoint.header.totalManaUsed.toBigInt()),
607
+ );
608
+
609
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
253
610
  if (this.config.fishermanMode) {
254
611
  this.log.info(
255
- `Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` +
612
+ `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
256
613
  `Skipping proposal in fisherman mode.`,
257
614
  {
258
- slot: this.slot,
615
+ slot: this.targetSlot,
259
616
  checkpoint: checkpoint.header.toInspect(),
260
617
  blocksBuilt: blocksInCheckpoint.length,
261
618
  },
262
619
  );
263
620
  this.metrics.recordCheckpointSuccess();
264
- return checkpoint;
621
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
622
+ return { checkpoint, proposal: undefined!, blockProposedAt: this.dateProvider.now() };
265
623
  }
266
624
 
267
- // Include the block pending broadcast in the checkpoint proposal if any
268
- const lastBlock = blockPendingBroadcast && {
269
- blockHeader: blockPendingBroadcast.block.header,
270
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
271
- txs: blockPendingBroadcast.txs,
272
- };
273
-
274
625
  // Create the checkpoint proposal and broadcast it
275
626
  const proposal = await this.validatorClient.createCheckpointProposal(
276
627
  checkpoint.header,
277
628
  checkpoint.archive.root,
278
- lastBlock,
629
+ this.checkpointNumber,
630
+ feeAssetPriceModifier,
631
+ blockPendingBroadcast,
279
632
  this.proposer,
280
633
  checkpointProposalOptions,
281
634
  );
282
635
 
283
636
  const blockProposedAt = this.dateProvider.now();
284
637
  await this.p2pClient.broadcastCheckpointProposal(proposal);
638
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
285
639
 
286
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
287
- const attestations = await this.waitForAttestations(proposal);
288
- const blockAttestedAt = this.dateProvider.now();
289
-
290
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
291
-
292
- // Proposer must sign over the attestations before pushing them to L1
293
- const signer = this.proposer ?? this.publisher.getSenderAddress();
294
- let attestationsSignature: Signature;
295
- try {
296
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
297
- attestations,
298
- signer,
299
- this.slot,
300
- this.checkpointNumber,
301
- );
302
- } catch (err) {
303
- // We shouldn't really get here since we yield to another HA node
304
- // as soon as we see these errors when creating block proposals.
305
- if (err instanceof DutyAlreadySignedError) {
306
- this.log.info(`Attestations signature for slot ${this.slot} already signed by another HA node, yielding`, {
307
- slot: this.slot,
308
- signedByNode: err.signedByNode,
309
- });
310
- return undefined;
311
- }
312
- if (err instanceof SlashingProtectionError) {
313
- this.log.info(`Attestations signature for slot ${this.slot} blocked by slashing protection, yielding`, {
314
- slot: this.slot,
315
- existingMessageHash: err.existingMessageHash,
316
- attemptedMessageHash: err.attemptedMessageHash,
317
- });
318
- return undefined;
319
- }
320
- throw err;
321
- }
322
-
323
- // Enqueue publishing the checkpoint to L1
324
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
325
- const aztecSlotDuration = this.l1Constants.slotDuration;
326
- const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
327
- const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
328
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
329
- txTimeoutAt,
330
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
331
- });
332
-
333
- return checkpoint;
640
+ // Return immediately after broadcast — attestation collection happens in the background
641
+ return { checkpoint, proposal, blockProposedAt };
334
642
  } catch (err) {
335
643
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
336
644
  // swallow this error. It's already been logged by a function deeper in the stack
337
645
  return undefined;
338
646
  }
339
647
 
340
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
648
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
341
649
  return undefined;
342
650
  }
343
651
  }
@@ -353,21 +661,18 @@ export class CheckpointProposalJob implements Traceable {
353
661
  blockProposalOptions: BlockProposalOptions,
354
662
  ): Promise<{
355
663
  blocksInCheckpoint: L2Block[];
356
- blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
664
+ blockPendingBroadcast: BlockProposal | undefined;
357
665
  }> {
358
666
  const blocksInCheckpoint: L2Block[] = [];
359
667
  const txHashesAlreadyIncluded = new Set<string>();
360
668
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
361
669
 
362
- // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
363
- let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
364
-
365
670
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
366
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
671
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
367
672
 
368
673
  while (true) {
369
674
  const blocksBuilt = blocksInCheckpoint.length;
370
- const indexWithinCheckpoint = blocksBuilt;
675
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
371
676
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
372
677
 
373
678
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -375,7 +680,7 @@ export class CheckpointProposalJob implements Traceable {
375
680
 
376
681
  if (!timingInfo.canStart) {
377
682
  this.log.debug(`Not enough time left in slot to start another block`, {
378
- slot: this.slot,
683
+ slot: this.targetSlot,
379
684
  blocksBuilt,
380
685
  secondsIntoSlot,
381
686
  });
@@ -394,24 +699,25 @@ export class CheckpointProposalJob implements Traceable {
394
699
  blockNumber,
395
700
  indexWithinCheckpoint,
396
701
  txHashesAlreadyIncluded,
397
- remainingBlobFields,
398
702
  });
399
703
 
400
- if (!buildResult && timingInfo.isLastBlock) {
401
- // If no block was produced due to not enough txs and this was the last subslot, exit
402
- break;
403
- } else if (!buildResult && timingInfo.deadline !== undefined) {
404
- // But if there is still time for more blocks, wait until the next subslot and try again
704
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
705
+ if ('failure' in buildResult) {
706
+ // If this was the last subslot, or we're running with a single block per slot, we're done
707
+ if (timingInfo.isLastBlock || timingInfo.deadline === undefined) {
708
+ break;
709
+ }
710
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
405
711
  await this.waitUntilNextSubslot(timingInfo.deadline);
406
712
  continue;
407
- } else if (!buildResult) {
408
- // Exit if there is no possibility of building more blocks
409
- break;
410
- } else if ('error' in buildResult) {
411
- // If there was an error building the block, just exit the loop and give up the rest of the slot
713
+ }
714
+
715
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
716
+ // We don't want to risk building more blocks if something went wrong.
717
+ if ('error' in buildResult) {
412
718
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
413
- this.log.warn(`Halting block building for slot ${this.slot}`, {
414
- slot: this.slot,
719
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
720
+ slot: this.targetSlot,
415
721
  blocksBuilt,
416
722
  error: buildResult.error,
417
723
  });
@@ -419,210 +725,262 @@ export class CheckpointProposalJob implements Traceable {
419
725
  break;
420
726
  }
421
727
 
422
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
728
+ const { block, usedTxs } = buildResult;
729
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
730
+ isFirstBlock: blocksBuilt === 0,
731
+ isLastBlock: timingInfo.isLastBlock,
732
+ });
733
+
423
734
  blocksInCheckpoint.push(block);
735
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
424
736
 
425
- // Update remaining blob fields for the next block
426
- remainingBlobFields = newRemainingBlobFields;
737
+ // Sign the block proposal. This will throw if HA signing fails.
738
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, blockProposalOptions);
427
739
 
428
- // Sync the proposed block to the archiver to make it available
429
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
430
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
431
- // Fire and forget - don't block the critical path, but log errors
432
- this.syncProposedBlockToArchiver(block).catch(err => {
433
- this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
434
- });
740
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
741
+ // so we avoid polluting our archive with a block that would fail.
742
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
743
+ // If this throws, we abort the entire checkpoint.
744
+ await this.syncProposedBlockToArchiver(block);
435
745
 
436
- // If this is the last block, exit the loop now so we start collecting attestations
746
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
437
747
  if (timingInfo.isLastBlock) {
438
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
439
- slot: this.slot,
748
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
749
+ slot: this.targetSlot,
440
750
  blockNumber,
441
751
  blocksBuilt,
442
752
  });
443
- blockPendingBroadcast = { block, txs: usedTxs };
753
+
754
+ blockPendingBroadcast = proposal;
444
755
  break;
445
756
  }
446
757
 
447
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
448
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
449
- if (!this.config.fishermanMode) {
450
- const proposal = await this.validatorClient.createBlockProposal(
451
- block.header,
452
- block.indexWithinCheckpoint,
453
- inHash,
454
- block.archive.root,
455
- usedTxs,
456
- this.proposer,
457
- blockProposalOptions,
458
- );
459
- await this.p2pClient.broadcastProposal(proposal);
460
- }
758
+ // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
759
+ proposal && (await this.p2pClient.broadcastProposal(proposal));
461
760
 
462
761
  // Wait until the next block's start time
463
762
  await this.waitUntilNextSubslot(timingInfo.deadline);
464
763
  }
465
764
 
466
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
467
- slot: this.slot,
765
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
766
+ slot: this.targetSlot,
468
767
  blocksBuilt: blocksInCheckpoint.length,
469
768
  });
470
769
 
471
770
  return { blocksInCheckpoint, blockPendingBroadcast };
472
771
  }
473
772
 
773
+ /** Creates a block proposal for a given block via the validator client (unless in fisherman mode) */
774
+ private createBlockProposal(
775
+ block: L2Block,
776
+ inHash: Fr,
777
+ usedTxs: Tx[],
778
+ blockProposalOptions: BlockProposalOptions,
779
+ ): Promise<BlockProposal | undefined> {
780
+ if (this.config.fishermanMode) {
781
+ this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
782
+ return Promise.resolve(undefined);
783
+ }
784
+ return this.validatorClient.createBlockProposal(
785
+ block.header,
786
+ this.checkpointNumber,
787
+ block.indexWithinCheckpoint,
788
+ inHash,
789
+ block.archive.root,
790
+ usedTxs,
791
+ this.proposer,
792
+ blockProposalOptions,
793
+ );
794
+ }
795
+
474
796
  /** Sleeps until it is time to produce the next block in the slot */
475
797
  @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
476
798
  private async waitUntilNextSubslot(nextSubslotStart: number) {
477
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
478
- this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
799
+ this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
800
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
801
+ slot: this.targetSlot,
802
+ });
479
803
  await this.waitUntilTimeInSlot(nextSubslotStart);
480
804
  }
481
805
 
482
806
  /** Builds a single block. Called from the main block building loop. */
483
807
  @trackSpan('CheckpointProposalJob.buildSingleBlock')
484
- private async buildSingleBlock(
808
+ protected async buildSingleBlock(
485
809
  checkpointBuilder: CheckpointBuilder,
486
810
  opts: {
487
811
  forceCreate?: boolean;
488
812
  blockTimestamp: bigint;
489
813
  blockNumber: BlockNumber;
490
- indexWithinCheckpoint: number;
814
+ indexWithinCheckpoint: IndexWithinCheckpoint;
491
815
  buildDeadline: Date | undefined;
492
816
  txHashesAlreadyIncluded: Set<string>;
493
- remainingBlobFields: number;
494
817
  },
495
- ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
496
- const {
497
- blockTimestamp,
498
- forceCreate,
499
- blockNumber,
500
- indexWithinCheckpoint,
501
- buildDeadline,
502
- txHashesAlreadyIncluded,
503
- remainingBlobFields,
504
- } = opts;
818
+ ): Promise<
819
+ { block: L2Block; usedTxs: Tx[] } | { failure: 'insufficient-txs' | 'insufficient-valid-txs' } | { error: Error }
820
+ > {
821
+ const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
822
+ opts;
505
823
 
506
824
  this.log.verbose(
507
- `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
825
+ `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot}`,
508
826
  { ...checkpointBuilder.getConstantData(), ...opts },
509
827
  );
510
828
 
511
829
  try {
512
830
  // Wait until we have enough txs to build the block
513
- const minTxs = this.config.minTxsPerBlock;
514
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
831
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
515
832
  if (!canStartBuilding) {
516
833
  this.log.warn(
517
- `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
518
- { blockNumber, slot: this.slot, indexWithinCheckpoint },
834
+ `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (got ${availableTxs} txs but needs ${minTxs})`,
835
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
519
836
  );
520
- this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.slot });
837
+ this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.targetSlot });
521
838
  this.metrics.recordBlockProposalFailed('insufficient_txs');
522
- return undefined;
839
+ return { failure: 'insufficient-txs' };
523
840
  }
524
841
 
525
842
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
526
843
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
527
844
  const pendingTxs = filter(
528
- this.p2pClient.iteratePendingTxs(),
845
+ this.p2pClient.iterateEligiblePendingTxs(),
529
846
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
530
847
  );
531
848
 
532
849
  this.log.debug(
533
- `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
534
- { slot: this.slot, blockNumber, indexWithinCheckpoint },
850
+ `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`,
851
+ { slot: this.targetSlot, blockNumber, indexWithinCheckpoint },
535
852
  );
536
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
853
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
537
854
 
538
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
539
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
540
- const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
541
-
542
- const blockBuilderOptions: PublicProcessorLimits = {
855
+ // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
856
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
857
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
858
+ const minValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
859
+ const blockBuilderOptions: BlockBuilderOptions = {
543
860
  maxTransactions: this.config.maxTxsPerBlock,
544
- maxBlockSize: this.config.maxBlockSizeInBytes,
545
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
546
- maxBlobFields: maxBlobFieldsForTxs,
861
+ maxBlockGas:
862
+ this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined
863
+ ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity)
864
+ : undefined,
547
865
  deadline: buildDeadline,
866
+ isBuildingProposal: true,
867
+ minValidTxs,
868
+ maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
869
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
548
870
  };
549
871
 
550
- // Actually build the block by executing txs
551
- const workTimer = new Timer();
552
- const {
553
- publicGas,
554
- block,
555
- publicProcessorDuration,
556
- numTxs,
557
- blockBuildingTimer,
558
- usedTxs,
559
- failedTxs,
560
- usedTxBlobFields,
561
- } = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
562
- const blockBuildDuration = workTimer.ms();
872
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
873
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
874
+ // updated for blocks that will be discarded.
875
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
876
+ checkpointBuilder,
877
+ pendingTxs,
878
+ blockNumber,
879
+ blockTimestamp,
880
+ blockBuilderOptions,
881
+ );
563
882
 
564
883
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
565
- await this.dropFailedTxsFromP2P(failedTxs);
884
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
566
885
 
567
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
568
- // too long, then we may not get to minTxsPerBlock after executing public functions.
569
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
570
- if (!forceCreate && numTxs < minValidTxs) {
886
+ if (buildResult.status === 'insufficient-valid-txs') {
571
887
  this.log.warn(
572
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
573
- { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint },
888
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`,
889
+ {
890
+ slot: this.targetSlot,
891
+ blockNumber,
892
+ numTxs: buildResult.processedCount,
893
+ indexWithinCheckpoint,
894
+ minValidTxs,
895
+ },
574
896
  );
575
- this.eventEmitter.emit('block-tx-count-check-failed', {
576
- minTxs: minValidTxs,
577
- availableTxs: numTxs,
578
- slot: this.slot,
897
+ this.eventEmitter.emit('block-build-failed', {
898
+ reason: `Insufficient valid txs`,
899
+ slot: this.targetSlot,
579
900
  });
580
901
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
581
- return undefined;
902
+ return { failure: 'insufficient-valid-txs' };
582
903
  }
583
904
 
584
905
  // Block creation succeeded, emit stats and metrics
906
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
907
+
585
908
  const blockStats = {
586
909
  eventName: 'l2-block-built',
587
910
  duration: blockBuildDuration,
588
911
  publicProcessDuration: publicProcessorDuration,
589
- rollupCircuitsDuration: blockBuildingTimer.ms(),
590
912
  ...block.getStats(),
591
913
  } satisfies L2BlockBuiltStats;
592
914
 
593
915
  const blockHash = await block.hash();
594
916
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
595
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
917
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
596
918
 
597
919
  this.log.info(
598
- `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`,
920
+ `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot} with ${numTxs} txs`,
599
921
  { blockHash, txHashes, manaPerSec, ...blockStats },
600
922
  );
601
923
 
602
- this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
603
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
924
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
925
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
926
+ this.eventEmitter.emit('block-proposed', {
927
+ blockNumber: block.number,
928
+ slot: this.targetSlot,
929
+ buildSlot: this.slotNow,
930
+ });
931
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
604
932
 
605
- return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
933
+ return { block, usedTxs };
606
934
  } catch (err: any) {
607
- this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
608
- this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
935
+ this.eventEmitter.emit('block-build-failed', {
936
+ reason: err.message,
937
+ slot: this.targetSlot,
938
+ });
939
+ this.log.error(`Error building block`, err, { blockNumber, slot: this.targetSlot });
609
940
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
610
941
  this.metrics.recordFailedBlock();
611
942
  return { error: err };
612
943
  }
613
944
  }
614
945
 
946
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
947
+ private async buildSingleBlockWithCheckpointBuilder(
948
+ checkpointBuilder: CheckpointBuilder,
949
+ pendingTxs: AsyncIterable<Tx>,
950
+ blockNumber: BlockNumber,
951
+ blockTimestamp: bigint,
952
+ blockBuilderOptions: BlockBuilderOptions,
953
+ ) {
954
+ try {
955
+ const workTimer = new Timer();
956
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
957
+ const blockBuildDuration = workTimer.ms();
958
+ return { ...result, blockBuildDuration, status: 'success' as const };
959
+ } catch (err: unknown) {
960
+ if (isErrorClass(err, InsufficientValidTxsError)) {
961
+ return {
962
+ failedTxs: err.failedTxs,
963
+ processedCount: err.processedCount,
964
+ status: 'insufficient-valid-txs' as const,
965
+ };
966
+ }
967
+ throw err;
968
+ }
969
+ }
970
+
615
971
  /** Waits until minTxs are available on the pool for building a block. */
616
972
  @trackSpan('CheckpointProposalJob.waitForMinTxs')
617
973
  private async waitForMinTxs(opts: {
618
974
  forceCreate?: boolean;
619
975
  blockNumber: BlockNumber;
620
- indexWithinCheckpoint: number;
976
+ indexWithinCheckpoint: IndexWithinCheckpoint;
621
977
  buildDeadline: Date | undefined;
622
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
623
- const minTxs = this.config.minTxsPerBlock;
978
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
624
979
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
625
980
 
981
+ // We only allow a block with 0 txs in the first block of the checkpoint
982
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
983
+
626
984
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
627
985
  const startBuildingDeadline = buildDeadline
628
986
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -634,20 +992,50 @@ export class CheckpointProposalJob implements Traceable {
634
992
  // If we're past deadline, or we have no deadline, give up
635
993
  const now = this.dateProvider.nowAsDate();
636
994
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
637
- return { canStartBuilding: false, availableTxs: availableTxs };
995
+ return { canStartBuilding: false, availableTxs, minTxs };
638
996
  }
639
997
 
640
998
  // Wait a bit before checking again
641
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
999
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
642
1000
  this.log.verbose(
643
- `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
644
- { blockNumber, slot: this.slot, indexWithinCheckpoint },
1001
+ `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`,
1002
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
645
1003
  );
646
- await sleep(TXS_POLLING_MS);
1004
+ await this.waitForTxsPollingInterval();
647
1005
  availableTxs = await this.p2pClient.getPendingTxCount();
648
1006
  }
649
1007
 
650
- return { canStartBuilding: true, availableTxs };
1008
+ return { canStartBuilding: true, availableTxs, minTxs };
1009
+ }
1010
+
1011
+ private async getSignedCommitteeAttestations(
1012
+ broadcast: CheckpointProposalBroadcast,
1013
+ ): Promise<{ attestations: CommitteeAttestationsAndSigners; attestationsSignature: Signature } | undefined> {
1014
+ const { proposal, blockProposedAt } = broadcast;
1015
+ this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.targetSlot);
1016
+ const attestations = await this.waitForAttestations(proposal);
1017
+ if (!attestations) {
1018
+ return undefined;
1019
+ }
1020
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
1021
+
1022
+ // Proposer must sign over the attestations before pushing them to L1
1023
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1024
+ try {
1025
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
1026
+ attestations,
1027
+ signer,
1028
+ this.targetSlot,
1029
+ this.checkpointNumber,
1030
+ );
1031
+ return { attestations, attestationsSignature };
1032
+ } catch (err) {
1033
+ if (this.handleHASigningError(err, 'Attestations signature')) {
1034
+ return;
1035
+ }
1036
+ this.log.error(`Error signing attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1037
+ return undefined;
1038
+ }
651
1039
  }
652
1040
 
653
1041
  /**
@@ -655,7 +1043,9 @@ export class CheckpointProposalJob implements Traceable {
655
1043
  * This is run after all blocks for the checkpoint have been built.
656
1044
  */
657
1045
  @trackSpan('CheckpointProposalJob.waitForAttestations')
658
- private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
1046
+ private async waitForAttestations(
1047
+ proposal: CheckpointProposal,
1048
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
659
1049
  if (this.config.fishermanMode) {
660
1050
  this.log.debug('Skipping attestation collection in fisherman mode');
661
1051
  return CommitteeAttestationsAndSigners.empty();
@@ -673,18 +1063,18 @@ export class CheckpointProposalJob implements Traceable {
673
1063
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
674
1064
  }
675
1065
 
676
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
1066
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
677
1067
 
678
1068
  if (this.config.skipCollectingAttestations) {
679
1069
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
680
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
1070
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
681
1071
  return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
682
1072
  }
683
1073
 
684
1074
  const attestationTimeAllowed = this.config.enforceTimeTable
685
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
1075
+ ? this.timetable.getCheckpointAttestationDeadline()
686
1076
  : this.l1Constants.slotDuration;
687
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
1077
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
688
1078
 
689
1079
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
690
1080
 
@@ -695,15 +1085,33 @@ export class CheckpointProposalJob implements Traceable {
695
1085
  proposal,
696
1086
  numberOfRequiredAttestations,
697
1087
  attestationDeadline,
1088
+ this.checkpointNumber,
698
1089
  );
699
1090
 
700
1091
  collectedAttestationsCount = attestations.length;
701
1092
 
1093
+ // Trim attestations to minimum required to save L1 calldata gas
1094
+ const localAddresses = this.validatorClient.getValidatorAddresses();
1095
+ const trimmed = trimAttestations(
1096
+ attestations,
1097
+ numberOfRequiredAttestations,
1098
+ this.attestorAddress,
1099
+ localAddresses,
1100
+ );
1101
+ if (trimmed.length < attestations.length) {
1102
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
1103
+ }
1104
+
702
1105
  // Rollup contract requires that the signatures are provided in the order of the committee
703
- const sorted = orderAttestations(attestations, committee);
1106
+ const sorted = orderAttestations(trimmed, committee);
704
1107
 
705
1108
  // Manipulate the attestations if we've been configured to do so
706
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
1109
+ if (
1110
+ this.config.injectFakeAttestation ||
1111
+ this.config.injectHighSValueAttestation ||
1112
+ this.config.injectUnrecoverableSignatureAttestation ||
1113
+ this.config.shuffleAttestationOrdering
1114
+ ) {
707
1115
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
708
1116
  }
709
1117
 
@@ -711,8 +1119,14 @@ export class CheckpointProposalJob implements Traceable {
711
1119
  } catch (err) {
712
1120
  if (err && err instanceof AttestationTimeoutError) {
713
1121
  collectedAttestationsCount = err.collectedCount;
1122
+ this.log.error(
1123
+ `Timeout while waiting for attestations for checkpoint proposal at slot ${proposal.slotNumber} (collected ${collectedAttestationsCount}/${numberOfRequiredAttestations})`,
1124
+ err,
1125
+ );
1126
+ } else {
1127
+ this.log.error(`Error collecting attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
714
1128
  }
715
- throw err;
1129
+ return undefined;
716
1130
  } finally {
717
1131
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
718
1132
  }
@@ -732,7 +1146,11 @@ export class CheckpointProposalJob implements Traceable {
732
1146
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
733
1147
  );
734
1148
 
735
- if (this.config.injectFakeAttestation) {
1149
+ if (
1150
+ this.config.injectFakeAttestation ||
1151
+ this.config.injectHighSValueAttestation ||
1152
+ this.config.injectUnrecoverableSignatureAttestation
1153
+ ) {
736
1154
  // Find non-empty attestations that are not from the proposer
737
1155
  const nonProposerIndices: number[] = [];
738
1156
  for (let i = 0; i < attestations.length; i++) {
@@ -742,8 +1160,20 @@ export class CheckpointProposalJob implements Traceable {
742
1160
  }
743
1161
  if (nonProposerIndices.length > 0) {
744
1162
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
745
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
746
- unfreeze(attestations[targetIndex]).signature = Signature.random();
1163
+ if (this.config.injectHighSValueAttestation) {
1164
+ this.log.warn(
1165
+ `Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
1166
+ );
1167
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
1168
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
1169
+ this.log.warn(
1170
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
1171
+ );
1172
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
1173
+ } else {
1174
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1175
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
1176
+ }
747
1177
  }
748
1178
  return new CommitteeAttestationsAndSigners(attestations);
749
1179
  }
@@ -752,11 +1182,20 @@ export class CheckpointProposalJob implements Traceable {
752
1182
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
753
1183
 
754
1184
  const shuffled = [...attestations];
755
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
756
- const valueI = shuffled[i];
757
- const valueJ = shuffled[j];
758
- shuffled[i] = valueJ;
759
- shuffled[j] = valueI;
1185
+
1186
+ // Find two non-proposer positions that both have non-empty signatures to swap.
1187
+ // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
1188
+ // signers array stays correctly aligned with L1's committee reconstruction.
1189
+ const swappable: number[] = [];
1190
+ for (let k = 0; k < shuffled.length; k++) {
1191
+ if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
1192
+ swappable.push(k);
1193
+ }
1194
+ }
1195
+ if (swappable.length >= 2) {
1196
+ const [i, j] = [swappable[0], swappable[1]];
1197
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
1198
+ }
760
1199
 
761
1200
  const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
762
1201
  return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
@@ -772,16 +1211,20 @@ export class CheckpointProposalJob implements Traceable {
772
1211
  const failedTxData = failedTxs.map(fail => fail.tx);
773
1212
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
774
1213
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
775
- await this.p2pClient.deleteTxs(failedTxHashes);
1214
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
776
1215
  }
777
1216
 
778
1217
  /**
779
1218
  * Adds the proposed block to the archiver so it's available via P2P.
780
1219
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
781
1220
  * would never receive its own block without this explicit sync.
1221
+ *
1222
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1223
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1224
+ * whenever the real proposer's block arrives from L1.
782
1225
  */
783
1226
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
784
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1227
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
785
1228
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
786
1229
  blockNumber: block.number,
787
1230
  slot: block.header.globalVariables.slotNumber,
@@ -799,27 +1242,49 @@ export class CheckpointProposalJob implements Traceable {
799
1242
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
800
1243
  // Perform L1 fee analysis before clearing requests
801
1244
  // The callback is invoked asynchronously after the next block is mined
802
- const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
1245
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, analysis =>
803
1246
  this.metrics.recordFishermanFeeAnalysis(analysis),
804
1247
  );
805
1248
 
806
1249
  if (checkpoint) {
807
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1250
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
808
1251
  ...checkpoint.toCheckpointInfo(),
809
1252
  ...checkpoint.getStats(),
810
1253
  feeAnalysisId: feeAnalysis?.id,
811
1254
  });
812
1255
  } else {
813
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
814
- slot: this.slot,
1256
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1257
+ slot: this.targetSlot,
815
1258
  feeAnalysisId: feeAnalysis?.id,
816
1259
  });
817
- this.metrics.recordBlockProposalFailed('block_build_failed');
1260
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
818
1261
  }
819
1262
 
820
1263
  this.publisher.clearPendingRequests();
821
1264
  }
822
1265
 
1266
+ /**
1267
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
1268
+ */
1269
+ private handleHASigningError(err: any, errorContext: string): boolean {
1270
+ if (err instanceof DutyAlreadySignedError) {
1271
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1272
+ slot: this.targetSlot,
1273
+ signedByNode: err.signedByNode,
1274
+ });
1275
+ return true;
1276
+ }
1277
+ if (err instanceof SlashingProtectionError) {
1278
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1279
+ slot: this.targetSlot,
1280
+ existingMessageHash: err.existingMessageHash,
1281
+ attemptedMessageHash: err.attemptedMessageHash,
1282
+ });
1283
+ return true;
1284
+ }
1285
+ return false;
1286
+ }
1287
+
823
1288
  /** Waits until a specific time within the current slot */
824
1289
  @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
825
1290
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
@@ -828,8 +1293,13 @@ export class CheckpointProposalJob implements Traceable {
828
1293
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
829
1294
  }
830
1295
 
1296
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
1297
+ protected async waitForTxsPollingInterval(): Promise<void> {
1298
+ await sleep(TXS_POLLING_MS);
1299
+ }
1300
+
831
1301
  private getSlotStartBuildTimestamp(): number {
832
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1302
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
833
1303
  }
834
1304
 
835
1305
  private getSecondsIntoSlot(): number {