@aztec/sequencer-client 0.0.1-commit.0b941701 → 0.0.1-commit.0dc957cde

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 +580 -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 +12 -12
  73. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  74. package/dest/test/mock_checkpoint_builder.js +45 -36
  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 -280
  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 +65 -53
  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();
116
-
117
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
118
- await Promise.all(votesPromises);
176
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
177
+ // Returns after broadcast — attestation collection is deferred.
178
+ const broadcast = await this.proposeCheckpoint();
119
179
 
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,212 +725,262 @@ export class CheckpointProposalJob implements Traceable {
419
725
  break;
420
726
  }
421
727
 
422
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
423
- blocksInCheckpoint.push(block);
424
-
425
- // Update remaining blob fields for the next block
426
- remainingBlobFields = newRemainingBlobFields;
427
-
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 });
728
+ const { block, usedTxs } = buildResult;
729
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
730
+ isFirstBlock: blocksBuilt === 0,
731
+ isLastBlock: timingInfo.isLastBlock,
434
732
  });
435
733
 
734
+ blocksInCheckpoint.push(block);
436
735
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
437
736
 
438
- // If this is the last block, exit the loop now so we start collecting attestations
737
+ // Sign the block proposal. This will throw if HA signing fails.
738
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, blockProposalOptions);
739
+
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);
745
+
746
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
439
747
  if (timingInfo.isLastBlock) {
440
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
441
- slot: this.slot,
748
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
749
+ slot: this.targetSlot,
442
750
  blockNumber,
443
751
  blocksBuilt,
444
752
  });
445
- blockPendingBroadcast = { block, txs: usedTxs };
753
+
754
+ blockPendingBroadcast = proposal;
446
755
  break;
447
756
  }
448
757
 
449
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
450
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
451
- if (!this.config.fishermanMode) {
452
- const proposal = await this.validatorClient.createBlockProposal(
453
- block.header,
454
- block.indexWithinCheckpoint,
455
- inHash,
456
- block.archive.root,
457
- usedTxs,
458
- this.proposer,
459
- blockProposalOptions,
460
- );
461
- await this.p2pClient.broadcastProposal(proposal);
462
- }
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));
463
760
 
464
761
  // Wait until the next block's start time
465
762
  await this.waitUntilNextSubslot(timingInfo.deadline);
466
763
  }
467
764
 
468
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
469
- slot: this.slot,
765
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
766
+ slot: this.targetSlot,
470
767
  blocksBuilt: blocksInCheckpoint.length,
471
768
  });
472
769
 
473
770
  return { blocksInCheckpoint, blockPendingBroadcast };
474
771
  }
475
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
+
476
796
  /** Sleeps until it is time to produce the next block in the slot */
477
797
  @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
478
798
  private async waitUntilNextSubslot(nextSubslotStart: number) {
479
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
480
- 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
+ });
481
803
  await this.waitUntilTimeInSlot(nextSubslotStart);
482
804
  }
483
805
 
484
806
  /** Builds a single block. Called from the main block building loop. */
485
807
  @trackSpan('CheckpointProposalJob.buildSingleBlock')
486
- private async buildSingleBlock(
808
+ protected async buildSingleBlock(
487
809
  checkpointBuilder: CheckpointBuilder,
488
810
  opts: {
489
811
  forceCreate?: boolean;
490
812
  blockTimestamp: bigint;
491
813
  blockNumber: BlockNumber;
492
- indexWithinCheckpoint: number;
814
+ indexWithinCheckpoint: IndexWithinCheckpoint;
493
815
  buildDeadline: Date | undefined;
494
816
  txHashesAlreadyIncluded: Set<string>;
495
- remainingBlobFields: number;
496
817
  },
497
- ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
498
- const {
499
- blockTimestamp,
500
- forceCreate,
501
- blockNumber,
502
- indexWithinCheckpoint,
503
- buildDeadline,
504
- txHashesAlreadyIncluded,
505
- remainingBlobFields,
506
- } = 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;
507
823
 
508
824
  this.log.verbose(
509
- `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}`,
510
826
  { ...checkpointBuilder.getConstantData(), ...opts },
511
827
  );
512
828
 
513
829
  try {
514
830
  // Wait until we have enough txs to build the block
515
- const minTxs = this.config.minTxsPerBlock;
516
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
831
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
517
832
  if (!canStartBuilding) {
518
833
  this.log.warn(
519
- `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
520
- { 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 },
521
836
  );
522
- 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 });
523
838
  this.metrics.recordBlockProposalFailed('insufficient_txs');
524
- return undefined;
839
+ return { failure: 'insufficient-txs' };
525
840
  }
526
841
 
527
842
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
528
843
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
529
844
  const pendingTxs = filter(
530
- this.p2pClient.iteratePendingTxs(),
845
+ this.p2pClient.iterateEligiblePendingTxs(),
531
846
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
532
847
  );
533
848
 
534
849
  this.log.debug(
535
- `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
536
- { 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 },
537
852
  );
538
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
539
-
540
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
541
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
542
- const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
853
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
543
854
 
544
- 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 = {
545
860
  maxTransactions: this.config.maxTxsPerBlock,
546
- maxBlockSize: this.config.maxBlockSizeInBytes,
547
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
548
- 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,
549
865
  deadline: buildDeadline,
866
+ isBuildingProposal: true,
867
+ minValidTxs,
868
+ maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
869
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
550
870
  };
551
871
 
552
- // Actually build the block by executing txs
553
- const workTimer = new Timer();
554
- const {
555
- publicGas,
556
- block,
557
- publicProcessorDuration,
558
- numTxs,
559
- blockBuildingTimer,
560
- usedTxs,
561
- failedTxs,
562
- usedTxBlobFields,
563
- } = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
564
- 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
+ );
565
882
 
566
883
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
567
- await this.dropFailedTxsFromP2P(failedTxs);
884
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
568
885
 
569
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
570
- // too long, then we may not get to minTxsPerBlock after executing public functions.
571
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
572
- if (!forceCreate && numTxs < minValidTxs) {
886
+ if (buildResult.status === 'insufficient-valid-txs') {
573
887
  this.log.warn(
574
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
575
- { 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
+ },
576
896
  );
577
- this.eventEmitter.emit('block-tx-count-check-failed', {
578
- minTxs: minValidTxs,
579
- availableTxs: numTxs,
580
- slot: this.slot,
897
+ this.eventEmitter.emit('block-build-failed', {
898
+ reason: `Insufficient valid txs`,
899
+ slot: this.targetSlot,
581
900
  });
582
901
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
583
- return undefined;
902
+ return { failure: 'insufficient-valid-txs' };
584
903
  }
585
904
 
586
905
  // Block creation succeeded, emit stats and metrics
906
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
907
+
587
908
  const blockStats = {
588
909
  eventName: 'l2-block-built',
589
910
  duration: blockBuildDuration,
590
911
  publicProcessDuration: publicProcessorDuration,
591
- rollupCircuitsDuration: blockBuildingTimer.ms(),
592
912
  ...block.getStats(),
593
913
  } satisfies L2BlockBuiltStats;
594
914
 
595
915
  const blockHash = await block.hash();
596
916
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
597
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
917
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
598
918
 
599
919
  this.log.info(
600
- `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`,
601
921
  { blockHash, txHashes, manaPerSec, ...blockStats },
602
922
  );
603
923
 
604
- this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
605
- 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);
606
932
 
607
- return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
933
+ return { block, usedTxs };
608
934
  } catch (err: any) {
609
- this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
610
- 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 });
611
940
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
612
941
  this.metrics.recordFailedBlock();
613
942
  return { error: err };
614
943
  }
615
944
  }
616
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
+
617
971
  /** Waits until minTxs are available on the pool for building a block. */
618
972
  @trackSpan('CheckpointProposalJob.waitForMinTxs')
619
973
  private async waitForMinTxs(opts: {
620
974
  forceCreate?: boolean;
621
975
  blockNumber: BlockNumber;
622
- indexWithinCheckpoint: number;
976
+ indexWithinCheckpoint: IndexWithinCheckpoint;
623
977
  buildDeadline: Date | undefined;
624
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
625
- const minTxs = this.config.minTxsPerBlock;
978
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
626
979
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
627
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
+
628
984
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
629
985
  const startBuildingDeadline = buildDeadline
630
986
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -636,20 +992,50 @@ export class CheckpointProposalJob implements Traceable {
636
992
  // If we're past deadline, or we have no deadline, give up
637
993
  const now = this.dateProvider.nowAsDate();
638
994
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
639
- return { canStartBuilding: false, availableTxs: availableTxs };
995
+ return { canStartBuilding: false, availableTxs, minTxs };
640
996
  }
641
997
 
642
998
  // Wait a bit before checking again
643
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
999
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
644
1000
  this.log.verbose(
645
- `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
646
- { 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 },
647
1003
  );
648
- await sleep(TXS_POLLING_MS);
1004
+ await this.waitForTxsPollingInterval();
649
1005
  availableTxs = await this.p2pClient.getPendingTxCount();
650
1006
  }
651
1007
 
652
- 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
+ }
653
1039
  }
654
1040
 
655
1041
  /**
@@ -657,7 +1043,9 @@ export class CheckpointProposalJob implements Traceable {
657
1043
  * This is run after all blocks for the checkpoint have been built.
658
1044
  */
659
1045
  @trackSpan('CheckpointProposalJob.waitForAttestations')
660
- private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
1046
+ private async waitForAttestations(
1047
+ proposal: CheckpointProposal,
1048
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
661
1049
  if (this.config.fishermanMode) {
662
1050
  this.log.debug('Skipping attestation collection in fisherman mode');
663
1051
  return CommitteeAttestationsAndSigners.empty();
@@ -675,18 +1063,18 @@ export class CheckpointProposalJob implements Traceable {
675
1063
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
676
1064
  }
677
1065
 
678
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
1066
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
679
1067
 
680
1068
  if (this.config.skipCollectingAttestations) {
681
1069
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
682
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
1070
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
683
1071
  return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
684
1072
  }
685
1073
 
686
1074
  const attestationTimeAllowed = this.config.enforceTimeTable
687
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
1075
+ ? this.timetable.getCheckpointAttestationDeadline()
688
1076
  : this.l1Constants.slotDuration;
689
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
1077
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
690
1078
 
691
1079
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
692
1080
 
@@ -697,15 +1085,33 @@ export class CheckpointProposalJob implements Traceable {
697
1085
  proposal,
698
1086
  numberOfRequiredAttestations,
699
1087
  attestationDeadline,
1088
+ this.checkpointNumber,
700
1089
  );
701
1090
 
702
1091
  collectedAttestationsCount = attestations.length;
703
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
+
704
1105
  // Rollup contract requires that the signatures are provided in the order of the committee
705
- const sorted = orderAttestations(attestations, committee);
1106
+ const sorted = orderAttestations(trimmed, committee);
706
1107
 
707
1108
  // Manipulate the attestations if we've been configured to do so
708
- 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
+ ) {
709
1115
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
710
1116
  }
711
1117
 
@@ -713,8 +1119,14 @@ export class CheckpointProposalJob implements Traceable {
713
1119
  } catch (err) {
714
1120
  if (err && err instanceof AttestationTimeoutError) {
715
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);
716
1128
  }
717
- throw err;
1129
+ return undefined;
718
1130
  } finally {
719
1131
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
720
1132
  }
@@ -734,7 +1146,11 @@ export class CheckpointProposalJob implements Traceable {
734
1146
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
735
1147
  );
736
1148
 
737
- if (this.config.injectFakeAttestation) {
1149
+ if (
1150
+ this.config.injectFakeAttestation ||
1151
+ this.config.injectHighSValueAttestation ||
1152
+ this.config.injectUnrecoverableSignatureAttestation
1153
+ ) {
738
1154
  // Find non-empty attestations that are not from the proposer
739
1155
  const nonProposerIndices: number[] = [];
740
1156
  for (let i = 0; i < attestations.length; i++) {
@@ -744,8 +1160,20 @@ export class CheckpointProposalJob implements Traceable {
744
1160
  }
745
1161
  if (nonProposerIndices.length > 0) {
746
1162
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
747
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
748
- 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
+ }
749
1177
  }
750
1178
  return new CommitteeAttestationsAndSigners(attestations);
751
1179
  }
@@ -754,11 +1182,20 @@ export class CheckpointProposalJob implements Traceable {
754
1182
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
755
1183
 
756
1184
  const shuffled = [...attestations];
757
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
758
- const valueI = shuffled[i];
759
- const valueJ = shuffled[j];
760
- shuffled[i] = valueJ;
761
- 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
+ }
762
1199
 
763
1200
  const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
764
1201
  return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
@@ -774,16 +1211,20 @@ export class CheckpointProposalJob implements Traceable {
774
1211
  const failedTxData = failedTxs.map(fail => fail.tx);
775
1212
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
776
1213
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
777
- await this.p2pClient.deleteTxs(failedTxHashes);
1214
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
778
1215
  }
779
1216
 
780
1217
  /**
781
1218
  * Adds the proposed block to the archiver so it's available via P2P.
782
1219
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
783
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.
784
1225
  */
785
1226
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
786
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1227
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
787
1228
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
788
1229
  blockNumber: block.number,
789
1230
  slot: block.header.globalVariables.slotNumber,
@@ -801,27 +1242,49 @@ export class CheckpointProposalJob implements Traceable {
801
1242
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
802
1243
  // Perform L1 fee analysis before clearing requests
803
1244
  // The callback is invoked asynchronously after the next block is mined
804
- const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
1245
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, analysis =>
805
1246
  this.metrics.recordFishermanFeeAnalysis(analysis),
806
1247
  );
807
1248
 
808
1249
  if (checkpoint) {
809
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1250
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
810
1251
  ...checkpoint.toCheckpointInfo(),
811
1252
  ...checkpoint.getStats(),
812
1253
  feeAnalysisId: feeAnalysis?.id,
813
1254
  });
814
1255
  } else {
815
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
816
- slot: this.slot,
1256
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1257
+ slot: this.targetSlot,
817
1258
  feeAnalysisId: feeAnalysis?.id,
818
1259
  });
819
- this.metrics.recordBlockProposalFailed('block_build_failed');
1260
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
820
1261
  }
821
1262
 
822
1263
  this.publisher.clearPendingRequests();
823
1264
  }
824
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
+
825
1288
  /** Waits until a specific time within the current slot */
826
1289
  @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
827
1290
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
@@ -830,8 +1293,13 @@ export class CheckpointProposalJob implements Traceable {
830
1293
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
831
1294
  }
832
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
+
833
1301
  private getSlotStartBuildTimestamp(): number {
834
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1302
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
835
1303
  }
836
1304
 
837
1305
  private getSecondsIntoSlot(): number {