@aztec/sequencer-client 0.0.1-commit.0c875d939 → 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 (99) 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 -6
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +49 -29
  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 +68 -48
  40. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  41. package/dest/publisher/sequencer-publisher.js +419 -135
  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 +40 -10
  46. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  47. package/dest/sequencer/checkpoint_proposal_job.js +522 -212
  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 +18 -8
  57. package/dest/sequencer/metrics.d.ts.map +1 -1
  58. package/dest/sequencer/metrics.js +85 -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 -97
  62. package/dest/sequencer/timetable.d.ts +17 -3
  63. package/dest/sequencer/timetable.d.ts.map +1 -1
  64. package/dest/sequencer/timetable.js +51 -43
  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 +7 -9
  70. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  71. package/dest/test/mock_checkpoint_builder.js +39 -30
  72. package/package.json +27 -28
  73. package/src/client/sequencer-client.ts +81 -30
  74. package/src/config.ts +61 -35
  75. package/src/global_variable_builder/README.md +44 -0
  76. package/src/global_variable_builder/fee_predictor.ts +172 -0
  77. package/src/global_variable_builder/fee_provider.ts +75 -0
  78. package/src/global_variable_builder/global_builder.ts +27 -63
  79. package/src/global_variable_builder/index.ts +3 -1
  80. package/src/publisher/config.ts +157 -45
  81. package/src/publisher/index.ts +3 -0
  82. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  83. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  84. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  85. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  86. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  87. package/src/publisher/sequencer-publisher.ts +472 -193
  88. package/src/sequencer/README.md +83 -13
  89. package/src/sequencer/chain_state_overrides.ts +87 -0
  90. package/src/sequencer/checkpoint_proposal_job.ts +665 -234
  91. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  92. package/src/sequencer/checkpoint_voter.ts +1 -12
  93. package/src/sequencer/events.ts +6 -1
  94. package/src/sequencer/metrics.ts +100 -26
  95. package/src/sequencer/sequencer.ts +227 -109
  96. package/src/sequencer/timetable.ts +64 -52
  97. package/src/sequencer/types.ts +1 -1
  98. package/src/test/index.ts +2 -4
  99. package/src/test/mock_checkpoint_builder.ts +51 -48
@@ -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,16 +505,15 @@ 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);
193
511
 
194
512
  // Get the fee asset price modifier from the oracle
195
513
  const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
196
514
 
197
515
  // Create a long-lived forked world state for the checkpoint builder
198
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
516
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
199
517
 
200
518
  // Create checkpoint builder for the entire slot
201
519
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
@@ -220,7 +538,8 @@ export class CheckpointProposalJob implements Traceable {
220
538
  };
221
539
 
222
540
  let blocksInCheckpoint: L2Block[] = [];
223
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
541
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
542
+ const checkpointBuildTimer = new Timer();
224
543
 
225
544
  try {
226
545
  // Main loop: build blocks for the checkpoint
@@ -243,94 +562,90 @@ export class CheckpointProposalJob implements Traceable {
243
562
  }
244
563
 
245
564
  if (blocksInCheckpoint.length === 0) {
246
- this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
247
- 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
+ );
248
576
  return undefined;
249
577
  }
250
578
 
251
579
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
252
580
  // broadcasted yet, and wait to collect the committee attestations.
253
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
581
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
254
582
  const checkpoint = await checkpointBuilder.completeCheckpoint();
255
583
 
256
- // 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
257
610
  if (this.config.fishermanMode) {
258
611
  this.log.info(
259
- `Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` +
612
+ `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
260
613
  `Skipping proposal in fisherman mode.`,
261
614
  {
262
- slot: this.slot,
615
+ slot: this.targetSlot,
263
616
  checkpoint: checkpoint.header.toInspect(),
264
617
  blocksBuilt: blocksInCheckpoint.length,
265
618
  },
266
619
  );
267
620
  this.metrics.recordCheckpointSuccess();
268
- 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() };
269
623
  }
270
624
 
271
- // Include the block pending broadcast in the checkpoint proposal if any
272
- const lastBlock = blockPendingBroadcast && {
273
- blockHeader: blockPendingBroadcast.block.header,
274
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
275
- txs: blockPendingBroadcast.txs,
276
- };
277
-
278
625
  // Create the checkpoint proposal and broadcast it
279
626
  const proposal = await this.validatorClient.createCheckpointProposal(
280
627
  checkpoint.header,
281
628
  checkpoint.archive.root,
629
+ this.checkpointNumber,
282
630
  feeAssetPriceModifier,
283
- lastBlock,
631
+ blockPendingBroadcast,
284
632
  this.proposer,
285
633
  checkpointProposalOptions,
286
634
  );
287
635
 
288
636
  const blockProposedAt = this.dateProvider.now();
289
637
  await this.p2pClient.broadcastCheckpointProposal(proposal);
638
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
290
639
 
291
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
292
- const attestations = await this.waitForAttestations(proposal);
293
- const blockAttestedAt = this.dateProvider.now();
294
-
295
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
296
-
297
- // Proposer must sign over the attestations before pushing them to L1
298
- const signer = this.proposer ?? this.publisher.getSenderAddress();
299
- let attestationsSignature: Signature;
300
- try {
301
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
302
- attestations,
303
- signer,
304
- this.slot,
305
- this.checkpointNumber,
306
- );
307
- } catch (err) {
308
- // We shouldn't really get here since we yield to another HA node
309
- // as soon as we see these errors when creating block or checkpoint proposals.
310
- if (this.handleHASigningError(err, 'Attestations signature')) {
311
- return undefined;
312
- }
313
- throw err;
314
- }
315
-
316
- // Enqueue publishing the checkpoint to L1
317
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
318
- const aztecSlotDuration = this.l1Constants.slotDuration;
319
- const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
320
- const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
321
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
322
- txTimeoutAt,
323
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
324
- });
325
-
326
- return checkpoint;
640
+ // Return immediately after broadcast — attestation collection happens in the background
641
+ return { checkpoint, proposal, blockProposedAt };
327
642
  } catch (err) {
328
643
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
329
644
  // swallow this error. It's already been logged by a function deeper in the stack
330
645
  return undefined;
331
646
  }
332
647
 
333
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
648
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
334
649
  return undefined;
335
650
  }
336
651
  }
@@ -346,17 +661,14 @@ export class CheckpointProposalJob implements Traceable {
346
661
  blockProposalOptions: BlockProposalOptions,
347
662
  ): Promise<{
348
663
  blocksInCheckpoint: L2Block[];
349
- blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
664
+ blockPendingBroadcast: BlockProposal | undefined;
350
665
  }> {
351
666
  const blocksInCheckpoint: L2Block[] = [];
352
667
  const txHashesAlreadyIncluded = new Set<string>();
353
668
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
354
669
 
355
- // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
356
- let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
357
-
358
670
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
359
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
671
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
360
672
 
361
673
  while (true) {
362
674
  const blocksBuilt = blocksInCheckpoint.length;
@@ -368,7 +680,7 @@ export class CheckpointProposalJob implements Traceable {
368
680
 
369
681
  if (!timingInfo.canStart) {
370
682
  this.log.debug(`Not enough time left in slot to start another block`, {
371
- slot: this.slot,
683
+ slot: this.targetSlot,
372
684
  blocksBuilt,
373
685
  secondsIntoSlot,
374
686
  });
@@ -387,25 +699,25 @@ export class CheckpointProposalJob implements Traceable {
387
699
  blockNumber,
388
700
  indexWithinCheckpoint,
389
701
  txHashesAlreadyIncluded,
390
- remainingBlobFields,
391
702
  });
392
703
 
393
- // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
394
- if (!buildResult && timingInfo.isLastBlock) {
395
- // If no block was produced due to not enough txs and this was the last subslot, exit
396
- break;
397
- } else if (!buildResult && timingInfo.deadline !== undefined) {
398
- // 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
399
711
  await this.waitUntilNextSubslot(timingInfo.deadline);
400
712
  continue;
401
- } else if (!buildResult) {
402
- // Exit if there is no possibility of building more blocks
403
- break;
404
- } else if ('error' in buildResult) {
405
- // 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) {
406
718
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
407
- this.log.warn(`Halting block building for slot ${this.slot}`, {
408
- slot: this.slot,
719
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
720
+ slot: this.targetSlot,
409
721
  blocksBuilt,
410
722
  error: buildResult.error,
411
723
  });
@@ -413,65 +725,81 @@ export class CheckpointProposalJob implements Traceable {
413
725
  break;
414
726
  }
415
727
 
416
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
417
- blocksInCheckpoint.push(block);
418
-
419
- // Update remaining blob fields for the next block
420
- remainingBlobFields = newRemainingBlobFields;
421
-
422
- // Sync the proposed block to the archiver to make it available
423
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
424
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
425
- // Fire and forget - don't block the critical path, but log errors
426
- this.syncProposedBlockToArchiver(block).catch(err => {
427
- 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,
428
732
  });
429
733
 
734
+ blocksInCheckpoint.push(block);
430
735
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
431
736
 
432
- // 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.
433
747
  if (timingInfo.isLastBlock) {
434
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
435
- slot: this.slot,
748
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
749
+ slot: this.targetSlot,
436
750
  blockNumber,
437
751
  blocksBuilt,
438
752
  });
439
- blockPendingBroadcast = { block, txs: usedTxs };
753
+
754
+ blockPendingBroadcast = proposal;
440
755
  break;
441
756
  }
442
757
 
443
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
444
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
445
- if (!this.config.fishermanMode) {
446
- const proposal = await this.validatorClient.createBlockProposal(
447
- block.header,
448
- block.indexWithinCheckpoint,
449
- inHash,
450
- block.archive.root,
451
- usedTxs,
452
- this.proposer,
453
- blockProposalOptions,
454
- );
455
- await this.p2pClient.broadcastProposal(proposal);
456
- }
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));
457
760
 
458
761
  // Wait until the next block's start time
459
762
  await this.waitUntilNextSubslot(timingInfo.deadline);
460
763
  }
461
764
 
462
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
463
- slot: this.slot,
765
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
766
+ slot: this.targetSlot,
464
767
  blocksBuilt: blocksInCheckpoint.length,
465
768
  });
466
769
 
467
770
  return { blocksInCheckpoint, blockPendingBroadcast };
468
771
  }
469
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
+
470
796
  /** Sleeps until it is time to produce the next block in the slot */
471
797
  @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
472
798
  private async waitUntilNextSubslot(nextSubslotStart: number) {
473
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
474
- 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
+ });
475
803
  await this.waitUntilTimeInSlot(nextSubslotStart);
476
804
  }
477
805
 
@@ -486,36 +814,29 @@ export class CheckpointProposalJob implements Traceable {
486
814
  indexWithinCheckpoint: IndexWithinCheckpoint;
487
815
  buildDeadline: Date | undefined;
488
816
  txHashesAlreadyIncluded: Set<string>;
489
- remainingBlobFields: number;
490
817
  },
491
- ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
492
- const {
493
- blockTimestamp,
494
- forceCreate,
495
- blockNumber,
496
- indexWithinCheckpoint,
497
- buildDeadline,
498
- txHashesAlreadyIncluded,
499
- remainingBlobFields,
500
- } = 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;
501
823
 
502
824
  this.log.verbose(
503
- `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}`,
504
826
  { ...checkpointBuilder.getConstantData(), ...opts },
505
827
  );
506
828
 
507
829
  try {
508
830
  // Wait until we have enough txs to build the block
509
- const minTxs = this.config.minTxsPerBlock;
510
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
831
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
511
832
  if (!canStartBuilding) {
512
833
  this.log.warn(
513
- `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
514
- { 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 },
515
836
  );
516
- 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 });
517
838
  this.metrics.recordBlockProposalFailed('insufficient_txs');
518
- return undefined;
839
+ return { failure: 'insufficient-txs' };
519
840
  }
520
841
 
521
842
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
@@ -526,24 +847,31 @@ export class CheckpointProposalJob implements Traceable {
526
847
  );
527
848
 
528
849
  this.log.debug(
529
- `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
530
- { 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 },
531
852
  );
532
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
533
-
534
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
535
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
536
- const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
853
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
537
854
 
538
- 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 = {
539
860
  maxTransactions: this.config.maxTxsPerBlock,
540
- maxBlockSize: this.config.maxBlockSizeInBytes,
541
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
542
- 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,
543
865
  deadline: buildDeadline,
866
+ isBuildingProposal: true,
867
+ minValidTxs,
868
+ maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
869
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
544
870
  };
545
871
 
546
- // 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.
547
875
  const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
548
876
  checkpointBuilder,
549
877
  pendingTxs,
@@ -555,22 +883,27 @@ export class CheckpointProposalJob implements Traceable {
555
883
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
556
884
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
557
885
 
558
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
559
- // too long, then we may not get to minTxsPerBlock after executing public functions.
560
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
561
- const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
562
- if (buildResult.status === 'no-valid-txs' || (!forceCreate && numTxs < minValidTxs)) {
886
+ if (buildResult.status === 'insufficient-valid-txs') {
563
887
  this.log.warn(
564
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
565
- { 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
+ },
566
896
  );
567
- 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
+ });
568
901
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
569
- return undefined;
902
+ return { failure: 'insufficient-valid-txs' };
570
903
  }
571
904
 
572
905
  // Block creation succeeded, emit stats and metrics
573
- const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
906
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
574
907
 
575
908
  const blockStats = {
576
909
  eventName: 'l2-block-built',
@@ -581,33 +914,42 @@ export class CheckpointProposalJob implements Traceable {
581
914
 
582
915
  const blockHash = await block.hash();
583
916
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
584
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
917
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
585
918
 
586
919
  this.log.info(
587
- `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`,
588
921
  { blockHash, txHashes, manaPerSec, ...blockStats },
589
922
  );
590
923
 
591
- this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
592
- 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);
593
932
 
594
- return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
933
+ return { block, usedTxs };
595
934
  } catch (err: any) {
596
- this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
597
- 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 });
598
940
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
599
941
  this.metrics.recordFailedBlock();
600
942
  return { error: err };
601
943
  }
602
944
  }
603
945
 
604
- /** Uses the checkpoint builder to build a block, catching specific txs */
946
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
605
947
  private async buildSingleBlockWithCheckpointBuilder(
606
948
  checkpointBuilder: CheckpointBuilder,
607
949
  pendingTxs: AsyncIterable<Tx>,
608
950
  blockNumber: BlockNumber,
609
951
  blockTimestamp: bigint,
610
- blockBuilderOptions: PublicProcessorLimits,
952
+ blockBuilderOptions: BlockBuilderOptions,
611
953
  ) {
612
954
  try {
613
955
  const workTimer = new Timer();
@@ -615,8 +957,12 @@ export class CheckpointProposalJob implements Traceable {
615
957
  const blockBuildDuration = workTimer.ms();
616
958
  return { ...result, blockBuildDuration, status: 'success' as const };
617
959
  } catch (err: unknown) {
618
- if (isErrorClass(err, NoValidTxsError)) {
619
- 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
+ };
620
966
  }
621
967
  throw err;
622
968
  }
@@ -629,7 +975,7 @@ export class CheckpointProposalJob implements Traceable {
629
975
  blockNumber: BlockNumber;
630
976
  indexWithinCheckpoint: IndexWithinCheckpoint;
631
977
  buildDeadline: Date | undefined;
632
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
978
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
633
979
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
634
980
 
635
981
  // We only allow a block with 0 txs in the first block of the checkpoint
@@ -646,20 +992,50 @@ export class CheckpointProposalJob implements Traceable {
646
992
  // If we're past deadline, or we have no deadline, give up
647
993
  const now = this.dateProvider.nowAsDate();
648
994
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
649
- return { canStartBuilding: false, availableTxs: availableTxs };
995
+ return { canStartBuilding: false, availableTxs, minTxs };
650
996
  }
651
997
 
652
998
  // Wait a bit before checking again
653
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
999
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
654
1000
  this.log.verbose(
655
- `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
656
- { 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 },
657
1003
  );
658
1004
  await this.waitForTxsPollingInterval();
659
1005
  availableTxs = await this.p2pClient.getPendingTxCount();
660
1006
  }
661
1007
 
662
- 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
+ }
663
1039
  }
664
1040
 
665
1041
  /**
@@ -667,7 +1043,9 @@ export class CheckpointProposalJob implements Traceable {
667
1043
  * This is run after all blocks for the checkpoint have been built.
668
1044
  */
669
1045
  @trackSpan('CheckpointProposalJob.waitForAttestations')
670
- private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
1046
+ private async waitForAttestations(
1047
+ proposal: CheckpointProposal,
1048
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
671
1049
  if (this.config.fishermanMode) {
672
1050
  this.log.debug('Skipping attestation collection in fisherman mode');
673
1051
  return CommitteeAttestationsAndSigners.empty();
@@ -685,16 +1063,16 @@ export class CheckpointProposalJob implements Traceable {
685
1063
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
686
1064
  }
687
1065
 
688
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
1066
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
689
1067
 
690
1068
  if (this.config.skipCollectingAttestations) {
691
1069
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
692
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
1070
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
693
1071
  return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
694
1072
  }
695
1073
 
696
1074
  const attestationTimeAllowed = this.config.enforceTimeTable
697
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
1075
+ ? this.timetable.getCheckpointAttestationDeadline()
698
1076
  : this.l1Constants.slotDuration;
699
1077
  const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
700
1078
 
@@ -707,15 +1085,33 @@ export class CheckpointProposalJob implements Traceable {
707
1085
  proposal,
708
1086
  numberOfRequiredAttestations,
709
1087
  attestationDeadline,
1088
+ this.checkpointNumber,
710
1089
  );
711
1090
 
712
1091
  collectedAttestationsCount = attestations.length;
713
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
+
714
1105
  // Rollup contract requires that the signatures are provided in the order of the committee
715
- const sorted = orderAttestations(attestations, committee);
1106
+ const sorted = orderAttestations(trimmed, committee);
716
1107
 
717
1108
  // Manipulate the attestations if we've been configured to do so
718
- 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
+ ) {
719
1115
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
720
1116
  }
721
1117
 
@@ -723,8 +1119,14 @@ export class CheckpointProposalJob implements Traceable {
723
1119
  } catch (err) {
724
1120
  if (err && err instanceof AttestationTimeoutError) {
725
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);
726
1128
  }
727
- throw err;
1129
+ return undefined;
728
1130
  } finally {
729
1131
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
730
1132
  }
@@ -744,7 +1146,11 @@ export class CheckpointProposalJob implements Traceable {
744
1146
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
745
1147
  );
746
1148
 
747
- if (this.config.injectFakeAttestation) {
1149
+ if (
1150
+ this.config.injectFakeAttestation ||
1151
+ this.config.injectHighSValueAttestation ||
1152
+ this.config.injectUnrecoverableSignatureAttestation
1153
+ ) {
748
1154
  // Find non-empty attestations that are not from the proposer
749
1155
  const nonProposerIndices: number[] = [];
750
1156
  for (let i = 0; i < attestations.length; i++) {
@@ -754,8 +1160,20 @@ export class CheckpointProposalJob implements Traceable {
754
1160
  }
755
1161
  if (nonProposerIndices.length > 0) {
756
1162
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
757
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
758
- 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
+ }
759
1177
  }
760
1178
  return new CommitteeAttestationsAndSigners(attestations);
761
1179
  }
@@ -764,11 +1182,20 @@ export class CheckpointProposalJob implements Traceable {
764
1182
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
765
1183
 
766
1184
  const shuffled = [...attestations];
767
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
768
- const valueI = shuffled[i];
769
- const valueJ = shuffled[j];
770
- shuffled[i] = valueJ;
771
- 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
+ }
772
1199
 
773
1200
  const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
774
1201
  return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
@@ -791,9 +1218,13 @@ export class CheckpointProposalJob implements Traceable {
791
1218
  * Adds the proposed block to the archiver so it's available via P2P.
792
1219
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
793
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.
794
1225
  */
795
1226
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
796
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1227
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
797
1228
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
798
1229
  blockNumber: block.number,
799
1230
  slot: block.header.globalVariables.slotNumber,
@@ -811,22 +1242,22 @@ export class CheckpointProposalJob implements Traceable {
811
1242
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
812
1243
  // Perform L1 fee analysis before clearing requests
813
1244
  // The callback is invoked asynchronously after the next block is mined
814
- const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
1245
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, analysis =>
815
1246
  this.metrics.recordFishermanFeeAnalysis(analysis),
816
1247
  );
817
1248
 
818
1249
  if (checkpoint) {
819
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1250
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
820
1251
  ...checkpoint.toCheckpointInfo(),
821
1252
  ...checkpoint.getStats(),
822
1253
  feeAnalysisId: feeAnalysis?.id,
823
1254
  });
824
1255
  } else {
825
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
826
- slot: this.slot,
1256
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1257
+ slot: this.targetSlot,
827
1258
  feeAnalysisId: feeAnalysis?.id,
828
1259
  });
829
- this.metrics.recordBlockProposalFailed('block_build_failed');
1260
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
830
1261
  }
831
1262
 
832
1263
  this.publisher.clearPendingRequests();
@@ -837,15 +1268,15 @@ export class CheckpointProposalJob implements Traceable {
837
1268
  */
838
1269
  private handleHASigningError(err: any, errorContext: string): boolean {
839
1270
  if (err instanceof DutyAlreadySignedError) {
840
- this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
841
- slot: this.slot,
1271
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1272
+ slot: this.targetSlot,
842
1273
  signedByNode: err.signedByNode,
843
1274
  });
844
1275
  return true;
845
1276
  }
846
1277
  if (err instanceof SlashingProtectionError) {
847
- this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
848
- slot: this.slot,
1278
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1279
+ slot: this.targetSlot,
849
1280
  existingMessageHash: err.existingMessageHash,
850
1281
  attemptedMessageHash: err.attemptedMessageHash,
851
1282
  });
@@ -868,7 +1299,7 @@ export class CheckpointProposalJob implements Traceable {
868
1299
  }
869
1300
 
870
1301
  private getSlotStartBuildTimestamp(): number {
871
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1302
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
872
1303
  }
873
1304
 
874
1305
  private getSecondsIntoSlot(): number {