@aztec/sequencer-client 0.0.1-commit.96bb3f7 → 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 (133) 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 -39
  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-metrics.d.ts +1 -1
  47. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  49. package/dest/publisher/sequencer-publisher.d.ts +94 -68
  50. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  51. package/dest/publisher/sequencer-publisher.js +446 -363
  52. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  53. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  54. package/dest/sequencer/automine/automine_factory.js +84 -0
  55. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  56. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  57. package/dest/sequencer/automine/automine_sequencer.js +506 -0
  58. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  59. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  60. package/dest/sequencer/chain_state_overrides.js +98 -0
  61. package/dest/sequencer/checkpoint_proposal_job.d.ts +81 -13
  62. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  63. package/dest/sequencer/checkpoint_proposal_job.js +874 -195
  64. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  65. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  66. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  67. package/dest/sequencer/checkpoint_voter.d.ts +3 -3
  68. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  69. package/dest/sequencer/checkpoint_voter.js +34 -13
  70. package/dest/sequencer/events.d.ts +47 -2
  71. package/dest/sequencer/events.d.ts.map +1 -1
  72. package/dest/sequencer/index.d.ts +3 -2
  73. package/dest/sequencer/index.d.ts.map +1 -1
  74. package/dest/sequencer/index.js +2 -1
  75. package/dest/sequencer/metrics.d.ts +23 -8
  76. package/dest/sequencer/metrics.d.ts.map +1 -1
  77. package/dest/sequencer/metrics.js +142 -36
  78. package/dest/sequencer/sequencer.d.ts +87 -26
  79. package/dest/sequencer/sequencer.d.ts.map +1 -1
  80. package/dest/sequencer/sequencer.js +408 -135
  81. package/dest/sequencer/timetable.d.ts +17 -6
  82. package/dest/sequencer/timetable.d.ts.map +1 -1
  83. package/dest/sequencer/timetable.js +51 -46
  84. package/dest/sequencer/types.d.ts +2 -2
  85. package/dest/sequencer/types.d.ts.map +1 -1
  86. package/dest/test/index.d.ts +3 -5
  87. package/dest/test/index.d.ts.map +1 -1
  88. package/dest/test/mock_checkpoint_builder.d.ts +23 -19
  89. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  90. package/dest/test/mock_checkpoint_builder.js +67 -38
  91. package/dest/test/utils.d.ts +8 -8
  92. package/dest/test/utils.d.ts.map +1 -1
  93. package/dest/test/utils.js +17 -15
  94. package/package.json +29 -28
  95. package/src/client/sequencer-client.ts +92 -35
  96. package/src/config.ts +103 -49
  97. package/src/global_variable_builder/README.md +44 -0
  98. package/src/global_variable_builder/fee_predictor.ts +172 -0
  99. package/src/global_variable_builder/fee_provider.ts +75 -0
  100. package/src/global_variable_builder/global_builder.ts +26 -63
  101. package/src/global_variable_builder/index.ts +3 -1
  102. package/src/index.ts +5 -1
  103. package/src/publisher/config.ts +157 -45
  104. package/src/publisher/index.ts +3 -0
  105. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  106. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  107. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  108. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  109. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  110. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  111. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  112. package/src/publisher/sequencer-publisher.ts +540 -460
  113. package/src/sequencer/README.md +152 -450
  114. package/src/sequencer/automine/README.md +46 -0
  115. package/src/sequencer/automine/automine_factory.ts +145 -0
  116. package/src/sequencer/automine/automine_sequencer.ts +592 -0
  117. package/src/sequencer/chain_state_overrides.ts +162 -0
  118. package/src/sequencer/checkpoint_proposal_job.ts +1088 -219
  119. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  120. package/src/sequencer/checkpoint_voter.ts +31 -17
  121. package/src/sequencer/events.ts +50 -2
  122. package/src/sequencer/index.ts +2 -1
  123. package/src/sequencer/metrics.ts +164 -39
  124. package/src/sequencer/sequencer.ts +509 -147
  125. package/src/sequencer/timetable.ts +70 -57
  126. package/src/sequencer/types.ts +1 -1
  127. package/src/test/index.ts +2 -4
  128. package/src/test/mock_checkpoint_builder.ts +122 -78
  129. package/src/test/utils.ts +50 -22
  130. package/dest/sequencer/block_builder.d.ts +0 -26
  131. package/dest/sequencer/block_builder.d.ts.map +0 -1
  132. package/dest/sequencer/block_builder.js +0 -129
  133. package/src/sequencer/block_builder.ts +0 -216
@@ -436,21 +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 { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
440
- import { BlockNumber } from '@aztec/foundation/branded-types';
439
+ import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint } from '@aztec/foundation/branded-types';
441
440
  import { randomInt } from '@aztec/foundation/crypto/random';
442
- import { Signature } from '@aztec/foundation/eth-signature';
441
+ import { flipSignature, generateRecoverableSignature, generateUnrecoverableSignature } from '@aztec/foundation/crypto/secp256k1-signer';
443
442
  import { filter } from '@aztec/foundation/iterator';
443
+ import { createLogger } from '@aztec/foundation/log';
444
+ import { retryUntil } from '@aztec/foundation/retry';
444
445
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
445
446
  import { Timer } from '@aztec/foundation/timer';
446
- import { unfreeze } from '@aztec/foundation/types';
447
+ import { isErrorClass, unfreeze } from '@aztec/foundation/types';
447
448
  import { CommitteeAttestationsAndSigners, MaliciousCommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
448
- 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';
449
451
  import { Gas } from '@aztec/stdlib/gas';
452
+ import { InsufficientValidTxsError } from '@aztec/stdlib/interfaces/server';
450
453
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
451
- import { orderAttestations } from '@aztec/stdlib/p2p';
454
+ import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
452
455
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
453
456
  import { Attributes, trackSpan } from '@aztec/telemetry-client';
457
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
458
+ import { buildCheckpointSimulationOverridesPlan } from './chain_state_overrides.js';
454
459
  import { CheckpointVoter } from './checkpoint_voter.js';
455
460
  import { SequencerInterruptedError } from './errors.js';
456
461
  import { SequencerState } from './utils.js';
@@ -459,7 +464,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
459
464
  return {
460
465
  // nullish operator needed for tests
461
466
  [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
462
- [Attributes.SLOT_NUMBER]: this.slot
467
+ [Attributes.SLOT_NUMBER]: this.targetSlot
463
468
  };
464
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');
465
470
  /**
@@ -468,9 +473,12 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
468
473
  * as well as enqueueing votes for slashing and governance proposals. This class is created from
469
474
  * the Sequencer once the check for being the proposer for the slot has succeeded.
470
475
  */ export class CheckpointProposalJob {
471
- slot;
476
+ slotNow;
477
+ targetSlot;
478
+ targetEpoch;
472
479
  checkpointNumber;
473
480
  syncedToBlockNumber;
481
+ checkpointedCheckpointNumber;
474
482
  proposer;
475
483
  publisher;
476
484
  attestorAddress;
@@ -480,19 +488,22 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
480
488
  p2pClient;
481
489
  worldState;
482
490
  l1ToL2MessageSource;
491
+ l2BlockSource;
483
492
  checkpointsBuilder;
484
493
  blockSink;
485
494
  l1Constants;
495
+ signatureContext;
486
496
  config;
487
497
  timetable;
488
498
  slasherClient;
489
499
  epochCache;
490
500
  dateProvider;
491
501
  metrics;
502
+ checkpointMetrics;
492
503
  eventEmitter;
493
504
  setStateFn;
494
- log;
495
505
  tracer;
506
+ proposedCheckpointData;
496
507
  static{
497
508
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
498
509
  [
@@ -537,11 +548,26 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
537
548
  ]
538
549
  ], []));
539
550
  }
540
- constructor(slot, checkpointNumber, syncedToBlockNumber, // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
541
- proposer, publisher, attestorAddress, invalidateCheckpoint, validatorClient, globalsBuilder, p2pClient, worldState, l1ToL2MessageSource, checkpointsBuilder, blockSink, l1Constants, config, timetable, slasherClient, epochCache, dateProvider, metrics, eventEmitter, setStateFn, log, tracer){
542
- this.slot = slot;
551
+ log;
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;
543
568
  this.checkpointNumber = checkpointNumber;
544
569
  this.syncedToBlockNumber = syncedToBlockNumber;
570
+ this.checkpointedCheckpointNumber = checkpointedCheckpointNumber;
545
571
  this.proposer = proposer;
546
572
  this.publisher = publisher;
547
573
  this.attestorAddress = attestorAddress;
@@ -551,58 +577,314 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
551
577
  this.p2pClient = p2pClient;
552
578
  this.worldState = worldState;
553
579
  this.l1ToL2MessageSource = l1ToL2MessageSource;
580
+ this.l2BlockSource = l2BlockSource;
554
581
  this.checkpointsBuilder = checkpointsBuilder;
555
582
  this.blockSink = blockSink;
556
583
  this.l1Constants = l1Constants;
584
+ this.signatureContext = signatureContext;
557
585
  this.config = config;
558
586
  this.timetable = timetable;
559
587
  this.slasherClient = slasherClient;
560
588
  this.epochCache = epochCache;
561
589
  this.dateProvider = dateProvider;
562
590
  this.metrics = metrics;
591
+ this.checkpointMetrics = checkpointMetrics;
563
592
  this.eventEmitter = eventEmitter;
564
593
  this.setStateFn = setStateFn;
565
- this.log = log;
566
594
  this.tracer = tracer;
595
+ this.proposedCheckpointData = proposedCheckpointData;
567
596
  _initProto(this);
597
+ this.log = createLogger('sequencer:checkpoint-proposal', {
598
+ ...bindings,
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
614
+ });
568
615
  }
569
616
  /**
570
617
  * Executes the checkpoint proposal job.
571
- * 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.
572
622
  */ async execute() {
573
623
  // Enqueue governance and slashing votes (returns promises that will be awaited later)
574
624
  // In fisherman mode, we simulate slashing but don't actually publish to L1
575
625
  // These are constant for the whole slot, so we only enqueue them once
576
- const votesPromises = new CheckpointVoter(this.slot, this.publisher, this.attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log).enqueueVotes();
577
- // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
578
- const checkpoint = await this.proposeCheckpoint();
579
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
580
- await Promise.all(votesPromises);
581
- if (checkpoint) {
582
- 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;
583
642
  }
643
+ const { checkpoint } = broadcast;
644
+ this.metrics.recordCheckpointProposalSuccess();
584
645
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
585
646
  if (this.config.fishermanMode) {
586
647
  await this.handleCheckpointEndAsFisherman(checkpoint);
587
- return;
648
+ return checkpoint;
588
649
  }
589
- // Then send everything to L1
590
- const l1Response = await this.publisher.sendRequests();
591
- const proposedAction = l1Response?.successfulActions.find((a)=>a === 'propose');
592
- if (proposedAction) {
593
- this.eventEmitter.emit('checkpoint-published', {
594
- checkpoint: this.checkpointNumber,
595
- 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)
596
742
  });
597
- const coinbase = checkpoint?.header.coinbase;
598
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
599
- return checkpoint;
600
- } else if (checkpoint) {
601
743
  this.eventEmitter.emit('checkpoint-publish-failed', {
602
- ...l1Response,
603
- 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
604
887
  });
605
- return undefined;
606
888
  }
607
889
  }
608
890
  async proposeCheckpoint() {
@@ -613,26 +895,77 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
613
895
  hasError: false
614
896
  };
615
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);
616
907
  // Get operator configured coinbase and fee recipient for this attestor
617
908
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
618
909
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
619
910
  // Start the checkpoint
620
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
621
- 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');
622
924
  // Enqueues checkpoint invalidation (constant for the whole slot)
623
925
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
624
926
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
625
927
  }
626
- // Create checkpoint builder for the slot
627
- 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);
628
943
  // Collect L1 to L2 messages for the checkpoint and compute their hash
629
944
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
630
945
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
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);
631
964
  const fork = _ts_add_disposable_resource(env, await this.worldState.fork(this.syncedToBlockNumber, {
632
965
  closeDelayMs: 12_000
633
- }), false);
966
+ }), true);
634
967
  // Create checkpoint builder for the entire slot
635
- const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, l1ToL2Messages, fork);
968
+ const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, this.log.getBindings());
636
969
  // Options for the validator client when creating block and checkpoint proposals
637
970
  const blockProposalOptions = {
638
971
  publishFullTxs: !!this.config.publishTxsWithProposals,
@@ -640,68 +973,176 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
640
973
  };
641
974
  const checkpointProposalOptions = {
642
975
  publishFullTxs: !!this.config.publishTxsWithProposals,
643
- broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal
976
+ broadcastInvalidCheckpointProposal: this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal
644
977
  };
645
- // Main loop: build blocks for the checkpoint
646
- const { blocksInCheckpoint, blockPendingBroadcast } = await this.buildBlocksForCheckpoint(checkpointBuilder, checkpointGlobalVariables.timestamp, inHash, blockProposalOptions);
978
+ let blocksInCheckpoint = [];
979
+ let blockPendingBroadcast = undefined;
980
+ const checkpointBuildTimer = new Timer();
981
+ try {
982
+ // Main loop: build blocks for the checkpoint
983
+ const result = await this.buildBlocksForCheckpoint(checkpointBuilder, checkpointGlobalVariables.timestamp, inHash, blockProposalOptions);
984
+ blocksInCheckpoint = result.blocksInCheckpoint;
985
+ blockPendingBroadcast = result.blockPendingBroadcast;
986
+ } catch (err) {
987
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
988
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
989
+ // which is normal for block building (may have picked different txs)
990
+ if (this.handleHASigningError(err, 'Block proposal')) {
991
+ return undefined;
992
+ }
993
+ throw err;
994
+ }
647
995
  if (blocksInCheckpoint.length === 0) {
648
- this.log.warn(`No blocks were built for slot ${this.slot}`, {
649
- 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'
650
1005
  });
651
1006
  this.eventEmitter.emit('checkpoint-empty', {
652
- 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'
653
1026
  });
654
1027
  return undefined;
655
1028
  }
656
1029
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
657
1030
  // broadcasted yet, and wait to collect the committee attestations.
658
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
1031
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
659
1032
  const checkpoint = await checkpointBuilder.completeCheckpoint();
660
- // 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
661
1074
  if (this.config.fishermanMode) {
662
- this.log.info(`Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` + `Skipping proposal in fisherman mode.`, {
663
- 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,
664
1077
  checkpoint: checkpoint.header.toInspect(),
665
1078
  blocksBuilt: blocksInCheckpoint.length
666
1079
  });
667
1080
  this.metrics.recordCheckpointSuccess();
668
- 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
+ };
1087
+ }
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.
1091
+ try {
1092
+ await this.publisher.validateBlockHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
1093
+ } catch (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;
669
1105
  }
670
- // Include the block pending broadcast in the checkpoint proposal if any
671
- const lastBlock = blockPendingBroadcast && {
672
- blockHeader: blockPendingBroadcast.block.header,
673
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
674
- txs: blockPendingBroadcast.txs
675
- };
676
1106
  // Create the checkpoint proposal and broadcast it
677
- const proposal = await this.validatorClient.createCheckpointProposal(checkpoint.header, checkpoint.archive.root, lastBlock, this.proposer, checkpointProposalOptions);
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);
678
1114
  const blockProposedAt = this.dateProvider.now();
679
- await this.p2pClient.broadcastCheckpointProposal(proposal);
680
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
681
- const attestations = await this.waitForAttestations(proposal);
682
- const blockAttestedAt = this.dateProvider.now();
683
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
684
- // Proposer must sign over the attestations before pushing them to L1
685
- const signer = this.proposer ?? this.publisher.getSenderAddress();
686
- const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer);
687
- // Enqueue publishing the checkpoint to L1
688
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
689
- const aztecSlotDuration = this.l1Constants.slotDuration;
690
- const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
691
- const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
692
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
693
- txTimeoutAt,
694
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber
695
- });
696
- return checkpoint;
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);
1122
+ }
1123
+ } else if (!this.config.skipBroadcastProposals) {
1124
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
1125
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
1126
+ }
1127
+ // Return immediately after broadcast attestation collection happens in the background
1128
+ return {
1129
+ checkpoint,
1130
+ proposal,
1131
+ blockProposedAt
1132
+ };
697
1133
  } catch (e) {
698
1134
  env.error = e;
699
1135
  env.hasError = true;
700
1136
  } finally{
701
- _ts_dispose_resources(env);
1137
+ const result = _ts_dispose_resources(env);
1138
+ if (result) await result;
702
1139
  }
703
1140
  } catch (err) {
704
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
1141
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
1142
+ // swallow this error. It's already been logged by a function deeper in the stack
1143
+ return undefined;
1144
+ }
1145
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
705
1146
  return undefined;
706
1147
  }
707
1148
  }
@@ -715,13 +1156,21 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
715
1156
  let blockPendingBroadcast = undefined;
716
1157
  while(true){
717
1158
  const blocksBuilt = blocksInCheckpoint.length;
718
- const indexWithinCheckpoint = blocksBuilt;
1159
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
719
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
+ }
720
1169
  const secondsIntoSlot = this.getSecondsIntoSlot();
721
1170
  const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
722
1171
  if (!timingInfo.canStart) {
723
1172
  this.log.debug(`Not enough time left in slot to start another block`, {
724
- slot: this.slot,
1173
+ slot: this.targetSlot,
725
1174
  blocksBuilt,
726
1175
  secondsIntoSlot
727
1176
  });
@@ -738,19 +1187,22 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
738
1187
  indexWithinCheckpoint,
739
1188
  txHashesAlreadyIncluded
740
1189
  });
741
- if (!buildResult && timingInfo.isLastBlock) {
742
- break;
743
- } else if (!buildResult && timingInfo.deadline !== undefined) {
744
- // 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
745
1197
  await this.waitUntilNextSubslot(timingInfo.deadline);
746
1198
  continue;
747
- } else if (!buildResult) {
748
- break;
749
- } else if ('error' in buildResult) {
750
- // 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) {
751
1203
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
752
- this.log.warn(`Halting block building for slot ${this.slot}`, {
753
- slot: this.slot,
1204
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
1205
+ slot: this.targetSlot,
754
1206
  blocksBuilt,
755
1207
  error: buildResult.error
756
1208
  });
@@ -758,35 +1210,41 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
758
1210
  break;
759
1211
  }
760
1212
  const { block, usedTxs } = buildResult;
1213
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
1214
+ isFirstBlock: blocksBuilt === 0,
1215
+ isLastBlock: timingInfo.isLastBlock
1216
+ });
761
1217
  blocksInCheckpoint.push(block);
762
- // Sync the proposed block to the archiver to make it available
763
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
764
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
1218
+ usedTxs.forEach((tx)=>txHashesAlreadyIncluded.add(tx.txHash.toString()));
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.
765
1228
  await this.syncProposedBlockToArchiver(block);
766
- // If this is the last block, exit the loop now so we start collecting attestations
1229
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
767
1230
  if (timingInfo.isLastBlock) {
768
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
769
- slot: this.slot,
1231
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
1232
+ slot: this.targetSlot,
770
1233
  blockNumber,
771
1234
  blocksBuilt
772
1235
  });
773
- blockPendingBroadcast = {
774
- block,
775
- txs: usedTxs
776
- };
1236
+ blockPendingBroadcast = proposal;
777
1237
  break;
778
1238
  }
779
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
780
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
781
- if (!this.config.fishermanMode) {
782
- 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) {
783
1241
  await this.p2pClient.broadcastProposal(proposal);
784
1242
  }
785
1243
  // Wait until the next block's start time
786
1244
  await this.waitUntilNextSubslot(timingInfo.deadline);
787
1245
  }
788
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
789
- slot: this.slot,
1246
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
1247
+ slot: this.targetSlot,
790
1248
  blocksBuilt: blocksInCheckpoint.length
791
1249
  });
792
1250
  return {
@@ -794,99 +1252,142 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
794
1252
  blockPendingBroadcast
795
1253
  };
796
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
+ }
797
1262
  /** Sleeps until it is time to produce the next block in the slot */ async waitUntilNextSubslot(nextSubslotStart) {
798
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
1263
+ this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
799
1264
  this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
800
- slot: this.slot
1265
+ slot: this.targetSlot
801
1266
  });
802
1267
  await this.waitUntilTimeInSlot(nextSubslotStart);
803
1268
  }
804
1269
  /** Builds a single block. Called from the main block building loop. */ async buildSingleBlock(checkpointBuilder, opts) {
805
1270
  const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } = opts;
806
- this.log.verbose(`Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`, {
1271
+ this.log.verbose(`Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot}`, {
807
1272
  ...checkpointBuilder.getConstantData(),
808
1273
  ...opts
809
1274
  });
810
1275
  try {
811
1276
  // Wait until we have enough txs to build the block
812
- const minTxs = this.config.minTxsPerBlock;
813
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
1277
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
814
1278
  if (!canStartBuilding) {
815
- 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',
816
1290
  blockNumber,
817
- slot: this.slot,
818
- indexWithinCheckpoint
1291
+ slot: this.targetSlot,
1292
+ checkpointNumber: this.checkpointNumber,
1293
+ indexWithinCheckpoint,
1294
+ availableTxs,
1295
+ minTxs
819
1296
  });
820
1297
  this.eventEmitter.emit('block-tx-count-check-failed', {
821
1298
  minTxs,
822
1299
  availableTxs,
823
- slot: this.slot
1300
+ slot: this.targetSlot
824
1301
  });
825
1302
  this.metrics.recordBlockProposalFailed('insufficient_txs');
826
- return undefined;
1303
+ return {
1304
+ failure: 'insufficient-txs'
1305
+ };
827
1306
  }
828
1307
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
829
1308
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
830
- const pendingTxs = filter(this.p2pClient.iteratePendingTxs(), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
831
- this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`, {
832
- 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,
833
1312
  blockNumber,
834
1313
  indexWithinCheckpoint
835
1314
  });
836
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
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;
837
1320
  const blockBuilderOptions = {
838
1321
  maxTransactions: this.config.maxTxsPerBlock,
839
- maxBlockSize: this.config.maxBlockSizeInBytes,
840
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
841
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
842
- 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
843
1328
  };
844
- // Actually build the block by executing txs
845
- const workTimer = new Timer();
846
- const { publicGas, block, publicProcessorDuration, numTxs, blockBuildingTimer, usedTxs, failedTxs } = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
847
- const blockBuildDuration = workTimer.ms();
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.
1332
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(checkpointBuilder, pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
848
1333
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
849
- await this.dropFailedTxsFromP2P(failedTxs);
850
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
851
- // too long, then we may not get to minTxsPerBlock after executing public functions.
852
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
853
- if (!forceCreate && numTxs < minValidTxs) {
854
- this.log.warn(`Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`, {
855
- slot: this.slot,
1334
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
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,
856
1340
  blockNumber,
857
- numTxs,
858
- indexWithinCheckpoint
1341
+ numTxs: buildResult.processedCount,
1342
+ indexWithinCheckpoint,
1343
+ minValidTxs
859
1344
  });
860
- this.eventEmitter.emit('block-tx-count-check-failed', {
861
- minTxs: minValidTxs,
862
- availableTxs: numTxs,
863
- slot: this.slot
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,
1349
+ blockNumber,
1350
+ numTxs: buildResult.processedCount,
1351
+ indexWithinCheckpoint,
1352
+ minValidTxs
1353
+ });
1354
+ this.eventEmitter.emit('block-build-failed', {
1355
+ reason: `Insufficient valid txs`,
1356
+ slot: this.targetSlot
864
1357
  });
865
1358
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
866
- return undefined;
1359
+ return {
1360
+ failure: 'insufficient-valid-txs'
1361
+ };
867
1362
  }
868
1363
  // Block creation succeeded, emit stats and metrics
1364
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
869
1365
  const blockStats = {
870
1366
  eventName: 'l2-block-built',
871
1367
  duration: blockBuildDuration,
872
1368
  publicProcessDuration: publicProcessorDuration,
873
- rollupCircuitsDuration: blockBuildingTimer.ms(),
874
1369
  ...block.getStats()
875
1370
  };
876
1371
  const blockHash = await block.hash();
877
1372
  const txHashes = block.body.txEffects.map((tx)=>tx.txHash);
878
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
879
- 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`, {
880
1375
  blockHash,
881
1376
  txHashes,
882
1377
  manaPerSec,
883
1378
  ...blockStats
884
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.
885
1382
  this.eventEmitter.emit('block-proposed', {
886
1383
  blockNumber: block.number,
887
- slot: this.slot
1384
+ blockHash,
1385
+ checkpointNumber: this.checkpointNumber,
1386
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1387
+ slot: this.targetSlot,
1388
+ buildSlot: this.slotNow
888
1389
  });
889
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
1390
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
890
1391
  return {
891
1392
  block,
892
1393
  usedTxs
@@ -894,11 +1395,19 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
894
1395
  } catch (err) {
895
1396
  this.eventEmitter.emit('block-build-failed', {
896
1397
  reason: err.message,
897
- 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
898
1405
  });
899
1406
  this.log.error(`Error building block`, err, {
900
- blockNumber,
901
- slot: this.slot
1407
+ reason: err instanceof Error ? err.message : String(err),
1408
+ slot: this.targetSlot,
1409
+ checkpointNumber: this.checkpointNumber,
1410
+ blockNumber
902
1411
  });
903
1412
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
904
1413
  this.metrics.recordFailedBlock();
@@ -907,9 +1416,31 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
907
1416
  };
908
1417
  }
909
1418
  }
1419
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */ async buildSingleBlockWithCheckpointBuilder(checkpointBuilder, pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions) {
1420
+ try {
1421
+ const workTimer = new Timer();
1422
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
1423
+ const blockBuildDuration = workTimer.ms();
1424
+ return {
1425
+ ...result,
1426
+ blockBuildDuration,
1427
+ status: 'success'
1428
+ };
1429
+ } catch (err) {
1430
+ if (isErrorClass(err, InsufficientValidTxsError)) {
1431
+ return {
1432
+ failedTxs: err.failedTxs,
1433
+ processedCount: err.processedCount,
1434
+ status: 'insufficient-valid-txs'
1435
+ };
1436
+ }
1437
+ throw err;
1438
+ }
1439
+ }
910
1440
  /** Waits until minTxs are available on the pool for building a block. */ async waitForMinTxs(opts) {
911
- const minTxs = this.config.minTxsPerBlock;
912
1441
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
1442
+ // We only allow a block with 0 txs in the first block of the checkpoint
1443
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
913
1444
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
914
1445
  const startBuildingDeadline = buildDeadline ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000) : undefined;
915
1446
  let availableTxs = await this.p2pClient.getPendingTxCount();
@@ -919,31 +1450,57 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
919
1450
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
920
1451
  return {
921
1452
  canStartBuilding: false,
922
- availableTxs: availableTxs
1453
+ availableTxs,
1454
+ minTxs
923
1455
  };
924
1456
  }
925
1457
  // Wait a bit before checking again
926
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
927
- 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})`, {
928
1460
  blockNumber,
929
- slot: this.slot,
1461
+ slot: this.targetSlot,
930
1462
  indexWithinCheckpoint
931
1463
  });
932
- await sleep(TXS_POLLING_MS);
1464
+ await this.waitForTxsPollingInterval();
933
1465
  availableTxs = await this.p2pClient.getPendingTxCount();
934
1466
  }
935
1467
  return {
936
1468
  canStartBuilding: true,
937
- availableTxs
1469
+ availableTxs,
1470
+ minTxs
938
1471
  };
939
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
+ }
940
1497
  /**
941
1498
  * Waits for enough attestations to be collected via p2p.
942
1499
  * This is run after all blocks for the checkpoint have been built.
943
1500
  */ async waitForAttestations(proposal) {
944
1501
  if (this.config.fishermanMode) {
945
1502
  this.log.debug('Skipping attestation collection in fisherman mode');
946
- return CommitteeAttestationsAndSigners.empty();
1503
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
947
1504
  }
948
1505
  const slotNumber = proposal.slotNumber;
949
1506
  const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
@@ -951,47 +1508,91 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
951
1508
  throw new Error('No committee when collecting attestations');
952
1509
  } else if (committee.length === 0) {
953
1510
  this.log.verbose(`Attesting committee is empty`);
954
- return CommitteeAttestationsAndSigners.empty();
1511
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
955
1512
  } else {
956
1513
  this.log.debug(`Attesting committee length is ${committee.length}`, {
957
1514
  committee
958
1515
  });
959
1516
  }
960
- const numberOfRequiredAttestations = Math.floor(committee.length * 2 / 3) + 1;
1517
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
961
1518
  if (this.config.skipCollectingAttestations) {
962
1519
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
963
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
964
- 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());
965
1525
  }
966
- const attestationTimeAllowed = this.config.enforceTimeTable ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT) : this.l1Constants.slotDuration;
967
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
1526
+ const attestationTimeAllowed = this.config.enforceTimeTable ? this.timetable.getCheckpointAttestationDeadline() : this.l1Constants.slotDuration;
1527
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
968
1528
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
969
1529
  const collectAttestationsTimer = new Timer();
970
1530
  let collectedAttestationsCount = 0;
971
1531
  try {
972
- const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline);
1532
+ const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline, this.checkpointNumber);
973
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
+ }
974
1540
  // Rollup contract requires that the signatures are provided in the order of the committee
975
- const sorted = orderAttestations(attestations, committee);
1541
+ const sorted = orderAttestations(trimmed, committee);
1542
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1543
+ submittedCount: trimmed.length
1544
+ });
976
1545
  // Manipulate the attestations if we've been configured to do so
977
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
1546
+ if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation || this.config.shuffleAttestationOrdering) {
978
1547
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
979
1548
  }
980
- return new CommitteeAttestationsAndSigners(sorted);
1549
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
981
1550
  } catch (err) {
982
1551
  if (err && err instanceof AttestationTimeoutError) {
983
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);
984
1564
  }
985
- throw err;
1565
+ return undefined;
986
1566
  } finally{
987
1567
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
988
1568
  }
989
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
+ }
990
1591
  /** Breaks the attestations before publishing based on attack configs */ manipulateAttestations(slotNumber, epoch, seed, committee, attestations) {
991
1592
  // Compute the proposer index in the committee, since we dont want to tweak it.
992
1593
  // Otherwise, the L1 rollup contract will reject the block outright.
993
1594
  const proposerIndex = Number(this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)));
994
- if (this.config.injectFakeAttestation) {
1595
+ if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation) {
995
1596
  // Find non-empty attestations that are not from the proposer
996
1597
  const nonProposerIndices = [];
997
1598
  for(let i = 0; i < attestations.length; i++){
@@ -1001,28 +1602,47 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1001
1602
  }
1002
1603
  if (nonProposerIndices.length > 0) {
1003
1604
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
1004
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1005
- 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
+ }
1006
1615
  }
1007
- return new CommitteeAttestationsAndSigners(attestations);
1616
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1008
1617
  }
1009
1618
  if (this.config.shuffleAttestationOrdering) {
1010
1619
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
1011
1620
  const shuffled = [
1012
1621
  ...attestations
1013
1622
  ];
1014
- const [i, j] = [
1015
- (proposerIndex + 1) % shuffled.length,
1016
- (proposerIndex + 2) % shuffled.length
1017
- ];
1018
- const valueI = shuffled[i];
1019
- const valueJ = shuffled[j];
1020
- shuffled[i] = valueJ;
1021
- shuffled[j] = valueI;
1022
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
1023
- 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());
1024
1644
  }
1025
- return new CommitteeAttestationsAndSigners(attestations);
1645
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1026
1646
  }
1027
1647
  async dropFailedTxsFromP2P(failedTxs) {
1028
1648
  if (failedTxs.length === 0) {
@@ -1031,15 +1651,18 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1031
1651
  const failedTxData = failedTxs.map((fail)=>fail.tx);
1032
1652
  const failedTxHashes = failedTxData.map((tx)=>tx.getTxHash());
1033
1653
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
1034
- await this.p2pClient.deleteTxs(failedTxHashes);
1654
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
1035
1655
  }
1036
1656
  /**
1037
1657
  * Adds the proposed block to the archiver so it's available via P2P.
1038
1658
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1039
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.
1040
1664
  */ async syncProposedBlockToArchiver(block) {
1041
- // TODO(palla/mbps): Change default to false once block sync is stable.
1042
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1665
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1043
1666
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1044
1667
  blockNumber: block.number,
1045
1668
  slot: block.header.globalVariables.slotNumber
@@ -1052,32 +1675,88 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1052
1675
  });
1053
1676
  await this.blockSink.addBlock(block);
1054
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
+ }
1055
1711
  /** Runs fee analysis and logs checkpoint outcome as fisherman */ async handleCheckpointEndAsFisherman(checkpoint) {
1056
1712
  // Perform L1 fee analysis before clearing requests
1057
1713
  // The callback is invoked asynchronously after the next block is mined
1058
- 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));
1059
1715
  if (checkpoint) {
1060
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1716
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
1061
1717
  ...checkpoint.toCheckpointInfo(),
1062
1718
  ...checkpoint.getStats(),
1063
1719
  feeAnalysisId: feeAnalysis?.id
1064
1720
  });
1065
1721
  } else {
1066
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
1067
- slot: this.slot,
1722
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1723
+ slot: this.targetSlot,
1068
1724
  feeAnalysisId: feeAnalysis?.id
1069
1725
  });
1070
- this.metrics.recordBlockProposalFailed('block_build_failed');
1726
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
1071
1727
  }
1072
1728
  this.publisher.clearPendingRequests();
1073
1729
  }
1730
+ /**
1731
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
1732
+ */ handleHASigningError(err, errorContext) {
1733
+ if (err instanceof DutyAlreadySignedError) {
1734
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1735
+ slot: this.targetSlot,
1736
+ signedByNode: err.signedByNode
1737
+ });
1738
+ return true;
1739
+ }
1740
+ if (err instanceof SlashingProtectionError) {
1741
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1742
+ slot: this.targetSlot,
1743
+ existingMessageHash: err.existingMessageHash,
1744
+ attemptedMessageHash: err.attemptedMessageHash
1745
+ });
1746
+ return true;
1747
+ }
1748
+ return false;
1749
+ }
1074
1750
  /** Waits until a specific time within the current slot */ async waitUntilTimeInSlot(targetSecondsIntoSlot) {
1075
1751
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1076
1752
  const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
1077
1753
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
1078
1754
  }
1755
+ /** Waits the polling interval for transactions. Extracted for test overriding. */ async waitForTxsPollingInterval() {
1756
+ await sleep(TXS_POLLING_MS);
1757
+ }
1079
1758
  getSlotStartBuildTimestamp() {
1080
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1759
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
1081
1760
  }
1082
1761
  getSecondsIntoSlot() {
1083
1762
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();