@aztec/sequencer-client 5.0.0-private.20260319 → 5.0.0-rc.2

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 (101) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +8 -3
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +17 -32
  5. package/dest/config.d.ts +10 -4
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +49 -25
  8. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  9. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  10. package/dest/global_variable_builder/fee_predictor.js +128 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_provider.js +67 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +13 -26
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +9 -67
  17. package/dest/global_variable_builder/index.d.ts +4 -2
  18. package/dest/global_variable_builder/index.d.ts.map +1 -1
  19. package/dest/global_variable_builder/index.js +2 -0
  20. package/dest/publisher/config.d.ts +19 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +30 -5
  23. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +3 -4
  24. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  25. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  26. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  27. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  28. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -5
  29. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  30. package/dest/publisher/sequencer-publisher-factory.js +2 -3
  31. package/dest/publisher/sequencer-publisher.d.ts +84 -65
  32. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher.js +403 -531
  34. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  35. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  36. package/dest/sequencer/automine/automine_factory.js +85 -0
  37. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  38. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  39. package/dest/sequencer/automine/automine_sequencer.js +689 -0
  40. package/dest/sequencer/automine/index.d.ts +3 -0
  41. package/dest/sequencer/automine/index.d.ts.map +1 -0
  42. package/dest/sequencer/automine/index.js +2 -0
  43. package/dest/sequencer/checkpoint_proposal_job.d.ts +73 -21
  44. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  45. package/dest/sequencer/checkpoint_proposal_job.js +709 -200
  46. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  47. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  48. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  49. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  50. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  51. package/dest/sequencer/checkpoint_voter.js +2 -5
  52. package/dest/sequencer/errors.d.ts +1 -8
  53. package/dest/sequencer/errors.d.ts.map +1 -1
  54. package/dest/sequencer/errors.js +0 -9
  55. package/dest/sequencer/events.d.ts +61 -4
  56. package/dest/sequencer/events.d.ts.map +1 -1
  57. package/dest/sequencer/metrics.d.ts +9 -10
  58. package/dest/sequencer/metrics.d.ts.map +1 -1
  59. package/dest/sequencer/metrics.js +34 -20
  60. package/dest/sequencer/sequencer.d.ts +117 -30
  61. package/dest/sequencer/sequencer.d.ts.map +1 -1
  62. package/dest/sequencer/sequencer.js +483 -158
  63. package/dest/sequencer/types.d.ts +2 -2
  64. package/dest/sequencer/types.d.ts.map +1 -1
  65. package/dest/test/index.d.ts +3 -3
  66. package/dest/test/index.d.ts.map +1 -1
  67. package/dest/test/utils.d.ts +15 -1
  68. package/dest/test/utils.d.ts.map +1 -1
  69. package/dest/test/utils.js +24 -7
  70. package/package.json +28 -27
  71. package/src/client/sequencer-client.ts +29 -41
  72. package/src/config.ts +58 -25
  73. package/src/global_variable_builder/README.md +44 -0
  74. package/src/global_variable_builder/fee_predictor.ts +172 -0
  75. package/src/global_variable_builder/fee_provider.ts +80 -0
  76. package/src/global_variable_builder/global_builder.ts +19 -89
  77. package/src/global_variable_builder/index.ts +3 -1
  78. package/src/publisher/config.ts +62 -7
  79. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  80. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  81. package/src/publisher/sequencer-publisher-factory.ts +3 -6
  82. package/src/publisher/sequencer-publisher.ts +456 -578
  83. package/src/sequencer/automine/README.md +60 -0
  84. package/src/sequencer/automine/automine_factory.ts +152 -0
  85. package/src/sequencer/automine/automine_sequencer.ts +795 -0
  86. package/src/sequencer/automine/index.ts +6 -0
  87. package/src/sequencer/checkpoint_proposal_job.ts +817 -225
  88. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  89. package/src/sequencer/checkpoint_voter.ts +1 -12
  90. package/src/sequencer/errors.ts +0 -15
  91. package/src/sequencer/events.ts +65 -4
  92. package/src/sequencer/metrics.ts +43 -24
  93. package/src/sequencer/sequencer.ts +557 -175
  94. package/src/sequencer/types.ts +1 -1
  95. package/src/test/index.ts +2 -2
  96. package/src/test/utils.ts +60 -10
  97. package/dest/sequencer/timetable.d.ts +0 -88
  98. package/dest/sequencer/timetable.d.ts.map +0 -1
  99. package/dest/sequencer/timetable.js +0 -222
  100. package/src/sequencer/README.md +0 -531
  101. package/src/sequencer/timetable.ts +0 -283
@@ -435,18 +435,20 @@ function applyDecs2203RFactory() {
435
435
  function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
436
436
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
437
437
  }
438
- var _dec, _dec1, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _initProto;
439
- import { BlockNumber, IndexWithinCheckpoint } from '@aztec/foundation/branded-types';
438
+ var _dec, _dec1, _dec2, _dec3, _dec4, _dec5, _dec6, _initProto;
439
+ import { PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
440
+ import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
440
441
  import { randomInt } from '@aztec/foundation/crypto/random';
441
442
  import { flipSignature, generateRecoverableSignature, generateUnrecoverableSignature } from '@aztec/foundation/crypto/secp256k1-signer';
443
+ import { InterruptError, TimeoutError } from '@aztec/foundation/error';
442
444
  import { filter } from '@aztec/foundation/iterator';
443
445
  import { createLogger } from '@aztec/foundation/log';
444
- import { sleep, sleepUntil } from '@aztec/foundation/sleep';
446
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
445
447
  import { Timer } from '@aztec/foundation/timer';
446
448
  import { isErrorClass, unfreeze } from '@aztec/foundation/types';
447
449
  import { CommitteeAttestationsAndSigners, MaliciousCommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
448
- import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
449
- import { getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
450
+ import { buildCheckpointSimulationOverridesPlan, getPreviousCheckpointOutHashes, validateCheckpoint } from '@aztec/stdlib/checkpoint';
451
+ import { computeQuorum, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
450
452
  import { Gas } from '@aztec/stdlib/gas';
451
453
  import { InsufficientValidTxsError } from '@aztec/stdlib/interfaces/server';
452
454
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
@@ -458,25 +460,25 @@ import { CheckpointVoter } from './checkpoint_voter.js';
458
460
  import { SequencerInterruptedError } from './errors.js';
459
461
  import { SequencerState } from './utils.js';
460
462
  /** How much time to sleep while waiting for min transactions to accumulate for a block */ const TXS_POLLING_MS = 500;
463
+ const ARCHIVER_SYNC_POLLING_MS = 200;
461
464
  _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('CheckpointProposalJob.proposeCheckpoint', function() {
462
465
  return {
463
466
  // nullish operator needed for tests
464
467
  [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
465
468
  [Attributes.SLOT_NUMBER]: this.targetSlot
466
469
  };
467
- }), _dec2 = trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint'), _dec3 = trackSpan('CheckpointProposalJob.waitUntilNextSubslot'), _dec4 = trackSpan('CheckpointProposalJob.buildSingleBlock'), _dec5 = trackSpan('CheckpointProposalJob.waitForMinTxs'), _dec6 = trackSpan('CheckpointProposalJob.waitForAttestations'), _dec7 = trackSpan('CheckpointProposalJob.waitUntilTimeInSlot');
470
+ }), _dec2 = trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint'), _dec3 = trackSpan('CheckpointProposalJob.waitUntilNextSubslot'), _dec4 = trackSpan('CheckpointProposalJob.buildSingleBlock'), _dec5 = trackSpan('CheckpointProposalJob.waitForMinTxs'), _dec6 = trackSpan('CheckpointProposalJob.waitForAttestations');
468
471
  /**
469
472
  * Handles the execution of a checkpoint proposal after the initial preparation phase.
470
473
  * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
471
474
  * as well as enqueueing votes for slashing and governance proposals. This class is created from
472
475
  * the Sequencer once the check for being the proposer for the slot has succeeded.
473
476
  */ export class CheckpointProposalJob {
474
- slotNow;
475
477
  targetSlot;
476
- epochNow;
477
478
  targetEpoch;
478
479
  checkpointNumber;
479
480
  syncedToBlockNumber;
481
+ checkpointedCheckpointNumber;
480
482
  proposer;
481
483
  publisher;
482
484
  attestorAddress;
@@ -490,15 +492,18 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
490
492
  checkpointsBuilder;
491
493
  blockSink;
492
494
  l1Constants;
495
+ signatureContext;
493
496
  config;
494
497
  timetable;
495
498
  slasherClient;
496
499
  epochCache;
497
500
  dateProvider;
498
501
  metrics;
502
+ checkpointMetrics;
499
503
  eventEmitter;
500
504
  setStateFn;
501
505
  tracer;
506
+ proposedCheckpointData;
502
507
  static{
503
508
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
504
509
  [
@@ -535,23 +540,30 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
535
540
  _dec6,
536
541
  2,
537
542
  "waitForAttestations"
538
- ],
539
- [
540
- _dec7,
541
- 2,
542
- "waitUntilTimeInSlot"
543
543
  ]
544
544
  ], []));
545
545
  }
546
546
  log;
547
- constructor(slotNow, targetSlot, epochNow, targetEpoch, checkpointNumber, syncedToBlockNumber, // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
548
- proposer, publisher, attestorAddress, invalidateCheckpoint, validatorClient, globalsBuilder, p2pClient, worldState, l1ToL2MessageSource, l2BlockSource, checkpointsBuilder, blockSink, l1Constants, config, timetable, slasherClient, epochCache, dateProvider, metrics, eventEmitter, setStateFn, tracer, bindings){
549
- this.slotNow = slotNow;
547
+ checkpointEventLog;
548
+ /** Tracks the fire-and-forget L1 submission promise so it can be awaited during shutdown. */ pendingL1Submission;
549
+ interruptibleSleep;
550
+ interrupted;
551
+ /**
552
+ * Chain state overrides built once per slot in proposeCheckpoint after the checkpoint is
553
+ * complete. Carries the pending parent override (archive + slot + fee header) for pipelining,
554
+ * or the invalidation pending override when rolling back. Consumed by
555
+ * publisher.validateBlockHeader before broadcast.
556
+ */ checkpointSimulationOverridesPlan;
557
+ getSignatureContext() {
558
+ return this.signatureContext;
559
+ }
560
+ constructor(targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
561
+ proposer, publisher, attestorAddress, invalidateCheckpoint, validatorClient, globalsBuilder, p2pClient, worldState, l1ToL2MessageSource, l2BlockSource, checkpointsBuilder, blockSink, l1Constants, signatureContext, config, timetable, slasherClient, epochCache, dateProvider, metrics, checkpointMetrics, eventEmitter, setStateFn, tracer, bindings, proposedCheckpointData){
550
562
  this.targetSlot = targetSlot;
551
- this.epochNow = epochNow;
552
563
  this.targetEpoch = targetEpoch;
553
564
  this.checkpointNumber = checkpointNumber;
554
565
  this.syncedToBlockNumber = syncedToBlockNumber;
566
+ this.checkpointedCheckpointNumber = checkpointedCheckpointNumber;
555
567
  this.proposer = proposer;
556
568
  this.publisher = publisher;
557
569
  this.attestorAddress = attestorAddress;
@@ -565,82 +577,354 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
565
577
  this.checkpointsBuilder = checkpointsBuilder;
566
578
  this.blockSink = blockSink;
567
579
  this.l1Constants = l1Constants;
580
+ this.signatureContext = signatureContext;
568
581
  this.config = config;
569
582
  this.timetable = timetable;
570
583
  this.slasherClient = slasherClient;
571
584
  this.epochCache = epochCache;
572
585
  this.dateProvider = dateProvider;
573
586
  this.metrics = metrics;
587
+ this.checkpointMetrics = checkpointMetrics;
574
588
  this.eventEmitter = eventEmitter;
575
589
  this.setStateFn = setStateFn;
576
590
  this.tracer = tracer;
577
- _initProto(this);
591
+ this.proposedCheckpointData = proposedCheckpointData;
592
+ this.interruptibleSleep = (_initProto(this), new InterruptibleSleep());
593
+ this.interrupted = false;
578
594
  this.log = createLogger('sequencer:checkpoint-proposal', {
579
595
  ...bindings,
580
- instanceId: `slot-${this.slotNow}`
596
+ instanceId: `slot-${this.getBuildSlot()}`
597
+ });
598
+ this.checkpointEventLog = createLogger('sequencer:checkpoint-events', {
599
+ ...bindings,
600
+ instanceId: `slot-${this.getBuildSlot()}`
581
601
  });
582
602
  }
583
- /** The wall-clock slot during which the proposer builds. */ get slot() {
584
- return this.slotNow;
603
+ /**
604
+ * The wall-clock slot during which this job builds, i.e. the slot one before {@link targetSlot} under
605
+ * proposer pipelining. Also the slot of the parent checkpoint this job builds on top of.
606
+ */ getBuildSlot() {
607
+ return SlotNumber(this.targetSlot - PROPOSER_PIPELINING_SLOT_OFFSET);
608
+ }
609
+ /**
610
+ * Sets the sequencer state for this job, reporting the target slot the checkpoint is being proposed for
611
+ * (not the wall-clock build slot). The slot is informational on the event payload/metrics; the job knows
612
+ * its own target slot, so callers only pass the state.
613
+ */ setState(state) {
614
+ this.setStateFn(state, this.targetSlot);
615
+ }
616
+ /** Awaits the pending L1 submission if one is in progress. Call during shutdown. */ async awaitPendingSubmission() {
617
+ this.log.info('Awaiting pending L1 payload submission');
618
+ await this.pendingL1Submission;
585
619
  }
586
- /** The wall-clock epoch. */ get epoch() {
587
- return this.epochNow;
620
+ /** Interrupts job-owned waits, including the publisher's send-at-slot sleep, so shutdown can finish. */ interrupt() {
621
+ this.interrupted = true;
622
+ this.interruptibleSleep.interrupt(true);
623
+ this.publisher.interrupt();
624
+ }
625
+ async awaitInterruptibleSleep(ms) {
626
+ if (this.interrupted) {
627
+ throw new SequencerInterruptedError();
628
+ }
629
+ if (ms <= 0) {
630
+ return;
631
+ }
632
+ try {
633
+ await this.interruptibleSleep.sleep(ms);
634
+ } catch (err) {
635
+ if (err instanceof InterruptError) {
636
+ throw new SequencerInterruptedError();
637
+ }
638
+ throw err;
639
+ }
640
+ }
641
+ logCheckpointEvent(eventName, message, fields) {
642
+ this.checkpointEventLog.debug(message, {
643
+ eventName: `sequencer-checkpoint-${eventName}`,
644
+ ...fields
645
+ });
588
646
  }
589
647
  /**
590
648
  * Executes the checkpoint proposal job.
591
- * Returns the published checkpoint if successful, undefined otherwise.
649
+ * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
650
+ * Attestation collection, signing, and L1 submission are backgrounded so the
651
+ * work loop can return to IDLE immediately for consecutive slot proposals.
652
+ * Returns the built checkpoint if successful, undefined otherwise.
592
653
  */ async execute() {
593
654
  // Enqueue governance and slashing votes (returns promises that will be awaited later)
594
655
  // In fisherman mode, we simulate slashing but don't actually publish to L1
595
656
  // These are constant for the whole slot, so we only enqueue them once
596
657
  const votesPromises = new CheckpointVoter(this.targetSlot, this.publisher, this.attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log).enqueueVotes();
597
- // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
598
- const checkpoint = await this.proposeCheckpoint();
599
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
600
- await Promise.all(votesPromises);
601
- if (checkpoint) {
602
- this.metrics.recordCheckpointProposalSuccess();
658
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
659
+ // Returns after broadcast — attestation collection is deferred.
660
+ const broadcast = await this.proposeCheckpoint();
661
+ if (!broadcast) {
662
+ await Promise.all(votesPromises);
663
+ // Still submit votes even without a checkpoint.
664
+ // Under proposer pipelining, vote-offenses signatures are EIP-712-bound to `targetSlot`
665
+ // (the pipelined slot in which the multicall is expected to mine). Submitting at the
666
+ // wall-clock time would let the multicall mine in a different L2 slot, causing
667
+ // signature verification to fail silently inside Multicall3. Delay submission to the
668
+ // start of `targetSlot` so the tx mines in the slot the vote was signed for.
669
+ if (!this.config.fishermanMode) {
670
+ this.pendingL1Submission = this.publisher.sendRequestsAt(this.targetSlot).then(()=>{});
671
+ }
672
+ return undefined;
603
673
  }
674
+ const { checkpoint } = broadcast;
675
+ this.metrics.recordCheckpointProposalSuccess();
604
676
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
605
677
  if (this.config.fishermanMode) {
606
678
  await this.handleCheckpointEndAsFisherman(checkpoint);
607
- return;
679
+ return checkpoint;
608
680
  }
609
- // If pipelining, wait until the submission slot so L1 recognizes the pipelined proposer
610
- if (this.epochCache.isProposerPipeliningEnabled()) {
611
- const submissionSlotTimestamp = getTimestampForSlot(this.targetSlot, this.l1Constants) - BigInt(this.l1Constants.ethereumSlotDuration);
612
- this.log.info(`Waiting until submission slot ${this.targetSlot} for L1 submission`, {
613
- slot: this.slot,
614
- submissionSlot: this.targetSlot,
615
- submissionSlotTimestamp
681
+ // Background the attestation signing L1 pipeline so the work loop is unblocked
682
+ this.pendingL1Submission = this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises);
683
+ // Return the built checkpoint immediately — the work loop is now unblocked
684
+ return checkpoint;
685
+ }
686
+ /**
687
+ * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
688
+ * Runs as a fire-and-forget task stored in `pendingL1Submission` so the work loop is unblocked.
689
+ */ async waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises) {
690
+ const { checkpoint } = broadcast;
691
+ try {
692
+ // Wait for all votes actions, enqueued at the beginning, to resolve
693
+ await Promise.all(votesPromises);
694
+ // Try to collect attestations from the committee
695
+ const signedAttestations = await this.getSignedCommitteeAttestations(broadcast);
696
+ // Wait for the previous checkpoint to land on L1 before submitting, so we can check it
697
+ // matches the proposed checkpoint we used as parent, and has valid attestations.
698
+ if (signedAttestations && await this.waitForValidParentCheckpointOnL1()) {
699
+ await this.enqueueCheckpointForSubmission({
700
+ checkpoint,
701
+ ...signedAttestations
702
+ });
703
+ }
704
+ // If we failed to collect attestations, at least check if we need to issue an invalidation
705
+ if (!signedAttestations && await this.waitForSyncedL2SlotNumber(this.getBuildSlot())) {
706
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
707
+ if (!validationStatus.valid) {
708
+ this.log.warn(`Checkpoint ${validationStatus.checkpoint.checkpointNumber} has invalid attestations, enqueuing invalidation in spite of attestation collection failure`, {
709
+ checkpoint: validationStatus.checkpoint,
710
+ reason: validationStatus.reason
711
+ });
712
+ await this.enqueueInvalidation(validationStatus);
713
+ }
714
+ }
715
+ // Send whatever was enqueued: votes + (propose | invalidation | nothing).
716
+ const l1Response = await this.publisher.sendRequestsAt(this.targetSlot);
717
+ const proposedAction = l1Response?.successfulActions.find((a)=>a === 'propose');
718
+ if (proposedAction) {
719
+ this.logCheckpointEvent('published', `Checkpoint published for slot ${this.targetSlot}`, {
720
+ slot: this.targetSlot,
721
+ checkpointNumber: this.checkpointNumber,
722
+ successfulActions: l1Response?.successfulActions,
723
+ sentActions: l1Response?.sentActions
724
+ });
725
+ this.eventEmitter.emit('checkpoint-published', {
726
+ checkpoint: this.checkpointNumber,
727
+ slot: this.targetSlot
728
+ });
729
+ const coinbase = checkpoint.header.coinbase;
730
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
731
+ } else {
732
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
733
+ slot: this.targetSlot,
734
+ checkpointNumber: this.checkpointNumber,
735
+ successfulActions: l1Response?.successfulActions,
736
+ failedActions: l1Response?.failedActions,
737
+ sentActions: l1Response?.sentActions,
738
+ expiredActions: l1Response?.expiredActions,
739
+ reason: 'propose_action_not_successful'
740
+ });
741
+ this.log.warn(`Checkpoint publish failed for slot ${this.targetSlot}`, {
742
+ slot: this.targetSlot,
743
+ checkpointNumber: this.checkpointNumber,
744
+ successfulActions: l1Response?.successfulActions,
745
+ failedActions: l1Response?.failedActions,
746
+ sentActions: l1Response?.sentActions,
747
+ expiredActions: l1Response?.expiredActions,
748
+ reason: 'propose_action_not_successful'
749
+ });
750
+ this.eventEmitter.emit('checkpoint-publish-failed', {
751
+ ...l1Response,
752
+ slot: this.targetSlot
753
+ });
754
+ this.metrics.recordPipelineDiscard();
755
+ }
756
+ } catch (err) {
757
+ if (err instanceof SequencerInterruptedError) {
758
+ return;
759
+ }
760
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
761
+ slot: this.targetSlot,
762
+ checkpointNumber: this.checkpointNumber,
763
+ reason: err instanceof Error ? err.message : String(err)
616
764
  });
617
- await sleepUntil(new Date(Number(submissionSlotTimestamp) * 1000), this.dateProvider.nowAsDate());
618
- // After waking, verify the parent checkpoint wasn't pruned during the sleep.
619
- // We check L1's pending tip directly instead of canProposeAt, which also validates the proposer
620
- // identity and would fail because the timestamp resolves to a different slot's proposer.
621
- const l1Tips = await this.publisher.rollupContract.getTips();
622
- if (l1Tips.pending < this.checkpointNumber - 1) {
623
- this.log.warn(`Parent checkpoint was pruned during pipelining sleep (L1 pending=${l1Tips.pending}, expected>=${this.checkpointNumber - 1}), skipping L1 submission for checkpoint ${this.checkpointNumber}`);
624
- return undefined;
765
+ this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err, {
766
+ slot: this.targetSlot,
767
+ checkpointNumber: this.checkpointNumber,
768
+ reason: err instanceof Error ? err.message : String(err)
769
+ });
770
+ this.eventEmitter.emit('checkpoint-publish-failed', {
771
+ slot: this.targetSlot
772
+ });
773
+ this.metrics.recordPipelineDiscard();
774
+ }
775
+ }
776
+ /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */ async enqueueCheckpointForSubmission(result) {
777
+ const { checkpoint, attestations, attestationsSignature } = result;
778
+ this.setState(SequencerState.PUBLISHING_CHECKPOINT);
779
+ // Latest L1 block the propose can still land in for the target slot: the last Ethereum block inside
780
+ // the target slot (`target_slot_start + S - E`). This is one ethereum slot later than
781
+ // `attestation_deadline` (= last_ethereum_block_in_target_slot - E), which bounds when validators must
782
+ // have signed, not when the proposer must have sent. Using the attestation deadline here is too tight:
783
+ // attestations are collected up to (and, when not enforcing, past) it, so the propose tx would be
784
+ // enqueued already expired and time out before it can mine.
785
+ const lastL1BlockInTargetSlot = Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) + this.l1Constants.slotDuration - this.l1Constants.ethereumSlotDuration;
786
+ const txTimeoutAt = new Date(lastL1BlockInTargetSlot * 1000);
787
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
788
+ if (this.config.skipPublishingCheckpointsPercent !== undefined && this.config.skipPublishingCheckpointsPercent > 0) {
789
+ const roll = Math.max(0, randomInt(100));
790
+ if (roll < this.config.skipPublishingCheckpointsPercent) {
791
+ this.log.warn(`Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${roll}`);
792
+ return;
625
793
  }
626
794
  }
627
- // Then send everything to L1
628
- const l1Response = await this.publisher.sendRequests();
629
- const proposedAction = l1Response?.successfulActions.find((a)=>a === 'propose');
630
- if (proposedAction) {
631
- this.eventEmitter.emit('checkpoint-published', {
632
- checkpoint: this.checkpointNumber,
633
- slot: this.slot
795
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
796
+ txTimeoutAt
797
+ });
798
+ }
799
+ /**
800
+ * Wait until the archiver syncs past the given L2 slot number.
801
+ * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
802
+ * L1 submission window and is no longer useful.
803
+ */ async waitForSyncedL2SlotNumber(waitForSlot) {
804
+ const targetSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
805
+ const targetSlotEndMs = (targetSlotStart + this.l1Constants.slotDuration) * 1000;
806
+ const syncDelayTolerance = this.l1Constants.ethereumSlotDuration * 2 * 1000;
807
+ const timeoutSeconds = Math.max(0.1, (targetSlotEndMs + syncDelayTolerance - this.dateProvider.now()) / 1000);
808
+ try {
809
+ const timer = new Timer();
810
+ while(true){
811
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
812
+ if (syncedSlot !== undefined && syncedSlot >= waitForSlot) {
813
+ return true;
814
+ }
815
+ if (timeoutSeconds && timer.s() > timeoutSeconds) {
816
+ throw new TimeoutError(`Timeout awaiting archiver sync past slot ${waitForSlot}`);
817
+ }
818
+ await this.awaitInterruptibleSleep(ARCHIVER_SYNC_POLLING_MS);
819
+ }
820
+ } catch (err) {
821
+ if (err instanceof SequencerInterruptedError) {
822
+ throw err;
823
+ }
824
+ this.log.warn(`Archiver did not sync L1 past slot ${waitForSlot} before slot ${this.targetSlot} expired, discarding pipelined work`, {
825
+ checkpointNumber: this.checkpointNumber
634
826
  });
635
- const coinbase = checkpoint?.header.coinbase;
636
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
637
- return checkpoint;
638
- } else if (checkpoint) {
639
- this.eventEmitter.emit('checkpoint-publish-failed', {
640
- ...l1Response,
641
- slot: this.slot
827
+ this.emitPipelinedCheckpointDiscarded('archiver-sync-timeout');
828
+ return false;
829
+ }
830
+ }
831
+ /**
832
+ * Waits for the parent checkpoint to land on L1 before submitting a pipelined checkpoint.
833
+ * Polls until the archiver has synced L1 past the parent's slot, then verifies:
834
+ * - If we built on a proposed parent: it must have landed on L1 with matching hash and valid attestations.
835
+ * - If we built without a proposed parent: no new checkpoint must have appeared for that slot.
836
+ * If the parent has invalid attestations, enqueues an invalidation. Returns whether to proceed with the proposal.
837
+ */ async waitForValidParentCheckpointOnL1() {
838
+ if (this.config.skipWaitForValidParentCheckpointOnL1) {
839
+ this.log.warn(`Skipping waitForValidParentCheckpointOnL1 due to test configuration`, {
840
+ checkpointNumber: this.checkpointNumber
841
+ });
842
+ return true;
843
+ }
844
+ const parentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 1);
845
+ // Wait until archiver has synced L1 past the parent's slot (the build slot, one before targetSlot)
846
+ if (!await this.waitForSyncedL2SlotNumber(this.getBuildSlot())) {
847
+ return false;
848
+ }
849
+ const tips = await this.l2BlockSource.getL2Tips();
850
+ const checkpointedNumber = tips.checkpointed.checkpoint.number;
851
+ // We built on top of a proposed checkpoint. Verify it landed on L1 as expected.
852
+ if (this.proposedCheckpointData) {
853
+ // After syncing from L1 we see the chain tip has invalid attestations. This means the parent checkpoint was posted
854
+ // with invalid attestations, or it built on top of something with invalid attestations and didnt invalidate them.
855
+ // Either way, we thought our parent would be valid, so we have to throw away our work. But at least we'll try and
856
+ // invalidate on L1 so we clean up the chain for the next proposer. And we'll slash them, but that's handled elsewhere.
857
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
858
+ if (!validationStatus.valid) {
859
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} has invalid attestations, discarding pipelined work`, {
860
+ checkpointNumber: this.checkpointNumber,
861
+ reason: validationStatus.reason
862
+ });
863
+ this.emitPipelinedCheckpointDiscarded('parent-invalid-attestations');
864
+ await this.enqueueInvalidation(validationStatus);
865
+ return false;
866
+ }
867
+ // The pending chain is valid. But did the parent checkpoint land on L1 at all?
868
+ if (checkpointedNumber < parentCheckpointNumber) {
869
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} did not land on L1, discarding pipelined work`, {
870
+ checkpointNumber: this.checkpointNumber,
871
+ checkpointedNumber
872
+ });
873
+ this.emitPipelinedCheckpointDiscarded('parent-not-on-l1');
874
+ return false;
875
+ }
876
+ // It landed. But is it the one we were expecting?
877
+ const expectedHash = this.proposedCheckpointData.header.hash().toString();
878
+ if (tips.checkpointed.checkpoint.hash !== expectedHash) {
879
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} hash mismatch on L1, discarding pipelined work`, {
880
+ checkpointNumber: this.checkpointNumber,
881
+ expectedHash,
882
+ actualHash: tips.checkpointed.checkpoint.hash
883
+ });
884
+ this.emitPipelinedCheckpointDiscarded('parent-hash-mismatch');
885
+ return false;
886
+ }
887
+ return true;
888
+ } else {
889
+ // We didn't see a proposed checkpoint at build time, so we built on checkpointed parent from two slots ago.
890
+ // But if a new checkpoint for the previous slot appeared on L1 in the meantime, our checkpoint assumed the wrong parent,
891
+ // so we have to discard our work. This can happen if we're somehow cut off from p2p and fail to see the checkpoint
892
+ // proposal for the previous slot.
893
+ if (checkpointedNumber > parentCheckpointNumber) {
894
+ this.log.warn(`Unexpected checkpoint ${checkpointedNumber} landed on L1 after we built on top of parent ${parentCheckpointNumber}, discarding pipelined work`, {
895
+ checkpointNumber: this.checkpointNumber,
896
+ checkpointedNumber
897
+ });
898
+ this.emitPipelinedCheckpointDiscarded('unexpected-parent-appeared');
899
+ return false;
900
+ }
901
+ return true;
902
+ }
903
+ }
904
+ /** Emits the pipelined-checkpoint-discarded event and records the metric. */ emitPipelinedCheckpointDiscarded(reason) {
905
+ this.metrics.recordPipelineParentCheckpointMismatch(reason);
906
+ this.eventEmitter.emit('pipelined-checkpoint-discarded', {
907
+ slot: this.targetSlot,
908
+ checkpointNumber: this.checkpointNumber,
909
+ reason
910
+ });
911
+ }
912
+ /** Simulates and enqueues an invalidation request for the invalid parent checkpoint. */ async enqueueInvalidation(validationStatus) {
913
+ if (this.config.skipInvalidateBlockAsProposer) {
914
+ this.log.warn(`Skipping checkpoint invalidation as proposer due to test configuration`);
915
+ return;
916
+ }
917
+ const invalidateRequest = await this.publisher.simulateInvalidateCheckpoint(validationStatus);
918
+ if (invalidateRequest) {
919
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
920
+ const txTimeoutAt = new Date((submissionSlotStart + this.l1Constants.slotDuration) * 1000);
921
+ this.publisher.enqueueInvalidateCheckpoint(invalidateRequest, {
922
+ txTimeoutAt
923
+ });
924
+ } else {
925
+ this.log.info(`Invalidation simulation returned undefined, checkpoint may have been removed already`, {
926
+ checkpointNumber: this.checkpointNumber
642
927
  });
643
- return undefined;
644
928
  }
645
929
  }
646
930
  async proposeCheckpoint() {
@@ -651,16 +935,28 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
651
935
  hasError: false
652
936
  };
653
937
  try {
938
+ const now = this.dateProvider.now();
939
+ if (this.proposedCheckpointData) {
940
+ // Measure against the wall-clock slot whose build window we are currently using.
941
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
942
+ // target-slot boundary a full slot away from the actual build start time.
943
+ const slotBoundaryMs = Number(getTimestampForSlot(this.getBuildSlot(), this.l1Constants)) * 1000;
944
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
945
+ }
946
+ this.checkpointMetrics.startCheckpointTiming(now);
654
947
  // Get operator configured coinbase and fee recipient for this attestor
655
948
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
656
949
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
657
950
  // Start the checkpoint
658
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
659
- this.log.info(`Starting checkpoint proposal`, {
660
- buildSlot: this.slot,
951
+ this.setState(SequencerState.INITIALIZING_CHECKPOINT);
952
+ this.logCheckpointEvent('slot-started', `Starting checkpoint proposal for slot ${this.targetSlot}`, {
953
+ buildSlot: this.getBuildSlot(),
661
954
  submissionSlot: this.targetSlot,
662
- pipelining: this.epochCache.isProposerPipeliningEnabled(),
955
+ slot: this.targetSlot,
956
+ checkpointNumber: this.checkpointNumber,
663
957
  proposer: this.proposer?.toString(),
958
+ attestorAddress: this.attestorAddress.toString(),
959
+ publisherAddress: this.publisher.getSenderAddress().toString(),
664
960
  coinbase: coinbase.toString()
665
961
  });
666
962
  this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
@@ -668,15 +964,41 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
668
964
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
669
965
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
670
966
  }
671
- // Create checkpoint builder for the slot
672
- const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(coinbase, feeRecipient, this.targetSlot);
967
+ // Build the simulation plan for this slot. When pipelining, this overrides L1's view of
968
+ // pending/archive/fee-header to "as if the proposed parent had landed", so both the
969
+ // mana-min-fee simulation (in the globals builder) and the pre-broadcast
970
+ // validateBlockHeader see the chain tip the eventual L1 send will see.
971
+ this.checkpointSimulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
972
+ checkpointNumber: this.checkpointNumber,
973
+ proposedCheckpointData: this.proposedCheckpointData,
974
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
975
+ checkpointedCheckpointNumber: this.checkpointedCheckpointNumber,
976
+ rollup: this.publisher.rollupContract,
977
+ signatureContext: this.signatureContext,
978
+ log: this.log
979
+ });
980
+ const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(coinbase, feeRecipient, this.targetSlot, this.checkpointSimulationOverridesPlan);
673
981
  // Collect L1 to L2 messages for the checkpoint and compute their hash
674
982
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
675
983
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
676
- // Collect the out hashes of all the checkpoints before this one in the same epoch
677
- const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.targetEpoch)).filter((c)=>c.checkpointNumber < this.checkpointNumber).map((c)=>c.checkpointOutHash);
678
- // Get the fee asset price modifier from the oracle
679
- const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
984
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
985
+ // Under pipelining the parent checkpoint may not be on L1 yet at build time, so the helper
986
+ // splices in the parent's checkpointOutHash from the locally-known proposed checkpoint so
987
+ // the resulting `epochOutHash` matches what validators (and L1) compute once the parent
988
+ // lands on L1.
989
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
990
+ blockSource: this.l2BlockSource,
991
+ epoch: this.targetEpoch,
992
+ checkpointNumber: this.checkpointNumber,
993
+ l1Constants: this.epochCache.getL1Constants(),
994
+ pipeliningEnabled: true,
995
+ proposedCheckpointData: this.proposedCheckpointData,
996
+ log: this.log
997
+ });
998
+ // Anchor the modifier to the predicted parent fee header: L1 will apply it against
999
+ // that, not against the latest published checkpoint (which lags by one under pipelining).
1000
+ const predictedParentEthPerFeeAssetE12 = this.checkpointSimulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
1001
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12);
680
1002
  const fork = _ts_add_disposable_resource(env, await this.worldState.fork(this.syncedToBlockNumber, {
681
1003
  closeDelayMs: 12_000
682
1004
  }), true);
@@ -689,7 +1011,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
689
1011
  };
690
1012
  const checkpointProposalOptions = {
691
1013
  publishFullTxs: !!this.config.publishTxsWithProposals,
692
- broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal
1014
+ broadcastInvalidCheckpointProposal: this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal
693
1015
  };
694
1016
  let blocksInCheckpoint = [];
695
1017
  let blockPendingBroadcast = undefined;
@@ -709,8 +1031,15 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
709
1031
  throw err;
710
1032
  }
711
1033
  if (blocksInCheckpoint.length === 0) {
1034
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1035
+ slot: this.targetSlot,
1036
+ checkpointNumber: this.checkpointNumber,
1037
+ reason: 'no_blocks_built'
1038
+ });
712
1039
  this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
713
- slot: this.targetSlot
1040
+ slot: this.targetSlot,
1041
+ checkpointNumber: this.checkpointNumber,
1042
+ reason: 'no_blocks_built'
714
1043
  });
715
1044
  this.eventEmitter.emit('checkpoint-empty', {
716
1045
  slot: this.targetSlot
@@ -719,16 +1048,25 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
719
1048
  }
720
1049
  const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
721
1050
  if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
1051
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1052
+ slot: this.targetSlot,
1053
+ checkpointNumber: this.checkpointNumber,
1054
+ blocksBuilt: blocksInCheckpoint.length,
1055
+ minBlocksForCheckpoint,
1056
+ reason: 'min_blocks_not_met'
1057
+ });
722
1058
  this.log.warn(`Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`, {
723
1059
  slot: this.targetSlot,
1060
+ checkpointNumber: this.checkpointNumber,
724
1061
  blocksBuilt: blocksInCheckpoint.length,
725
- minBlocksForCheckpoint
1062
+ minBlocksForCheckpoint,
1063
+ reason: 'min_blocks_not_met'
726
1064
  });
727
1065
  return undefined;
728
1066
  }
729
1067
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
730
1068
  // broadcasted yet, and wait to collect the committee attestations.
731
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
1069
+ this.setState(SequencerState.ASSEMBLING_CHECKPOINT);
732
1070
  const checkpoint = await checkpointBuilder.completeCheckpoint();
733
1071
  // Final validation: per-block limits are only checked if the operator set them explicitly.
734
1072
  // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
@@ -741,14 +1079,36 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
741
1079
  maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint
742
1080
  });
743
1081
  } catch (err) {
744
- this.log.error(`Built an invalid checkpoint at slot ${this.slot} (skipping proposal)`, err, {
1082
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1083
+ slot: this.targetSlot,
1084
+ checkpointNumber: this.checkpointNumber,
1085
+ blocksBuilt: blocksInCheckpoint.length,
1086
+ reason: 'invalid_checkpoint',
1087
+ checkpoint: checkpoint.header.toInspect()
1088
+ });
1089
+ this.log.error(`Built an invalid checkpoint at slot ${this.targetSlot} (skipping proposal)`, err, {
1090
+ slot: this.targetSlot,
1091
+ checkpointNumber: this.checkpointNumber,
1092
+ blocksBuilt: blocksInCheckpoint.length,
1093
+ reason: 'invalid_checkpoint',
745
1094
  checkpoint: checkpoint.header.toInspect()
746
1095
  });
747
1096
  return undefined;
748
1097
  }
749
1098
  // Record checkpoint-level build metrics
750
- this.metrics.recordCheckpointBuild(checkpointBuildTimer.ms(), blocksInCheckpoint.length, checkpoint.getStats().txCount, Number(checkpoint.header.totalManaUsed.toBigInt()));
751
- // Do not collect attestations nor publish to L1 in fisherman mode
1099
+ this.checkpointMetrics.recordCheckpointBuild(checkpointBuildTimer.ms(), blocksInCheckpoint.length, checkpoint.getStats().txCount, Number(checkpoint.header.totalManaUsed.toBigInt()));
1100
+ this.logCheckpointEvent('built', `Checkpoint built for slot ${this.targetSlot}`, {
1101
+ slot: this.targetSlot,
1102
+ buildSlot: this.getBuildSlot(),
1103
+ checkpointNumber: this.checkpointNumber,
1104
+ proposer: this.proposer?.toString(),
1105
+ attestorAddress: this.attestorAddress.toString(),
1106
+ publisherAddress: this.publisher.getSenderAddress().toString(),
1107
+ blocksBuilt: blocksInCheckpoint.length,
1108
+ txCount: checkpoint.getStats().txCount,
1109
+ totalMana: Number(checkpoint.header.totalManaUsed.toBigInt())
1110
+ });
1111
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
752
1112
  if (this.config.fishermanMode) {
753
1113
  this.log.info(`Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` + `Skipping proposal in fisherman mode.`, {
754
1114
  slot: this.targetSlot,
@@ -756,53 +1116,58 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
756
1116
  blocksBuilt: blocksInCheckpoint.length
757
1117
  });
758
1118
  this.metrics.recordCheckpointSuccess();
759
- return checkpoint;
1119
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
1120
+ return {
1121
+ checkpoint,
1122
+ proposal: undefined,
1123
+ blockProposedAt: this.dateProvider.now()
1124
+ };
760
1125
  }
761
- // Include the block pending broadcast in the checkpoint proposal if any
762
- const lastBlock = blockPendingBroadcast && {
763
- blockHeader: blockPendingBroadcast.block.header,
764
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
765
- txs: blockPendingBroadcast.txs
766
- };
767
- // Create the checkpoint proposal and broadcast it
768
- const proposal = await this.validatorClient.createCheckpointProposal(checkpoint.header, checkpoint.archive.root, feeAssetPriceModifier, lastBlock, this.proposer, checkpointProposalOptions);
769
- const blockProposedAt = this.dateProvider.now();
770
- await this.p2pClient.broadcastCheckpointProposal(proposal);
771
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.targetSlot);
772
- const attestations = await this.waitForAttestations(proposal);
773
- const blockAttestedAt = this.dateProvider.now();
774
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
775
- // Proposer must sign over the attestations before pushing them to L1
776
- const signer = this.proposer ?? this.publisher.getSenderAddress();
777
- let attestationsSignature;
1126
+ // Validate the header against L1 state before broadcasting.
1127
+ // If this fails the slot is aborted before any gossip work; state drift between here
1128
+ // and the eventual L1 send is caught by the bundle simulate at send time.
778
1129
  try {
779
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer, this.targetSlot, this.checkpointNumber);
1130
+ await this.publisher.validateBlockHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
780
1131
  } catch (err) {
781
- // We shouldn't really get here since we yield to another HA node
782
- // as soon as we see these errors when creating block or checkpoint proposals.
783
- if (this.handleHASigningError(err, 'Attestations signature')) {
784
- return undefined;
785
- }
786
- throw err;
1132
+ this.log.error(`Pre-broadcast header validation failed for slot ${this.targetSlot}; aborting`, err, {
1133
+ slot: this.targetSlot,
1134
+ checkpointNumber: this.checkpointNumber
1135
+ });
1136
+ this.metrics.recordCheckpointProposalFailed('header_validation_failed');
1137
+ this.eventEmitter.emit('header-validation-failed', {
1138
+ slot: this.targetSlot,
1139
+ checkpointNumber: this.checkpointNumber,
1140
+ reason: err instanceof Error ? err.message : String(err)
1141
+ });
1142
+ return undefined;
787
1143
  }
788
- // Enqueue publishing the checkpoint to L1
789
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.targetSlot);
790
- const aztecSlotDuration = this.l1Constants.slotDuration;
791
- const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
792
- const txTimeoutAt = new Date((submissionSlotStart + aztecSlotDuration) * 1000);
793
- // If we have been configured to potentially skip publishing checkpoint then roll the dice here
794
- if (this.config.skipPublishingCheckpointsPercent !== undefined && this.config.skipPublishingCheckpointsPercent > 0) {
795
- const result = Math.max(0, randomInt(100));
796
- if (result < this.config.skipPublishingCheckpointsPercent) {
797
- this.log.warn(`Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${result}`);
798
- return checkpoint;
1144
+ // Create the checkpoint proposal and broadcast it
1145
+ const proposal = await this.validatorClient.createCheckpointProposal(checkpoint.header, checkpoint.archive.root, this.checkpointNumber, feeAssetPriceModifier, blockPendingBroadcast, this.proposer, checkpointProposalOptions);
1146
+ // Advance our own optimistic proposed-checkpoint tip locally before gossiping. Gossipsub
1147
+ // doesn't echo our own messages back, so this is how the proposer makes its own proposed
1148
+ // checkpoint visible for pipelining the next slot. Built from local checkpoint data — never
1149
+ // from the broadcast proposal archive, which may be deliberately corrupted under test flags.
1150
+ // Fail closed: if this throws, the outer catch aborts the slot before gossiping.
1151
+ await this.syncProposedCheckpointToArchiver(checkpoint, blocksInCheckpoint.length, feeAssetPriceModifier);
1152
+ const blockProposedAt = this.dateProvider.now();
1153
+ if (this.config.skipBroadcastCheckpointProposal) {
1154
+ // Test-only: suppress the CheckpointProposal so peers never see a proposed checkpoint for
1155
+ // this slot, but still broadcast the held last block standalone so peers' archivers ingest
1156
+ // it as a proposed-but-uncheckpointed tip — the exact orphan-block state that
1157
+ // pruneOrphanProposedBlocks / checkSync must handle.
1158
+ if (blockPendingBroadcast && !this.config.skipBroadcastProposals) {
1159
+ await this.p2pClient.broadcastProposal(blockPendingBroadcast);
799
1160
  }
1161
+ } else if (!this.config.skipBroadcastProposals) {
1162
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
1163
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
800
1164
  }
801
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
802
- txTimeoutAt,
803
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber
804
- });
805
- return checkpoint;
1165
+ // Return immediately after broadcast — attestation collection happens in the background
1166
+ return {
1167
+ checkpoint,
1168
+ proposal,
1169
+ blockProposedAt
1170
+ };
806
1171
  } catch (e) {
807
1172
  env.error = e;
808
1173
  env.hasError = true;
@@ -815,7 +1180,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
815
1180
  // swallow this error. It's already been logged by a function deeper in the stack
816
1181
  return undefined;
817
1182
  }
818
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
1183
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
819
1184
  return undefined;
820
1185
  }
821
1186
  }
@@ -831,13 +1196,21 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
831
1196
  const blocksBuilt = blocksInCheckpoint.length;
832
1197
  const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
833
1198
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
834
- const secondsIntoSlot = this.getSecondsIntoSlot();
835
- const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
1199
+ if (blocksBuilt >= this.config.maxBlocksPerCheckpoint) {
1200
+ this.log.debug(`Reached max blocks per checkpoint`, {
1201
+ slot: this.targetSlot,
1202
+ blocksBuilt,
1203
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint
1204
+ });
1205
+ break;
1206
+ }
1207
+ const nowSeconds = this.dateProvider.now() / 1000;
1208
+ const timingInfo = this.timetable.selectNextSubslot(this.targetSlot, nowSeconds);
836
1209
  if (!timingInfo.canStart) {
837
1210
  this.log.debug(`Not enough time left in slot to start another block`, {
838
1211
  slot: this.targetSlot,
839
1212
  blocksBuilt,
840
- secondsIntoSlot
1213
+ nowSeconds
841
1214
  });
842
1215
  break;
843
1216
  }
@@ -846,23 +1219,24 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
846
1219
  blockTimestamp: timestamp,
847
1220
  // Create an empty block if we haven't already and this is the last one
848
1221
  forceCreate: timingInfo.isLastBlock && blocksBuilt === 0 && this.config.buildCheckpointIfEmpty,
849
- // Build deadline is only set if we are enforcing the timetable
850
- buildDeadline: timingInfo.deadline ? new Date((this.getSlotStartBuildTimestamp() + timingInfo.deadline) * 1000) : undefined,
1222
+ buildDeadline: new Date(timingInfo.deadline * 1000),
851
1223
  blockNumber,
852
1224
  indexWithinCheckpoint,
853
1225
  txHashesAlreadyIncluded
854
1226
  });
855
- // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
856
- if (!buildResult && timingInfo.isLastBlock) {
857
- break;
858
- } else if (!buildResult && timingInfo.deadline !== undefined) {
859
- // But if there is still time for more blocks, wait until the next subslot and try again
1227
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
1228
+ if ('failure' in buildResult) {
1229
+ // If this was the last subslot, we're done.
1230
+ if (timingInfo.isLastBlock) {
1231
+ break;
1232
+ }
1233
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
860
1234
  await this.waitUntilNextSubslot(timingInfo.deadline);
861
1235
  continue;
862
- } else if (!buildResult) {
863
- break;
864
- } else if ('error' in buildResult) {
865
- // If there was an error building the block, just exit the loop and give up the rest of the slot
1236
+ }
1237
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
1238
+ // We don't want to risk building more blocks if something went wrong.
1239
+ if ('error' in buildResult) {
866
1240
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
867
1241
  this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
868
1242
  slot: this.targetSlot,
@@ -873,34 +1247,36 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
873
1247
  break;
874
1248
  }
875
1249
  const { block, usedTxs } = buildResult;
1250
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
1251
+ isFirstBlock: blocksBuilt === 0,
1252
+ isLastBlock: timingInfo.isLastBlock
1253
+ });
876
1254
  blocksInCheckpoint.push(block);
877
1255
  usedTxs.forEach((tx)=>txHashesAlreadyIncluded.add(tx.txHash.toString()));
878
- // If this is the last block, sync it to the archiver and exit the loop
879
- // so we can build the checkpoint and start collecting attestations.
1256
+ // Sign the block proposal. This will throw if HA signing fails.
1257
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, {
1258
+ ...blockProposalOptions,
1259
+ broadcastInvalidBlockProposal: blockProposalOptions.broadcastInvalidBlockProposal || block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint
1260
+ });
1261
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
1262
+ // so we avoid polluting our archive with a block that would fail.
1263
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
1264
+ // If this throws, we abort the entire checkpoint.
1265
+ await this.syncProposedBlockToArchiver(block);
1266
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
880
1267
  if (timingInfo.isLastBlock) {
881
- await this.syncProposedBlockToArchiver(block);
882
1268
  this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
883
1269
  slot: this.targetSlot,
884
1270
  blockNumber,
885
1271
  blocksBuilt
886
1272
  });
887
- blockPendingBroadcast = {
888
- block,
889
- txs: usedTxs
890
- };
1273
+ blockPendingBroadcast = proposal;
891
1274
  break;
892
1275
  }
893
- // Broadcast the block proposal (unless we're in fisherman mode) unless the block is the last one,
894
- // in which case we'll broadcast it along with the checkpoint at the end of the loop.
895
- // Note that we only send the block to the archiver if we manage to create the proposal, so if there's
896
- // a HA error we don't pollute our archiver with a block that won't make it to the chain.
897
- const proposal = await this.createBlockProposal(block, inHash, usedTxs, blockProposalOptions);
898
- // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal.
899
- // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
900
- // If this throws, we abort the entire checkpoint.
901
- await this.syncProposedBlockToArchiver(block);
902
1276
  // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
903
- proposal && await this.p2pClient.broadcastProposal(proposal);
1277
+ if (proposal && !this.config.skipBroadcastProposals) {
1278
+ await this.p2pClient.broadcastProposal(proposal);
1279
+ }
904
1280
  // Wait until the next block's start time
905
1281
  await this.waitUntilNextSubslot(timingInfo.deadline);
906
1282
  }
@@ -918,14 +1294,17 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
918
1294
  this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
919
1295
  return Promise.resolve(undefined);
920
1296
  }
921
- return this.validatorClient.createBlockProposal(block.header, block.indexWithinCheckpoint, inHash, block.archive.root, usedTxs, this.proposer, blockProposalOptions);
1297
+ return this.validatorClient.createBlockProposal(block.header, this.checkpointNumber, block.indexWithinCheckpoint, inHash, block.archive.root, usedTxs, this.proposer, blockProposalOptions);
922
1298
  }
923
- /** Sleeps until it is time to produce the next block in the slot */ async waitUntilNextSubslot(nextSubslotStart) {
924
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
925
- this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
1299
+ /**
1300
+ * Sleeps until it is time to produce the next block in the slot.
1301
+ * @param nextSubslotStart - Absolute wall-clock timestamp in seconds of the previous sub-slot deadline.
1302
+ */ async waitUntilNextSubslot(nextSubslotStart) {
1303
+ this.setState(SequencerState.WAITING_UNTIL_NEXT_BLOCK);
1304
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s`, {
926
1305
  slot: this.targetSlot
927
1306
  });
928
- await this.waitUntilTimeInSlot(nextSubslotStart);
1307
+ await this.awaitInterruptibleSleep(Math.max(0, nextSubslotStart * 1000 - this.dateProvider.now()));
929
1308
  }
930
1309
  /** Builds a single block. Called from the main block building loop. */ async buildSingleBlock(checkpointBuilder, opts) {
931
1310
  const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } = opts;
@@ -937,10 +1316,23 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
937
1316
  // Wait until we have enough txs to build the block
938
1317
  const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
939
1318
  if (!canStartBuilding) {
940
- this.log.warn(`Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (got ${availableTxs} txs but needs ${minTxs})`, {
1319
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1320
+ reason: 'insufficient_txs',
1321
+ blockNumber,
1322
+ slot: this.targetSlot,
1323
+ checkpointNumber: this.checkpointNumber,
1324
+ indexWithinCheckpoint,
1325
+ availableTxs,
1326
+ minTxs
1327
+ });
1328
+ this.log.verbose(`Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (got ${availableTxs} txs but needs ${minTxs})`, {
1329
+ reason: 'insufficient_txs',
941
1330
  blockNumber,
942
1331
  slot: this.targetSlot,
943
- indexWithinCheckpoint
1332
+ checkpointNumber: this.checkpointNumber,
1333
+ indexWithinCheckpoint,
1334
+ availableTxs,
1335
+ minTxs
944
1336
  });
945
1337
  this.eventEmitter.emit('block-tx-count-check-failed', {
946
1338
  minTxs,
@@ -948,17 +1340,23 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
948
1340
  slot: this.targetSlot
949
1341
  });
950
1342
  this.metrics.recordBlockProposalFailed('insufficient_txs');
951
- return undefined;
1343
+ return {
1344
+ failure: 'insufficient-txs'
1345
+ };
952
1346
  }
953
1347
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
954
1348
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
955
- const pendingTxs = filter(this.p2pClient.iterateEligiblePendingTxs(), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
1349
+ // Block building only executes txs, so we skip loading their proofs unless these same tx objects get attached
1350
+ // to the broadcasted proposals via publishTxsWithProposals.
1351
+ const pendingTxs = filter(this.p2pClient.iterateEligiblePendingTxs({
1352
+ includeProof: !!this.config.publishTxsWithProposals
1353
+ }), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
956
1354
  this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`, {
957
1355
  slot: this.targetSlot,
958
1356
  blockNumber,
959
1357
  indexWithinCheckpoint
960
1358
  });
961
- this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
1359
+ this.setState(SequencerState.CREATING_BLOCK);
962
1360
  // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
963
1361
  // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
964
1362
  // minValidTxs is passed into the builder so it can reject the block *before* updating state.
@@ -969,8 +1367,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
969
1367
  deadline: buildDeadline,
970
1368
  isBuildingProposal: true,
971
1369
  minValidTxs,
972
- maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
973
- perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier
1370
+ maxBlocksPerCheckpoint: this.timetable.getMaxBlocksPerCheckpoint(),
1371
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
1372
+ perBlockDAAllocationMultiplier: this.config.perBlockDAAllocationMultiplier
974
1373
  };
975
1374
  // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
976
1375
  // if the number of successfully processed txs is below minValidTxs, ensuring state is not
@@ -979,8 +1378,19 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
979
1378
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
980
1379
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
981
1380
  if (buildResult.status === 'insufficient-valid-txs') {
1381
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1382
+ reason: 'insufficient_valid_txs',
1383
+ slot: this.targetSlot,
1384
+ checkpointNumber: this.checkpointNumber,
1385
+ blockNumber,
1386
+ numTxs: buildResult.processedCount,
1387
+ indexWithinCheckpoint,
1388
+ minValidTxs
1389
+ });
982
1390
  this.log.warn(`Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`, {
1391
+ reason: 'insufficient_valid_txs',
983
1392
  slot: this.targetSlot,
1393
+ checkpointNumber: this.checkpointNumber,
984
1394
  blockNumber,
985
1395
  numTxs: buildResult.processedCount,
986
1396
  indexWithinCheckpoint,
@@ -991,7 +1401,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
991
1401
  slot: this.targetSlot
992
1402
  });
993
1403
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
994
- return undefined;
1404
+ return {
1405
+ failure: 'insufficient-valid-txs'
1406
+ };
995
1407
  }
996
1408
  // Block creation succeeded, emit stats and metrics
997
1409
  const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
@@ -1010,12 +1422,17 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1010
1422
  manaPerSec,
1011
1423
  ...blockStats
1012
1424
  });
1425
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
1426
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
1013
1427
  this.eventEmitter.emit('block-proposed', {
1014
1428
  blockNumber: block.number,
1429
+ blockHash,
1430
+ checkpointNumber: this.checkpointNumber,
1431
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1015
1432
  slot: this.targetSlot,
1016
- buildSlot: this.slotNow
1433
+ buildSlot: this.getBuildSlot()
1017
1434
  });
1018
- this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
1435
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
1019
1436
  return {
1020
1437
  block,
1021
1438
  usedTxs
@@ -1025,9 +1442,17 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1025
1442
  reason: err.message,
1026
1443
  slot: this.targetSlot
1027
1444
  });
1445
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1446
+ reason: err instanceof Error ? err.message : String(err),
1447
+ slot: this.targetSlot,
1448
+ checkpointNumber: this.checkpointNumber,
1449
+ blockNumber
1450
+ });
1028
1451
  this.log.error(`Error building block`, err, {
1029
- blockNumber,
1030
- slot: this.targetSlot
1452
+ reason: err instanceof Error ? err.message : String(err),
1453
+ slot: this.targetSlot,
1454
+ checkpointNumber: this.checkpointNumber,
1455
+ blockNumber
1031
1456
  });
1032
1457
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
1033
1458
  this.metrics.recordFailedBlock();
@@ -1061,8 +1486,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1061
1486
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
1062
1487
  // We only allow a block with 0 txs in the first block of the checkpoint
1063
1488
  const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
1064
- // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
1065
- const startBuildingDeadline = buildDeadline ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000) : undefined;
1489
+ // Latest time to keep waiting for txs: wait_for_txs_deadline = block_build_deadline(k) - min_block_duration.
1490
+ const startBuildingDeadline = buildDeadline ? new Date(buildDeadline.getTime() - this.timetable.minBlockDuration * 1000) : undefined;
1066
1491
  let availableTxs = await this.p2pClient.getPendingTxCount();
1067
1492
  while(!forceCreate && availableTxs < minTxs){
1068
1493
  // If we're past deadline, or we have no deadline, give up
@@ -1075,7 +1500,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1075
1500
  };
1076
1501
  }
1077
1502
  // Wait a bit before checking again
1078
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
1503
+ this.setState(SequencerState.WAITING_FOR_TXS);
1079
1504
  this.log.verbose(`Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`, {
1080
1505
  blockNumber,
1081
1506
  slot: this.targetSlot,
@@ -1090,13 +1515,37 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1090
1515
  minTxs
1091
1516
  };
1092
1517
  }
1518
+ async getSignedCommitteeAttestations(broadcast) {
1519
+ const { proposal, blockProposedAt } = broadcast;
1520
+ this.setState(SequencerState.COLLECTING_ATTESTATIONS);
1521
+ const attestations = await this.waitForAttestations(proposal);
1522
+ if (!attestations) {
1523
+ return undefined;
1524
+ }
1525
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
1526
+ // Proposer must sign over the attestations before pushing them to L1
1527
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1528
+ try {
1529
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer, this.targetSlot, this.checkpointNumber);
1530
+ return {
1531
+ attestations,
1532
+ attestationsSignature
1533
+ };
1534
+ } catch (err) {
1535
+ if (this.handleHASigningError(err, 'Attestations signature')) {
1536
+ return;
1537
+ }
1538
+ this.log.error(`Error signing attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1539
+ return undefined;
1540
+ }
1541
+ }
1093
1542
  /**
1094
1543
  * Waits for enough attestations to be collected via p2p.
1095
1544
  * This is run after all blocks for the checkpoint have been built.
1096
1545
  */ async waitForAttestations(proposal) {
1097
1546
  if (this.config.fishermanMode) {
1098
1547
  this.log.debug('Skipping attestation collection in fisherman mode');
1099
- return CommitteeAttestationsAndSigners.empty();
1548
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1100
1549
  }
1101
1550
  const slotNumber = proposal.slotNumber;
1102
1551
  const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
@@ -1104,25 +1553,29 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1104
1553
  throw new Error('No committee when collecting attestations');
1105
1554
  } else if (committee.length === 0) {
1106
1555
  this.log.verbose(`Attesting committee is empty`);
1107
- return CommitteeAttestationsAndSigners.empty();
1556
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1108
1557
  } else {
1109
1558
  this.log.debug(`Attesting committee length is ${committee.length}`, {
1110
1559
  committee
1111
1560
  });
1112
1561
  }
1113
- const numberOfRequiredAttestations = Math.floor(committee.length * 2 / 3) + 1;
1562
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
1114
1563
  if (this.config.skipCollectingAttestations) {
1115
1564
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
1116
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
1117
- return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
1565
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
1566
+ this.logCheckpointAttestations('collected', committee, attestations ?? [], numberOfRequiredAttestations, {
1567
+ reason: 'collect_own_only'
1568
+ });
1569
+ return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee), this.getSignatureContext());
1118
1570
  }
1119
- const attestationTimeAllowed = this.config.enforceTimeTable ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT) : this.l1Constants.slotDuration;
1120
- const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
1121
- this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
1571
+ // Hard attestation-collection cutoff = the single consensus attestation_deadline (target_slot_start + S - 2E).
1572
+ const attestationDeadlineSeconds = this.timetable.getAttestationDeadline(this.targetSlot);
1573
+ const attestationDeadline = new Date(attestationDeadlineSeconds * 1000);
1574
+ this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, Math.max(0, attestationDeadline.getTime() - this.dateProvider.now()));
1122
1575
  const collectAttestationsTimer = new Timer();
1123
1576
  let collectedAttestationsCount = 0;
1124
1577
  try {
1125
- const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline);
1578
+ const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline, this.checkpointNumber);
1126
1579
  collectedAttestationsCount = attestations.length;
1127
1580
  // Trim attestations to minimum required to save L1 calldata gas
1128
1581
  const localAddresses = this.validatorClient.getValidatorAddresses();
@@ -1132,20 +1585,55 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1132
1585
  }
1133
1586
  // Rollup contract requires that the signatures are provided in the order of the committee
1134
1587
  const sorted = orderAttestations(trimmed, committee);
1588
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1589
+ submittedCount: trimmed.length
1590
+ });
1135
1591
  // Manipulate the attestations if we've been configured to do so
1136
1592
  if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation || this.config.shuffleAttestationOrdering) {
1137
1593
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
1138
1594
  }
1139
- return new CommitteeAttestationsAndSigners(sorted);
1595
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
1140
1596
  } catch (err) {
1141
1597
  if (err && err instanceof AttestationTimeoutError) {
1142
1598
  collectedAttestationsCount = err.collectedCount;
1599
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1600
+ collectedCount: collectedAttestationsCount,
1601
+ reason: 'timeout'
1602
+ });
1603
+ this.log.error(`Timeout while waiting for attestations for checkpoint proposal at slot ${proposal.slotNumber} (collected ${collectedAttestationsCount}/${numberOfRequiredAttestations})`, err);
1604
+ } else {
1605
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1606
+ collectedCount: collectedAttestationsCount,
1607
+ reason: err instanceof Error ? err.message : String(err)
1608
+ });
1609
+ this.log.error(`Error collecting attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1143
1610
  }
1144
- throw err;
1611
+ return undefined;
1145
1612
  } finally{
1146
1613
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
1147
1614
  }
1148
1615
  }
1616
+ logCheckpointAttestations(status, committee, attestations, requiredAttestations, opts = {}) {
1617
+ const signedValidators = attestations?.map((attestation)=>attestation.getSender()?.toString()).filter((address)=>address !== undefined) ?? [];
1618
+ const collectedCount = opts.collectedCount ?? new Set(signedValidators).size;
1619
+ const missingValidatorCount = status === 'failed' ? Math.max(0, requiredAttestations - collectedCount) : undefined;
1620
+ this.logCheckpointEvent(`attestations-${status}`, `Checkpoint attestations ${status} for slot ${this.targetSlot}`, {
1621
+ slot: this.targetSlot,
1622
+ checkpointNumber: this.checkpointNumber,
1623
+ committeeSize: committee.length,
1624
+ requiredAttestations,
1625
+ collectedAttestations: collectedCount,
1626
+ ...opts.submittedCount !== undefined && {
1627
+ submittedAttestations: opts.submittedCount
1628
+ },
1629
+ ...missingValidatorCount !== undefined && {
1630
+ missingValidatorCount
1631
+ },
1632
+ ...opts.reason !== undefined && {
1633
+ reason: opts.reason
1634
+ }
1635
+ });
1636
+ }
1149
1637
  /** Breaks the attestations before publishing based on attack configs */ manipulateAttestations(slotNumber, epoch, seed, committee, attestations) {
1150
1638
  // Compute the proposer index in the committee, since we dont want to tweak it.
1151
1639
  // Otherwise, the L1 rollup contract will reject the block outright.
@@ -1171,7 +1659,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1171
1659
  unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
1172
1660
  }
1173
1661
  }
1174
- return new CommitteeAttestationsAndSigners(attestations);
1662
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1175
1663
  }
1176
1664
  if (this.config.shuffleAttestationOrdering) {
1177
1665
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
@@ -1197,10 +1685,10 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1197
1685
  shuffled[i]
1198
1686
  ];
1199
1687
  }
1200
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
1201
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
1688
+ const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
1689
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
1202
1690
  }
1203
- return new CommitteeAttestationsAndSigners(attestations);
1691
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1204
1692
  }
1205
1693
  async dropFailedTxsFromP2P(failedTxs) {
1206
1694
  if (failedTxs.length === 0) {
@@ -1215,8 +1703,12 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1215
1703
  * Adds the proposed block to the archiver so it's available via P2P.
1216
1704
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1217
1705
  * would never receive its own block without this explicit sync.
1706
+ *
1707
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1708
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1709
+ * whenever the real proposer's block arrives from L1.
1218
1710
  */ async syncProposedBlockToArchiver(block) {
1219
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1711
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1220
1712
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1221
1713
  blockNumber: block.number,
1222
1714
  slot: block.header.globalVariables.slotNumber
@@ -1229,6 +1721,35 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1229
1721
  });
1230
1722
  await this.blockSink.addBlock(block);
1231
1723
  }
1724
+ /**
1725
+ * Adds the proposed checkpoint to the archiver so the proposer's optimistic proposed-checkpoint
1726
+ * tip advances locally. Gossip doesn't echo our own messages back, so without this the proposer
1727
+ * would never see its own proposed checkpoint and couldn't pipeline the next slot.
1728
+ *
1729
+ * Skipped whenever proposed blocks aren't pushed (`skipPushProposedBlocksToArchiver`, fisherman
1730
+ * mode): the archiver derives the checkpoint archive from its stored blocks, so without them the
1731
+ * push would fail. All blocks were already added (and awaited) during block building, so this
1732
+ * needs no retry — they are guaranteed present by the time we get here.
1733
+ */ async syncProposedCheckpointToArchiver(checkpoint, blockCount, feeAssetPriceModifier) {
1734
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1735
+ return;
1736
+ }
1737
+ const startBlock = BlockNumber(this.syncedToBlockNumber + 1);
1738
+ this.log.debug(`Syncing proposed checkpoint ${this.checkpointNumber} to archiver`, {
1739
+ checkpointNumber: this.checkpointNumber,
1740
+ slot: this.targetSlot,
1741
+ startBlock,
1742
+ blockCount
1743
+ });
1744
+ await this.blockSink.addProposedCheckpoint({
1745
+ header: checkpoint.header,
1746
+ checkpointNumber: this.checkpointNumber,
1747
+ startBlock,
1748
+ blockCount,
1749
+ totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
1750
+ feeAssetPriceModifier
1751
+ });
1752
+ }
1232
1753
  /** Runs fee analysis and logs checkpoint outcome as fisherman */ async handleCheckpointEndAsFisherman(checkpoint) {
1233
1754
  // Perform L1 fee analysis before clearing requests
1234
1755
  // The callback is invoked asynchronously after the next block is mined
@@ -1268,20 +1789,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1268
1789
  }
1269
1790
  return false;
1270
1791
  }
1271
- /** Waits until a specific time within the current slot */ async waitUntilTimeInSlot(targetSecondsIntoSlot) {
1272
- const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1273
- const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
1274
- await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
1275
- }
1276
1792
  /** Waits the polling interval for transactions. Extracted for test overriding. */ async waitForTxsPollingInterval() {
1277
- await sleep(TXS_POLLING_MS);
1278
- }
1279
- getSlotStartBuildTimestamp() {
1280
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1281
- }
1282
- getSecondsIntoSlot() {
1283
- const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1284
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1793
+ await this.awaitInterruptibleSleep(TXS_POLLING_MS);
1285
1794
  }
1286
1795
  getPublisher() {
1287
1796
  return this.publisher;