@aztec/sequencer-client 5.0.0-private.20260319 → 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 (105) 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 +48 -24
  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 +70 -64
  32. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher.js +312 -533
  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 +73 -21
  47. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  48. package/dest/sequencer/checkpoint_proposal_job.js +709 -199
  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 +61 -4
  59. package/dest/sequencer/events.d.ts.map +1 -1
  60. package/dest/sequencer/metrics.d.ts +9 -10
  61. package/dest/sequencer/metrics.d.ts.map +1 -1
  62. package/dest/sequencer/metrics.js +34 -20
  63. package/dest/sequencer/sequencer.d.ts +112 -27
  64. package/dest/sequencer/sequencer.d.ts.map +1 -1
  65. package/dest/sequencer/sequencer.js +467 -147
  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/utils.d.ts +15 -1
  71. package/dest/test/utils.d.ts.map +1 -1
  72. package/dest/test/utils.js +23 -6
  73. package/package.json +28 -27
  74. package/src/client/sequencer-client.ts +29 -41
  75. package/src/config.ts +57 -24
  76. package/src/global_variable_builder/README.md +44 -0
  77. package/src/global_variable_builder/fee_predictor.ts +172 -0
  78. package/src/global_variable_builder/fee_provider.ts +80 -0
  79. package/src/global_variable_builder/global_builder.ts +25 -63
  80. package/src/global_variable_builder/index.ts +3 -1
  81. package/src/publisher/config.ts +40 -6
  82. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  83. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  84. package/src/publisher/sequencer-publisher-factory.ts +3 -6
  85. package/src/publisher/sequencer-publisher.ts +368 -577
  86. package/src/sequencer/automine/README.md +60 -0
  87. package/src/sequencer/automine/automine_factory.ts +152 -0
  88. package/src/sequencer/automine/automine_sequencer.ts +783 -0
  89. package/src/sequencer/automine/index.ts +6 -0
  90. package/src/sequencer/chain_state_overrides.ts +169 -0
  91. package/src/sequencer/checkpoint_proposal_job.ts +818 -224
  92. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  93. package/src/sequencer/checkpoint_voter.ts +1 -12
  94. package/src/sequencer/errors.ts +0 -15
  95. package/src/sequencer/events.ts +65 -4
  96. package/src/sequencer/metrics.ts +43 -24
  97. package/src/sequencer/sequencer.ts +542 -164
  98. package/src/sequencer/types.ts +1 -1
  99. package/src/test/index.ts +2 -2
  100. package/src/test/utils.ts +59 -10
  101. package/dest/sequencer/timetable.d.ts +0 -88
  102. package/dest/sequencer/timetable.d.ts.map +0 -1
  103. package/dest/sequencer/timetable.js +0 -222
  104. package/src/sequencer/README.md +0 -531
  105. 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 { 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,29 +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
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
- slotNow;
475
478
  targetSlot;
476
- epochNow;
477
479
  targetEpoch;
478
480
  checkpointNumber;
479
481
  syncedToBlockNumber;
482
+ checkpointedCheckpointNumber;
480
483
  proposer;
481
484
  publisher;
482
485
  attestorAddress;
@@ -490,15 +493,18 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
490
493
  checkpointsBuilder;
491
494
  blockSink;
492
495
  l1Constants;
496
+ signatureContext;
493
497
  config;
494
498
  timetable;
495
499
  slasherClient;
496
500
  epochCache;
497
501
  dateProvider;
498
502
  metrics;
503
+ checkpointMetrics;
499
504
  eventEmitter;
500
505
  setStateFn;
501
506
  tracer;
507
+ proposedCheckpointData;
502
508
  static{
503
509
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
504
510
  [
@@ -535,23 +541,30 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
535
541
  _dec6,
536
542
  2,
537
543
  "waitForAttestations"
538
- ],
539
- [
540
- _dec7,
541
- 2,
542
- "waitUntilTimeInSlot"
543
544
  ]
544
545
  ], []));
545
546
  }
546
547
  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;
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){
550
563
  this.targetSlot = targetSlot;
551
- this.epochNow = epochNow;
552
564
  this.targetEpoch = targetEpoch;
553
565
  this.checkpointNumber = checkpointNumber;
554
566
  this.syncedToBlockNumber = syncedToBlockNumber;
567
+ this.checkpointedCheckpointNumber = checkpointedCheckpointNumber;
555
568
  this.proposer = proposer;
556
569
  this.publisher = publisher;
557
570
  this.attestorAddress = attestorAddress;
@@ -565,82 +578,354 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
565
578
  this.checkpointsBuilder = checkpointsBuilder;
566
579
  this.blockSink = blockSink;
567
580
  this.l1Constants = l1Constants;
581
+ this.signatureContext = signatureContext;
568
582
  this.config = config;
569
583
  this.timetable = timetable;
570
584
  this.slasherClient = slasherClient;
571
585
  this.epochCache = epochCache;
572
586
  this.dateProvider = dateProvider;
573
587
  this.metrics = metrics;
588
+ this.checkpointMetrics = checkpointMetrics;
574
589
  this.eventEmitter = eventEmitter;
575
590
  this.setStateFn = setStateFn;
576
591
  this.tracer = tracer;
577
- _initProto(this);
592
+ this.proposedCheckpointData = proposedCheckpointData;
593
+ this.interruptibleSleep = (_initProto(this), new InterruptibleSleep());
594
+ this.interrupted = false;
578
595
  this.log = createLogger('sequencer:checkpoint-proposal', {
579
596
  ...bindings,
580
- instanceId: `slot-${this.slotNow}`
597
+ instanceId: `slot-${this.getBuildSlot()}`
598
+ });
599
+ this.checkpointEventLog = createLogger('sequencer:checkpoint-events', {
600
+ ...bindings,
601
+ instanceId: `slot-${this.getBuildSlot()}`
581
602
  });
582
603
  }
583
- /** The wall-clock slot during which the proposer builds. */ get slot() {
584
- return this.slotNow;
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;
585
620
  }
586
- /** The wall-clock epoch. */ get epoch() {
587
- return this.epochNow;
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
646
+ });
588
647
  }
589
648
  /**
590
649
  * Executes the checkpoint proposal job.
591
- * 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.
592
654
  */ async execute() {
593
655
  // Enqueue governance and slashing votes (returns promises that will be awaited later)
594
656
  // In fisherman mode, we simulate slashing but don't actually publish to L1
595
657
  // These are constant for the whole slot, so we only enqueue them once
596
658
  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();
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;
603
674
  }
675
+ const { checkpoint } = broadcast;
676
+ this.metrics.recordCheckpointProposalSuccess();
604
677
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
605
678
  if (this.config.fishermanMode) {
606
679
  await this.handleCheckpointEndAsFisherman(checkpoint);
607
- return;
680
+ return checkpoint;
608
681
  }
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
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)
616
765
  });
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;
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)
770
+ });
771
+ this.eventEmitter.emit('checkpoint-publish-failed', {
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;
625
794
  }
626
795
  }
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
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
634
827
  });
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
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
642
928
  });
643
- return undefined;
644
929
  }
645
930
  }
646
931
  async proposeCheckpoint() {
@@ -651,16 +936,28 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
651
936
  hasError: false
652
937
  };
653
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);
654
948
  // Get operator configured coinbase and fee recipient for this attestor
655
949
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
656
950
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
657
951
  // Start the checkpoint
658
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
659
- this.log.info(`Starting checkpoint proposal`, {
660
- buildSlot: this.slot,
952
+ this.setState(SequencerState.INITIALIZING_CHECKPOINT);
953
+ this.logCheckpointEvent('slot-started', `Starting checkpoint proposal for slot ${this.targetSlot}`, {
954
+ buildSlot: this.getBuildSlot(),
661
955
  submissionSlot: this.targetSlot,
662
- pipelining: this.epochCache.isProposerPipeliningEnabled(),
956
+ slot: this.targetSlot,
957
+ checkpointNumber: this.checkpointNumber,
663
958
  proposer: this.proposer?.toString(),
959
+ attestorAddress: this.attestorAddress.toString(),
960
+ publisherAddress: this.publisher.getSenderAddress().toString(),
664
961
  coinbase: coinbase.toString()
665
962
  });
666
963
  this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
@@ -668,15 +965,41 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
668
965
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
669
966
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
670
967
  }
671
- // Create checkpoint builder for the slot
672
- const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(coinbase, feeRecipient, this.targetSlot);
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);
673
982
  // Collect L1 to L2 messages for the checkpoint and compute their hash
674
983
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
675
984
  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();
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);
680
1003
  const fork = _ts_add_disposable_resource(env, await this.worldState.fork(this.syncedToBlockNumber, {
681
1004
  closeDelayMs: 12_000
682
1005
  }), true);
@@ -689,7 +1012,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
689
1012
  };
690
1013
  const checkpointProposalOptions = {
691
1014
  publishFullTxs: !!this.config.publishTxsWithProposals,
692
- broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal
1015
+ broadcastInvalidCheckpointProposal: this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal
693
1016
  };
694
1017
  let blocksInCheckpoint = [];
695
1018
  let blockPendingBroadcast = undefined;
@@ -709,8 +1032,15 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
709
1032
  throw err;
710
1033
  }
711
1034
  if (blocksInCheckpoint.length === 0) {
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
+ });
712
1040
  this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
713
- slot: this.targetSlot
1041
+ slot: this.targetSlot,
1042
+ checkpointNumber: this.checkpointNumber,
1043
+ reason: 'no_blocks_built'
714
1044
  });
715
1045
  this.eventEmitter.emit('checkpoint-empty', {
716
1046
  slot: this.targetSlot
@@ -719,16 +1049,25 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
719
1049
  }
720
1050
  const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
721
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
+ });
722
1059
  this.log.warn(`Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`, {
723
1060
  slot: this.targetSlot,
1061
+ checkpointNumber: this.checkpointNumber,
724
1062
  blocksBuilt: blocksInCheckpoint.length,
725
- minBlocksForCheckpoint
1063
+ minBlocksForCheckpoint,
1064
+ reason: 'min_blocks_not_met'
726
1065
  });
727
1066
  return undefined;
728
1067
  }
729
1068
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
730
1069
  // broadcasted yet, and wait to collect the committee attestations.
731
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
1070
+ this.setState(SequencerState.ASSEMBLING_CHECKPOINT);
732
1071
  const checkpoint = await checkpointBuilder.completeCheckpoint();
733
1072
  // Final validation: per-block limits are only checked if the operator set them explicitly.
734
1073
  // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
@@ -741,14 +1080,36 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
741
1080
  maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint
742
1081
  });
743
1082
  } catch (err) {
744
- 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',
745
1095
  checkpoint: checkpoint.header.toInspect()
746
1096
  });
747
1097
  return undefined;
748
1098
  }
749
1099
  // 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
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
752
1113
  if (this.config.fishermanMode) {
753
1114
  this.log.info(`Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` + `Skipping proposal in fisherman mode.`, {
754
1115
  slot: this.targetSlot,
@@ -756,53 +1117,58 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
756
1117
  blocksBuilt: blocksInCheckpoint.length
757
1118
  });
758
1119
  this.metrics.recordCheckpointSuccess();
759
- 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
+ };
760
1126
  }
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;
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.
778
1130
  try {
779
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer, this.targetSlot, this.checkpointNumber);
1131
+ await this.publisher.validateBlockHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
780
1132
  } 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;
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;
787
1144
  }
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;
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);
799
1161
  }
1162
+ } else if (!this.config.skipBroadcastProposals) {
1163
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
1164
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
800
1165
  }
801
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
802
- txTimeoutAt,
803
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber
804
- });
805
- return checkpoint;
1166
+ // Return immediately after broadcast — attestation collection happens in the background
1167
+ return {
1168
+ checkpoint,
1169
+ proposal,
1170
+ blockProposedAt
1171
+ };
806
1172
  } catch (e) {
807
1173
  env.error = e;
808
1174
  env.hasError = true;
@@ -815,7 +1181,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
815
1181
  // swallow this error. It's already been logged by a function deeper in the stack
816
1182
  return undefined;
817
1183
  }
818
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
1184
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
819
1185
  return undefined;
820
1186
  }
821
1187
  }
@@ -831,13 +1197,21 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
831
1197
  const blocksBuilt = blocksInCheckpoint.length;
832
1198
  const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
833
1199
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
834
- const secondsIntoSlot = this.getSecondsIntoSlot();
835
- 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);
836
1210
  if (!timingInfo.canStart) {
837
1211
  this.log.debug(`Not enough time left in slot to start another block`, {
838
1212
  slot: this.targetSlot,
839
1213
  blocksBuilt,
840
- secondsIntoSlot
1214
+ nowSeconds
841
1215
  });
842
1216
  break;
843
1217
  }
@@ -846,23 +1220,24 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
846
1220
  blockTimestamp: timestamp,
847
1221
  // Create an empty block if we haven't already and this is the last one
848
1222
  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,
1223
+ buildDeadline: new Date(timingInfo.deadline * 1000),
851
1224
  blockNumber,
852
1225
  indexWithinCheckpoint,
853
1226
  txHashesAlreadyIncluded
854
1227
  });
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
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
860
1235
  await this.waitUntilNextSubslot(timingInfo.deadline);
861
1236
  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
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) {
866
1241
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
867
1242
  this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
868
1243
  slot: this.targetSlot,
@@ -873,34 +1248,36 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
873
1248
  break;
874
1249
  }
875
1250
  const { block, usedTxs } = buildResult;
1251
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
1252
+ isFirstBlock: blocksBuilt === 0,
1253
+ isLastBlock: timingInfo.isLastBlock
1254
+ });
876
1255
  blocksInCheckpoint.push(block);
877
1256
  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.
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.
880
1268
  if (timingInfo.isLastBlock) {
881
- await this.syncProposedBlockToArchiver(block);
882
1269
  this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
883
1270
  slot: this.targetSlot,
884
1271
  blockNumber,
885
1272
  blocksBuilt
886
1273
  });
887
- blockPendingBroadcast = {
888
- block,
889
- txs: usedTxs
890
- };
1274
+ blockPendingBroadcast = proposal;
891
1275
  break;
892
1276
  }
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
1277
  // 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);
1278
+ if (proposal && !this.config.skipBroadcastProposals) {
1279
+ await this.p2pClient.broadcastProposal(proposal);
1280
+ }
904
1281
  // Wait until the next block's start time
905
1282
  await this.waitUntilNextSubslot(timingInfo.deadline);
906
1283
  }
@@ -918,14 +1295,17 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
918
1295
  this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
919
1296
  return Promise.resolve(undefined);
920
1297
  }
921
- return this.validatorClient.createBlockProposal(block.header, block.indexWithinCheckpoint, inHash, block.archive.root, usedTxs, this.proposer, blockProposalOptions);
1298
+ return this.validatorClient.createBlockProposal(block.header, this.checkpointNumber, block.indexWithinCheckpoint, inHash, block.archive.root, usedTxs, this.proposer, blockProposalOptions);
922
1299
  }
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`, {
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`, {
926
1306
  slot: this.targetSlot
927
1307
  });
928
- await this.waitUntilTimeInSlot(nextSubslotStart);
1308
+ await this.awaitInterruptibleSleep(Math.max(0, nextSubslotStart * 1000 - this.dateProvider.now()));
929
1309
  }
930
1310
  /** Builds a single block. Called from the main block building loop. */ async buildSingleBlock(checkpointBuilder, opts) {
931
1311
  const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } = opts;
@@ -937,10 +1317,23 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
937
1317
  // Wait until we have enough txs to build the block
938
1318
  const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
939
1319
  if (!canStartBuilding) {
1320
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1321
+ reason: 'insufficient_txs',
1322
+ blockNumber,
1323
+ slot: this.targetSlot,
1324
+ checkpointNumber: this.checkpointNumber,
1325
+ indexWithinCheckpoint,
1326
+ availableTxs,
1327
+ minTxs
1328
+ });
940
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',
941
1331
  blockNumber,
942
1332
  slot: this.targetSlot,
943
- indexWithinCheckpoint
1333
+ checkpointNumber: this.checkpointNumber,
1334
+ indexWithinCheckpoint,
1335
+ availableTxs,
1336
+ minTxs
944
1337
  });
945
1338
  this.eventEmitter.emit('block-tx-count-check-failed', {
946
1339
  minTxs,
@@ -948,17 +1341,23 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
948
1341
  slot: this.targetSlot
949
1342
  });
950
1343
  this.metrics.recordBlockProposalFailed('insufficient_txs');
951
- return undefined;
1344
+ return {
1345
+ failure: 'insufficient-txs'
1346
+ };
952
1347
  }
953
1348
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
954
1349
  // 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()));
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()));
956
1355
  this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`, {
957
1356
  slot: this.targetSlot,
958
1357
  blockNumber,
959
1358
  indexWithinCheckpoint
960
1359
  });
961
- this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
1360
+ this.setState(SequencerState.CREATING_BLOCK);
962
1361
  // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
963
1362
  // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
964
1363
  // minValidTxs is passed into the builder so it can reject the block *before* updating state.
@@ -969,8 +1368,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
969
1368
  deadline: buildDeadline,
970
1369
  isBuildingProposal: true,
971
1370
  minValidTxs,
972
- maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
973
- perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier
1371
+ maxBlocksPerCheckpoint: this.timetable.getMaxBlocksPerCheckpoint(),
1372
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
1373
+ perBlockDAAllocationMultiplier: this.config.perBlockDAAllocationMultiplier
974
1374
  };
975
1375
  // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
976
1376
  // if the number of successfully processed txs is below minValidTxs, ensuring state is not
@@ -979,8 +1379,19 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
979
1379
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
980
1380
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
981
1381
  if (buildResult.status === 'insufficient-valid-txs') {
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
+ });
982
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',
983
1393
  slot: this.targetSlot,
1394
+ checkpointNumber: this.checkpointNumber,
984
1395
  blockNumber,
985
1396
  numTxs: buildResult.processedCount,
986
1397
  indexWithinCheckpoint,
@@ -991,7 +1402,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
991
1402
  slot: this.targetSlot
992
1403
  });
993
1404
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
994
- return undefined;
1405
+ return {
1406
+ failure: 'insufficient-valid-txs'
1407
+ };
995
1408
  }
996
1409
  // Block creation succeeded, emit stats and metrics
997
1410
  const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
@@ -1010,12 +1423,17 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1010
1423
  manaPerSec,
1011
1424
  ...blockStats
1012
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.
1013
1428
  this.eventEmitter.emit('block-proposed', {
1014
1429
  blockNumber: block.number,
1430
+ blockHash,
1431
+ checkpointNumber: this.checkpointNumber,
1432
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1015
1433
  slot: this.targetSlot,
1016
- buildSlot: this.slotNow
1434
+ buildSlot: this.getBuildSlot()
1017
1435
  });
1018
- this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
1436
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
1019
1437
  return {
1020
1438
  block,
1021
1439
  usedTxs
@@ -1025,9 +1443,17 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1025
1443
  reason: err.message,
1026
1444
  slot: this.targetSlot
1027
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
1451
+ });
1028
1452
  this.log.error(`Error building block`, err, {
1029
- blockNumber,
1030
- slot: this.targetSlot
1453
+ reason: err instanceof Error ? err.message : String(err),
1454
+ slot: this.targetSlot,
1455
+ checkpointNumber: this.checkpointNumber,
1456
+ blockNumber
1031
1457
  });
1032
1458
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
1033
1459
  this.metrics.recordFailedBlock();
@@ -1061,8 +1487,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1061
1487
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
1062
1488
  // We only allow a block with 0 txs in the first block of the checkpoint
1063
1489
  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;
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;
1066
1492
  let availableTxs = await this.p2pClient.getPendingTxCount();
1067
1493
  while(!forceCreate && availableTxs < minTxs){
1068
1494
  // If we're past deadline, or we have no deadline, give up
@@ -1075,7 +1501,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1075
1501
  };
1076
1502
  }
1077
1503
  // Wait a bit before checking again
1078
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
1504
+ this.setState(SequencerState.WAITING_FOR_TXS);
1079
1505
  this.log.verbose(`Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`, {
1080
1506
  blockNumber,
1081
1507
  slot: this.targetSlot,
@@ -1090,13 +1516,37 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1090
1516
  minTxs
1091
1517
  };
1092
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
+ }
1093
1543
  /**
1094
1544
  * Waits for enough attestations to be collected via p2p.
1095
1545
  * This is run after all blocks for the checkpoint have been built.
1096
1546
  */ async waitForAttestations(proposal) {
1097
1547
  if (this.config.fishermanMode) {
1098
1548
  this.log.debug('Skipping attestation collection in fisherman mode');
1099
- return CommitteeAttestationsAndSigners.empty();
1549
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1100
1550
  }
1101
1551
  const slotNumber = proposal.slotNumber;
1102
1552
  const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
@@ -1104,25 +1554,29 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1104
1554
  throw new Error('No committee when collecting attestations');
1105
1555
  } else if (committee.length === 0) {
1106
1556
  this.log.verbose(`Attesting committee is empty`);
1107
- return CommitteeAttestationsAndSigners.empty();
1557
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1108
1558
  } else {
1109
1559
  this.log.debug(`Attesting committee length is ${committee.length}`, {
1110
1560
  committee
1111
1561
  });
1112
1562
  }
1113
- const numberOfRequiredAttestations = Math.floor(committee.length * 2 / 3) + 1;
1563
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
1114
1564
  if (this.config.skipCollectingAttestations) {
1115
1565
  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));
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());
1118
1571
  }
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);
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()));
1122
1576
  const collectAttestationsTimer = new Timer();
1123
1577
  let collectedAttestationsCount = 0;
1124
1578
  try {
1125
- const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline);
1579
+ const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline, this.checkpointNumber);
1126
1580
  collectedAttestationsCount = attestations.length;
1127
1581
  // Trim attestations to minimum required to save L1 calldata gas
1128
1582
  const localAddresses = this.validatorClient.getValidatorAddresses();
@@ -1132,20 +1586,55 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1132
1586
  }
1133
1587
  // Rollup contract requires that the signatures are provided in the order of the committee
1134
1588
  const sorted = orderAttestations(trimmed, committee);
1589
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1590
+ submittedCount: trimmed.length
1591
+ });
1135
1592
  // Manipulate the attestations if we've been configured to do so
1136
1593
  if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation || this.config.shuffleAttestationOrdering) {
1137
1594
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
1138
1595
  }
1139
- return new CommitteeAttestationsAndSigners(sorted);
1596
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
1140
1597
  } catch (err) {
1141
1598
  if (err && err instanceof AttestationTimeoutError) {
1142
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);
1143
1611
  }
1144
- throw err;
1612
+ return undefined;
1145
1613
  } finally{
1146
1614
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
1147
1615
  }
1148
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
+ }
1149
1638
  /** Breaks the attestations before publishing based on attack configs */ manipulateAttestations(slotNumber, epoch, seed, committee, attestations) {
1150
1639
  // Compute the proposer index in the committee, since we dont want to tweak it.
1151
1640
  // Otherwise, the L1 rollup contract will reject the block outright.
@@ -1171,7 +1660,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1171
1660
  unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
1172
1661
  }
1173
1662
  }
1174
- return new CommitteeAttestationsAndSigners(attestations);
1663
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1175
1664
  }
1176
1665
  if (this.config.shuffleAttestationOrdering) {
1177
1666
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
@@ -1197,10 +1686,10 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1197
1686
  shuffled[i]
1198
1687
  ];
1199
1688
  }
1200
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
1201
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
1689
+ const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
1690
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
1202
1691
  }
1203
- return new CommitteeAttestationsAndSigners(attestations);
1692
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1204
1693
  }
1205
1694
  async dropFailedTxsFromP2P(failedTxs) {
1206
1695
  if (failedTxs.length === 0) {
@@ -1215,8 +1704,12 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1215
1704
  * Adds the proposed block to the archiver so it's available via P2P.
1216
1705
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1217
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.
1218
1711
  */ async syncProposedBlockToArchiver(block) {
1219
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1712
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1220
1713
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1221
1714
  blockNumber: block.number,
1222
1715
  slot: block.header.globalVariables.slotNumber
@@ -1229,6 +1722,35 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1229
1722
  });
1230
1723
  await this.blockSink.addBlock(block);
1231
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
+ }
1232
1754
  /** Runs fee analysis and logs checkpoint outcome as fisherman */ async handleCheckpointEndAsFisherman(checkpoint) {
1233
1755
  // Perform L1 fee analysis before clearing requests
1234
1756
  // The callback is invoked asynchronously after the next block is mined
@@ -1268,20 +1790,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1268
1790
  }
1269
1791
  return false;
1270
1792
  }
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
1793
  /** 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));
1794
+ await this.awaitInterruptibleSleep(TXS_POLLING_MS);
1285
1795
  }
1286
1796
  getPublisher() {
1287
1797
  return this.publisher;