@aztec/sequencer-client 0.0.1-commit.86469d5 → 0.0.1-commit.8655d4a

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 (125) hide show
  1. package/README.md +282 -21
  2. package/dest/client/sequencer-client.d.ts +19 -9
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +67 -33
  5. package/dest/config.d.ts +29 -7
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +77 -37
  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 -16
  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 +47 -17
  24. package/dest/publisher/config.d.ts.map +1 -1
  25. package/dest/publisher/config.js +121 -42
  26. package/dest/publisher/index.d.ts +2 -1
  27. package/dest/publisher/index.d.ts.map +1 -1
  28. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  29. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  31. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  32. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  33. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  34. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  35. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  36. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  37. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  38. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  39. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  40. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  41. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  42. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  43. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -5
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +27 -3
  46. package/dest/publisher/sequencer-publisher.d.ts +94 -67
  47. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher.js +440 -378
  49. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  50. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  51. package/dest/sequencer/automine/automine_factory.js +84 -0
  52. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  53. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  54. package/dest/sequencer/automine/automine_sequencer.js +506 -0
  55. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  56. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  57. package/dest/sequencer/chain_state_overrides.js +98 -0
  58. package/dest/sequencer/checkpoint_proposal_job.d.ts +56 -11
  59. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  60. package/dest/sequencer/checkpoint_proposal_job.js +805 -225
  61. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  62. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  63. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  64. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  65. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  66. package/dest/sequencer/checkpoint_voter.js +2 -5
  67. package/dest/sequencer/events.d.ts +47 -2
  68. package/dest/sequencer/events.d.ts.map +1 -1
  69. package/dest/sequencer/index.d.ts +3 -1
  70. package/dest/sequencer/index.d.ts.map +1 -1
  71. package/dest/sequencer/index.js +2 -0
  72. package/dest/sequencer/metrics.d.ts +23 -8
  73. package/dest/sequencer/metrics.d.ts.map +1 -1
  74. package/dest/sequencer/metrics.js +117 -21
  75. package/dest/sequencer/sequencer.d.ts +74 -21
  76. package/dest/sequencer/sequencer.d.ts.map +1 -1
  77. package/dest/sequencer/sequencer.js +353 -136
  78. package/dest/sequencer/timetable.d.ts +17 -6
  79. package/dest/sequencer/timetable.d.ts.map +1 -1
  80. package/dest/sequencer/timetable.js +51 -46
  81. package/dest/sequencer/types.d.ts +2 -2
  82. package/dest/sequencer/types.d.ts.map +1 -1
  83. package/dest/test/index.d.ts +3 -5
  84. package/dest/test/index.d.ts.map +1 -1
  85. package/dest/test/mock_checkpoint_builder.d.ts +11 -11
  86. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  87. package/dest/test/mock_checkpoint_builder.js +45 -34
  88. package/dest/test/utils.d.ts +3 -3
  89. package/dest/test/utils.d.ts.map +1 -1
  90. package/dest/test/utils.js +10 -8
  91. package/package.json +27 -28
  92. package/src/client/sequencer-client.ts +92 -35
  93. package/src/config.ts +102 -46
  94. package/src/global_variable_builder/README.md +44 -0
  95. package/src/global_variable_builder/fee_predictor.ts +172 -0
  96. package/src/global_variable_builder/fee_provider.ts +75 -0
  97. package/src/global_variable_builder/global_builder.ts +26 -63
  98. package/src/global_variable_builder/index.ts +3 -1
  99. package/src/index.ts +10 -1
  100. package/src/publisher/config.ts +157 -45
  101. package/src/publisher/index.ts +3 -0
  102. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  103. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  104. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  105. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  106. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  107. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  108. package/src/publisher/sequencer-publisher.ts +533 -469
  109. package/src/sequencer/README.md +152 -450
  110. package/src/sequencer/automine/README.md +46 -0
  111. package/src/sequencer/automine/automine_factory.ts +145 -0
  112. package/src/sequencer/automine/automine_sequencer.ts +592 -0
  113. package/src/sequencer/chain_state_overrides.ts +162 -0
  114. package/src/sequencer/checkpoint_proposal_job.ts +984 -245
  115. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  116. package/src/sequencer/checkpoint_voter.ts +1 -12
  117. package/src/sequencer/events.ts +50 -2
  118. package/src/sequencer/index.ts +2 -0
  119. package/src/sequencer/metrics.ts +132 -25
  120. package/src/sequencer/sequencer.ts +444 -154
  121. package/src/sequencer/timetable.ts +70 -57
  122. package/src/sequencer/types.ts +1 -1
  123. package/src/test/index.ts +2 -4
  124. package/src/test/mock_checkpoint_builder.ts +63 -49
  125. package/src/test/utils.ts +31 -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
- import { orderAttestations } from '@aztec/stdlib/p2p';
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.recordBlockProposalSuccess();
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,29 +895,77 @@ _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 previousCheckpoints = (await this.l2BlockSource.getCheckpointsForEpoch(this.epoch)).filter((c)=>c.number < this.checkpointNumber);
644
- const previousCheckpointOutHashes = previousCheckpoints.map((c)=>c.getCheckpointOutHash());
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);
645
964
  const fork = _ts_add_disposable_resource(env, await this.worldState.fork(this.syncedToBlockNumber, {
646
965
  closeDelayMs: 12_000
647
- }), false);
966
+ }), true);
648
967
  // Create checkpoint builder for the entire slot
649
- const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, l1ToL2Messages, previousCheckpointOutHashes, fork, this.log.getBindings());
968
+ const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, this.log.getBindings());
650
969
  // Options for the validator client when creating block and checkpoint proposals
651
970
  const blockProposalOptions = {
652
971
  publishFullTxs: !!this.config.publishTxsWithProposals,
@@ -654,10 +973,11 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
654
973
  };
655
974
  const checkpointProposalOptions = {
656
975
  publishFullTxs: !!this.config.publishTxsWithProposals,
657
- broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal
976
+ broadcastInvalidCheckpointProposal: this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal
658
977
  };
659
978
  let blocksInCheckpoint = [];
660
979
  let blockPendingBroadcast = undefined;
980
+ const checkpointBuildTimer = new Timer();
661
981
  try {
662
982
  // Main loop: build blocks for the checkpoint
663
983
  const result = await this.buildBlocksForCheckpoint(checkpointBuilder, checkpointGlobalVariables.timestamp, inHash, blockProposalOptions);
@@ -673,77 +993,156 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
673
993
  throw err;
674
994
  }
675
995
  if (blocksInCheckpoint.length === 0) {
676
- this.log.warn(`No blocks were built for slot ${this.slot}`, {
677
- 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'
678
1005
  });
679
1006
  this.eventEmitter.emit('checkpoint-empty', {
680
- slot: this.slot
1007
+ slot: this.targetSlot
1008
+ });
1009
+ return undefined;
1010
+ }
1011
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
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
+ });
1020
+ this.log.warn(`Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`, {
1021
+ slot: this.targetSlot,
1022
+ checkpointNumber: this.checkpointNumber,
1023
+ blocksBuilt: blocksInCheckpoint.length,
1024
+ minBlocksForCheckpoint,
1025
+ reason: 'min_blocks_not_met'
681
1026
  });
682
1027
  return undefined;
683
1028
  }
684
1029
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
685
1030
  // broadcasted yet, and wait to collect the committee attestations.
686
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
1031
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
687
1032
  const checkpoint = await checkpointBuilder.completeCheckpoint();
688
- // Do not collect attestations nor publish to L1 in fisherman mode
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
+ }
1060
+ // Record checkpoint-level build metrics
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
689
1074
  if (this.config.fishermanMode) {
690
- this.log.info(`Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` + `Skipping proposal in fisherman mode.`, {
691
- 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,
692
1077
  checkpoint: checkpoint.header.toInspect(),
693
1078
  blocksBuilt: blocksInCheckpoint.length
694
1079
  });
695
1080
  this.metrics.recordCheckpointSuccess();
696
- 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
+ };
697
1087
  }
698
- // Include the block pending broadcast in the checkpoint proposal if any
699
- const lastBlock = blockPendingBroadcast && {
700
- blockHeader: blockPendingBroadcast.block.header,
701
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
702
- txs: blockPendingBroadcast.txs
703
- };
704
- // Create the checkpoint proposal and broadcast it
705
- const proposal = await this.validatorClient.createCheckpointProposal(checkpoint.header, checkpoint.archive.root, lastBlock, this.proposer, checkpointProposalOptions);
706
- const blockProposedAt = this.dateProvider.now();
707
- await this.p2pClient.broadcastCheckpointProposal(proposal);
708
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
709
- const attestations = await this.waitForAttestations(proposal);
710
- const blockAttestedAt = this.dateProvider.now();
711
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
712
- // Proposer must sign over the attestations before pushing them to L1
713
- const signer = this.proposer ?? this.publisher.getSenderAddress();
714
- 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.
715
1091
  try {
716
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer, this.slot, this.checkpointNumber);
1092
+ await this.publisher.validateBlockHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
717
1093
  } catch (err) {
718
- // We shouldn't really get here since we yield to another HA node
719
- // as soon as we see these errors when creating block or checkpoint proposals.
720
- if (this.handleHASigningError(err, 'Attestations signature')) {
721
- return undefined;
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;
1105
+ }
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);
722
1122
  }
723
- throw err;
1123
+ } else if (!this.config.skipBroadcastProposals) {
1124
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
1125
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
724
1126
  }
725
- // Enqueue publishing the checkpoint to L1
726
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
727
- const aztecSlotDuration = this.l1Constants.slotDuration;
728
- const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
729
- const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
730
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
731
- txTimeoutAt,
732
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber
733
- });
734
- return checkpoint;
1127
+ // Return immediately after broadcast attestation collection happens in the background
1128
+ return {
1129
+ checkpoint,
1130
+ proposal,
1131
+ blockProposedAt
1132
+ };
735
1133
  } catch (e) {
736
1134
  env.error = e;
737
1135
  env.hasError = true;
738
1136
  } finally{
739
- _ts_dispose_resources(env);
1137
+ const result = _ts_dispose_resources(env);
1138
+ if (result) await result;
740
1139
  }
741
1140
  } catch (err) {
742
1141
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
743
1142
  // swallow this error. It's already been logged by a function deeper in the stack
744
1143
  return undefined;
745
1144
  }
746
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
1145
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
747
1146
  return undefined;
748
1147
  }
749
1148
  }
@@ -753,19 +1152,25 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
753
1152
  const blocksInCheckpoint = [];
754
1153
  const txHashesAlreadyIncluded = new Set();
755
1154
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
756
- // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
757
- let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
758
1155
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
759
1156
  let blockPendingBroadcast = undefined;
760
1157
  while(true){
761
1158
  const blocksBuilt = blocksInCheckpoint.length;
762
1159
  const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
763
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
+ }
764
1169
  const secondsIntoSlot = this.getSecondsIntoSlot();
765
1170
  const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
766
1171
  if (!timingInfo.canStart) {
767
1172
  this.log.debug(`Not enough time left in slot to start another block`, {
768
- slot: this.slot,
1173
+ slot: this.targetSlot,
769
1174
  blocksBuilt,
770
1175
  secondsIntoSlot
771
1176
  });
@@ -780,68 +1185,66 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
780
1185
  buildDeadline: timingInfo.deadline ? new Date((this.getSlotStartBuildTimestamp() + timingInfo.deadline) * 1000) : undefined,
781
1186
  blockNumber,
782
1187
  indexWithinCheckpoint,
783
- txHashesAlreadyIncluded,
784
- remainingBlobFields
1188
+ txHashesAlreadyIncluded
785
1189
  });
786
- // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
787
- if (!buildResult && timingInfo.isLastBlock) {
788
- break;
789
- } else if (!buildResult && timingInfo.deadline !== undefined) {
790
- // 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
791
1197
  await this.waitUntilNextSubslot(timingInfo.deadline);
792
1198
  continue;
793
- } else if (!buildResult) {
794
- break;
795
- } else if ('error' in buildResult) {
796
- // 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) {
797
1203
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
798
- this.log.warn(`Halting block building for slot ${this.slot}`, {
799
- slot: this.slot,
1204
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
1205
+ slot: this.targetSlot,
800
1206
  blocksBuilt,
801
1207
  error: buildResult.error
802
1208
  });
803
1209
  }
804
1210
  break;
805
1211
  }
806
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
807
- blocksInCheckpoint.push(block);
808
- // Update remaining blob fields for the next block
809
- remainingBlobFields = newRemainingBlobFields;
810
- // Sync the proposed block to the archiver to make it available
811
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
812
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
813
- // Fire and forget - don't block the critical path, but log errors
814
- this.syncProposedBlockToArchiver(block).catch((err)=>{
815
- this.log.error(`Failed to sync proposed block ${block.number} to archiver`, {
816
- blockNumber: block.number,
817
- err
818
- });
1212
+ const { block, usedTxs } = buildResult;
1213
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
1214
+ isFirstBlock: blocksBuilt === 0,
1215
+ isLastBlock: timingInfo.isLastBlock
819
1216
  });
1217
+ blocksInCheckpoint.push(block);
820
1218
  usedTxs.forEach((tx)=>txHashesAlreadyIncluded.add(tx.txHash.toString()));
821
- // 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.
822
1230
  if (timingInfo.isLastBlock) {
823
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
824
- slot: this.slot,
1231
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
1232
+ slot: this.targetSlot,
825
1233
  blockNumber,
826
1234
  blocksBuilt
827
1235
  });
828
- blockPendingBroadcast = {
829
- block,
830
- txs: usedTxs
831
- };
1236
+ blockPendingBroadcast = proposal;
832
1237
  break;
833
1238
  }
834
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
835
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
836
- if (!this.config.fishermanMode) {
837
- 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) {
838
1241
  await this.p2pClient.broadcastProposal(proposal);
839
1242
  }
840
1243
  // Wait until the next block's start time
841
1244
  await this.waitUntilNextSubslot(timingInfo.deadline);
842
1245
  }
843
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
844
- slot: this.slot,
1246
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
1247
+ slot: this.targetSlot,
845
1248
  blocksBuilt: blocksInCheckpoint.length
846
1249
  });
847
1250
  return {
@@ -849,82 +1252,116 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
849
1252
  blockPendingBroadcast
850
1253
  };
851
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
+ }
852
1262
  /** Sleeps until it is time to produce the next block in the slot */ async waitUntilNextSubslot(nextSubslotStart) {
853
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
1263
+ this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
854
1264
  this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
855
- slot: this.slot
1265
+ slot: this.targetSlot
856
1266
  });
857
1267
  await this.waitUntilTimeInSlot(nextSubslotStart);
858
1268
  }
859
1269
  /** Builds a single block. Called from the main block building loop. */ async buildSingleBlock(checkpointBuilder, opts) {
860
- const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded, remainingBlobFields } = opts;
861
- 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}`, {
862
1272
  ...checkpointBuilder.getConstantData(),
863
1273
  ...opts
864
1274
  });
865
1275
  try {
866
1276
  // Wait until we have enough txs to build the block
867
- const minTxs = this.config.minTxsPerBlock;
868
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
1277
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
869
1278
  if (!canStartBuilding) {
870
- 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',
1281
+ blockNumber,
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',
871
1290
  blockNumber,
872
- slot: this.slot,
873
- indexWithinCheckpoint
1291
+ slot: this.targetSlot,
1292
+ checkpointNumber: this.checkpointNumber,
1293
+ indexWithinCheckpoint,
1294
+ availableTxs,
1295
+ minTxs
874
1296
  });
875
1297
  this.eventEmitter.emit('block-tx-count-check-failed', {
876
1298
  minTxs,
877
1299
  availableTxs,
878
- slot: this.slot
1300
+ slot: this.targetSlot
879
1301
  });
880
1302
  this.metrics.recordBlockProposalFailed('insufficient_txs');
881
- return undefined;
1303
+ return {
1304
+ failure: 'insufficient-txs'
1305
+ };
882
1306
  }
883
1307
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
884
1308
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
885
- const pendingTxs = filter(this.p2pClient.iteratePendingTxs(), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
886
- this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`, {
887
- slot: this.slot,
1309
+ const pendingTxs = filter(this.p2pClient.iterateEligiblePendingTxs(), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
1310
+ this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`, {
1311
+ slot: this.targetSlot,
888
1312
  blockNumber,
889
1313
  indexWithinCheckpoint
890
1314
  });
891
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
892
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
893
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
894
- 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;
895
1320
  const blockBuilderOptions = {
896
1321
  maxTransactions: this.config.maxTxsPerBlock,
897
- maxBlockSize: this.config.maxBlockSizeInBytes,
898
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
899
- maxBlobFields: maxBlobFieldsForTxs,
900
- 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
901
1328
  };
902
- // 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.
903
1332
  const buildResult = await this.buildSingleBlockWithCheckpointBuilder(checkpointBuilder, pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
904
1333
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
905
1334
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
906
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
907
- // too long, then we may not get to minTxsPerBlock after executing public functions.
908
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
909
- const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
910
- if (buildResult.status === 'no-valid-txs' || !forceCreate && numTxs < minValidTxs) {
911
- this.log.warn(`Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`, {
912
- 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,
913
1349
  blockNumber,
914
- numTxs,
1350
+ numTxs: buildResult.processedCount,
915
1351
  indexWithinCheckpoint,
916
- minValidTxs,
917
- buildResult: buildResult.status
1352
+ minValidTxs
918
1353
  });
919
1354
  this.eventEmitter.emit('block-build-failed', {
920
1355
  reason: `Insufficient valid txs`,
921
- slot: this.slot
1356
+ slot: this.targetSlot
922
1357
  });
923
1358
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
924
- return undefined;
1359
+ return {
1360
+ failure: 'insufficient-valid-txs'
1361
+ };
925
1362
  }
926
1363
  // Block creation succeeded, emit stats and metrics
927
- const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
1364
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
928
1365
  const blockStats = {
929
1366
  eventName: 'l2-block-built',
930
1367
  duration: blockBuildDuration,
@@ -933,31 +1370,44 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
933
1370
  };
934
1371
  const blockHash = await block.hash();
935
1372
  const txHashes = block.body.txEffects.map((tx)=>tx.txHash);
936
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
937
- 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`, {
938
1375
  blockHash,
939
1376
  txHashes,
940
1377
  manaPerSec,
941
1378
  ...blockStats
942
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.
943
1382
  this.eventEmitter.emit('block-proposed', {
944
1383
  blockNumber: block.number,
945
- slot: this.slot
1384
+ blockHash,
1385
+ checkpointNumber: this.checkpointNumber,
1386
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1387
+ slot: this.targetSlot,
1388
+ buildSlot: this.slotNow
946
1389
  });
947
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
1390
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
948
1391
  return {
949
1392
  block,
950
- usedTxs,
951
- remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields
1393
+ usedTxs
952
1394
  };
953
1395
  } catch (err) {
954
1396
  this.eventEmitter.emit('block-build-failed', {
955
1397
  reason: err.message,
956
- 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
957
1405
  });
958
1406
  this.log.error(`Error building block`, err, {
959
- blockNumber,
960
- slot: this.slot
1407
+ reason: err instanceof Error ? err.message : String(err),
1408
+ slot: this.targetSlot,
1409
+ checkpointNumber: this.checkpointNumber,
1410
+ blockNumber
961
1411
  });
962
1412
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
963
1413
  this.metrics.recordFailedBlock();
@@ -966,7 +1416,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
966
1416
  };
967
1417
  }
968
1418
  }
969
- /** 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) {
970
1420
  try {
971
1421
  const workTimer = new Timer();
972
1422
  const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
@@ -977,10 +1427,11 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
977
1427
  status: 'success'
978
1428
  };
979
1429
  } catch (err) {
980
- if (isErrorClass(err, NoValidTxsError)) {
1430
+ if (isErrorClass(err, InsufficientValidTxsError)) {
981
1431
  return {
982
1432
  failedTxs: err.failedTxs,
983
- status: 'no-valid-txs'
1433
+ processedCount: err.processedCount,
1434
+ status: 'insufficient-valid-txs'
984
1435
  };
985
1436
  }
986
1437
  throw err;
@@ -999,31 +1450,57 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
999
1450
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
1000
1451
  return {
1001
1452
  canStartBuilding: false,
1002
- availableTxs: availableTxs
1453
+ availableTxs,
1454
+ minTxs
1003
1455
  };
1004
1456
  }
1005
1457
  // Wait a bit before checking again
1006
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
1007
- 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})`, {
1008
1460
  blockNumber,
1009
- slot: this.slot,
1461
+ slot: this.targetSlot,
1010
1462
  indexWithinCheckpoint
1011
1463
  });
1012
- await sleep(TXS_POLLING_MS);
1464
+ await this.waitForTxsPollingInterval();
1013
1465
  availableTxs = await this.p2pClient.getPendingTxCount();
1014
1466
  }
1015
1467
  return {
1016
1468
  canStartBuilding: true,
1017
- availableTxs
1469
+ availableTxs,
1470
+ minTxs
1018
1471
  };
1019
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
+ }
1020
1497
  /**
1021
1498
  * Waits for enough attestations to be collected via p2p.
1022
1499
  * This is run after all blocks for the checkpoint have been built.
1023
1500
  */ async waitForAttestations(proposal) {
1024
1501
  if (this.config.fishermanMode) {
1025
1502
  this.log.debug('Skipping attestation collection in fisherman mode');
1026
- return CommitteeAttestationsAndSigners.empty();
1503
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1027
1504
  }
1028
1505
  const slotNumber = proposal.slotNumber;
1029
1506
  const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
@@ -1031,47 +1508,91 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1031
1508
  throw new Error('No committee when collecting attestations');
1032
1509
  } else if (committee.length === 0) {
1033
1510
  this.log.verbose(`Attesting committee is empty`);
1034
- return CommitteeAttestationsAndSigners.empty();
1511
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1035
1512
  } else {
1036
1513
  this.log.debug(`Attesting committee length is ${committee.length}`, {
1037
1514
  committee
1038
1515
  });
1039
1516
  }
1040
- const numberOfRequiredAttestations = Math.floor(committee.length * 2 / 3) + 1;
1517
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
1041
1518
  if (this.config.skipCollectingAttestations) {
1042
1519
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
1043
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
1044
- 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());
1045
1525
  }
1046
- 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;
1047
1527
  const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
1048
1528
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
1049
1529
  const collectAttestationsTimer = new Timer();
1050
1530
  let collectedAttestationsCount = 0;
1051
1531
  try {
1052
- const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline);
1532
+ const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline, this.checkpointNumber);
1053
1533
  collectedAttestationsCount = attestations.length;
1534
+ // Trim attestations to minimum required to save L1 calldata gas
1535
+ const localAddresses = this.validatorClient.getValidatorAddresses();
1536
+ const trimmed = trimAttestations(attestations, numberOfRequiredAttestations, this.attestorAddress, localAddresses);
1537
+ if (trimmed.length < attestations.length) {
1538
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
1539
+ }
1054
1540
  // Rollup contract requires that the signatures are provided in the order of the committee
1055
- const sorted = orderAttestations(attestations, committee);
1541
+ const sorted = orderAttestations(trimmed, committee);
1542
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1543
+ submittedCount: trimmed.length
1544
+ });
1056
1545
  // Manipulate the attestations if we've been configured to do so
1057
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
1546
+ if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation || this.config.shuffleAttestationOrdering) {
1058
1547
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
1059
1548
  }
1060
- return new CommitteeAttestationsAndSigners(sorted);
1549
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
1061
1550
  } catch (err) {
1062
1551
  if (err && err instanceof AttestationTimeoutError) {
1063
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);
1064
1564
  }
1065
- throw err;
1565
+ return undefined;
1066
1566
  } finally{
1067
1567
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
1068
1568
  }
1069
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
+ }
1070
1591
  /** Breaks the attestations before publishing based on attack configs */ manipulateAttestations(slotNumber, epoch, seed, committee, attestations) {
1071
1592
  // Compute the proposer index in the committee, since we dont want to tweak it.
1072
1593
  // Otherwise, the L1 rollup contract will reject the block outright.
1073
1594
  const proposerIndex = Number(this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)));
1074
- if (this.config.injectFakeAttestation) {
1595
+ if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation) {
1075
1596
  // Find non-empty attestations that are not from the proposer
1076
1597
  const nonProposerIndices = [];
1077
1598
  for(let i = 0; i < attestations.length; i++){
@@ -1081,28 +1602,47 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1081
1602
  }
1082
1603
  if (nonProposerIndices.length > 0) {
1083
1604
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
1084
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1085
- 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
+ }
1086
1615
  }
1087
- return new CommitteeAttestationsAndSigners(attestations);
1616
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1088
1617
  }
1089
1618
  if (this.config.shuffleAttestationOrdering) {
1090
1619
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
1091
1620
  const shuffled = [
1092
1621
  ...attestations
1093
1622
  ];
1094
- const [i, j] = [
1095
- (proposerIndex + 1) % shuffled.length,
1096
- (proposerIndex + 2) % shuffled.length
1097
- ];
1098
- const valueI = shuffled[i];
1099
- const valueJ = shuffled[j];
1100
- shuffled[i] = valueJ;
1101
- shuffled[j] = valueI;
1102
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
1103
- 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());
1104
1644
  }
1105
- return new CommitteeAttestationsAndSigners(attestations);
1645
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1106
1646
  }
1107
1647
  async dropFailedTxsFromP2P(failedTxs) {
1108
1648
  if (failedTxs.length === 0) {
@@ -1111,14 +1651,18 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1111
1651
  const failedTxData = failedTxs.map((fail)=>fail.tx);
1112
1652
  const failedTxHashes = failedTxData.map((tx)=>tx.getTxHash());
1113
1653
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
1114
- await this.p2pClient.deleteTxs(failedTxHashes);
1654
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
1115
1655
  }
1116
1656
  /**
1117
1657
  * Adds the proposed block to the archiver so it's available via P2P.
1118
1658
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1119
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.
1120
1664
  */ async syncProposedBlockToArchiver(block) {
1121
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1665
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1122
1666
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1123
1667
  blockNumber: block.number,
1124
1668
  slot: block.header.globalVariables.slotNumber
@@ -1131,22 +1675,55 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1131
1675
  });
1132
1676
  await this.blockSink.addBlock(block);
1133
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
+ }
1134
1711
  /** Runs fee analysis and logs checkpoint outcome as fisherman */ async handleCheckpointEndAsFisherman(checkpoint) {
1135
1712
  // Perform L1 fee analysis before clearing requests
1136
1713
  // The callback is invoked asynchronously after the next block is mined
1137
- 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));
1138
1715
  if (checkpoint) {
1139
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1716
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
1140
1717
  ...checkpoint.toCheckpointInfo(),
1141
1718
  ...checkpoint.getStats(),
1142
1719
  feeAnalysisId: feeAnalysis?.id
1143
1720
  });
1144
1721
  } else {
1145
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
1146
- slot: this.slot,
1722
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1723
+ slot: this.targetSlot,
1147
1724
  feeAnalysisId: feeAnalysis?.id
1148
1725
  });
1149
- this.metrics.recordBlockProposalFailed('block_build_failed');
1726
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
1150
1727
  }
1151
1728
  this.publisher.clearPendingRequests();
1152
1729
  }
@@ -1154,15 +1731,15 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1154
1731
  * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
1155
1732
  */ handleHASigningError(err, errorContext) {
1156
1733
  if (err instanceof DutyAlreadySignedError) {
1157
- this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
1158
- slot: this.slot,
1734
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1735
+ slot: this.targetSlot,
1159
1736
  signedByNode: err.signedByNode
1160
1737
  });
1161
1738
  return true;
1162
1739
  }
1163
1740
  if (err instanceof SlashingProtectionError) {
1164
- this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
1165
- slot: this.slot,
1741
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1742
+ slot: this.targetSlot,
1166
1743
  existingMessageHash: err.existingMessageHash,
1167
1744
  attemptedMessageHash: err.attemptedMessageHash
1168
1745
  });
@@ -1175,8 +1752,11 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1175
1752
  const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
1176
1753
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
1177
1754
  }
1755
+ /** Waits the polling interval for transactions. Extracted for test overriding. */ async waitForTxsPollingInterval() {
1756
+ await sleep(TXS_POLLING_MS);
1757
+ }
1178
1758
  getSlotStartBuildTimestamp() {
1179
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1759
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
1180
1760
  }
1181
1761
  getSecondsIntoSlot() {
1182
1762
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();