@aztec/sequencer-client 0.0.1-commit.fffb133c → 0.0.1-dev

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 (66) hide show
  1. package/dest/client/sequencer-client.d.ts +16 -7
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +56 -23
  4. package/dest/config.d.ts +25 -6
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +46 -28
  7. package/dest/global_variable_builder/global_builder.d.ts +14 -10
  8. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  9. package/dest/global_variable_builder/global_builder.js +22 -21
  10. package/dest/global_variable_builder/index.d.ts +2 -2
  11. package/dest/global_variable_builder/index.d.ts.map +1 -1
  12. package/dest/publisher/config.d.ts +31 -17
  13. package/dest/publisher/config.d.ts.map +1 -1
  14. package/dest/publisher/config.js +101 -42
  15. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -3
  16. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  17. package/dest/publisher/sequencer-publisher-factory.js +13 -2
  18. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  19. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  20. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  21. package/dest/publisher/sequencer-publisher.d.ts +28 -14
  22. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  23. package/dest/publisher/sequencer-publisher.js +137 -74
  24. package/dest/sequencer/checkpoint_proposal_job.d.ts +35 -10
  25. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  26. package/dest/sequencer/checkpoint_proposal_job.js +212 -137
  27. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  28. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  29. package/dest/sequencer/checkpoint_voter.js +2 -5
  30. package/dest/sequencer/metrics.d.ts +17 -5
  31. package/dest/sequencer/metrics.d.ts.map +1 -1
  32. package/dest/sequencer/metrics.js +111 -30
  33. package/dest/sequencer/sequencer.d.ts +29 -13
  34. package/dest/sequencer/sequencer.d.ts.map +1 -1
  35. package/dest/sequencer/sequencer.js +48 -44
  36. package/dest/sequencer/timetable.d.ts +4 -6
  37. package/dest/sequencer/timetable.d.ts.map +1 -1
  38. package/dest/sequencer/timetable.js +7 -11
  39. package/dest/sequencer/types.d.ts +2 -2
  40. package/dest/sequencer/types.d.ts.map +1 -1
  41. package/dest/test/index.d.ts +3 -5
  42. package/dest/test/index.d.ts.map +1 -1
  43. package/dest/test/mock_checkpoint_builder.d.ts +12 -12
  44. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  45. package/dest/test/mock_checkpoint_builder.js +47 -36
  46. package/dest/test/utils.d.ts +3 -3
  47. package/dest/test/utils.d.ts.map +1 -1
  48. package/dest/test/utils.js +5 -4
  49. package/package.json +28 -28
  50. package/src/client/sequencer-client.ts +78 -21
  51. package/src/config.ts +61 -38
  52. package/src/global_variable_builder/global_builder.ts +23 -24
  53. package/src/global_variable_builder/index.ts +1 -1
  54. package/src/publisher/config.ts +112 -43
  55. package/src/publisher/sequencer-publisher-factory.ts +23 -6
  56. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  57. package/src/publisher/sequencer-publisher.ts +149 -90
  58. package/src/sequencer/checkpoint_proposal_job.ts +309 -186
  59. package/src/sequencer/checkpoint_voter.ts +1 -12
  60. package/src/sequencer/metrics.ts +124 -32
  61. package/src/sequencer/sequencer.ts +61 -50
  62. package/src/sequencer/timetable.ts +13 -12
  63. package/src/sequencer/types.ts +1 -1
  64. package/src/test/index.ts +2 -4
  65. package/src/test/mock_checkpoint_builder.ts +67 -53
  66. package/src/test/utils.ts +5 -2
@@ -436,20 +436,21 @@ 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 } from '@aztec/foundation/branded-types';
439
+ import { BlockNumber, 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';
443
+ import { createLogger } from '@aztec/foundation/log';
445
444
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
446
445
  import { Timer } from '@aztec/foundation/timer';
447
- import { unfreeze } from '@aztec/foundation/types';
446
+ import { isErrorClass, unfreeze } from '@aztec/foundation/types';
448
447
  import { CommitteeAttestationsAndSigners, MaliciousCommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
448
+ import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
449
449
  import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
450
450
  import { Gas } from '@aztec/stdlib/gas';
451
+ import { InsufficientValidTxsError } from '@aztec/stdlib/interfaces/server';
451
452
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
452
- import { orderAttestations } from '@aztec/stdlib/p2p';
453
+ import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
453
454
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
454
455
  import { Attributes, trackSpan } from '@aztec/telemetry-client';
455
456
  import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
@@ -495,7 +496,6 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
495
496
  metrics;
496
497
  eventEmitter;
497
498
  setStateFn;
498
- log;
499
499
  tracer;
500
500
  static{
501
501
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
@@ -541,8 +541,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
541
541
  ]
542
542
  ], []));
543
543
  }
544
+ log;
544
545
  constructor(epoch, slot, checkpointNumber, syncedToBlockNumber, // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
545
- proposer, publisher, attestorAddress, invalidateCheckpoint, validatorClient, globalsBuilder, p2pClient, worldState, l1ToL2MessageSource, l2BlockSource, checkpointsBuilder, blockSink, l1Constants, config, timetable, slasherClient, epochCache, dateProvider, metrics, eventEmitter, setStateFn, log, tracer){
546
+ proposer, publisher, attestorAddress, invalidateCheckpoint, validatorClient, globalsBuilder, p2pClient, worldState, l1ToL2MessageSource, l2BlockSource, checkpointsBuilder, blockSink, l1Constants, config, timetable, slasherClient, epochCache, dateProvider, metrics, eventEmitter, setStateFn, tracer, bindings){
546
547
  this.epoch = epoch;
547
548
  this.slot = slot;
548
549
  this.checkpointNumber = checkpointNumber;
@@ -568,9 +569,12 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
568
569
  this.metrics = metrics;
569
570
  this.eventEmitter = eventEmitter;
570
571
  this.setStateFn = setStateFn;
571
- this.log = log;
572
572
  this.tracer = tracer;
573
573
  _initProto(this);
574
+ this.log = createLogger('sequencer:checkpoint-proposal', {
575
+ ...bindings,
576
+ instanceId: `slot-${slot}`
577
+ });
574
578
  }
575
579
  /**
576
580
  * Executes the checkpoint proposal job.
@@ -585,7 +589,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
585
589
  // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
586
590
  await Promise.all(votesPromises);
587
591
  if (checkpoint) {
588
- this.metrics.recordBlockProposalSuccess();
592
+ this.metrics.recordCheckpointProposalSuccess();
589
593
  }
590
594
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
591
595
  if (this.config.fishermanMode) {
@@ -635,13 +639,14 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
635
639
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
636
640
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
637
641
  // Collect the out hashes of all the checkpoints before this one in the same epoch
638
- const previousCheckpoints = (await this.l2BlockSource.getCheckpointsForEpoch(this.epoch)).filter((c)=>c.number < this.checkpointNumber);
639
- const previousCheckpointOutHashes = previousCheckpoints.map((c)=>c.getCheckpointOutHash());
642
+ const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.epoch)).filter((c)=>c.checkpointNumber < this.checkpointNumber).map((c)=>c.checkpointOutHash);
643
+ // Get the fee asset price modifier from the oracle
644
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
640
645
  const fork = _ts_add_disposable_resource(env, await this.worldState.fork(this.syncedToBlockNumber, {
641
646
  closeDelayMs: 12_000
642
- }), false);
647
+ }), true);
643
648
  // Create checkpoint builder for the entire slot
644
- const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, l1ToL2Messages, previousCheckpointOutHashes, fork);
649
+ const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, this.log.getBindings());
645
650
  // Options for the validator client when creating block and checkpoint proposals
646
651
  const blockProposalOptions = {
647
652
  publishFullTxs: !!this.config.publishTxsWithProposals,
@@ -653,6 +658,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
653
658
  };
654
659
  let blocksInCheckpoint = [];
655
660
  let blockPendingBroadcast = undefined;
661
+ const checkpointBuildTimer = new Timer();
656
662
  try {
657
663
  // Main loop: build blocks for the checkpoint
658
664
  const result = await this.buildBlocksForCheckpoint(checkpointBuilder, checkpointGlobalVariables.timestamp, inHash, blockProposalOptions);
@@ -662,19 +668,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
662
668
  // These errors are expected in HA mode, so we yield and let another HA node handle the slot
663
669
  // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
664
670
  // which is normal for block building (may have picked different txs)
665
- if (err instanceof DutyAlreadySignedError) {
666
- this.log.info(`Checkpoint proposal for slot ${this.slot} already signed by another HA node, yielding`, {
667
- slot: this.slot,
668
- signedByNode: err.signedByNode
669
- });
670
- return undefined;
671
- }
672
- if (err instanceof SlashingProtectionError) {
673
- this.log.info(`Checkpoint proposal for slot ${this.slot} blocked by slashing protection, yielding`, {
674
- slot: this.slot,
675
- existingMessageHash: err.existingMessageHash,
676
- attemptedMessageHash: err.attemptedMessageHash
677
- });
671
+ if (this.handleHASigningError(err, 'Block proposal')) {
678
672
  return undefined;
679
673
  }
680
674
  throw err;
@@ -688,10 +682,37 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
688
682
  });
689
683
  return undefined;
690
684
  }
685
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
686
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
687
+ this.log.warn(`Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`, {
688
+ slot: this.slot,
689
+ blocksBuilt: blocksInCheckpoint.length,
690
+ minBlocksForCheckpoint
691
+ });
692
+ return undefined;
693
+ }
691
694
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
692
695
  // broadcasted yet, and wait to collect the committee attestations.
693
696
  this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
694
697
  const checkpoint = await checkpointBuilder.completeCheckpoint();
698
+ // Final validation: per-block limits are only checked if the operator set them explicitly.
699
+ // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
700
+ try {
701
+ validateCheckpoint(checkpoint, {
702
+ rollupManaLimit: this.l1Constants.rollupManaLimit,
703
+ maxL2BlockGas: this.config.maxL2BlockGas,
704
+ maxDABlockGas: this.config.maxDABlockGas,
705
+ maxTxsPerBlock: this.config.maxTxsPerBlock,
706
+ maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint
707
+ });
708
+ } catch (err) {
709
+ this.log.error(`Built an invalid checkpoint at slot ${this.slot} (skipping proposal)`, err, {
710
+ checkpoint: checkpoint.header.toInspect()
711
+ });
712
+ return undefined;
713
+ }
714
+ // Record checkpoint-level build metrics
715
+ this.metrics.recordCheckpointBuild(checkpointBuildTimer.ms(), blocksInCheckpoint.length, checkpoint.getStats().txCount, Number(checkpoint.header.totalManaUsed.toBigInt()));
695
716
  // Do not collect attestations nor publish to L1 in fisherman mode
696
717
  if (this.config.fishermanMode) {
697
718
  this.log.info(`Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` + `Skipping proposal in fisherman mode.`, {
@@ -702,14 +723,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
702
723
  this.metrics.recordCheckpointSuccess();
703
724
  return checkpoint;
704
725
  }
705
- // Include the block pending broadcast in the checkpoint proposal if any
706
- const lastBlock = blockPendingBroadcast && {
707
- blockHeader: blockPendingBroadcast.block.header,
708
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
709
- txs: blockPendingBroadcast.txs
710
- };
711
726
  // Create the checkpoint proposal and broadcast it
712
- const proposal = await this.validatorClient.createCheckpointProposal(checkpoint.header, checkpoint.archive.root, lastBlock, this.proposer, checkpointProposalOptions);
727
+ const proposal = await this.validatorClient.createCheckpointProposal(checkpoint.header, checkpoint.archive.root, feeAssetPriceModifier, blockPendingBroadcast, this.proposer, checkpointProposalOptions);
713
728
  const blockProposedAt = this.dateProvider.now();
714
729
  await this.p2pClient.broadcastCheckpointProposal(proposal);
715
730
  this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
@@ -723,20 +738,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
723
738
  attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer, this.slot, this.checkpointNumber);
724
739
  } catch (err) {
725
740
  // We shouldn't really get here since we yield to another HA node
726
- // as soon as we see these errors when creating block proposals.
727
- if (err instanceof DutyAlreadySignedError) {
728
- this.log.info(`Attestations signature for slot ${this.slot} already signed by another HA node, yielding`, {
729
- slot: this.slot,
730
- signedByNode: err.signedByNode
731
- });
732
- return undefined;
733
- }
734
- if (err instanceof SlashingProtectionError) {
735
- this.log.info(`Attestations signature for slot ${this.slot} blocked by slashing protection, yielding`, {
736
- slot: this.slot,
737
- existingMessageHash: err.existingMessageHash,
738
- attemptedMessageHash: err.attemptedMessageHash
739
- });
741
+ // as soon as we see these errors when creating block or checkpoint proposals.
742
+ if (this.handleHASigningError(err, 'Attestations signature')) {
740
743
  return undefined;
741
744
  }
742
745
  throw err;
@@ -746,6 +749,14 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
746
749
  const aztecSlotDuration = this.l1Constants.slotDuration;
747
750
  const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
748
751
  const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
752
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
753
+ if (this.config.skipPublishingCheckpointsPercent !== undefined && this.config.skipPublishingCheckpointsPercent > 0) {
754
+ const result = Math.max(0, randomInt(100));
755
+ if (result < this.config.skipPublishingCheckpointsPercent) {
756
+ this.log.warn(`Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${result}`);
757
+ return checkpoint;
758
+ }
759
+ }
749
760
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
750
761
  txTimeoutAt,
751
762
  forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber
@@ -755,7 +766,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
755
766
  env.error = e;
756
767
  env.hasError = true;
757
768
  } finally{
758
- _ts_dispose_resources(env);
769
+ const result = _ts_dispose_resources(env);
770
+ if (result) await result;
759
771
  }
760
772
  } catch (err) {
761
773
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
@@ -772,19 +784,18 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
772
784
  const blocksInCheckpoint = [];
773
785
  const txHashesAlreadyIncluded = new Set();
774
786
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
775
- // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
776
- let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
787
+ const slot = this.slot;
777
788
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
778
789
  let blockPendingBroadcast = undefined;
779
790
  while(true){
780
791
  const blocksBuilt = blocksInCheckpoint.length;
781
- const indexWithinCheckpoint = blocksBuilt;
792
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
782
793
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
783
794
  const secondsIntoSlot = this.getSecondsIntoSlot();
784
795
  const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
785
796
  if (!timingInfo.canStart) {
786
797
  this.log.debug(`Not enough time left in slot to start another block`, {
787
- slot: this.slot,
798
+ slot,
788
799
  blocksBuilt,
789
800
  secondsIntoSlot
790
801
  });
@@ -799,62 +810,52 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
799
810
  buildDeadline: timingInfo.deadline ? new Date((this.getSlotStartBuildTimestamp() + timingInfo.deadline) * 1000) : undefined,
800
811
  blockNumber,
801
812
  indexWithinCheckpoint,
802
- txHashesAlreadyIncluded,
803
- remainingBlobFields
813
+ txHashesAlreadyIncluded
804
814
  });
805
- if (!buildResult && timingInfo.isLastBlock) {
806
- break;
807
- } else if (!buildResult && timingInfo.deadline !== undefined) {
808
- // But if there is still time for more blocks, wait until the next subslot and try again
815
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
816
+ if ('failure' in buildResult) {
817
+ // If this was the last subslot, or we're running with a single block per slot, we're done
818
+ if (timingInfo.isLastBlock || timingInfo.deadline === undefined) {
819
+ break;
820
+ }
821
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
809
822
  await this.waitUntilNextSubslot(timingInfo.deadline);
810
823
  continue;
811
- } else if (!buildResult) {
812
- break;
813
- } else if ('error' in buildResult) {
814
- // If there was an error building the block, just exit the loop and give up the rest of the slot
824
+ }
825
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
826
+ // We don't want to risk building more blocks if something went wrong.
827
+ if ('error' in buildResult) {
815
828
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
816
- this.log.warn(`Halting block building for slot ${this.slot}`, {
817
- slot: this.slot,
829
+ this.log.warn(`Halting block building for slot ${slot}`, {
830
+ slot,
818
831
  blocksBuilt,
819
832
  error: buildResult.error
820
833
  });
821
834
  }
822
835
  break;
823
836
  }
824
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
837
+ const { block, usedTxs } = buildResult;
825
838
  blocksInCheckpoint.push(block);
826
- // Update remaining blob fields for the next block
827
- remainingBlobFields = newRemainingBlobFields;
828
- // Sync the proposed block to the archiver to make it available
829
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
830
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
831
- // Fire and forget - don't block the critical path, but log errors
832
- this.syncProposedBlockToArchiver(block).catch((err)=>{
833
- this.log.error(`Failed to sync proposed block ${block.number} to archiver`, {
834
- blockNumber: block.number,
835
- err
836
- });
837
- });
838
839
  usedTxs.forEach((tx)=>txHashesAlreadyIncluded.add(tx.txHash.toString()));
839
- // If this is the last block, exit the loop now so we start collecting attestations
840
+ // Sign the block proposal. This will throw if HA signing fails.
841
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, blockProposalOptions);
842
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
843
+ // so we avoid polluting our archive with a block that would fail.
844
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
845
+ // If this throws, we abort the entire checkpoint.
846
+ await this.syncProposedBlockToArchiver(block);
847
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
840
848
  if (timingInfo.isLastBlock) {
841
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
842
- slot: this.slot,
849
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${slot}`, {
850
+ slot,
843
851
  blockNumber,
844
852
  blocksBuilt
845
853
  });
846
- blockPendingBroadcast = {
847
- block,
848
- txs: usedTxs
849
- };
854
+ blockPendingBroadcast = proposal;
850
855
  break;
851
856
  }
852
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
853
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
854
- if (!this.config.fishermanMode) {
855
- const proposal = await this.validatorClient.createBlockProposal(block.header, block.indexWithinCheckpoint, inHash, block.archive.root, usedTxs, this.proposer, blockProposalOptions);
856
- await this.p2pClient.broadcastProposal(proposal);
857
- }
857
+ // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
858
+ proposal && await this.p2pClient.broadcastProposal(proposal);
858
859
  // Wait until the next block's start time
859
860
  await this.waitUntilNextSubslot(timingInfo.deadline);
860
861
  }
@@ -867,6 +868,13 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
867
868
  blockPendingBroadcast
868
869
  };
869
870
  }
871
+ /** Creates a block proposal for a given block via the validator client (unless in fisherman mode) */ createBlockProposal(block, inHash, usedTxs, blockProposalOptions) {
872
+ if (this.config.fishermanMode) {
873
+ this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
874
+ return Promise.resolve(undefined);
875
+ }
876
+ return this.validatorClient.createBlockProposal(block.header, block.indexWithinCheckpoint, inHash, block.archive.root, usedTxs, this.proposer, blockProposalOptions);
877
+ }
870
878
  /** Sleeps until it is time to produce the next block in the slot */ async waitUntilNextSubslot(nextSubslotStart) {
871
879
  this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
872
880
  this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
@@ -875,15 +883,14 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
875
883
  await this.waitUntilTimeInSlot(nextSubslotStart);
876
884
  }
877
885
  /** Builds a single block. Called from the main block building loop. */ async buildSingleBlock(checkpointBuilder, opts) {
878
- const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded, remainingBlobFields } = opts;
886
+ const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } = opts;
879
887
  this.log.verbose(`Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`, {
880
888
  ...checkpointBuilder.getConstantData(),
881
889
  ...opts
882
890
  });
883
891
  try {
884
892
  // Wait until we have enough txs to build the block
885
- const minTxs = this.config.minTxsPerBlock;
886
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
893
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
887
894
  if (!canStartBuilding) {
888
895
  this.log.warn(`Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`, {
889
896
  blockNumber,
@@ -896,62 +903,66 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
896
903
  slot: this.slot
897
904
  });
898
905
  this.metrics.recordBlockProposalFailed('insufficient_txs');
899
- return undefined;
906
+ return {
907
+ failure: 'insufficient-txs'
908
+ };
900
909
  }
901
910
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
902
911
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
903
- const pendingTxs = filter(this.p2pClient.iteratePendingTxs(), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
912
+ const pendingTxs = filter(this.p2pClient.iterateEligiblePendingTxs(), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
904
913
  this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`, {
905
914
  slot: this.slot,
906
915
  blockNumber,
907
916
  indexWithinCheckpoint
908
917
  });
909
918
  this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
910
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
911
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
912
- const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
919
+ // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
920
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
921
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
922
+ const minValidTxs = forceCreate ? 0 : this.config.minValidTxsPerBlock ?? minTxs;
913
923
  const blockBuilderOptions = {
914
924
  maxTransactions: this.config.maxTxsPerBlock,
915
- maxBlockSize: this.config.maxBlockSizeInBytes,
916
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
917
- maxBlobFields: maxBlobFieldsForTxs,
918
- deadline: buildDeadline
925
+ maxBlockGas: this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity) : undefined,
926
+ deadline: buildDeadline,
927
+ isBuildingProposal: true,
928
+ minValidTxs,
929
+ maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
930
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier
919
931
  };
920
- // Actually build the block by executing txs
921
- const workTimer = new Timer();
922
- const { publicGas, block, publicProcessorDuration, numTxs, blockBuildingTimer, usedTxs, failedTxs, usedTxBlobFields } = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
923
- const blockBuildDuration = workTimer.ms();
932
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
933
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
934
+ // updated for blocks that will be discarded.
935
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(checkpointBuilder, pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
924
936
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
925
- await this.dropFailedTxsFromP2P(failedTxs);
926
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
927
- // too long, then we may not get to minTxsPerBlock after executing public functions.
928
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
929
- if (!forceCreate && numTxs < minValidTxs) {
930
- 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})`, {
937
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
938
+ if (buildResult.status === 'insufficient-valid-txs') {
939
+ this.log.warn(`Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`, {
931
940
  slot: this.slot,
932
941
  blockNumber,
933
- numTxs,
934
- indexWithinCheckpoint
942
+ numTxs: buildResult.processedCount,
943
+ indexWithinCheckpoint,
944
+ minValidTxs
935
945
  });
936
- this.eventEmitter.emit('block-tx-count-check-failed', {
937
- minTxs: minValidTxs,
938
- availableTxs: numTxs,
946
+ this.eventEmitter.emit('block-build-failed', {
947
+ reason: `Insufficient valid txs`,
939
948
  slot: this.slot
940
949
  });
941
950
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
942
- return undefined;
951
+ return {
952
+ failure: 'insufficient-valid-txs'
953
+ };
943
954
  }
944
955
  // Block creation succeeded, emit stats and metrics
956
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
945
957
  const blockStats = {
946
958
  eventName: 'l2-block-built',
947
959
  duration: blockBuildDuration,
948
960
  publicProcessDuration: publicProcessorDuration,
949
- rollupCircuitsDuration: blockBuildingTimer.ms(),
950
961
  ...block.getStats()
951
962
  };
952
963
  const blockHash = await block.hash();
953
964
  const txHashes = block.body.txEffects.map((tx)=>tx.txHash);
954
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
965
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
955
966
  this.log.info(`Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`, {
956
967
  blockHash,
957
968
  txHashes,
@@ -962,11 +973,10 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
962
973
  blockNumber: block.number,
963
974
  slot: this.slot
964
975
  });
965
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
976
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
966
977
  return {
967
978
  block,
968
- usedTxs,
969
- remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields
979
+ usedTxs
970
980
  };
971
981
  } catch (err) {
972
982
  this.eventEmitter.emit('block-build-failed', {
@@ -984,9 +994,31 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
984
994
  };
985
995
  }
986
996
  }
997
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */ async buildSingleBlockWithCheckpointBuilder(checkpointBuilder, pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions) {
998
+ try {
999
+ const workTimer = new Timer();
1000
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
1001
+ const blockBuildDuration = workTimer.ms();
1002
+ return {
1003
+ ...result,
1004
+ blockBuildDuration,
1005
+ status: 'success'
1006
+ };
1007
+ } catch (err) {
1008
+ if (isErrorClass(err, InsufficientValidTxsError)) {
1009
+ return {
1010
+ failedTxs: err.failedTxs,
1011
+ processedCount: err.processedCount,
1012
+ status: 'insufficient-valid-txs'
1013
+ };
1014
+ }
1015
+ throw err;
1016
+ }
1017
+ }
987
1018
  /** Waits until minTxs are available on the pool for building a block. */ async waitForMinTxs(opts) {
988
- const minTxs = this.config.minTxsPerBlock;
989
1019
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
1020
+ // We only allow a block with 0 txs in the first block of the checkpoint
1021
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
990
1022
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
991
1023
  const startBuildingDeadline = buildDeadline ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000) : undefined;
992
1024
  let availableTxs = await this.p2pClient.getPendingTxCount();
@@ -996,7 +1028,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
996
1028
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
997
1029
  return {
998
1030
  canStartBuilding: false,
999
- availableTxs: availableTxs
1031
+ availableTxs,
1032
+ minTxs
1000
1033
  };
1001
1034
  }
1002
1035
  // Wait a bit before checking again
@@ -1006,12 +1039,13 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1006
1039
  slot: this.slot,
1007
1040
  indexWithinCheckpoint
1008
1041
  });
1009
- await sleep(TXS_POLLING_MS);
1042
+ await this.waitForTxsPollingInterval();
1010
1043
  availableTxs = await this.p2pClient.getPendingTxCount();
1011
1044
  }
1012
1045
  return {
1013
1046
  canStartBuilding: true,
1014
- availableTxs
1047
+ availableTxs,
1048
+ minTxs
1015
1049
  };
1016
1050
  }
1017
1051
  /**
@@ -1041,17 +1075,23 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1041
1075
  return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
1042
1076
  }
1043
1077
  const attestationTimeAllowed = this.config.enforceTimeTable ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT) : this.l1Constants.slotDuration;
1044
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
1078
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
1045
1079
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
1046
1080
  const collectAttestationsTimer = new Timer();
1047
1081
  let collectedAttestationsCount = 0;
1048
1082
  try {
1049
1083
  const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline);
1050
1084
  collectedAttestationsCount = attestations.length;
1085
+ // Trim attestations to minimum required to save L1 calldata gas
1086
+ const localAddresses = this.validatorClient.getValidatorAddresses();
1087
+ const trimmed = trimAttestations(attestations, numberOfRequiredAttestations, this.attestorAddress, localAddresses);
1088
+ if (trimmed.length < attestations.length) {
1089
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
1090
+ }
1051
1091
  // Rollup contract requires that the signatures are provided in the order of the committee
1052
- const sorted = orderAttestations(attestations, committee);
1092
+ const sorted = orderAttestations(trimmed, committee);
1053
1093
  // Manipulate the attestations if we've been configured to do so
1054
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
1094
+ if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation || this.config.shuffleAttestationOrdering) {
1055
1095
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
1056
1096
  }
1057
1097
  return new CommitteeAttestationsAndSigners(sorted);
@@ -1068,7 +1108,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1068
1108
  // Compute the proposer index in the committee, since we dont want to tweak it.
1069
1109
  // Otherwise, the L1 rollup contract will reject the block outright.
1070
1110
  const proposerIndex = Number(this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)));
1071
- if (this.config.injectFakeAttestation) {
1111
+ if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation) {
1072
1112
  // Find non-empty attestations that are not from the proposer
1073
1113
  const nonProposerIndices = [];
1074
1114
  for(let i = 0; i < attestations.length; i++){
@@ -1078,8 +1118,16 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1078
1118
  }
1079
1119
  if (nonProposerIndices.length > 0) {
1080
1120
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
1081
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1082
- unfreeze(attestations[targetIndex]).signature = Signature.random();
1121
+ if (this.config.injectHighSValueAttestation) {
1122
+ this.log.warn(`Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1123
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
1124
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
1125
+ this.log.warn(`Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1126
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
1127
+ } else {
1128
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1129
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
1130
+ }
1083
1131
  }
1084
1132
  return new CommitteeAttestationsAndSigners(attestations);
1085
1133
  }
@@ -1108,14 +1156,18 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1108
1156
  const failedTxData = failedTxs.map((fail)=>fail.tx);
1109
1157
  const failedTxHashes = failedTxData.map((tx)=>tx.getTxHash());
1110
1158
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
1111
- await this.p2pClient.deleteTxs(failedTxHashes);
1159
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
1112
1160
  }
1113
1161
  /**
1114
1162
  * Adds the proposed block to the archiver so it's available via P2P.
1115
1163
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1116
1164
  * would never receive its own block without this explicit sync.
1165
+ *
1166
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1167
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1168
+ * whenever the real proposer's block arrives from L1.
1117
1169
  */ async syncProposedBlockToArchiver(block) {
1118
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1170
+ if (this.config.skipPushProposedBlocksToArchiver !== false || this.config.fishermanMode) {
1119
1171
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1120
1172
  blockNumber: block.number,
1121
1173
  slot: block.header.globalVariables.slotNumber
@@ -1143,15 +1195,38 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1143
1195
  slot: this.slot,
1144
1196
  feeAnalysisId: feeAnalysis?.id
1145
1197
  });
1146
- this.metrics.recordBlockProposalFailed('block_build_failed');
1198
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
1147
1199
  }
1148
1200
  this.publisher.clearPendingRequests();
1149
1201
  }
1202
+ /**
1203
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
1204
+ */ handleHASigningError(err, errorContext) {
1205
+ if (err instanceof DutyAlreadySignedError) {
1206
+ this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
1207
+ slot: this.slot,
1208
+ signedByNode: err.signedByNode
1209
+ });
1210
+ return true;
1211
+ }
1212
+ if (err instanceof SlashingProtectionError) {
1213
+ this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
1214
+ slot: this.slot,
1215
+ existingMessageHash: err.existingMessageHash,
1216
+ attemptedMessageHash: err.attemptedMessageHash
1217
+ });
1218
+ return true;
1219
+ }
1220
+ return false;
1221
+ }
1150
1222
  /** Waits until a specific time within the current slot */ async waitUntilTimeInSlot(targetSecondsIntoSlot) {
1151
1223
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1152
1224
  const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
1153
1225
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
1154
1226
  }
1227
+ /** Waits the polling interval for transactions. Extracted for test overriding. */ async waitForTxsPollingInterval() {
1228
+ await sleep(TXS_POLLING_MS);
1229
+ }
1155
1230
  getSlotStartBuildTimestamp() {
1156
1231
  return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1157
1232
  }