@aztec/sequencer-client 0.0.1-commit.f650c0a5c → 0.0.1-commit.f7ea82942

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 (65) hide show
  1. package/dest/client/sequencer-client.d.ts +3 -1
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +3 -0
  4. package/dest/config.d.ts +1 -1
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +8 -11
  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 +4 -9
  14. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  15. package/dest/global_variable_builder/global_builder.js +3 -41
  16. package/dest/global_variable_builder/index.d.ts +3 -1
  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 +1 -1
  20. package/dest/publisher/config.d.ts.map +1 -1
  21. package/dest/publisher/config.js +2 -2
  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.d.ts +10 -28
  25. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  26. package/dest/publisher/sequencer-publisher.js +24 -43
  27. package/dest/sequencer/chain_state_overrides.d.ts +25 -0
  28. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  29. package/dest/sequencer/chain_state_overrides.js +39 -0
  30. package/dest/sequencer/checkpoint_proposal_job.d.ts +24 -21
  31. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  32. package/dest/sequencer/checkpoint_proposal_job.js +263 -120
  33. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  34. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  35. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  36. package/dest/sequencer/events.d.ts +6 -1
  37. package/dest/sequencer/events.d.ts.map +1 -1
  38. package/dest/sequencer/metrics.d.ts +7 -10
  39. package/dest/sequencer/metrics.d.ts.map +1 -1
  40. package/dest/sequencer/metrics.js +27 -20
  41. package/dest/sequencer/sequencer.d.ts +5 -2
  42. package/dest/sequencer/sequencer.d.ts.map +1 -1
  43. package/dest/sequencer/sequencer.js +15 -11
  44. package/dest/sequencer/timetable.d.ts +11 -1
  45. package/dest/sequencer/timetable.d.ts.map +1 -1
  46. package/dest/sequencer/timetable.js +42 -43
  47. package/package.json +27 -27
  48. package/src/client/sequencer-client.ts +5 -0
  49. package/src/config.ts +8 -11
  50. package/src/global_variable_builder/README.md +44 -0
  51. package/src/global_variable_builder/fee_predictor.ts +172 -0
  52. package/src/global_variable_builder/fee_provider.ts +75 -0
  53. package/src/global_variable_builder/global_builder.ts +7 -54
  54. package/src/global_variable_builder/index.ts +2 -0
  55. package/src/publisher/config.ts +6 -4
  56. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  57. package/src/publisher/sequencer-publisher.ts +49 -83
  58. package/src/sequencer/README.md +9 -8
  59. package/src/sequencer/chain_state_overrides.ts +87 -0
  60. package/src/sequencer/checkpoint_proposal_job.ts +328 -162
  61. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  62. package/src/sequencer/events.ts +5 -0
  63. package/src/sequencer/metrics.ts +35 -25
  64. package/src/sequencer/sequencer.ts +22 -11
  65. package/src/sequencer/timetable.ts +50 -49
@@ -1,5 +1,5 @@
1
1
  import type { EpochCache } from '@aztec/epoch-cache';
2
- import { type FeeHeader, RollupContract } from '@aztec/ethereum/contracts';
2
+ import type { SimulationOverridesPlan } from '@aztec/ethereum/contracts';
3
3
  import {
4
4
  BlockNumber,
5
5
  CheckpointNumber,
@@ -18,6 +18,7 @@ import { EthAddress } from '@aztec/foundation/eth-address';
18
18
  import { Signature } from '@aztec/foundation/eth-signature';
19
19
  import { filter } from '@aztec/foundation/iterator';
20
20
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
21
+ import { retryUntil } from '@aztec/foundation/retry';
21
22
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
22
23
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
23
24
  import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
@@ -30,6 +31,7 @@ import {
30
31
  type L2BlockSink,
31
32
  type L2BlockSource,
32
33
  MaliciousCommitteeAttestationsAndSigners,
34
+ type ValidateCheckpointResult,
33
35
  } from '@aztec/stdlib/block';
34
36
  import { type Checkpoint, type ProposedCheckpointData, validateCheckpoint } from '@aztec/stdlib/checkpoint';
35
37
  import { computeQuorum, getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
@@ -57,6 +59,11 @@ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validato
57
59
 
58
60
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
59
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';
60
67
  import { CheckpointVoter } from './checkpoint_voter.js';
61
68
  import { SequencerInterruptedError } from './errors.js';
62
69
  import type { SequencerEvents } from './events.js';
@@ -68,7 +75,14 @@ import { SequencerState } from './utils.js';
68
75
  /** How much time to sleep while waiting for min transactions to accumulate for a block */
69
76
  const TXS_POLLING_MS = 500;
70
77
 
71
- /** Result from proposeCheckpoint when a checkpoint was successfully built and attested. */
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. */
72
86
  type CheckpointProposalResult = {
73
87
  checkpoint: Checkpoint;
74
88
  attestations: CommitteeAttestationsAndSigners;
@@ -87,8 +101,8 @@ export class CheckpointProposalJob implements Traceable {
87
101
  /** Tracks the fire-and-forget L1 submission promise so it can be awaited during shutdown. */
88
102
  private pendingL1Submission: Promise<void> | undefined;
89
103
 
90
- /** Fee header override computed during proposeCheckpoint, reused in enqueueCheckpointForSubmission. */
91
- private computedForceProposedFeeHeader?: { checkpointNumber: CheckpointNumber; feeHeader: FeeHeader };
104
+ /** Pipelined parent chain state used while building and later submitting this checkpoint. */
105
+ private pipelinedParentSimulationOverridesPlan?: SimulationOverridesPlan;
92
106
 
93
107
  constructor(
94
108
  private readonly slotNow: SlotNumber,
@@ -116,7 +130,8 @@ export class CheckpointProposalJob implements Traceable {
116
130
  private readonly epochCache: EpochCache,
117
131
  private readonly dateProvider: DateProvider,
118
132
  private readonly metrics: SequencerMetrics,
119
- private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
133
+ private readonly checkpointMetrics: CheckpointProposalJobMetricsRecorder,
134
+ protected readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
120
135
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
121
136
  public readonly tracer: Tracer,
122
137
  bindings?: LoggerBindings,
@@ -136,8 +151,9 @@ export class CheckpointProposalJob implements Traceable {
136
151
 
137
152
  /**
138
153
  * Executes the checkpoint proposal job.
139
- * Builds blocks, collects attestations, enqueues requests, and schedules L1 submission as a
140
- * background task so the work loop can return to IDLE immediately.
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.
141
157
  * Returns the built checkpoint if successful, undefined otherwise.
142
158
  */
143
159
  @trackSpan('CheckpointProposalJob.execute')
@@ -157,71 +173,100 @@ export class CheckpointProposalJob implements Traceable {
157
173
  this.log,
158
174
  ).enqueueVotes();
159
175
 
160
- // Build and propose the checkpoint. Builds blocks, broadcasts, collects attestations, and signs.
161
- // Does NOT enqueue to L1 yet that happens after the pipeline sleep.
162
- const proposalResult = await this.proposeCheckpoint();
163
- const checkpoint = proposalResult?.checkpoint;
164
-
165
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
166
- await Promise.all(votesPromises);
176
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
177
+ // Returns after broadcastattestation collection is deferred.
178
+ const broadcast = await this.proposeCheckpoint();
167
179
 
168
- if (checkpoint) {
169
- this.metrics.recordCheckpointProposalSuccess();
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;
170
187
  }
171
188
 
189
+ const { checkpoint } = broadcast;
190
+ this.metrics.recordCheckpointProposalSuccess();
191
+
172
192
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
173
193
  if (this.config.fishermanMode) {
174
194
  await this.handleCheckpointEndAsFisherman(checkpoint);
175
- return;
195
+ return checkpoint;
176
196
  }
177
197
 
178
- // Enqueue the checkpoint for L1 submission
179
- if (proposalResult) {
180
- try {
181
- await this.enqueueCheckpointForSubmission(proposalResult);
182
- } catch (err) {
183
- this.log.error(`Failed to enqueue checkpoint for L1 submission at slot ${this.targetSlot}`, err);
184
- // Continue to sendRequestsAt so votes are still sent
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 });
185
227
  }
186
- }
187
228
 
188
- // Compute the earliest time to submit: pipeline slot start when pipelining, now otherwise.
189
- const submitAfter = this.epochCache.isProposerPipeliningEnabled()
190
- ? new Date(Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) * 1000)
191
- : new Date(this.dateProvider.now());
192
-
193
- // Schedule L1 submission in the background so the work loop returns immediately.
194
- // The publisher will sleep until submitAfter, then send the bundled requests.
195
- // The promise is stored so it can be awaited during shutdown.
196
- this.pendingL1Submission = this.publisher
197
- .sendRequestsAt(submitAfter)
198
- .then(async l1Response => {
199
- const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
200
- if (proposedAction) {
201
- this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
202
- const coinbase = checkpoint?.header.coinbase;
203
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
204
- } else if (checkpoint) {
205
- this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
206
-
207
- if (this.epochCache.isProposerPipeliningEnabled()) {
208
- this.metrics.recordPipelineDiscard();
209
- }
210
- }
211
- })
212
- .catch(err => {
213
- this.log.error(`Background L1 submission failed for slot ${this.targetSlot}`, err);
214
- if (checkpoint) {
215
- this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
216
-
217
- if (this.epochCache.isProposerPipeliningEnabled()) {
218
- this.metrics.recordPipelineDiscard();
219
- }
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);
220
239
  }
221
- });
240
+ }
222
241
 
223
- // Return the built checkpoint immediately the work loop is now unblocked
224
- return checkpoint;
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
+ }
225
270
  }
226
271
 
227
272
  /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */
@@ -247,13 +292,155 @@ export class CheckpointProposalJob implements Traceable {
247
292
  }
248
293
  }
249
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
+
250
303
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
251
304
  txTimeoutAt,
252
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
253
- forceProposedFeeHeader: this.computedForceProposedFeeHeader,
305
+ ...(submissionSimulationOverridesPlan ? { simulationOverridesPlan: submissionSimulationOverridesPlan } : {}),
254
306
  });
255
307
  }
256
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
+ });
441
+ }
442
+ }
443
+
257
444
  @trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
258
445
  return {
259
446
  // nullish operator needed for tests
@@ -261,8 +448,18 @@ export class CheckpointProposalJob implements Traceable {
261
448
  [Attributes.SLOT_NUMBER]: this.targetSlot,
262
449
  };
263
450
  })
264
- private async proposeCheckpoint(): Promise<CheckpointProposalResult | undefined> {
451
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
265
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
+
266
463
  // Get operator configured coinbase and fee recipient for this attestor
267
464
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
268
465
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
@@ -287,21 +484,20 @@ export class CheckpointProposalJob implements Traceable {
287
484
  // When pipelining, force the proposed checkpoint number and fee header to our parent so the
288
485
  // fee computation sees the same chain tip that L1 will see once the previous pipelined checkpoint lands.
289
486
  const isPipelining = this.epochCache.isProposerPipeliningEnabled();
290
- const parentCheckpointNumber = isPipelining ? CheckpointNumber(this.checkpointNumber - 1) : undefined;
291
-
292
- // Compute the parent's fee header override when pipelining
293
- if (isPipelining && this.proposedCheckpointData) {
294
- this.computedForceProposedFeeHeader = await this.computeForceProposedFeeHeader(parentCheckpointNumber!);
295
- }
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;
296
495
 
297
496
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
298
497
  coinbase,
299
498
  feeRecipient,
300
499
  this.targetSlot,
301
- {
302
- forcePendingCheckpointNumber: parentCheckpointNumber,
303
- forceProposedFeeHeader: this.computedForceProposedFeeHeader,
304
- },
500
+ this.pipelinedParentSimulationOverridesPlan,
305
501
  );
306
502
 
307
503
  // Collect L1 to L2 messages for the checkpoint and compute their hash
@@ -403,14 +599,14 @@ export class CheckpointProposalJob implements Traceable {
403
599
  }
404
600
 
405
601
  // Record checkpoint-level build metrics
406
- this.metrics.recordCheckpointBuild(
602
+ this.checkpointMetrics.recordCheckpointBuild(
407
603
  checkpointBuildTimer.ms(),
408
604
  blocksInCheckpoint.length,
409
605
  checkpoint.getStats().txCount,
410
606
  Number(checkpoint.header.totalManaUsed.toBigInt()),
411
607
  );
412
608
 
413
- // Do not collect attestations nor publish to L1 in fisherman mode
609
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
414
610
  if (this.config.fishermanMode) {
415
611
  this.log.info(
416
612
  `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
@@ -422,17 +618,15 @@ export class CheckpointProposalJob implements Traceable {
422
618
  },
423
619
  );
424
620
  this.metrics.recordCheckpointSuccess();
425
- return {
426
- checkpoint,
427
- attestations: CommitteeAttestationsAndSigners.empty(),
428
- attestationsSignature: Signature.empty(),
429
- };
621
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
622
+ return { checkpoint, proposal: undefined!, blockProposedAt: this.dateProvider.now() };
430
623
  }
431
624
 
432
625
  // Create the checkpoint proposal and broadcast it
433
626
  const proposal = await this.validatorClient.createCheckpointProposal(
434
627
  checkpoint.header,
435
628
  checkpoint.archive.root,
629
+ this.checkpointNumber,
436
630
  feeAssetPriceModifier,
437
631
  blockPendingBroadcast,
438
632
  this.proposer,
@@ -441,34 +635,10 @@ export class CheckpointProposalJob implements Traceable {
441
635
 
442
636
  const blockProposedAt = this.dateProvider.now();
443
637
  await this.p2pClient.broadcastCheckpointProposal(proposal);
638
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
444
639
 
445
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.targetSlot);
446
- const attestations = await this.waitForAttestations(proposal);
447
- const blockAttestedAt = this.dateProvider.now();
448
-
449
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
450
-
451
- // Proposer must sign over the attestations before pushing them to L1
452
- const signer = this.proposer ?? this.publisher.getSenderAddress();
453
- let attestationsSignature: Signature;
454
- try {
455
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
456
- attestations,
457
- signer,
458
- this.targetSlot,
459
- this.checkpointNumber,
460
- );
461
- } catch (err) {
462
- // We shouldn't really get here since we yield to another HA node
463
- // as soon as we see these errors when creating block or checkpoint proposals.
464
- if (this.handleHASigningError(err, 'Attestations signature')) {
465
- return undefined;
466
- }
467
- throw err;
468
- }
469
-
470
- // Return the result for the caller to enqueue after the pipeline sleep
471
- return { checkpoint, attestations, attestationsSignature };
640
+ // Return immediately after broadcast — attestation collection happens in the background
641
+ return { checkpoint, proposal, blockProposedAt };
472
642
  } catch (err) {
473
643
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
474
644
  // swallow this error. It's already been logged by a function deeper in the stack
@@ -556,6 +726,11 @@ export class CheckpointProposalJob implements Traceable {
556
726
  }
557
727
 
558
728
  const { block, usedTxs } = buildResult;
729
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
730
+ isFirstBlock: blocksBuilt === 0,
731
+ isLastBlock: timingInfo.isLastBlock,
732
+ });
733
+
559
734
  blocksInCheckpoint.push(block);
560
735
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
561
736
 
@@ -575,6 +750,7 @@ export class CheckpointProposalJob implements Traceable {
575
750
  blockNumber,
576
751
  blocksBuilt,
577
752
  });
753
+
578
754
  blockPendingBroadcast = proposal;
579
755
  break;
580
756
  }
@@ -607,6 +783,7 @@ export class CheckpointProposalJob implements Traceable {
607
783
  }
608
784
  return this.validatorClient.createBlockProposal(
609
785
  block.header,
786
+ this.checkpointNumber,
610
787
  block.indexWithinCheckpoint,
611
788
  inHash,
612
789
  block.archive.root,
@@ -751,7 +928,7 @@ export class CheckpointProposalJob implements Traceable {
751
928
  slot: this.targetSlot,
752
929
  buildSlot: this.slotNow,
753
930
  });
754
- this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
931
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
755
932
 
756
933
  return { block, usedTxs };
757
934
  } catch (err: any) {
@@ -831,12 +1008,44 @@ export class CheckpointProposalJob implements Traceable {
831
1008
  return { canStartBuilding: true, availableTxs, minTxs };
832
1009
  }
833
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
+ }
1039
+ }
1040
+
834
1041
  /**
835
1042
  * Waits for enough attestations to be collected via p2p.
836
1043
  * This is run after all blocks for the checkpoint have been built.
837
1044
  */
838
1045
  @trackSpan('CheckpointProposalJob.waitForAttestations')
839
- private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
1046
+ private async waitForAttestations(
1047
+ proposal: CheckpointProposal,
1048
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
840
1049
  if (this.config.fishermanMode) {
841
1050
  this.log.debug('Skipping attestation collection in fisherman mode');
842
1051
  return CommitteeAttestationsAndSigners.empty();
@@ -858,12 +1067,12 @@ export class CheckpointProposalJob implements Traceable {
858
1067
 
859
1068
  if (this.config.skipCollectingAttestations) {
860
1069
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
861
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
1070
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
862
1071
  return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
863
1072
  }
864
1073
 
865
1074
  const attestationTimeAllowed = this.config.enforceTimeTable
866
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
1075
+ ? this.timetable.getCheckpointAttestationDeadline()
867
1076
  : this.l1Constants.slotDuration;
868
1077
  const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
869
1078
 
@@ -876,6 +1085,7 @@ export class CheckpointProposalJob implements Traceable {
876
1085
  proposal,
877
1086
  numberOfRequiredAttestations,
878
1087
  attestationDeadline,
1088
+ this.checkpointNumber,
879
1089
  );
880
1090
 
881
1091
  collectedAttestationsCount = attestations.length;
@@ -909,8 +1119,14 @@ export class CheckpointProposalJob implements Traceable {
909
1119
  } catch (err) {
910
1120
  if (err && err instanceof AttestationTimeoutError) {
911
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);
912
1128
  }
913
- throw err;
1129
+ return undefined;
914
1130
  } finally {
915
1131
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
916
1132
  }
@@ -1069,56 +1285,6 @@ export class CheckpointProposalJob implements Traceable {
1069
1285
  return false;
1070
1286
  }
1071
1287
 
1072
- /**
1073
- * In times of congestion we need to simulate using the correct fee header override for the previous block
1074
- * We calculate the correct fee header values.
1075
- *
1076
- * If we are in block 1, or the checkpoint we are querying does not exist, we return undefined. However
1077
- * If we are pipelining - where this function is called, the grandparentCheckpointNumber should always exist
1078
- * @param parentCheckpointNumber
1079
- * @returns
1080
- */
1081
- protected async computeForceProposedFeeHeader(parentCheckpointNumber: CheckpointNumber): Promise<
1082
- | {
1083
- checkpointNumber: CheckpointNumber;
1084
- feeHeader: FeeHeader;
1085
- }
1086
- | undefined
1087
- > {
1088
- if (!this.proposedCheckpointData) {
1089
- return undefined;
1090
- }
1091
-
1092
- const rollup = this.publisher.rollupContract;
1093
- const grandparentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 2);
1094
- try {
1095
- const [grandparentCheckpoint, manaTarget] = await Promise.all([
1096
- rollup.getCheckpoint(grandparentCheckpointNumber),
1097
- rollup.getManaTarget(),
1098
- ]);
1099
-
1100
- if (!grandparentCheckpoint || !grandparentCheckpoint.feeHeader) {
1101
- this.log.error(
1102
- `Grandparent checkpoint or its feeHeader is undefined for checkpointNumber=${grandparentCheckpointNumber.toString()}`,
1103
- );
1104
- return undefined;
1105
- } else {
1106
- const parentFeeHeader = RollupContract.computeChildFeeHeader(
1107
- grandparentCheckpoint.feeHeader,
1108
- this.proposedCheckpointData.totalManaUsed,
1109
- this.proposedCheckpointData.feeAssetPriceModifier,
1110
- manaTarget,
1111
- );
1112
- return { checkpointNumber: parentCheckpointNumber, feeHeader: parentFeeHeader };
1113
- }
1114
- } catch (err) {
1115
- this.log.error(
1116
- `Failed to fetch grandparent checkpoint or mana target for checkpointNumber=${grandparentCheckpointNumber.toString()}: ${err}`,
1117
- );
1118
- return undefined;
1119
- }
1120
- }
1121
-
1122
1288
  /** Waits until a specific time within the current slot */
1123
1289
  @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
1124
1290
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {