@aztec/sequencer-client 5.0.0-private.20260318 → 5.0.0-rc.1

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