@aztec/sequencer-client 0.0.1-commit.9d2bcf6d → 0.0.1-commit.9ebd450e8

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 (103) 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.d.ts +75 -48
  40. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  41. package/dest/publisher/sequencer-publisher.js +432 -139
  42. package/dest/sequencer/chain_state_overrides.d.ts +25 -0
  43. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  44. package/dest/sequencer/chain_state_overrides.js +39 -0
  45. package/dest/sequencer/checkpoint_proposal_job.d.ts +42 -10
  46. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  47. package/dest/sequencer/checkpoint_proposal_job.js +531 -216
  48. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  49. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  50. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  51. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  52. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  53. package/dest/sequencer/checkpoint_voter.js +2 -5
  54. package/dest/sequencer/events.d.ts +7 -1
  55. package/dest/sequencer/events.d.ts.map +1 -1
  56. package/dest/sequencer/metrics.d.ts +21 -8
  57. package/dest/sequencer/metrics.d.ts.map +1 -1
  58. package/dest/sequencer/metrics.js +110 -21
  59. package/dest/sequencer/sequencer.d.ts +43 -17
  60. package/dest/sequencer/sequencer.d.ts.map +1 -1
  61. package/dest/sequencer/sequencer.js +158 -96
  62. package/dest/sequencer/timetable.d.ts +17 -6
  63. package/dest/sequencer/timetable.d.ts.map +1 -1
  64. package/dest/sequencer/timetable.js +51 -46
  65. package/dest/sequencer/types.d.ts +2 -2
  66. package/dest/sequencer/types.d.ts.map +1 -1
  67. package/dest/test/index.d.ts +3 -5
  68. package/dest/test/index.d.ts.map +1 -1
  69. package/dest/test/mock_checkpoint_builder.d.ts +11 -11
  70. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  71. package/dest/test/mock_checkpoint_builder.js +45 -34
  72. package/dest/test/utils.d.ts +3 -3
  73. package/dest/test/utils.d.ts.map +1 -1
  74. package/dest/test/utils.js +5 -4
  75. package/package.json +27 -28
  76. package/src/client/sequencer-client.ts +81 -30
  77. package/src/config.ts +70 -46
  78. package/src/global_variable_builder/README.md +44 -0
  79. package/src/global_variable_builder/fee_predictor.ts +172 -0
  80. package/src/global_variable_builder/fee_provider.ts +75 -0
  81. package/src/global_variable_builder/global_builder.ts +27 -63
  82. package/src/global_variable_builder/index.ts +3 -1
  83. package/src/publisher/config.ts +157 -45
  84. package/src/publisher/index.ts +3 -0
  85. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  86. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  87. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  88. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  89. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  90. package/src/publisher/sequencer-publisher.ts +499 -198
  91. package/src/sequencer/README.md +83 -13
  92. package/src/sequencer/chain_state_overrides.ts +87 -0
  93. package/src/sequencer/checkpoint_proposal_job.ts +678 -237
  94. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  95. package/src/sequencer/checkpoint_voter.ts +1 -12
  96. package/src/sequencer/events.ts +6 -1
  97. package/src/sequencer/metrics.ts +124 -26
  98. package/src/sequencer/sequencer.ts +227 -108
  99. package/src/sequencer/timetable.ts +70 -57
  100. package/src/sequencer/types.ts +1 -1
  101. package/src/test/index.ts +2 -4
  102. package/src/test/mock_checkpoint_builder.ts +63 -49
  103. package/src/test/utils.ts +5 -2
@@ -1,6 +1,5 @@
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';
2
+ import type { SimulationOverridesPlan } from '@aztec/ethereum/contracts';
4
3
  import {
5
4
  BlockNumber,
6
5
  CheckpointNumber,
@@ -9,11 +8,17 @@ import {
9
8
  SlotNumber,
10
9
  } from '@aztec/foundation/branded-types';
11
10
  import { randomInt } from '@aztec/foundation/crypto/random';
11
+ import {
12
+ flipSignature,
13
+ generateRecoverableSignature,
14
+ generateUnrecoverableSignature,
15
+ } from '@aztec/foundation/crypto/secp256k1-signer';
12
16
  import { Fr } from '@aztec/foundation/curves/bn254';
13
17
  import { EthAddress } from '@aztec/foundation/eth-address';
14
18
  import { Signature } from '@aztec/foundation/eth-signature';
15
19
  import { filter } from '@aztec/foundation/iterator';
16
20
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
21
+ import { retryUntil } from '@aztec/foundation/retry';
17
22
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
18
23
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
19
24
  import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
@@ -26,19 +31,25 @@ import {
26
31
  type L2BlockSink,
27
32
  type L2BlockSource,
28
33
  MaliciousCommitteeAttestationsAndSigners,
34
+ type ValidateCheckpointResult,
29
35
  } from '@aztec/stdlib/block';
30
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
31
- 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';
32
38
  import { Gas } from '@aztec/stdlib/gas';
33
39
  import {
34
- NoValidTxsError,
35
- type PublicProcessorLimits,
40
+ type BlockBuilderOptions,
41
+ InsufficientValidTxsError,
36
42
  type ResolvedSequencerConfig,
37
43
  type WorldStateSynchronizer,
38
44
  } from '@aztec/stdlib/interfaces/server';
39
45
  import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
40
- import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
41
- 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';
42
53
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
43
54
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
44
55
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
@@ -48,6 +59,11 @@ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validato
48
59
 
49
60
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
50
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';
51
67
  import { CheckpointVoter } from './checkpoint_voter.js';
52
68
  import { SequencerInterruptedError } from './errors.js';
53
69
  import type { SequencerEvents } from './events.js';
@@ -59,6 +75,20 @@ import { SequencerState } from './utils.js';
59
75
  /** How much time to sleep while waiting for min transactions to accumulate for a block */
60
76
  const TXS_POLLING_MS = 500;
61
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
+
62
92
  /**
63
93
  * Handles the execution of a checkpoint proposal after the initial preparation phase.
64
94
  * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
@@ -68,9 +98,16 @@ const TXS_POLLING_MS = 500;
68
98
  export class CheckpointProposalJob implements Traceable {
69
99
  protected readonly log: Logger;
70
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
+
71
107
  constructor(
72
- private readonly epoch: EpochNumber,
73
- private readonly slot: SlotNumber,
108
+ private readonly slotNow: SlotNumber,
109
+ private readonly targetSlot: SlotNumber,
110
+ private readonly targetEpoch: EpochNumber,
74
111
  private readonly checkpointNumber: CheckpointNumber,
75
112
  private readonly syncedToBlockNumber: BlockNumber,
76
113
  // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
@@ -93,17 +130,31 @@ export class CheckpointProposalJob implements Traceable {
93
130
  private readonly epochCache: EpochCache,
94
131
  private readonly dateProvider: DateProvider,
95
132
  private readonly metrics: SequencerMetrics,
96
- private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
133
+ private readonly checkpointMetrics: CheckpointProposalJobMetricsRecorder,
134
+ protected readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
97
135
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
98
136
  public readonly tracer: Tracer,
99
137
  bindings?: LoggerBindings,
138
+ private readonly proposedCheckpointData?: ProposedCheckpointData,
100
139
  ) {
101
- this.log = createLogger('sequencer:checkpoint-proposal', { ...bindings, instanceId: `slot-${slot}` });
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;
102
150
  }
103
151
 
104
152
  /**
105
153
  * Executes the checkpoint proposal job.
106
- * 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.
107
158
  */
108
159
  @trackSpan('CheckpointProposalJob.execute')
109
160
  public async execute(): Promise<Checkpoint | undefined> {
@@ -111,7 +162,7 @@ export class CheckpointProposalJob implements Traceable {
111
162
  // In fisherman mode, we simulate slashing but don't actually publish to L1
112
163
  // These are constant for the whole slot, so we only enqueue them once
113
164
  const votesPromises = new CheckpointVoter(
114
- this.slot,
165
+ this.targetSlot,
115
166
  this.publisher,
116
167
  this.attestorAddress,
117
168
  this.validatorClient,
@@ -122,33 +173,271 @@ export class CheckpointProposalJob implements Traceable {
122
173
  this.log,
123
174
  ).enqueueVotes();
124
175
 
125
- // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
126
- 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();
127
179
 
128
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
129
- await Promise.all(votesPromises);
130
-
131
- if (checkpoint) {
132
- 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;
133
187
  }
134
188
 
189
+ const { checkpoint } = broadcast;
190
+ this.metrics.recordCheckpointProposalSuccess();
191
+
135
192
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
136
193
  if (this.config.fishermanMode) {
137
194
  await this.handleCheckpointEndAsFisherman(checkpoint);
138
- return;
195
+ return checkpoint;
139
196
  }
140
197
 
141
- // Then send everything to L1
142
- const l1Response = await this.publisher.sendRequests();
143
- const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
144
- if (proposedAction) {
145
- this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.slot });
146
- const coinbase = checkpoint?.header.coinbase;
147
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
148
- return checkpoint;
149
- } else if (checkpoint) {
150
- this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.slot });
151
- 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
+ });
152
441
  }
153
442
  }
154
443
 
@@ -156,29 +445,59 @@ export class CheckpointProposalJob implements Traceable {
156
445
  return {
157
446
  // nullish operator needed for tests
158
447
  [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
159
- [Attributes.SLOT_NUMBER]: this.slot,
448
+ [Attributes.SLOT_NUMBER]: this.targetSlot,
160
449
  };
161
450
  })
162
- private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
451
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
163
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
+
164
463
  // Get operator configured coinbase and fee recipient for this attestor
165
464
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
166
465
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
167
466
 
168
467
  // Start the checkpoint
169
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
170
- 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');
171
477
 
172
478
  // Enqueues checkpoint invalidation (constant for the whole slot)
173
479
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
174
480
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
175
481
  }
176
482
 
177
- // 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
+
178
496
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
179
497
  coinbase,
180
498
  feeRecipient,
181
- this.slot,
499
+ this.targetSlot,
500
+ this.pipelinedParentSimulationOverridesPlan,
182
501
  );
183
502
 
184
503
  // Collect L1 to L2 messages for the checkpoint and compute their hash
@@ -186,18 +505,21 @@ export class CheckpointProposalJob implements Traceable {
186
505
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
187
506
 
188
507
  // Collect the out hashes of all the checkpoints before this one in the same epoch
189
- const previousCheckpoints = (await this.l2BlockSource.getCheckpointsForEpoch(this.epoch)).filter(
190
- c => c.number < this.checkpointNumber,
191
- );
192
- 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();
193
514
 
194
515
  // Create a long-lived forked world state for the checkpoint builder
195
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
516
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
196
517
 
197
518
  // Create checkpoint builder for the entire slot
198
519
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
199
520
  this.checkpointNumber,
200
521
  checkpointGlobalVariables,
522
+ feeAssetPriceModifier,
201
523
  l1ToL2Messages,
202
524
  previousCheckpointOutHashes,
203
525
  fork,
@@ -216,7 +538,8 @@ export class CheckpointProposalJob implements Traceable {
216
538
  };
217
539
 
218
540
  let blocksInCheckpoint: L2Block[] = [];
219
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
541
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
542
+ const checkpointBuildTimer = new Timer();
220
543
 
221
544
  try {
222
545
  // Main loop: build blocks for the checkpoint
@@ -239,93 +562,90 @@ export class CheckpointProposalJob implements Traceable {
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 or checkpoint proposals.
305
- if (this.handleHASigningError(err, 'Attestations signature')) {
306
- return undefined;
307
- }
308
- throw err;
309
- }
310
-
311
- // Enqueue publishing the checkpoint to L1
312
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
313
- const aztecSlotDuration = this.l1Constants.slotDuration;
314
- const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
315
- const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
316
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
317
- txTimeoutAt,
318
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
319
- });
320
-
321
- return checkpoint;
640
+ // Return immediately after broadcast — attestation collection happens in the background
641
+ return { checkpoint, proposal, blockProposedAt };
322
642
  } catch (err) {
323
643
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
324
644
  // swallow this error. It's already been logged by a function deeper in the stack
325
645
  return undefined;
326
646
  }
327
647
 
328
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
648
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
329
649
  return undefined;
330
650
  }
331
651
  }
@@ -341,17 +661,14 @@ export class CheckpointProposalJob implements Traceable {
341
661
  blockProposalOptions: BlockProposalOptions,
342
662
  ): Promise<{
343
663
  blocksInCheckpoint: L2Block[];
344
- blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
664
+ blockPendingBroadcast: BlockProposal | undefined;
345
665
  }> {
346
666
  const blocksInCheckpoint: L2Block[] = [];
347
667
  const txHashesAlreadyIncluded = new Set<string>();
348
668
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
349
669
 
350
- // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
351
- let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
352
-
353
670
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
354
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
671
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
355
672
 
356
673
  while (true) {
357
674
  const blocksBuilt = blocksInCheckpoint.length;
@@ -363,7 +680,7 @@ export class CheckpointProposalJob implements Traceable {
363
680
 
364
681
  if (!timingInfo.canStart) {
365
682
  this.log.debug(`Not enough time left in slot to start another block`, {
366
- slot: this.slot,
683
+ slot: this.targetSlot,
367
684
  blocksBuilt,
368
685
  secondsIntoSlot,
369
686
  });
@@ -382,25 +699,25 @@ export class CheckpointProposalJob implements Traceable {
382
699
  blockNumber,
383
700
  indexWithinCheckpoint,
384
701
  txHashesAlreadyIncluded,
385
- remainingBlobFields,
386
702
  });
387
703
 
388
- // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
389
- if (!buildResult && timingInfo.isLastBlock) {
390
- // If no block was produced due to not enough txs and this was the last subslot, exit
391
- break;
392
- } else if (!buildResult && timingInfo.deadline !== undefined) {
393
- // 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
394
711
  await this.waitUntilNextSubslot(timingInfo.deadline);
395
712
  continue;
396
- } else if (!buildResult) {
397
- // Exit if there is no possibility of building more blocks
398
- break;
399
- } else if ('error' in buildResult) {
400
- // 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) {
401
718
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
402
- this.log.warn(`Halting block building for slot ${this.slot}`, {
403
- slot: this.slot,
719
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
720
+ slot: this.targetSlot,
404
721
  blocksBuilt,
405
722
  error: buildResult.error,
406
723
  });
@@ -408,65 +725,81 @@ export class CheckpointProposalJob implements Traceable {
408
725
  break;
409
726
  }
410
727
 
411
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
412
- blocksInCheckpoint.push(block);
413
-
414
- // Update remaining blob fields for the next block
415
- remainingBlobFields = newRemainingBlobFields;
416
-
417
- // Sync the proposed block to the archiver to make it available
418
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
419
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
420
- // Fire and forget - don't block the critical path, but log errors
421
- this.syncProposedBlockToArchiver(block).catch(err => {
422
- 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,
423
732
  });
424
733
 
734
+ blocksInCheckpoint.push(block);
425
735
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
426
736
 
427
- // 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.
428
747
  if (timingInfo.isLastBlock) {
429
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
430
- slot: this.slot,
748
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
749
+ slot: this.targetSlot,
431
750
  blockNumber,
432
751
  blocksBuilt,
433
752
  });
434
- blockPendingBroadcast = { block, txs: usedTxs };
753
+
754
+ blockPendingBroadcast = proposal;
435
755
  break;
436
756
  }
437
757
 
438
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
439
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
440
- if (!this.config.fishermanMode) {
441
- const proposal = await this.validatorClient.createBlockProposal(
442
- block.header,
443
- block.indexWithinCheckpoint,
444
- inHash,
445
- block.archive.root,
446
- usedTxs,
447
- this.proposer,
448
- blockProposalOptions,
449
- );
450
- await this.p2pClient.broadcastProposal(proposal);
451
- }
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));
452
760
 
453
761
  // Wait until the next block's start time
454
762
  await this.waitUntilNextSubslot(timingInfo.deadline);
455
763
  }
456
764
 
457
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
458
- slot: this.slot,
765
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
766
+ slot: this.targetSlot,
459
767
  blocksBuilt: blocksInCheckpoint.length,
460
768
  });
461
769
 
462
770
  return { blocksInCheckpoint, blockPendingBroadcast };
463
771
  }
464
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
+
465
796
  /** Sleeps until it is time to produce the next block in the slot */
466
797
  @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
467
798
  private async waitUntilNextSubslot(nextSubslotStart: number) {
468
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
469
- 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
+ });
470
803
  await this.waitUntilTimeInSlot(nextSubslotStart);
471
804
  }
472
805
 
@@ -481,64 +814,64 @@ export class CheckpointProposalJob implements Traceable {
481
814
  indexWithinCheckpoint: IndexWithinCheckpoint;
482
815
  buildDeadline: Date | undefined;
483
816
  txHashesAlreadyIncluded: Set<string>;
484
- remainingBlobFields: number;
485
817
  },
486
- ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
487
- const {
488
- blockTimestamp,
489
- forceCreate,
490
- blockNumber,
491
- indexWithinCheckpoint,
492
- buildDeadline,
493
- txHashesAlreadyIncluded,
494
- remainingBlobFields,
495
- } = 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;
496
823
 
497
824
  this.log.verbose(
498
- `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}`,
499
826
  { ...checkpointBuilder.getConstantData(), ...opts },
500
827
  );
501
828
 
502
829
  try {
503
830
  // Wait until we have enough txs to build the block
504
- const minTxs = this.config.minTxsPerBlock;
505
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
831
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
506
832
  if (!canStartBuilding) {
507
833
  this.log.warn(
508
- `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
509
- { 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 },
510
836
  );
511
- 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 });
512
838
  this.metrics.recordBlockProposalFailed('insufficient_txs');
513
- return undefined;
839
+ return { failure: 'insufficient-txs' };
514
840
  }
515
841
 
516
842
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
517
843
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
518
844
  const pendingTxs = filter(
519
- this.p2pClient.iteratePendingTxs(),
845
+ this.p2pClient.iterateEligiblePendingTxs(),
520
846
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
521
847
  );
522
848
 
523
849
  this.log.debug(
524
- `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
525
- { 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 },
526
852
  );
527
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
853
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
528
854
 
529
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
530
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
531
- const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
532
-
533
- 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 = {
534
860
  maxTransactions: this.config.maxTxsPerBlock,
535
- maxBlockSize: this.config.maxBlockSizeInBytes,
536
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
537
- 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,
538
865
  deadline: buildDeadline,
866
+ isBuildingProposal: true,
867
+ minValidTxs,
868
+ maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
869
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
539
870
  };
540
871
 
541
- // Actually build the block by executing txs
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.
542
875
  const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
543
876
  checkpointBuilder,
544
877
  pendingTxs,
@@ -550,22 +883,27 @@ export class CheckpointProposalJob implements Traceable {
550
883
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
551
884
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
552
885
 
553
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
554
- // too long, then we may not get to minTxsPerBlock after executing public functions.
555
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
556
- const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
557
- if (buildResult.status === 'no-valid-txs' || (!forceCreate && numTxs < minValidTxs)) {
886
+ if (buildResult.status === 'insufficient-valid-txs') {
558
887
  this.log.warn(
559
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
560
- { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint, minValidTxs, buildResult: buildResult.status },
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
+ },
561
896
  );
562
- this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
897
+ this.eventEmitter.emit('block-build-failed', {
898
+ reason: `Insufficient valid txs`,
899
+ slot: this.targetSlot,
900
+ });
563
901
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
564
- return undefined;
902
+ return { failure: 'insufficient-valid-txs' };
565
903
  }
566
904
 
567
905
  // Block creation succeeded, emit stats and metrics
568
- const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
906
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
569
907
 
570
908
  const blockStats = {
571
909
  eventName: 'l2-block-built',
@@ -576,33 +914,42 @@ export class CheckpointProposalJob implements Traceable {
576
914
 
577
915
  const blockHash = await block.hash();
578
916
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
579
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
917
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
580
918
 
581
919
  this.log.info(
582
- `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`,
583
921
  { blockHash, txHashes, manaPerSec, ...blockStats },
584
922
  );
585
923
 
586
- this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
587
- 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);
588
932
 
589
- return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
933
+ return { block, usedTxs };
590
934
  } catch (err: any) {
591
- this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
592
- 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 });
593
940
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
594
941
  this.metrics.recordFailedBlock();
595
942
  return { error: err };
596
943
  }
597
944
  }
598
945
 
599
- /** Uses the checkpoint builder to build a block, catching specific txs */
946
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
600
947
  private async buildSingleBlockWithCheckpointBuilder(
601
948
  checkpointBuilder: CheckpointBuilder,
602
949
  pendingTxs: AsyncIterable<Tx>,
603
950
  blockNumber: BlockNumber,
604
951
  blockTimestamp: bigint,
605
- blockBuilderOptions: PublicProcessorLimits,
952
+ blockBuilderOptions: BlockBuilderOptions,
606
953
  ) {
607
954
  try {
608
955
  const workTimer = new Timer();
@@ -610,8 +957,12 @@ export class CheckpointProposalJob implements Traceable {
610
957
  const blockBuildDuration = workTimer.ms();
611
958
  return { ...result, blockBuildDuration, status: 'success' as const };
612
959
  } catch (err: unknown) {
613
- if (isErrorClass(err, NoValidTxsError)) {
614
- return { failedTxs: err.failedTxs, status: 'no-valid-txs' as const };
960
+ if (isErrorClass(err, InsufficientValidTxsError)) {
961
+ return {
962
+ failedTxs: err.failedTxs,
963
+ processedCount: err.processedCount,
964
+ status: 'insufficient-valid-txs' as const,
965
+ };
615
966
  }
616
967
  throw err;
617
968
  }
@@ -624,7 +975,7 @@ export class CheckpointProposalJob implements Traceable {
624
975
  blockNumber: BlockNumber;
625
976
  indexWithinCheckpoint: IndexWithinCheckpoint;
626
977
  buildDeadline: Date | undefined;
627
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
978
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
628
979
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
629
980
 
630
981
  // We only allow a block with 0 txs in the first block of the checkpoint
@@ -641,20 +992,50 @@ export class CheckpointProposalJob implements Traceable {
641
992
  // If we're past deadline, or we have no deadline, give up
642
993
  const now = this.dateProvider.nowAsDate();
643
994
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
644
- return { canStartBuilding: false, availableTxs: availableTxs };
995
+ return { canStartBuilding: false, availableTxs, minTxs };
645
996
  }
646
997
 
647
998
  // Wait a bit before checking again
648
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
999
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
649
1000
  this.log.verbose(
650
- `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
651
- { 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 },
652
1003
  );
653
- await sleep(TXS_POLLING_MS);
1004
+ await this.waitForTxsPollingInterval();
654
1005
  availableTxs = await this.p2pClient.getPendingTxCount();
655
1006
  }
656
1007
 
657
- 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
+ }
658
1039
  }
659
1040
 
660
1041
  /**
@@ -662,7 +1043,9 @@ export class CheckpointProposalJob implements Traceable {
662
1043
  * This is run after all blocks for the checkpoint have been built.
663
1044
  */
664
1045
  @trackSpan('CheckpointProposalJob.waitForAttestations')
665
- private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
1046
+ private async waitForAttestations(
1047
+ proposal: CheckpointProposal,
1048
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
666
1049
  if (this.config.fishermanMode) {
667
1050
  this.log.debug('Skipping attestation collection in fisherman mode');
668
1051
  return CommitteeAttestationsAndSigners.empty();
@@ -680,16 +1063,16 @@ export class CheckpointProposalJob implements Traceable {
680
1063
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
681
1064
  }
682
1065
 
683
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
1066
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
684
1067
 
685
1068
  if (this.config.skipCollectingAttestations) {
686
1069
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
687
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
1070
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
688
1071
  return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
689
1072
  }
690
1073
 
691
1074
  const attestationTimeAllowed = this.config.enforceTimeTable
692
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
1075
+ ? this.timetable.getCheckpointAttestationDeadline()
693
1076
  : this.l1Constants.slotDuration;
694
1077
  const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
695
1078
 
@@ -702,15 +1085,33 @@ export class CheckpointProposalJob implements Traceable {
702
1085
  proposal,
703
1086
  numberOfRequiredAttestations,
704
1087
  attestationDeadline,
1088
+ this.checkpointNumber,
705
1089
  );
706
1090
 
707
1091
  collectedAttestationsCount = attestations.length;
708
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
+
709
1105
  // Rollup contract requires that the signatures are provided in the order of the committee
710
- const sorted = orderAttestations(attestations, committee);
1106
+ const sorted = orderAttestations(trimmed, committee);
711
1107
 
712
1108
  // Manipulate the attestations if we've been configured to do so
713
- 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
+ ) {
714
1115
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
715
1116
  }
716
1117
 
@@ -718,8 +1119,14 @@ export class CheckpointProposalJob implements Traceable {
718
1119
  } catch (err) {
719
1120
  if (err && err instanceof AttestationTimeoutError) {
720
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);
721
1128
  }
722
- throw err;
1129
+ return undefined;
723
1130
  } finally {
724
1131
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
725
1132
  }
@@ -739,7 +1146,11 @@ export class CheckpointProposalJob implements Traceable {
739
1146
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
740
1147
  );
741
1148
 
742
- if (this.config.injectFakeAttestation) {
1149
+ if (
1150
+ this.config.injectFakeAttestation ||
1151
+ this.config.injectHighSValueAttestation ||
1152
+ this.config.injectUnrecoverableSignatureAttestation
1153
+ ) {
743
1154
  // Find non-empty attestations that are not from the proposer
744
1155
  const nonProposerIndices: number[] = [];
745
1156
  for (let i = 0; i < attestations.length; i++) {
@@ -749,8 +1160,20 @@ export class CheckpointProposalJob implements Traceable {
749
1160
  }
750
1161
  if (nonProposerIndices.length > 0) {
751
1162
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
752
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
753
- 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
+ }
754
1177
  }
755
1178
  return new CommitteeAttestationsAndSigners(attestations);
756
1179
  }
@@ -759,11 +1182,20 @@ export class CheckpointProposalJob implements Traceable {
759
1182
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
760
1183
 
761
1184
  const shuffled = [...attestations];
762
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
763
- const valueI = shuffled[i];
764
- const valueJ = shuffled[j];
765
- shuffled[i] = valueJ;
766
- 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
+ }
767
1199
 
768
1200
  const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
769
1201
  return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
@@ -779,16 +1211,20 @@ export class CheckpointProposalJob implements Traceable {
779
1211
  const failedTxData = failedTxs.map(fail => fail.tx);
780
1212
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
781
1213
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
782
- await this.p2pClient.deleteTxs(failedTxHashes);
1214
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
783
1215
  }
784
1216
 
785
1217
  /**
786
1218
  * Adds the proposed block to the archiver so it's available via P2P.
787
1219
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
788
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.
789
1225
  */
790
1226
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
791
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1227
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
792
1228
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
793
1229
  blockNumber: block.number,
794
1230
  slot: block.header.globalVariables.slotNumber,
@@ -806,22 +1242,22 @@ export class CheckpointProposalJob implements Traceable {
806
1242
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
807
1243
  // Perform L1 fee analysis before clearing requests
808
1244
  // The callback is invoked asynchronously after the next block is mined
809
- const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
1245
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, analysis =>
810
1246
  this.metrics.recordFishermanFeeAnalysis(analysis),
811
1247
  );
812
1248
 
813
1249
  if (checkpoint) {
814
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1250
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
815
1251
  ...checkpoint.toCheckpointInfo(),
816
1252
  ...checkpoint.getStats(),
817
1253
  feeAnalysisId: feeAnalysis?.id,
818
1254
  });
819
1255
  } else {
820
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
821
- slot: this.slot,
1256
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1257
+ slot: this.targetSlot,
822
1258
  feeAnalysisId: feeAnalysis?.id,
823
1259
  });
824
- this.metrics.recordBlockProposalFailed('block_build_failed');
1260
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
825
1261
  }
826
1262
 
827
1263
  this.publisher.clearPendingRequests();
@@ -832,15 +1268,15 @@ export class CheckpointProposalJob implements Traceable {
832
1268
  */
833
1269
  private handleHASigningError(err: any, errorContext: string): boolean {
834
1270
  if (err instanceof DutyAlreadySignedError) {
835
- this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
836
- slot: this.slot,
1271
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1272
+ slot: this.targetSlot,
837
1273
  signedByNode: err.signedByNode,
838
1274
  });
839
1275
  return true;
840
1276
  }
841
1277
  if (err instanceof SlashingProtectionError) {
842
- this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
843
- slot: this.slot,
1278
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1279
+ slot: this.targetSlot,
844
1280
  existingMessageHash: err.existingMessageHash,
845
1281
  attemptedMessageHash: err.attemptedMessageHash,
846
1282
  });
@@ -857,8 +1293,13 @@ export class CheckpointProposalJob implements Traceable {
857
1293
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
858
1294
  }
859
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
+
860
1301
  private getSlotStartBuildTimestamp(): number {
861
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1302
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
862
1303
  }
863
1304
 
864
1305
  private getSecondsIntoSlot(): number {