@aztec/sequencer-client 0.0.1-commit.96dac018d → 0.0.1-commit.993d240

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