@aztec/sequencer-client 0.0.1-commit.358457c → 0.0.1-commit.3750d92a7

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 (80) hide show
  1. package/dest/client/sequencer-client.d.ts +6 -1
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +49 -27
  4. package/dest/config.d.ts +25 -5
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +36 -25
  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 -14
  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 +13 -1
  20. package/dest/publisher/config.d.ts.map +1 -1
  21. package/dest/publisher/config.js +19 -4
  22. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +3 -4
  23. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  24. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -5
  25. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  26. package/dest/publisher/sequencer-publisher-factory.js +16 -3
  27. package/dest/publisher/sequencer-publisher.d.ts +55 -43
  28. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  29. package/dest/publisher/sequencer-publisher.js +180 -116
  30. package/dest/sequencer/chain_state_overrides.d.ts +25 -0
  31. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  32. package/dest/sequencer/chain_state_overrides.js +39 -0
  33. package/dest/sequencer/checkpoint_proposal_job.d.ts +26 -9
  34. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  35. package/dest/sequencer/checkpoint_proposal_job.js +350 -214
  36. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  37. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  38. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  39. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  40. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  41. package/dest/sequencer/checkpoint_voter.js +2 -5
  42. package/dest/sequencer/events.d.ts +2 -1
  43. package/dest/sequencer/events.d.ts.map +1 -1
  44. package/dest/sequencer/metrics.d.ts +9 -10
  45. package/dest/sequencer/metrics.d.ts.map +1 -1
  46. package/dest/sequencer/metrics.js +23 -20
  47. package/dest/sequencer/sequencer.d.ts +29 -11
  48. package/dest/sequencer/sequencer.d.ts.map +1 -1
  49. package/dest/sequencer/sequencer.js +137 -74
  50. package/dest/sequencer/timetable.d.ts +17 -3
  51. package/dest/sequencer/timetable.d.ts.map +1 -1
  52. package/dest/sequencer/timetable.js +51 -43
  53. package/dest/sequencer/types.d.ts +2 -2
  54. package/dest/sequencer/types.d.ts.map +1 -1
  55. package/dest/test/mock_checkpoint_builder.d.ts +7 -9
  56. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  57. package/dest/test/mock_checkpoint_builder.js +39 -30
  58. package/package.json +27 -28
  59. package/src/client/sequencer-client.ts +61 -28
  60. package/src/config.ts +44 -27
  61. package/src/global_variable_builder/README.md +44 -0
  62. package/src/global_variable_builder/fee_predictor.ts +172 -0
  63. package/src/global_variable_builder/fee_provider.ts +75 -0
  64. package/src/global_variable_builder/global_builder.ts +26 -62
  65. package/src/global_variable_builder/index.ts +3 -1
  66. package/src/publisher/config.ts +38 -4
  67. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  68. package/src/publisher/sequencer-publisher-factory.ts +18 -6
  69. package/src/publisher/sequencer-publisher.ts +263 -167
  70. package/src/sequencer/README.md +83 -13
  71. package/src/sequencer/chain_state_overrides.ts +87 -0
  72. package/src/sequencer/checkpoint_proposal_job.ts +452 -241
  73. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  74. package/src/sequencer/checkpoint_voter.ts +1 -12
  75. package/src/sequencer/events.ts +1 -1
  76. package/src/sequencer/metrics.ts +29 -25
  77. package/src/sequencer/sequencer.ts +198 -81
  78. package/src/sequencer/timetable.ts +64 -52
  79. package/src/sequencer/types.ts +1 -1
  80. 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,6 +8,11 @@ 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';
@@ -27,17 +31,22 @@ import {
27
31
  type L2BlockSource,
28
32
  MaliciousCommitteeAttestationsAndSigners,
29
33
  } from '@aztec/stdlib/block';
30
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
31
- import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
34
+ import { type Checkpoint, type ProposedCheckpointData, validateCheckpoint } from '@aztec/stdlib/checkpoint';
35
+ import { computeQuorum, getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
32
36
  import { Gas } from '@aztec/stdlib/gas';
33
37
  import {
34
- NoValidTxsError,
35
- type PublicProcessorLimits,
38
+ type BlockBuilderOptions,
39
+ InsufficientValidTxsError,
36
40
  type ResolvedSequencerConfig,
37
41
  type WorldStateSynchronizer,
38
42
  } from '@aztec/stdlib/interfaces/server';
39
43
  import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
40
- import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
44
+ import type {
45
+ BlockProposal,
46
+ BlockProposalOptions,
47
+ CheckpointProposal,
48
+ CheckpointProposalOptions,
49
+ } from '@aztec/stdlib/p2p';
41
50
  import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
42
51
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
43
52
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
@@ -48,6 +57,11 @@ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validato
48
57
 
49
58
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
50
59
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
60
+ import {
61
+ buildPipelinedParentSimulationOverridesPlan,
62
+ buildSubmissionSimulationOverridesPlan,
63
+ } from './chain_state_overrides.js';
64
+ import type { CheckpointProposalJobMetricsRecorder } from './checkpoint_proposal_job_metrics.js';
51
65
  import { CheckpointVoter } from './checkpoint_voter.js';
52
66
  import { SequencerInterruptedError } from './errors.js';
53
67
  import type { SequencerEvents } from './events.js';
@@ -59,6 +73,20 @@ import { SequencerState } from './utils.js';
59
73
  /** How much time to sleep while waiting for min transactions to accumulate for a block */
60
74
  const TXS_POLLING_MS = 500;
61
75
 
76
+ /** Result from proposeCheckpoint when a checkpoint was successfully built and broadcast. */
77
+ type CheckpointProposalBroadcast = {
78
+ checkpoint: Checkpoint;
79
+ proposal: CheckpointProposal;
80
+ blockProposedAt: number;
81
+ };
82
+
83
+ /** Result after attestation collection and signing, ready for L1 submission. */
84
+ type CheckpointProposalResult = {
85
+ checkpoint: Checkpoint;
86
+ attestations: CommitteeAttestationsAndSigners;
87
+ attestationsSignature: Signature;
88
+ };
89
+
62
90
  /**
63
91
  * Handles the execution of a checkpoint proposal after the initial preparation phase.
64
92
  * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
@@ -68,9 +96,16 @@ const TXS_POLLING_MS = 500;
68
96
  export class CheckpointProposalJob implements Traceable {
69
97
  protected readonly log: Logger;
70
98
 
99
+ /** Tracks the fire-and-forget L1 submission promise so it can be awaited during shutdown. */
100
+ private pendingL1Submission: Promise<void> | undefined;
101
+
102
+ /** Pipelined parent chain state used while building and later submitting this checkpoint. */
103
+ private pipelinedParentSimulationOverridesPlan?: SimulationOverridesPlan;
104
+
71
105
  constructor(
72
- private readonly epoch: EpochNumber,
73
- private readonly slot: SlotNumber,
106
+ private readonly slotNow: SlotNumber,
107
+ private readonly targetSlot: SlotNumber,
108
+ private readonly targetEpoch: EpochNumber,
74
109
  private readonly checkpointNumber: CheckpointNumber,
75
110
  private readonly syncedToBlockNumber: BlockNumber,
76
111
  // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
@@ -93,17 +128,31 @@ export class CheckpointProposalJob implements Traceable {
93
128
  private readonly epochCache: EpochCache,
94
129
  private readonly dateProvider: DateProvider,
95
130
  private readonly metrics: SequencerMetrics,
131
+ private readonly checkpointMetrics: CheckpointProposalJobMetricsRecorder,
96
132
  private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
97
133
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
98
134
  public readonly tracer: Tracer,
99
135
  bindings?: LoggerBindings,
136
+ private readonly proposedCheckpointData?: ProposedCheckpointData,
100
137
  ) {
101
- this.log = createLogger('sequencer:checkpoint-proposal', { ...bindings, instanceId: `slot-${slot}` });
138
+ this.log = createLogger('sequencer:checkpoint-proposal', {
139
+ ...bindings,
140
+ instanceId: `slot-${this.slotNow}`,
141
+ });
142
+ }
143
+
144
+ /** Awaits the pending L1 submission if one is in progress. Call during shutdown. */
145
+ public async awaitPendingSubmission(): Promise<void> {
146
+ this.log.info('Awaiting pending L1 payload submission');
147
+ await this.pendingL1Submission;
102
148
  }
103
149
 
104
150
  /**
105
151
  * Executes the checkpoint proposal job.
106
- * Returns the published checkpoint if successful, undefined otherwise.
152
+ * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
153
+ * Attestation collection, signing, and L1 submission are backgrounded so the
154
+ * work loop can return to IDLE immediately for consecutive slot proposals.
155
+ * Returns the built checkpoint if successful, undefined otherwise.
107
156
  */
108
157
  @trackSpan('CheckpointProposalJob.execute')
109
158
  public async execute(): Promise<Checkpoint | undefined> {
@@ -111,7 +160,7 @@ export class CheckpointProposalJob implements Traceable {
111
160
  // In fisherman mode, we simulate slashing but don't actually publish to L1
112
161
  // These are constant for the whole slot, so we only enqueue them once
113
162
  const votesPromises = new CheckpointVoter(
114
- this.slot,
163
+ this.targetSlot,
115
164
  this.publisher,
116
165
  this.attestorAddress,
117
166
  this.validatorClient,
@@ -122,63 +171,195 @@ export class CheckpointProposalJob implements Traceable {
122
171
  this.log,
123
172
  ).enqueueVotes();
124
173
 
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();
127
-
128
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
129
- await Promise.all(votesPromises);
174
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
175
+ // Returns after broadcast — attestation collection is deferred.
176
+ const broadcast = await this.proposeCheckpoint();
130
177
 
131
- if (checkpoint) {
132
- this.metrics.recordCheckpointProposalSuccess();
178
+ if (!broadcast) {
179
+ await Promise.all(votesPromises);
180
+ // Still submit votes even without a checkpoint
181
+ if (!this.config.fishermanMode) {
182
+ this.pendingL1Submission = this.publisher.sendRequestsAt(this.dateProvider.nowAsDate()).then(() => {});
183
+ }
184
+ return undefined;
133
185
  }
134
186
 
187
+ const { checkpoint } = broadcast;
188
+ this.metrics.recordCheckpointProposalSuccess();
189
+
135
190
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
136
191
  if (this.config.fishermanMode) {
137
192
  await this.handleCheckpointEndAsFisherman(checkpoint);
138
- return;
193
+ return checkpoint;
139
194
  }
140
195
 
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;
196
+ // Background the attestation signing → L1 pipeline so the work loop is unblocked
197
+ this.pendingL1Submission = this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises);
198
+
199
+ // Return the built checkpoint immediately — the work loop is now unblocked
200
+ return checkpoint;
201
+ }
202
+
203
+ /**
204
+ * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
205
+ * Runs as a fire-and-forget task stored in `pendingL1Submission` so the work loop is unblocked.
206
+ */
207
+ private async waitForAttestationsAndEnqueueSubmissionAsync(
208
+ broadcast: CheckpointProposalBroadcast,
209
+ votesPromises: Promise<unknown>[],
210
+ ): Promise<void> {
211
+ const { checkpoint, proposal, blockProposedAt } = broadcast;
212
+ try {
213
+ await Promise.all(votesPromises);
214
+
215
+ this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.targetSlot);
216
+ const attestations = await this.waitForAttestations(proposal);
217
+
218
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
219
+
220
+ // Proposer must sign over the attestations before pushing them to L1
221
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
222
+ let attestationsSignature: Signature;
223
+ try {
224
+ attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
225
+ attestations,
226
+ signer,
227
+ this.targetSlot,
228
+ this.checkpointNumber,
229
+ );
230
+ } catch (err) {
231
+ if (this.handleHASigningError(err, 'Attestations signature')) {
232
+ return;
233
+ }
234
+ throw err;
235
+ }
236
+
237
+ // Enqueue the checkpoint for L1 submission
238
+ await this.enqueueCheckpointForSubmission({ checkpoint, attestations, attestationsSignature });
239
+
240
+ // Compute the earliest time to submit: pipeline slot start when pipelining, now otherwise.
241
+ const submitAfter = this.epochCache.isProposerPipeliningEnabled()
242
+ ? new Date(Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) * 1000)
243
+ : new Date(this.dateProvider.now());
244
+
245
+ const l1Response = await this.publisher.sendRequestsAt(submitAfter);
246
+ const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
247
+ if (proposedAction) {
248
+ this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
249
+ const coinbase = checkpoint.header.coinbase;
250
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
251
+ } else {
252
+ this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
253
+ if (this.epochCache.isProposerPipeliningEnabled()) {
254
+ this.metrics.recordPipelineDiscard();
255
+ }
256
+ }
257
+ } catch (err) {
258
+ if (err instanceof SequencerInterruptedError) {
259
+ return;
260
+ }
261
+ this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err);
262
+ this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
263
+ if (this.epochCache.isProposerPipeliningEnabled()) {
264
+ this.metrics.recordPipelineDiscard();
265
+ }
152
266
  }
153
267
  }
154
268
 
269
+ /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */
270
+ private async enqueueCheckpointForSubmission(result: CheckpointProposalResult): Promise<void> {
271
+ const { checkpoint, attestations, attestationsSignature } = result;
272
+
273
+ this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.targetSlot);
274
+ const aztecSlotDuration = this.l1Constants.slotDuration;
275
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
276
+ const txTimeoutAt = new Date((submissionSlotStart + aztecSlotDuration) * 1000);
277
+
278
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
279
+ if (
280
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
281
+ this.config.skipPublishingCheckpointsPercent > 0
282
+ ) {
283
+ const roll = Math.max(0, randomInt(100));
284
+ if (roll < this.config.skipPublishingCheckpointsPercent) {
285
+ this.log.warn(
286
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${roll}`,
287
+ );
288
+ return;
289
+ }
290
+ }
291
+
292
+ const isPipelining = this.epochCache.isProposerPipeliningEnabled();
293
+ const submissionSimulationOverridesPlan = buildSubmissionSimulationOverridesPlan({
294
+ pipelinedParentPlan: this.pipelinedParentSimulationOverridesPlan,
295
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
296
+ lastArchiveRoot: checkpoint.header.lastArchiveRoot,
297
+ pipeliningEnabled: isPipelining,
298
+ });
299
+
300
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
301
+ txTimeoutAt,
302
+ ...(submissionSimulationOverridesPlan ? { simulationOverridesPlan: submissionSimulationOverridesPlan } : {}),
303
+ });
304
+ }
305
+
155
306
  @trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
156
307
  return {
157
308
  // nullish operator needed for tests
158
309
  [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
159
- [Attributes.SLOT_NUMBER]: this.slot,
310
+ [Attributes.SLOT_NUMBER]: this.targetSlot,
160
311
  };
161
312
  })
162
- private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
313
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
163
314
  try {
315
+ const now = this.dateProvider.now();
316
+ if (this.epochCache.isProposerPipeliningEnabled() && this.proposedCheckpointData) {
317
+ // Measure against the wall-clock slot whose build window we are currently using.
318
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
319
+ // target-slot boundary a full slot away from the actual build start time.
320
+ const slotBoundaryMs = Number(getTimestampForSlot(this.slotNow, this.l1Constants)) * 1000;
321
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
322
+ }
323
+ this.checkpointMetrics.startCheckpointTiming(now);
324
+
164
325
  // Get operator configured coinbase and fee recipient for this attestor
165
326
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
166
327
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
167
328
 
168
329
  // Start the checkpoint
169
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
170
- this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
330
+ this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
331
+ this.log.info(`Starting checkpoint proposal`, {
332
+ buildSlot: this.slotNow,
333
+ submissionSlot: this.targetSlot,
334
+ pipelining: this.epochCache.isProposerPipeliningEnabled(),
335
+ proposer: this.proposer?.toString(),
336
+ coinbase: coinbase.toString(),
337
+ });
338
+ this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
171
339
 
172
340
  // Enqueues checkpoint invalidation (constant for the whole slot)
173
341
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
174
342
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
175
343
  }
176
344
 
177
- // Create checkpoint builder for the slot
345
+ // Create checkpoint builder for the slot.
346
+ // When pipelining, force the proposed checkpoint number and fee header to our parent so the
347
+ // fee computation sees the same chain tip that L1 will see once the previous pipelined checkpoint lands.
348
+ const isPipelining = this.epochCache.isProposerPipeliningEnabled();
349
+ this.pipelinedParentSimulationOverridesPlan = isPipelining
350
+ ? await buildPipelinedParentSimulationOverridesPlan({
351
+ checkpointNumber: this.checkpointNumber,
352
+ proposedCheckpointData: this.proposedCheckpointData,
353
+ rollup: this.publisher.rollupContract,
354
+ log: this.log,
355
+ })
356
+ : undefined;
357
+
178
358
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
179
359
  coinbase,
180
360
  feeRecipient,
181
- this.slot,
361
+ this.targetSlot,
362
+ this.pipelinedParentSimulationOverridesPlan,
182
363
  );
183
364
 
184
365
  // Collect L1 to L2 messages for the checkpoint and compute their hash
@@ -186,7 +367,7 @@ export class CheckpointProposalJob implements Traceable {
186
367
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
187
368
 
188
369
  // Collect the out hashes of all the checkpoints before this one in the same epoch
189
- const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.epoch))
370
+ const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.targetEpoch))
190
371
  .filter(c => c.checkpointNumber < this.checkpointNumber)
191
372
  .map(c => c.checkpointOutHash);
192
373
 
@@ -219,7 +400,7 @@ export class CheckpointProposalJob implements Traceable {
219
400
  };
220
401
 
221
402
  let blocksInCheckpoint: L2Block[] = [];
222
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
403
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
223
404
  const checkpointBuildTimer = new Timer();
224
405
 
225
406
  try {
@@ -243,8 +424,8 @@ export class CheckpointProposalJob implements Traceable {
243
424
  }
244
425
 
245
426
  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 });
427
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, { slot: this.targetSlot });
428
+ this.eventEmitter.emit('checkpoint-empty', { slot: this.targetSlot });
248
429
  return undefined;
249
430
  }
250
431
 
@@ -252,117 +433,81 @@ export class CheckpointProposalJob implements Traceable {
252
433
  if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
253
434
  this.log.warn(
254
435
  `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
255
- { slot: this.slot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
436
+ { slot: this.targetSlot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
256
437
  );
257
438
  return undefined;
258
439
  }
259
440
 
260
441
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
261
442
  // broadcasted yet, and wait to collect the committee attestations.
262
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
443
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
263
444
  const checkpoint = await checkpointBuilder.completeCheckpoint();
264
445
 
446
+ // Final validation: per-block limits are only checked if the operator set them explicitly.
447
+ // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
448
+ try {
449
+ validateCheckpoint(checkpoint, {
450
+ rollupManaLimit: this.l1Constants.rollupManaLimit,
451
+ maxL2BlockGas: this.config.maxL2BlockGas,
452
+ maxDABlockGas: this.config.maxDABlockGas,
453
+ maxTxsPerBlock: this.config.maxTxsPerBlock,
454
+ maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
455
+ });
456
+ } catch (err) {
457
+ this.log.error(`Built an invalid checkpoint at slot ${this.slotNow} (skipping proposal)`, err, {
458
+ checkpoint: checkpoint.header.toInspect(),
459
+ });
460
+ return undefined;
461
+ }
462
+
265
463
  // Record checkpoint-level build metrics
266
- this.metrics.recordCheckpointBuild(
464
+ this.checkpointMetrics.recordCheckpointBuild(
267
465
  checkpointBuildTimer.ms(),
268
466
  blocksInCheckpoint.length,
269
467
  checkpoint.getStats().txCount,
270
468
  Number(checkpoint.header.totalManaUsed.toBigInt()),
271
469
  );
272
470
 
273
- // Do not collect attestations nor publish to L1 in fisherman mode
471
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
274
472
  if (this.config.fishermanMode) {
275
473
  this.log.info(
276
- `Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` +
474
+ `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
277
475
  `Skipping proposal in fisherman mode.`,
278
476
  {
279
- slot: this.slot,
477
+ slot: this.targetSlot,
280
478
  checkpoint: checkpoint.header.toInspect(),
281
479
  blocksBuilt: blocksInCheckpoint.length,
282
480
  },
283
481
  );
284
482
  this.metrics.recordCheckpointSuccess();
285
- return checkpoint;
483
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
484
+ return { checkpoint, proposal: undefined!, blockProposedAt: this.dateProvider.now() };
286
485
  }
287
486
 
288
- // Include the block pending broadcast in the checkpoint proposal if any
289
- const lastBlock = blockPendingBroadcast && {
290
- blockHeader: blockPendingBroadcast.block.header,
291
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
292
- txs: blockPendingBroadcast.txs,
293
- };
294
-
295
487
  // Create the checkpoint proposal and broadcast it
296
488
  const proposal = await this.validatorClient.createCheckpointProposal(
297
489
  checkpoint.header,
298
490
  checkpoint.archive.root,
491
+ this.checkpointNumber,
299
492
  feeAssetPriceModifier,
300
- lastBlock,
493
+ blockPendingBroadcast,
301
494
  this.proposer,
302
495
  checkpointProposalOptions,
303
496
  );
304
497
 
305
498
  const blockProposedAt = this.dateProvider.now();
306
499
  await this.p2pClient.broadcastCheckpointProposal(proposal);
500
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
307
501
 
308
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
309
- const attestations = await this.waitForAttestations(proposal);
310
- const blockAttestedAt = this.dateProvider.now();
311
-
312
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
313
-
314
- // Proposer must sign over the attestations before pushing them to L1
315
- const signer = this.proposer ?? this.publisher.getSenderAddress();
316
- let attestationsSignature: Signature;
317
- try {
318
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
319
- attestations,
320
- signer,
321
- this.slot,
322
- this.checkpointNumber,
323
- );
324
- } catch (err) {
325
- // We shouldn't really get here since we yield to another HA node
326
- // as soon as we see these errors when creating block or checkpoint proposals.
327
- if (this.handleHASigningError(err, 'Attestations signature')) {
328
- return undefined;
329
- }
330
- throw err;
331
- }
332
-
333
- // Enqueue publishing the checkpoint to L1
334
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
335
- const aztecSlotDuration = this.l1Constants.slotDuration;
336
- const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
337
- const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
338
-
339
- // If we have been configured to potentially skip publishing checkpoint then roll the dice here
340
- if (
341
- this.config.skipPublishingCheckpointsPercent !== undefined &&
342
- this.config.skipPublishingCheckpointsPercent > 0
343
- ) {
344
- const result = Math.max(0, randomInt(100));
345
- if (result < this.config.skipPublishingCheckpointsPercent) {
346
- this.log.warn(
347
- `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${result}`,
348
- );
349
- return checkpoint;
350
- }
351
- }
352
-
353
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
354
- txTimeoutAt,
355
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
356
- });
357
-
358
- return checkpoint;
502
+ // Return immediately after broadcast — attestation collection happens in the background
503
+ return { checkpoint, proposal, blockProposedAt };
359
504
  } catch (err) {
360
505
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
361
506
  // swallow this error. It's already been logged by a function deeper in the stack
362
507
  return undefined;
363
508
  }
364
509
 
365
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
510
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
366
511
  return undefined;
367
512
  }
368
513
  }
@@ -378,17 +523,14 @@ export class CheckpointProposalJob implements Traceable {
378
523
  blockProposalOptions: BlockProposalOptions,
379
524
  ): Promise<{
380
525
  blocksInCheckpoint: L2Block[];
381
- blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
526
+ blockPendingBroadcast: BlockProposal | undefined;
382
527
  }> {
383
528
  const blocksInCheckpoint: L2Block[] = [];
384
529
  const txHashesAlreadyIncluded = new Set<string>();
385
530
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
386
531
 
387
- // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
388
- let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
389
-
390
532
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
391
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
533
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
392
534
 
393
535
  while (true) {
394
536
  const blocksBuilt = blocksInCheckpoint.length;
@@ -400,7 +542,7 @@ export class CheckpointProposalJob implements Traceable {
400
542
 
401
543
  if (!timingInfo.canStart) {
402
544
  this.log.debug(`Not enough time left in slot to start another block`, {
403
- slot: this.slot,
545
+ slot: this.targetSlot,
404
546
  blocksBuilt,
405
547
  secondsIntoSlot,
406
548
  });
@@ -419,25 +561,25 @@ export class CheckpointProposalJob implements Traceable {
419
561
  blockNumber,
420
562
  indexWithinCheckpoint,
421
563
  txHashesAlreadyIncluded,
422
- remainingBlobFields,
423
564
  });
424
565
 
425
- // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
426
- if (!buildResult && timingInfo.isLastBlock) {
427
- // If no block was produced due to not enough txs and this was the last subslot, exit
428
- break;
429
- } else if (!buildResult && timingInfo.deadline !== undefined) {
430
- // But if there is still time for more blocks, wait until the next subslot and try again
566
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
567
+ if ('failure' in buildResult) {
568
+ // If this was the last subslot, or we're running with a single block per slot, we're done
569
+ if (timingInfo.isLastBlock || timingInfo.deadline === undefined) {
570
+ break;
571
+ }
572
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
431
573
  await this.waitUntilNextSubslot(timingInfo.deadline);
432
574
  continue;
433
- } else if (!buildResult) {
434
- // Exit if there is no possibility of building more blocks
435
- break;
436
- } else if ('error' in buildResult) {
437
- // If there was an error building the block, just exit the loop and give up the rest of the slot
575
+ }
576
+
577
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
578
+ // We don't want to risk building more blocks if something went wrong.
579
+ if ('error' in buildResult) {
438
580
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
439
- this.log.warn(`Halting block building for slot ${this.slot}`, {
440
- slot: this.slot,
581
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
582
+ slot: this.targetSlot,
441
583
  blocksBuilt,
442
584
  error: buildResult.error,
443
585
  });
@@ -445,65 +587,81 @@ export class CheckpointProposalJob implements Traceable {
445
587
  break;
446
588
  }
447
589
 
448
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
449
- blocksInCheckpoint.push(block);
450
-
451
- // Update remaining blob fields for the next block
452
- remainingBlobFields = newRemainingBlobFields;
453
-
454
- // Sync the proposed block to the archiver to make it available
455
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
456
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
457
- // Fire and forget - don't block the critical path, but log errors
458
- this.syncProposedBlockToArchiver(block).catch(err => {
459
- this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
590
+ const { block, usedTxs } = buildResult;
591
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
592
+ isFirstBlock: blocksBuilt === 0,
593
+ isLastBlock: timingInfo.isLastBlock,
460
594
  });
461
595
 
596
+ blocksInCheckpoint.push(block);
462
597
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
463
598
 
464
- // If this is the last block, exit the loop now so we start collecting attestations
599
+ // Sign the block proposal. This will throw if HA signing fails.
600
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, blockProposalOptions);
601
+
602
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
603
+ // so we avoid polluting our archive with a block that would fail.
604
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
605
+ // If this throws, we abort the entire checkpoint.
606
+ await this.syncProposedBlockToArchiver(block);
607
+
608
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
465
609
  if (timingInfo.isLastBlock) {
466
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
467
- slot: this.slot,
610
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
611
+ slot: this.targetSlot,
468
612
  blockNumber,
469
613
  blocksBuilt,
470
614
  });
471
- blockPendingBroadcast = { block, txs: usedTxs };
615
+
616
+ blockPendingBroadcast = proposal;
472
617
  break;
473
618
  }
474
619
 
475
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
476
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
477
- if (!this.config.fishermanMode) {
478
- const proposal = await this.validatorClient.createBlockProposal(
479
- block.header,
480
- block.indexWithinCheckpoint,
481
- inHash,
482
- block.archive.root,
483
- usedTxs,
484
- this.proposer,
485
- blockProposalOptions,
486
- );
487
- await this.p2pClient.broadcastProposal(proposal);
488
- }
620
+ // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
621
+ proposal && (await this.p2pClient.broadcastProposal(proposal));
489
622
 
490
623
  // Wait until the next block's start time
491
624
  await this.waitUntilNextSubslot(timingInfo.deadline);
492
625
  }
493
626
 
494
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
495
- slot: this.slot,
627
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
628
+ slot: this.targetSlot,
496
629
  blocksBuilt: blocksInCheckpoint.length,
497
630
  });
498
631
 
499
632
  return { blocksInCheckpoint, blockPendingBroadcast };
500
633
  }
501
634
 
635
+ /** Creates a block proposal for a given block via the validator client (unless in fisherman mode) */
636
+ private createBlockProposal(
637
+ block: L2Block,
638
+ inHash: Fr,
639
+ usedTxs: Tx[],
640
+ blockProposalOptions: BlockProposalOptions,
641
+ ): Promise<BlockProposal | undefined> {
642
+ if (this.config.fishermanMode) {
643
+ this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
644
+ return Promise.resolve(undefined);
645
+ }
646
+ return this.validatorClient.createBlockProposal(
647
+ block.header,
648
+ this.checkpointNumber,
649
+ block.indexWithinCheckpoint,
650
+ inHash,
651
+ block.archive.root,
652
+ usedTxs,
653
+ this.proposer,
654
+ blockProposalOptions,
655
+ );
656
+ }
657
+
502
658
  /** Sleeps until it is time to produce the next block in the slot */
503
659
  @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
504
660
  private async waitUntilNextSubslot(nextSubslotStart: number) {
505
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
506
- this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
661
+ this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
662
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
663
+ slot: this.targetSlot,
664
+ });
507
665
  await this.waitUntilTimeInSlot(nextSubslotStart);
508
666
  }
509
667
 
@@ -518,36 +676,29 @@ export class CheckpointProposalJob implements Traceable {
518
676
  indexWithinCheckpoint: IndexWithinCheckpoint;
519
677
  buildDeadline: Date | undefined;
520
678
  txHashesAlreadyIncluded: Set<string>;
521
- remainingBlobFields: number;
522
679
  },
523
- ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
524
- const {
525
- blockTimestamp,
526
- forceCreate,
527
- blockNumber,
528
- indexWithinCheckpoint,
529
- buildDeadline,
530
- txHashesAlreadyIncluded,
531
- remainingBlobFields,
532
- } = opts;
680
+ ): Promise<
681
+ { block: L2Block; usedTxs: Tx[] } | { failure: 'insufficient-txs' | 'insufficient-valid-txs' } | { error: Error }
682
+ > {
683
+ const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
684
+ opts;
533
685
 
534
686
  this.log.verbose(
535
- `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
687
+ `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot}`,
536
688
  { ...checkpointBuilder.getConstantData(), ...opts },
537
689
  );
538
690
 
539
691
  try {
540
692
  // Wait until we have enough txs to build the block
541
- const minTxs = this.config.minTxsPerBlock;
542
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
693
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
543
694
  if (!canStartBuilding) {
544
695
  this.log.warn(
545
- `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
546
- { blockNumber, slot: this.slot, indexWithinCheckpoint },
696
+ `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (got ${availableTxs} txs but needs ${minTxs})`,
697
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
547
698
  );
548
- this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.slot });
699
+ this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.targetSlot });
549
700
  this.metrics.recordBlockProposalFailed('insufficient_txs');
550
- return undefined;
701
+ return { failure: 'insufficient-txs' };
551
702
  }
552
703
 
553
704
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
@@ -558,24 +709,31 @@ export class CheckpointProposalJob implements Traceable {
558
709
  );
559
710
 
560
711
  this.log.debug(
561
- `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
562
- { slot: this.slot, blockNumber, indexWithinCheckpoint },
712
+ `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`,
713
+ { slot: this.targetSlot, blockNumber, indexWithinCheckpoint },
563
714
  );
564
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
715
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
565
716
 
566
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
567
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
568
- const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
569
-
570
- const blockBuilderOptions: PublicProcessorLimits = {
717
+ // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
718
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
719
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
720
+ const minValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
721
+ const blockBuilderOptions: BlockBuilderOptions = {
571
722
  maxTransactions: this.config.maxTxsPerBlock,
572
- maxBlockSize: this.config.maxBlockSizeInBytes,
573
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
574
- maxBlobFields: maxBlobFieldsForTxs,
723
+ maxBlockGas:
724
+ this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined
725
+ ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity)
726
+ : undefined,
575
727
  deadline: buildDeadline,
728
+ isBuildingProposal: true,
729
+ minValidTxs,
730
+ maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
731
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
576
732
  };
577
733
 
578
- // Actually build the block by executing txs
734
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
735
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
736
+ // updated for blocks that will be discarded.
579
737
  const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
580
738
  checkpointBuilder,
581
739
  pendingTxs,
@@ -587,22 +745,27 @@ export class CheckpointProposalJob implements Traceable {
587
745
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
588
746
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
589
747
 
590
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
591
- // too long, then we may not get to minTxsPerBlock after executing public functions.
592
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
593
- const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
594
- if (buildResult.status === 'no-valid-txs' || (!forceCreate && numTxs < minValidTxs)) {
748
+ if (buildResult.status === 'insufficient-valid-txs') {
595
749
  this.log.warn(
596
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
597
- { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint, minValidTxs, buildResult: buildResult.status },
750
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`,
751
+ {
752
+ slot: this.targetSlot,
753
+ blockNumber,
754
+ numTxs: buildResult.processedCount,
755
+ indexWithinCheckpoint,
756
+ minValidTxs,
757
+ },
598
758
  );
599
- this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
759
+ this.eventEmitter.emit('block-build-failed', {
760
+ reason: `Insufficient valid txs`,
761
+ slot: this.targetSlot,
762
+ });
600
763
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
601
- return undefined;
764
+ return { failure: 'insufficient-valid-txs' };
602
765
  }
603
766
 
604
767
  // Block creation succeeded, emit stats and metrics
605
- const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
768
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
606
769
 
607
770
  const blockStats = {
608
771
  eventName: 'l2-block-built',
@@ -613,33 +776,42 @@ export class CheckpointProposalJob implements Traceable {
613
776
 
614
777
  const blockHash = await block.hash();
615
778
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
616
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
779
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
617
780
 
618
781
  this.log.info(
619
- `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`,
782
+ `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot} with ${numTxs} txs`,
620
783
  { blockHash, txHashes, manaPerSec, ...blockStats },
621
784
  );
622
785
 
623
- this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
624
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
786
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
787
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
788
+ this.eventEmitter.emit('block-proposed', {
789
+ blockNumber: block.number,
790
+ slot: this.targetSlot,
791
+ buildSlot: this.slotNow,
792
+ });
793
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
625
794
 
626
- return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
795
+ return { block, usedTxs };
627
796
  } catch (err: any) {
628
- this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
629
- this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
797
+ this.eventEmitter.emit('block-build-failed', {
798
+ reason: err.message,
799
+ slot: this.targetSlot,
800
+ });
801
+ this.log.error(`Error building block`, err, { blockNumber, slot: this.targetSlot });
630
802
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
631
803
  this.metrics.recordFailedBlock();
632
804
  return { error: err };
633
805
  }
634
806
  }
635
807
 
636
- /** Uses the checkpoint builder to build a block, catching specific txs */
808
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
637
809
  private async buildSingleBlockWithCheckpointBuilder(
638
810
  checkpointBuilder: CheckpointBuilder,
639
811
  pendingTxs: AsyncIterable<Tx>,
640
812
  blockNumber: BlockNumber,
641
813
  blockTimestamp: bigint,
642
- blockBuilderOptions: PublicProcessorLimits,
814
+ blockBuilderOptions: BlockBuilderOptions,
643
815
  ) {
644
816
  try {
645
817
  const workTimer = new Timer();
@@ -647,8 +819,12 @@ export class CheckpointProposalJob implements Traceable {
647
819
  const blockBuildDuration = workTimer.ms();
648
820
  return { ...result, blockBuildDuration, status: 'success' as const };
649
821
  } catch (err: unknown) {
650
- if (isErrorClass(err, NoValidTxsError)) {
651
- return { failedTxs: err.failedTxs, status: 'no-valid-txs' as const };
822
+ if (isErrorClass(err, InsufficientValidTxsError)) {
823
+ return {
824
+ failedTxs: err.failedTxs,
825
+ processedCount: err.processedCount,
826
+ status: 'insufficient-valid-txs' as const,
827
+ };
652
828
  }
653
829
  throw err;
654
830
  }
@@ -661,7 +837,7 @@ export class CheckpointProposalJob implements Traceable {
661
837
  blockNumber: BlockNumber;
662
838
  indexWithinCheckpoint: IndexWithinCheckpoint;
663
839
  buildDeadline: Date | undefined;
664
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
840
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
665
841
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
666
842
 
667
843
  // We only allow a block with 0 txs in the first block of the checkpoint
@@ -678,20 +854,20 @@ export class CheckpointProposalJob implements Traceable {
678
854
  // If we're past deadline, or we have no deadline, give up
679
855
  const now = this.dateProvider.nowAsDate();
680
856
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
681
- return { canStartBuilding: false, availableTxs: availableTxs };
857
+ return { canStartBuilding: false, availableTxs, minTxs };
682
858
  }
683
859
 
684
860
  // Wait a bit before checking again
685
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
861
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
686
862
  this.log.verbose(
687
- `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
688
- { blockNumber, slot: this.slot, indexWithinCheckpoint },
863
+ `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`,
864
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
689
865
  );
690
866
  await this.waitForTxsPollingInterval();
691
867
  availableTxs = await this.p2pClient.getPendingTxCount();
692
868
  }
693
869
 
694
- return { canStartBuilding: true, availableTxs };
870
+ return { canStartBuilding: true, availableTxs, minTxs };
695
871
  }
696
872
 
697
873
  /**
@@ -717,16 +893,16 @@ export class CheckpointProposalJob implements Traceable {
717
893
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
718
894
  }
719
895
 
720
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
896
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
721
897
 
722
898
  if (this.config.skipCollectingAttestations) {
723
899
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
724
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
900
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
725
901
  return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
726
902
  }
727
903
 
728
904
  const attestationTimeAllowed = this.config.enforceTimeTable
729
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
905
+ ? this.timetable.getCheckpointAttestationDeadline()
730
906
  : this.l1Constants.slotDuration;
731
907
  const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
732
908
 
@@ -739,6 +915,7 @@ export class CheckpointProposalJob implements Traceable {
739
915
  proposal,
740
916
  numberOfRequiredAttestations,
741
917
  attestationDeadline,
918
+ this.checkpointNumber,
742
919
  );
743
920
 
744
921
  collectedAttestationsCount = attestations.length;
@@ -759,7 +936,12 @@ export class CheckpointProposalJob implements Traceable {
759
936
  const sorted = orderAttestations(trimmed, committee);
760
937
 
761
938
  // Manipulate the attestations if we've been configured to do so
762
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
939
+ if (
940
+ this.config.injectFakeAttestation ||
941
+ this.config.injectHighSValueAttestation ||
942
+ this.config.injectUnrecoverableSignatureAttestation ||
943
+ this.config.shuffleAttestationOrdering
944
+ ) {
763
945
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
764
946
  }
765
947
 
@@ -788,7 +970,11 @@ export class CheckpointProposalJob implements Traceable {
788
970
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
789
971
  );
790
972
 
791
- if (this.config.injectFakeAttestation) {
973
+ if (
974
+ this.config.injectFakeAttestation ||
975
+ this.config.injectHighSValueAttestation ||
976
+ this.config.injectUnrecoverableSignatureAttestation
977
+ ) {
792
978
  // Find non-empty attestations that are not from the proposer
793
979
  const nonProposerIndices: number[] = [];
794
980
  for (let i = 0; i < attestations.length; i++) {
@@ -798,8 +984,20 @@ export class CheckpointProposalJob implements Traceable {
798
984
  }
799
985
  if (nonProposerIndices.length > 0) {
800
986
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
801
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
802
- unfreeze(attestations[targetIndex]).signature = Signature.random();
987
+ if (this.config.injectHighSValueAttestation) {
988
+ this.log.warn(
989
+ `Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
990
+ );
991
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
992
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
993
+ this.log.warn(
994
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
995
+ );
996
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
997
+ } else {
998
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
999
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
1000
+ }
803
1001
  }
804
1002
  return new CommitteeAttestationsAndSigners(attestations);
805
1003
  }
@@ -808,11 +1006,20 @@ export class CheckpointProposalJob implements Traceable {
808
1006
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
809
1007
 
810
1008
  const shuffled = [...attestations];
811
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
812
- const valueI = shuffled[i];
813
- const valueJ = shuffled[j];
814
- shuffled[i] = valueJ;
815
- shuffled[j] = valueI;
1009
+
1010
+ // Find two non-proposer positions that both have non-empty signatures to swap.
1011
+ // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
1012
+ // signers array stays correctly aligned with L1's committee reconstruction.
1013
+ const swappable: number[] = [];
1014
+ for (let k = 0; k < shuffled.length; k++) {
1015
+ if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
1016
+ swappable.push(k);
1017
+ }
1018
+ }
1019
+ if (swappable.length >= 2) {
1020
+ const [i, j] = [swappable[0], swappable[1]];
1021
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
1022
+ }
816
1023
 
817
1024
  const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
818
1025
  return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
@@ -835,9 +1042,13 @@ export class CheckpointProposalJob implements Traceable {
835
1042
  * Adds the proposed block to the archiver so it's available via P2P.
836
1043
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
837
1044
  * would never receive its own block without this explicit sync.
1045
+ *
1046
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1047
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1048
+ * whenever the real proposer's block arrives from L1.
838
1049
  */
839
1050
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
840
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1051
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
841
1052
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
842
1053
  blockNumber: block.number,
843
1054
  slot: block.header.globalVariables.slotNumber,
@@ -855,19 +1066,19 @@ export class CheckpointProposalJob implements Traceable {
855
1066
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
856
1067
  // Perform L1 fee analysis before clearing requests
857
1068
  // The callback is invoked asynchronously after the next block is mined
858
- const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
1069
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, analysis =>
859
1070
  this.metrics.recordFishermanFeeAnalysis(analysis),
860
1071
  );
861
1072
 
862
1073
  if (checkpoint) {
863
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1074
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
864
1075
  ...checkpoint.toCheckpointInfo(),
865
1076
  ...checkpoint.getStats(),
866
1077
  feeAnalysisId: feeAnalysis?.id,
867
1078
  });
868
1079
  } else {
869
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
870
- slot: this.slot,
1080
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1081
+ slot: this.targetSlot,
871
1082
  feeAnalysisId: feeAnalysis?.id,
872
1083
  });
873
1084
  this.metrics.recordCheckpointProposalFailed('block_build_failed');
@@ -881,15 +1092,15 @@ export class CheckpointProposalJob implements Traceable {
881
1092
  */
882
1093
  private handleHASigningError(err: any, errorContext: string): boolean {
883
1094
  if (err instanceof DutyAlreadySignedError) {
884
- this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
885
- slot: this.slot,
1095
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1096
+ slot: this.targetSlot,
886
1097
  signedByNode: err.signedByNode,
887
1098
  });
888
1099
  return true;
889
1100
  }
890
1101
  if (err instanceof SlashingProtectionError) {
891
- this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
892
- slot: this.slot,
1102
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1103
+ slot: this.targetSlot,
893
1104
  existingMessageHash: err.existingMessageHash,
894
1105
  attemptedMessageHash: err.attemptedMessageHash,
895
1106
  });
@@ -912,7 +1123,7 @@ export class CheckpointProposalJob implements Traceable {
912
1123
  }
913
1124
 
914
1125
  private getSlotStartBuildTimestamp(): number {
915
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1126
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
916
1127
  }
917
1128
 
918
1129
  private getSecondsIntoSlot(): number {