@aztec-labs/sequencer-client 6.0.0-rc.3 → 6.0.0

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 (78) hide show
  1. package/README.md +1 -1
  2. package/dest/client/sequencer-client.d.ts +1 -1
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +7 -2
  5. package/dest/config.d.ts +2 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +5 -0
  8. package/dest/index.d.ts +2 -2
  9. package/dest/index.d.ts.map +1 -1
  10. package/dest/index.js +1 -1
  11. package/dest/publisher/config.d.ts +7 -4
  12. package/dest/publisher/config.d.ts.map +1 -1
  13. package/dest/publisher/config.js +12 -10
  14. package/dest/publisher/gas_constants.d.ts +39 -0
  15. package/dest/publisher/gas_constants.d.ts.map +1 -0
  16. package/dest/publisher/gas_constants.js +42 -0
  17. package/dest/publisher/index.d.ts +2 -1
  18. package/dest/publisher/index.d.ts.map +1 -1
  19. package/dest/publisher/index.js +1 -0
  20. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +1 -1
  21. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -1
  22. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +1 -0
  23. package/dest/publisher/publisher-manager-metrics.d.ts +19 -0
  24. package/dest/publisher/publisher-manager-metrics.d.ts.map +1 -0
  25. package/dest/publisher/publisher-manager-metrics.js +67 -0
  26. package/dest/publisher/sequencer-publisher-factory.d.ts +8 -4
  27. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  28. package/dest/publisher/sequencer-publisher-factory.js +16 -6
  29. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -3
  30. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  31. package/dest/publisher/sequencer-publisher-metrics.js +0 -8
  32. package/dest/publisher/sequencer-publisher.d.ts +17 -4
  33. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  34. package/dest/publisher/sequencer-publisher.js +168 -17
  35. package/dest/publisher/write_json.d.ts +1 -1
  36. package/dest/publisher/write_json.d.ts.map +1 -1
  37. package/dest/publisher/write_json.js +3 -1
  38. package/dest/sequencer/attestation_manipulation.d.ts +24 -0
  39. package/dest/sequencer/attestation_manipulation.d.ts.map +1 -0
  40. package/dest/sequencer/attestation_manipulation.js +72 -0
  41. package/dest/sequencer/automine/automine_factory.d.ts +1 -1
  42. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -1
  43. package/dest/sequencer/automine/automine_factory.js +5 -1
  44. package/dest/sequencer/checkpoint_inbox_consumption.d.ts +135 -0
  45. package/dest/sequencer/checkpoint_inbox_consumption.d.ts.map +1 -0
  46. package/dest/sequencer/checkpoint_inbox_consumption.js +275 -0
  47. package/dest/sequencer/checkpoint_proposal_job.d.ts +27 -23
  48. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  49. package/dest/sequencer/checkpoint_proposal_job.js +323 -527
  50. package/dest/sequencer/inbox_message_selection.d.ts +17 -16
  51. package/dest/sequencer/inbox_message_selection.d.ts.map +1 -1
  52. package/dest/sequencer/inbox_message_selection.js +20 -7
  53. package/dest/sequencer/metrics.d.ts +4 -4
  54. package/dest/sequencer/metrics.d.ts.map +1 -1
  55. package/dest/sequencer/metrics.js +6 -9
  56. package/dest/sequencer/sequencer.d.ts +9 -4
  57. package/dest/sequencer/sequencer.d.ts.map +1 -1
  58. package/dest/sequencer/sequencer.js +129 -38
  59. package/package.json +23 -23
  60. package/src/client/sequencer-client.ts +6 -1
  61. package/src/config.ts +7 -0
  62. package/src/index.ts +0 -3
  63. package/src/publisher/config.ts +20 -11
  64. package/src/publisher/gas_constants.ts +51 -0
  65. package/src/publisher/index.ts +1 -0
  66. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +1 -0
  67. package/src/publisher/publisher-manager-metrics.ts +76 -0
  68. package/src/publisher/sequencer-publisher-factory.ts +18 -7
  69. package/src/publisher/sequencer-publisher-metrics.ts +0 -12
  70. package/src/publisher/sequencer-publisher.ts +201 -24
  71. package/src/publisher/write_json.ts +3 -1
  72. package/src/sequencer/attestation_manipulation.ts +123 -0
  73. package/src/sequencer/automine/automine_factory.ts +4 -0
  74. package/src/sequencer/checkpoint_inbox_consumption.ts +340 -0
  75. package/src/sequencer/checkpoint_proposal_job.ts +434 -632
  76. package/src/sequencer/inbox_message_selection.ts +45 -24
  77. package/src/sequencer/metrics.ts +7 -9
  78. package/src/sequencer/sequencer.ts +116 -27
@@ -436,36 +436,33 @@ 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, _initProto;
439
- import { PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec-labs/epoch-cache';
439
+ import { PROPOSER_PIPELINING_SLOT_OFFSET, requireStableCommittee } from '@aztec-labs/epoch-cache';
440
440
  import { SimulationOverridesBuilder } from '@aztec-labs/ethereum/contracts';
441
- import { maxBigint, minBigint } from '@aztec-labs/foundation/bigint';
442
441
  import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec-labs/foundation/branded-types';
443
442
  import { randomInt } from '@aztec-labs/foundation/crypto/random';
444
- import { flipSignature, generateRecoverableSignature, generateUnrecoverableSignature } from '@aztec-labs/foundation/crypto/secp256k1-signer';
445
443
  import { InterruptError, TimeoutError } from '@aztec-labs/foundation/error';
446
444
  import { filter } from '@aztec-labs/foundation/iterator';
447
445
  import { createLogger } from '@aztec-labs/foundation/log';
448
446
  import { InterruptibleSleep } from '@aztec-labs/foundation/sleep';
449
447
  import { Timer, executeTimeout } from '@aztec-labs/foundation/timer';
450
- import { isErrorClass, unfreeze } from '@aztec-labs/foundation/types';
451
- import { CommitteeAttestationsAndSigners, MaliciousCommitteeAttestationsAndSigners, MaliciousYParityCommitteeAttestationsAndSigners } from '@aztec-labs/stdlib/block';
448
+ import { isErrorClass } from '@aztec-labs/foundation/types';
449
+ import { CommitteeAttestation, CommitteeAttestationsAndSigners } from '@aztec-labs/stdlib/block';
452
450
  import { buildCheckpointSimulationOverridesPlan, getPreviousCheckpointInboxRollingHash, getPreviousCheckpointOutHashes, validateCheckpoint } from '@aztec-labs/stdlib/checkpoint';
453
- import { computeQuorum, getTimestampForSlot } from '@aztec-labs/stdlib/epoch-helpers';
451
+ import { computeQuorum, getLastL1SlotTimestampForL2Slot, getTimestampForSlot } from '@aztec-labs/stdlib/epoch-helpers';
454
452
  import { Gas } from '@aztec-labs/stdlib/gas';
455
453
  import { InsufficientValidTxsError } from '@aztec-labs/stdlib/interfaces/server';
456
- import { InboxMessagePrefixRef } from '@aztec-labs/stdlib/messaging';
457
- import { orderAttestations, trimAttestations } from '@aztec-labs/stdlib/p2p';
458
- import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
454
+ import { getCoordinationSignatureTypedData, orderAttestations, trimAttestations } from '@aztec-labs/stdlib/p2p';
459
455
  import { AttestationTimeoutError } from '@aztec-labs/stdlib/validators';
460
456
  import { Attributes, trackSpan } from '@aztec-labs/telemetry-client';
461
457
  import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec-labs/validator-ha-signer/errors';
458
+ import { DutyType } from '@aztec-labs/validator-ha-signer/types';
459
+ import { hasAttestationManipulation, manipulateAttestations } from './attestation_manipulation.js';
460
+ import { CheckpointInboxConsumption } from './checkpoint_inbox_consumption.js';
462
461
  import { CheckpointVoter } from './checkpoint_voter.js';
463
462
  import { SequencerInterruptedError } from './errors.js';
464
- import { PROTOCOL_INBOX_CONSUMPTION_CAPS, getEndpointUpperBound, mustQueryEndpoint, resolveEndpoint, selectOrdinaryMessageEnd, selectSafeLocalEnd } from './inbox_message_selection.js';
465
463
  import { SequencerState } from './utils.js';
466
464
  /** How much time to sleep while waiting for min transactions to accumulate for a block */ const TXS_POLLING_MS = 500;
467
465
  const ARCHIVER_SYNC_POLLING_MS = 200;
468
- /** Cap on the Inbox endpoint read a block makes near the checkpoint cap, well under a sub-slot. */ const INBOX_ENDPOINT_READ_TIMEOUT_MS = 2_000;
469
466
  /** An empty transaction stream, for a block built over Inbox messages alone. */ async function* noTransactions() {}
470
467
  /** An integrated preflight did not deliver a usable verdict before the deadline of the phase it serves. */ class PreflightDeadlineError extends Error {
471
468
  deadline;
@@ -568,11 +565,10 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
568
565
  interruptibleSleep;
569
566
  interrupted;
570
567
  /**
571
- * Chain state overrides built once per slot in proposeCheckpoint after the checkpoint is
572
- * complete. Carries the pending parent override (archive + slot + fee header) for pipelining,
573
- * or the invalidation pending override when rolling back. Consumed by the pre-gossip
574
- * publisher.validateCheckpointHeaderAndInbox preflight.
575
- */ checkpointSimulationOverridesPlan;
568
+ * Hash of this checkpoint's first block once it is in the local archiver, until the checkpoint itself is handed to
569
+ * the archiver. While set, giving the checkpoint up leaves blocks on the local chain that no checkpoint will cover.
570
+ */ unclaimedFirstBlockHash;
571
+ /** Whether an HA peer holds one of this slot's signing duties, and so may be proposing the blocks pushed here. */ yieldedToHAPeer;
576
572
  getSignatureContext() {
577
573
  return this.signatureContext;
578
574
  }
@@ -617,6 +613,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
617
613
  this.submission = Promise.resolve();
618
614
  this.interruptibleSleep = new InterruptibleSleep();
619
615
  this.interrupted = false;
616
+ this.yieldedToHAPeer = false;
620
617
  this.log = createLogger('sequencer:checkpoint-proposal', {
621
618
  ...bindings,
622
619
  instanceId: `slot-${this.getBuildSlot()}`
@@ -696,6 +693,19 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
696
693
  ...fields
697
694
  });
698
695
  }
696
+ /** Emits a failure checkpoint event followed by the operator log line for it, both carrying the same context. */ reportCheckpointFailure(event, message, context, log) {
697
+ const eventMessages = {
698
+ 'build-failed': `Checkpoint build failed for slot ${this.targetSlot}`,
699
+ 'publish-failed': `Checkpoint publish failed for slot ${this.targetSlot}`,
700
+ 'block-build-failed': `Block build failed for slot ${this.targetSlot}`
701
+ };
702
+ this.logCheckpointEvent(event, eventMessages[event], context);
703
+ if (log.level === 'error') {
704
+ this.log.error(message, log.err, context);
705
+ } else {
706
+ this.log[log.level](message, context);
707
+ }
708
+ }
699
709
  /**
700
710
  * Executes the checkpoint proposal job.
701
711
  * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
@@ -710,8 +720,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
710
720
  this.votePreparation = votesPromises;
711
721
  // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
712
722
  // Returns after broadcast — attestation collection is deferred.
713
- const broadcast = await this.proposeCheckpoint();
714
- if (!broadcast) {
723
+ const outcome = await this.proposeCheckpoint();
724
+ if (!outcome) {
725
+ await this.pruneAbandonedCheckpointBlocks();
715
726
  await Promise.all(votesPromises);
716
727
  // Still submit votes even without a checkpoint.
717
728
  // Under proposer pipelining, vote-offenses signatures are EIP-712-bound to `targetSlot`
@@ -724,15 +735,15 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
724
735
  }
725
736
  return undefined;
726
737
  }
727
- const { checkpoint } = broadcast;
738
+ const { checkpoint } = outcome;
728
739
  this.metrics.recordCheckpointProposalSuccess();
729
740
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
730
- if (this.config.fishermanMode) {
741
+ if (outcome.kind === 'built-only') {
731
742
  await this.handleCheckpointEndAsFisherman(checkpoint);
732
743
  return checkpoint;
733
744
  }
734
745
  // Background the attestation → signing → L1 pipeline so the work loop is unblocked
735
- this.submission = this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises);
746
+ this.submission = this.waitForAttestationsAndEnqueueSubmissionAsync(outcome, votesPromises);
736
747
  // Return the built checkpoint immediately — the work loop is now unblocked
737
748
  return checkpoint;
738
749
  }
@@ -740,7 +751,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
740
751
  * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
741
752
  * Runs as a fire-and-forget task tracked in the sequencer's shared tracker so the work loop is unblocked.
742
753
  */ async waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises) {
743
- const { checkpoint, streamingState } = broadcast;
754
+ const { checkpoint, consumedTotalMsgCount, simulationOverridesPlan } = broadcast;
744
755
  try {
745
756
  // Wait for all votes actions, enqueued at the beginning, to resolve
746
757
  await Promise.all(votesPromises);
@@ -760,8 +771,11 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
760
771
  }
761
772
  // Attestation collection took seconds and L1 may have moved: re-run the integrated header and Inbox
762
773
  // preflight against L1's current state, and take the bucket hint from it.
763
- const bucketHint = await this.preflightBeforePublication(checkpoint.header, streamingState);
774
+ const bucketHint = await this.preflightBeforePublication(checkpoint.header, consumedTotalMsgCount, simulationOverridesPlan);
764
775
  if (bucketHint !== undefined && await this.checkpointBlocksAreStillLocal(checkpoint)) {
776
+ if (this.config.republishAfterFakeAttestation) {
777
+ await this.publishWithFakeAttestationAndEnqueueInvalidation(checkpoint, signedAttestations.attestations, bucketHint);
778
+ }
765
779
  await this.enqueueCheckpointForSubmission({
766
780
  checkpoint,
767
781
  ...signedAttestations,
@@ -795,18 +809,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
795
809
  slot: this.targetSlot
796
810
  });
797
811
  const coinbase = checkpoint.header.coinbase;
798
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
812
+ await this.metrics.incFilledSlot(coinbase);
799
813
  } else {
800
- this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
801
- slot: this.targetSlot,
802
- checkpointNumber: this.checkpointNumber,
803
- successfulActions: l1Response?.successfulActions,
804
- failedActions: l1Response?.failedActions,
805
- sentActions: l1Response?.sentActions,
806
- expiredActions: l1Response?.expiredActions,
807
- reason: 'propose_action_not_successful'
808
- });
809
- this.log.warn(`Checkpoint publish failed for slot ${this.targetSlot}`, {
814
+ this.reportCheckpointFailure('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
810
815
  slot: this.targetSlot,
811
816
  checkpointNumber: this.checkpointNumber,
812
817
  successfulActions: l1Response?.successfulActions,
@@ -814,6 +819,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
814
819
  sentActions: l1Response?.sentActions,
815
820
  expiredActions: l1Response?.expiredActions,
816
821
  reason: 'propose_action_not_successful'
822
+ }, {
823
+ level: 'warn'
817
824
  });
818
825
  this.eventEmitter.emit('checkpoint-publish-failed', {
819
826
  ...l1Response,
@@ -825,15 +832,13 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
825
832
  if (err instanceof SequencerInterruptedError) {
826
833
  return;
827
834
  }
828
- this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
829
- slot: this.targetSlot,
830
- checkpointNumber: this.checkpointNumber,
831
- reason: err instanceof Error ? err.message : String(err)
832
- });
833
- this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err, {
835
+ this.reportCheckpointFailure('publish-failed', `Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, {
834
836
  slot: this.targetSlot,
835
837
  checkpointNumber: this.checkpointNumber,
836
838
  reason: err instanceof Error ? err.message : String(err)
839
+ }, {
840
+ level: 'error',
841
+ err
837
842
  });
838
843
  this.eventEmitter.emit('checkpoint-publish-failed', {
839
844
  slot: this.targetSlot
@@ -851,10 +856,10 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
851
856
  *
852
857
  * Returns the live bucket sequence to publish as the unsigned `propose` hint, or undefined when the checkpoint can
853
858
  * no longer be published, in which case the slot is abandoned without touching the signed contents.
854
- */ async preflightBeforePublication(header, streamingState) {
855
- const overridesPlan = await this.getPublicationSimulationOverridesPlan();
859
+ */ async preflightBeforePublication(header, consumedTotalMsgCount, buildPlan) {
860
+ const overridesPlan = await this.getPublicationSimulationOverridesPlan(buildPlan);
856
861
  try {
857
- return await this.preflightWithinDeadline(header, streamingState, overridesPlan, this.getL1PublishDeadline());
862
+ return await this.preflightWithinDeadline(header, consumedTotalMsgCount, overridesPlan, this.getL1PublishDeadline());
858
863
  } catch (err) {
859
864
  if (err instanceof SequencerInterruptedError) {
860
865
  throw err;
@@ -863,13 +868,14 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
863
868
  const context = {
864
869
  slot: this.targetSlot,
865
870
  checkpointNumber: this.checkpointNumber,
866
- consumedTotalMsgCount: streamingState.cursor.totalMessageCount,
871
+ consumedTotalMsgCount,
867
872
  inboxRollingHash: header.inboxRollingHash.toString(),
868
873
  reason,
869
874
  error: err instanceof Error ? err.message : String(err)
870
875
  };
871
- this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, context);
872
- this.log.warn(`Pre-publication header and Inbox preflight did not clear the checkpoint; abandoning slot ${this.targetSlot}`, context);
876
+ this.reportCheckpointFailure('publish-failed', `Pre-publication header and Inbox preflight did not clear the checkpoint; abandoning slot ${this.targetSlot}`, context, {
877
+ level: 'warn'
878
+ });
873
879
  this.metrics.recordCheckpointProposalFailed(reason);
874
880
  this.eventEmitter.emit('checkpoint-publish-failed', {
875
881
  slot: this.targetSlot
@@ -882,13 +888,13 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
882
888
  * once the phase it serves has run out of time, and a verdict arriving after the deadline, or after the job was
883
889
  * interrupted, is not acted on: signing or enqueueing on it would commit this node past the point at which the
884
890
  * checkpoint can still land.
885
- */ async preflightWithinDeadline(header, streamingState, overridesPlan, deadline) {
891
+ */ async preflightWithinDeadline(header, consumedTotalMsgCount, overridesPlan, deadline) {
886
892
  const remainingMs = deadline.getTime() - this.dateProvider.now();
887
893
  if (remainingMs <= 0) {
888
894
  throw new PreflightDeadlineError(deadline);
889
895
  }
890
896
  const bucketHint = await executeTimeout(()=>this.publisher.validateCheckpointHeaderAndInbox(header, {
891
- expectedTotal: streamingState.cursor.totalMessageCount,
897
+ expectedTotal: consumedTotalMsgCount,
892
898
  expectedParentCheckpointNumber: CheckpointNumber(this.checkpointNumber - 1)
893
899
  }, overridesPlan), remainingMs, ()=>new PreflightDeadlineError(deadline));
894
900
  if (this.interrupted) {
@@ -912,8 +918,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
912
918
  * tight: attestations are collected up to (and, when not enforcing, past) it, so the propose tx would be enqueued
913
919
  * already expired and time out before it can mine.
914
920
  */ getL1PublishDeadline() {
915
- const lastL1BlockInTargetSlot = Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) + this.l1Constants.slotDuration - this.l1Constants.ethereumSlotDuration;
916
- return new Date(lastL1BlockInTargetSlot * 1000);
921
+ return new Date(Number(getLastL1SlotTimestampForL2Slot(this.targetSlot, this.l1Constants)) * 1000);
917
922
  }
918
923
  /**
919
924
  * The state overrides for the pre-publication preflight: only what the send will actually observe that the current
@@ -926,9 +931,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
926
931
  *
927
932
  * Under the test-only `skipWaitForValidParentCheckpointOnL1` the parent was never confirmed on L1, so the build-time
928
933
  * plan describing it is reused; that keeps the hypothetical context the test asked for and is not a production path.
929
- */ async getPublicationSimulationOverridesPlan() {
934
+ */ async getPublicationSimulationOverridesPlan(buildPlan) {
930
935
  if (this.config.skipWaitForValidParentCheckpointOnL1) {
931
- return this.checkpointSimulationOverridesPlan;
936
+ return buildPlan;
932
937
  }
933
938
  const builder = new SimulationOverridesBuilder();
934
939
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
@@ -936,7 +941,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
936
941
  pending: this.invalidateCheckpoint.forcePendingCheckpointNumber
937
942
  });
938
943
  }
939
- const provenPin = this.checkpointSimulationOverridesPlan?.chainTipsOverride?.proven;
944
+ const provenPin = buildPlan?.chainTipsOverride?.proven;
940
945
  if (provenPin !== undefined && await this.l2BlockSource.isPruneDueAtSlot(this.targetSlot)) {
941
946
  this.log.warn(`Assuming proof for epoch ending at checkpoint ${provenPin} lands by target slot ${this.targetSlot} for the publication preflight`, {
942
947
  slot: this.targetSlot,
@@ -991,8 +996,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
991
996
  localBlockHash: local?.blockHash.toString(),
992
997
  reason: 'checkpoint_blocks_pruned'
993
998
  };
994
- this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, context);
995
- this.log.warn(`The local archiver no longer holds the blocks of this checkpoint; abandoning slot ${this.targetSlot} rather ` + `than publishing a checkpoint this node cannot serve`, context);
999
+ this.reportCheckpointFailure('publish-failed', `The local archiver no longer holds the blocks of this checkpoint; abandoning slot ${this.targetSlot} rather ` + `than publishing a checkpoint this node cannot serve`, context, {
1000
+ level: 'warn'
1001
+ });
996
1002
  this.metrics.recordCheckpointProposalFailed('checkpoint_blocks_pruned');
997
1003
  return false;
998
1004
  }
@@ -1013,6 +1019,57 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1013
1019
  });
1014
1020
  }
1015
1021
  /**
1022
+ * Test-only (`republishAfterFakeAttestation`): publishes the checkpoint with one of the collected attestations
1023
+ * replaced by a fake one, waits for the local archiver to flag it, and enqueues its invalidation, so the next send
1024
+ * bundles the invalidation with the checkpoint carrying the collected attestations.
1025
+ */ async publishWithFakeAttestationAndEnqueueInvalidation(checkpoint, collected, bucketHint) {
1026
+ const logCtx = {
1027
+ slot: this.targetSlot,
1028
+ checkpointNumber: this.checkpointNumber
1029
+ };
1030
+ const lookup = requireStableCommittee(await this.epochCache.getCommittee(this.targetSlot));
1031
+ const fakeAttestations = manipulateAttestations({
1032
+ config: {
1033
+ injectFakeAttestation: true
1034
+ },
1035
+ epochCache: this.epochCache,
1036
+ signatureContext: this.getSignatureContext(),
1037
+ log: this.log,
1038
+ slotNumber: this.targetSlot,
1039
+ epoch: lookup.epoch,
1040
+ seed: lookup.seed,
1041
+ committee: lookup.state === 'members' ? lookup.committee : [],
1042
+ // Copies, since the manipulation overwrites a signature in place and the collected set is published afterwards.
1043
+ attestations: collected.attestations.map((a)=>new CommitteeAttestation(a.address, a.signature))
1044
+ });
1045
+ // The slot's slashing-protected signature already covers the collected attestations, and the protection would
1046
+ // refuse a second payload for the slot, so this throwaway set is signed under an unprotected context.
1047
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1048
+ const fakeAttestationsSignature = await this.validatorClient.signWithAddress(signer, getCoordinationSignatureTypedData(fakeAttestations), {
1049
+ dutyType: DutyType.AUTH_REQUEST
1050
+ });
1051
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, fakeAttestations, fakeAttestationsSignature, bucketHint, {
1052
+ txTimeoutAt: this.getL1PublishDeadline()
1053
+ });
1054
+ this.log.warn(`Publishing checkpoint ${this.checkpointNumber} with a fake attestation`, logCtx);
1055
+ const response = await this.publisher.sendRequests(this.targetSlot);
1056
+ if (!response?.successfulActions.includes('propose')) {
1057
+ this.log.warn(`Checkpoint ${this.checkpointNumber} with a fake attestation did not land`, logCtx);
1058
+ return;
1059
+ }
1060
+ const deadlineMs = this.getL1PublishDeadline().getTime();
1061
+ while(this.dateProvider.now() < deadlineMs){
1062
+ const status = await this.l2BlockSource.getPendingChainValidationStatus();
1063
+ if (!status.valid && status.checkpoint.checkpointNumber === this.checkpointNumber) {
1064
+ this.log.warn(`Invalidating checkpoint ${this.checkpointNumber} before publishing it again`, logCtx);
1065
+ await this.enqueueInvalidation(status);
1066
+ return;
1067
+ }
1068
+ await this.awaitInterruptibleSleep(ARCHIVER_SYNC_POLLING_MS);
1069
+ }
1070
+ this.log.warn(`Archiver did not flag checkpoint ${this.checkpointNumber} before the publish deadline`, logCtx);
1071
+ }
1072
+ /**
1016
1073
  * Wait until the archiver syncs past the given L2 slot number.
1017
1074
  * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
1018
1075
  * L1 submission window and is no longer useful.
@@ -1175,7 +1232,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1175
1232
  publisherAddress: this.publisher.getSenderAddress().toString(),
1176
1233
  coinbase: coinbase.toString()
1177
1234
  });
1178
- this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
1235
+ this.metrics.incOpenSlot(this.targetSlot);
1179
1236
  // Enqueues checkpoint invalidation (constant for the whole slot)
1180
1237
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
1181
1238
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
@@ -1184,7 +1241,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1184
1241
  // pending/archive/fee-header to "as if the proposed parent had landed", so both the
1185
1242
  // mana-min-fee simulation (in the globals builder) and the pre-gossip
1186
1243
  // validateCheckpointHeaderAndInbox preflight see the chain tip the eventual L1 send will see.
1187
- this.checkpointSimulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
1244
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
1188
1245
  checkpointNumber: this.checkpointNumber,
1189
1246
  proposedCheckpointData: this.proposedCheckpointData,
1190
1247
  invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
@@ -1193,7 +1250,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1193
1250
  signatureContext: this.signatureContext,
1194
1251
  log: this.log
1195
1252
  });
1196
- const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(coinbase, feeRecipient, this.targetSlot, this.checkpointSimulationOverridesPlan);
1253
+ const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(coinbase, feeRecipient, this.targetSlot, simulationOverridesPlan);
1197
1254
  // Collect the out hashes of all the checkpoints before this one in the same epoch.
1198
1255
  // Under pipelining the parent checkpoint may not be on L1 yet at build time, so the helper
1199
1256
  // splices in the parent's checkpointOutHash from the locally-known proposed checkpoint so
@@ -1203,6 +1260,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1203
1260
  blockSource: this.l2BlockSource,
1204
1261
  epoch: this.targetEpoch,
1205
1262
  checkpointNumber: this.checkpointNumber,
1263
+ // The rollup's epoch duration, as validators use: the job's own constants take it from node config.
1206
1264
  l1Constants: this.epochCache.getL1Constants(),
1207
1265
  pipeliningEnabled: true,
1208
1266
  proposedCheckpointData: this.proposedCheckpointData,
@@ -1219,7 +1277,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1219
1277
  });
1220
1278
  // Anchor the modifier to the predicted parent fee header: L1 will apply it against
1221
1279
  // that, not against the latest published checkpoint (which lags by one under pipelining).
1222
- const predictedParentEthPerFeeAssetE12 = this.checkpointSimulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
1280
+ const predictedParentEthPerFeeAssetE12 = simulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
1223
1281
  const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12);
1224
1282
  const fork = _ts_add_disposable_resource(env, await this.worldState.fork(this.syncedToBlockNumber, {
1225
1283
  closeDelayMs: 12_000
@@ -1227,7 +1285,16 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1227
1285
  // Streaming Inbox: the consumption cursor starts at the parent state this checkpoint builds on. The fork's
1228
1286
  // L1-to-L2 tree leaf count is the parent's cumulative consumed total (compact indexing), whose prefix hash the
1229
1287
  // local message log serves.
1230
- const initialStreamingState = await this.resolveStreamingCheckpointStart(fork);
1288
+ const consumption = await CheckpointInboxConsumption.start(fork, {
1289
+ messageSource: this.l1ToL2MessageSource,
1290
+ inbox: this.inbox,
1291
+ dateProvider: this.dateProvider,
1292
+ log: this.log,
1293
+ logContext: {
1294
+ slot: this.targetSlot,
1295
+ checkpointNumber: this.checkpointNumber
1296
+ }
1297
+ });
1231
1298
  // Create checkpoint builder for the entire slot
1232
1299
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, feeAssetPriceModifier, previousCheckpointOutHashes, previousInboxRollingHash, fork, this.log.getBindings());
1233
1300
  // Options for the validator client when creating block and checkpoint proposals
@@ -1241,20 +1308,15 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1241
1308
  };
1242
1309
  let blocksInCheckpoint = [];
1243
1310
  let blockPendingBroadcast = undefined;
1244
- // Consumption state after the last block built. The pre-gossip preflight validates the header against it and it
1245
- // travels with the broadcast result so the pre-publication preflight can re-resolve the bucket hint. Every path
1246
- // that reads it below is reached only once the block loop has returned its final state.
1247
- let streamingState = initialStreamingState;
1248
1311
  const checkpointBuildTimer = new Timer();
1249
1312
  try {
1250
1313
  // Main loop: build blocks for the checkpoint
1251
- const result = await this.buildBlocksForCheckpoint(checkpointBuilder, checkpointGlobalVariables.timestamp, blockProposalOptions, initialStreamingState);
1314
+ const result = await this.buildBlocksForCheckpoint(checkpointBuilder, checkpointGlobalVariables.timestamp, blockProposalOptions, consumption);
1252
1315
  if (result.aborted) {
1253
1316
  return undefined;
1254
1317
  }
1255
1318
  blocksInCheckpoint = result.blocksInCheckpoint;
1256
1319
  blockPendingBroadcast = result.blockPendingBroadcast;
1257
- streamingState = result.streamingState;
1258
1320
  } catch (err) {
1259
1321
  // These errors are expected in HA mode, so we yield and let another HA node handle the slot
1260
1322
  // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
@@ -1265,15 +1327,12 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1265
1327
  throw err;
1266
1328
  }
1267
1329
  if (blocksInCheckpoint.length === 0) {
1268
- this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1269
- slot: this.targetSlot,
1270
- checkpointNumber: this.checkpointNumber,
1271
- reason: 'no_blocks_built'
1272
- });
1273
- this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
1330
+ this.reportCheckpointFailure('build-failed', `No blocks were built for slot ${this.targetSlot}`, {
1274
1331
  slot: this.targetSlot,
1275
1332
  checkpointNumber: this.checkpointNumber,
1276
1333
  reason: 'no_blocks_built'
1334
+ }, {
1335
+ level: 'warn'
1277
1336
  });
1278
1337
  this.eventEmitter.emit('checkpoint-empty', {
1279
1338
  slot: this.targetSlot
@@ -1282,19 +1341,14 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1282
1341
  }
1283
1342
  const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
1284
1343
  if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
1285
- this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1286
- slot: this.targetSlot,
1287
- checkpointNumber: this.checkpointNumber,
1288
- blocksBuilt: blocksInCheckpoint.length,
1289
- minBlocksForCheckpoint,
1290
- reason: 'min_blocks_not_met'
1291
- });
1292
- this.log.warn(`Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`, {
1344
+ this.reportCheckpointFailure('build-failed', `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`, {
1293
1345
  slot: this.targetSlot,
1294
1346
  checkpointNumber: this.checkpointNumber,
1295
1347
  blocksBuilt: blocksInCheckpoint.length,
1296
1348
  minBlocksForCheckpoint,
1297
1349
  reason: 'min_blocks_not_met'
1350
+ }, {
1351
+ level: 'warn'
1298
1352
  });
1299
1353
  return undefined;
1300
1354
  }
@@ -1313,19 +1367,15 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1313
1367
  maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint
1314
1368
  });
1315
1369
  } catch (err) {
1316
- this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1317
- slot: this.targetSlot,
1318
- checkpointNumber: this.checkpointNumber,
1319
- blocksBuilt: blocksInCheckpoint.length,
1320
- reason: 'invalid_checkpoint',
1321
- checkpoint: checkpoint.header.toInspect()
1322
- });
1323
- this.log.error(`Built an invalid checkpoint at slot ${this.targetSlot} (skipping proposal)`, err, {
1370
+ this.reportCheckpointFailure('build-failed', `Built an invalid checkpoint at slot ${this.targetSlot} (skipping proposal)`, {
1324
1371
  slot: this.targetSlot,
1325
1372
  checkpointNumber: this.checkpointNumber,
1326
1373
  blocksBuilt: blocksInCheckpoint.length,
1327
1374
  reason: 'invalid_checkpoint',
1328
1375
  checkpoint: checkpoint.header.toInspect()
1376
+ }, {
1377
+ level: 'error',
1378
+ err
1329
1379
  });
1330
1380
  return undefined;
1331
1381
  }
@@ -1350,13 +1400,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1350
1400
  blocksBuilt: blocksInCheckpoint.length
1351
1401
  });
1352
1402
  this.metrics.recordCheckpointSuccess();
1353
- // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection and never
1354
- // publishes.
1355
1403
  return {
1356
- checkpoint,
1357
- proposal: undefined,
1358
- blockProposedAt: this.dateProvider.now(),
1359
- streamingState
1404
+ kind: 'built-only',
1405
+ checkpoint
1360
1406
  };
1361
1407
  }
1362
1408
  // Validate the header and the Inbox consumption against L1 state before broadcasting: the parent the header
@@ -1367,7 +1413,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1367
1413
  // The simulation is bounded by the attestation deadline: a verdict that arrives once no validator can attest
1368
1414
  // any more must not lead to signing.
1369
1415
  try {
1370
- await this.preflightWithinDeadline(checkpoint.header, streamingState, this.checkpointSimulationOverridesPlan, this.getAttestationDeadline());
1416
+ await this.preflightWithinDeadline(checkpoint.header, consumption.consumedTotalMsgCount, simulationOverridesPlan, this.getAttestationDeadline());
1371
1417
  } catch (err) {
1372
1418
  if (err instanceof SequencerInterruptedError) {
1373
1419
  return undefined;
@@ -1376,7 +1422,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1376
1422
  this.log.error(`Pre-broadcast header and Inbox validation failed for slot ${this.targetSlot}; aborting`, err, {
1377
1423
  slot: this.targetSlot,
1378
1424
  checkpointNumber: this.checkpointNumber,
1379
- consumedTotalMsgCount: streamingState.cursor.totalMessageCount,
1425
+ consumedTotalMsgCount: consumption.consumedTotalMsgCount,
1380
1426
  inboxRollingHash: checkpoint.header.inboxRollingHash.toString(),
1381
1427
  reason
1382
1428
  });
@@ -1395,7 +1441,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1395
1441
  // checkpoint visible for pipelining the next slot. Built from local checkpoint data — never
1396
1442
  // from the broadcast proposal archive, which may be deliberately corrupted under test flags.
1397
1443
  // Fail closed: if this throws, the outer catch aborts the slot before gossiping.
1398
- await this.syncProposedCheckpointToArchiver(checkpoint, blocksInCheckpoint.length, feeAssetPriceModifier);
1444
+ await this.syncProposedCheckpointToArchiver(checkpoint, proposal, blocksInCheckpoint.length, feeAssetPriceModifier);
1399
1445
  const blockProposedAt = this.dateProvider.now();
1400
1446
  if (this.config.skipBroadcastCheckpointProposal) {
1401
1447
  // Test-only: suppress the CheckpointProposal so peers never see a proposed checkpoint for
@@ -1411,10 +1457,12 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1411
1457
  }
1412
1458
  // Return immediately after broadcast — attestation collection happens in the background.
1413
1459
  return {
1460
+ kind: 'broadcast',
1414
1461
  checkpoint,
1415
1462
  proposal,
1416
1463
  blockProposedAt,
1417
- streamingState
1464
+ consumedTotalMsgCount: consumption.consumedTotalMsgCount,
1465
+ simulationOverridesPlan
1418
1466
  };
1419
1467
  } catch (e) {
1420
1468
  env.error = e;
@@ -1426,6 +1474,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1426
1474
  } catch (err) {
1427
1475
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
1428
1476
  // swallow this error. It's already been logged by a function deeper in the stack
1477
+ this.yieldedToHAPeer = true;
1429
1478
  return undefined;
1430
1479
  }
1431
1480
  this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
@@ -1434,16 +1483,12 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1434
1483
  }
1435
1484
  /**
1436
1485
  * Builds blocks for a checkpoint within the current slot.
1437
- */ async buildBlocksForCheckpoint(checkpointBuilder, timestamp, blockProposalOptions, initialStreamingState) {
1486
+ */ async buildBlocksForCheckpoint(checkpointBuilder, timestamp, blockProposalOptions, consumption) {
1438
1487
  const blocksInCheckpoint = [];
1439
1488
  const txHashesAlreadyIncluded = new Set();
1440
1489
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
1441
1490
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
1442
1491
  let blockPendingBroadcast = undefined;
1443
- let streamingState = initialStreamingState;
1444
- // Streaming Inbox: the loop ran out of sub-slots rather than finishing the checkpoint, so the cursor may be
1445
- // sitting at a prefix that is not a live L1 bucket end.
1446
- let ranOutOfSubslots = false;
1447
1492
  while(true){
1448
1493
  const blocksBuilt = blocksInCheckpoint.length;
1449
1494
  const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
@@ -1464,7 +1509,28 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1464
1509
  blocksBuilt,
1465
1510
  nowSeconds
1466
1511
  });
1467
- ranOutOfSubslots = true;
1512
+ // Streaming Inbox: the sub-slot schedule ran out mid-checkpoint, so the cursor may sit at a prefix that is not
1513
+ // a live L1 bucket end, which no checkpoint can be published on. Resolve once and, if it is not one, build one
1514
+ // more block rather than lose the slot; this is the only place the loop overrides the timetable. A cursor
1515
+ // still at the checkpoint start needs nothing: the parent checkpoint already ended on a live bucket end.
1516
+ if (consumption.hasConsumedInThisCheckpoint) {
1517
+ const forced = await this.buildForcedEndpointBlock(checkpointBuilder, consumption, {
1518
+ blockTimestamp: timestamp,
1519
+ blockNumber,
1520
+ indexWithinCheckpoint,
1521
+ txHashesAlreadyIncluded,
1522
+ blockProposalOptions
1523
+ });
1524
+ if (forced.kind === 'aborted') {
1525
+ return {
1526
+ aborted: true
1527
+ };
1528
+ }
1529
+ if (forced.kind === 'built') {
1530
+ blocksInCheckpoint.push(forced.block);
1531
+ blockPendingBroadcast = forced.proposal;
1532
+ }
1533
+ }
1468
1534
  break;
1469
1535
  }
1470
1536
  // Streaming Inbox: select this block's message range against the current (not-yet-advanced) consumption
@@ -1474,14 +1540,14 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1474
1540
  // includes the block that reaches the per-checkpoint block cap, not just the timetable's last sub-slot.
1475
1541
  const maxBlocks = Math.min(this.config.maxBlocksPerCheckpoint, this.timetable.getMaxBlocksPerCheckpoint());
1476
1542
  const isCheckpointFinalBlock = timingInfo.isLastBlock || blocksBuilt + 1 >= maxBlocks;
1477
- const selection = await this.selectStreamingBundle(streamingState, {
1543
+ const selection = await consumption.selectRange({
1478
1544
  isFinalBlock: isCheckpointFinalBlock,
1479
1545
  buildDeadline: timingInfo.deadline
1480
1546
  });
1481
1547
  // No checkpoint ending on the messages this block could consume can be published: stop before signing
1482
1548
  // anything more and give up the slot.
1483
1549
  if (selection.kind === 'abort') {
1484
- this.reportStreamingAbort(streamingState, selection.reason, {
1550
+ this.reportStreamingAbort(consumption, selection.reason, {
1485
1551
  blocksBuilt,
1486
1552
  blockNumber,
1487
1553
  ...selection.context
@@ -1502,7 +1568,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1502
1568
  l1ToL2Messages: selection.range.messages
1503
1569
  });
1504
1570
  // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
1505
- if ('failure' in buildResult) {
1571
+ if (buildResult.kind === 'skipped') {
1506
1572
  // If this was the last subslot, we're done.
1507
1573
  if (timingInfo.isLastBlock) {
1508
1574
  break;
@@ -1513,7 +1579,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1513
1579
  }
1514
1580
  // If there was an error building the block, we just exit the loop and give up the rest of the slot.
1515
1581
  // We don't want to risk building more blocks if something went wrong.
1516
- if ('error' in buildResult) {
1582
+ if (buildResult.kind === 'failed') {
1517
1583
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
1518
1584
  this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
1519
1585
  slot: this.targetSlot,
@@ -1530,33 +1596,14 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1530
1596
  });
1531
1597
  blocksInCheckpoint.push(block);
1532
1598
  usedTxs.forEach((tx)=>txHashesAlreadyIncluded.add(tx.txHash.toString()));
1533
- // Streaming Inbox: the block built successfully, so advance the cursor to the prefix it consumed through and
1534
- // sign that prefix as this block's reference. A block that consumed nothing re-signs the cursor's prefix.
1535
- streamingState = {
1536
- ...streamingState,
1537
- cursor: selection.range.end
1538
- };
1539
- const blockPrefixRef = InboxMessagePrefixRef.fromPosition(streamingState.cursor);
1540
- // Sign the block proposal. This will throw if HA signing fails.
1541
- const proposal = await this.createBlockProposal(block, usedTxs, {
1542
- ...blockProposalOptions,
1543
- broadcastInvalidBlockProposal: blockProposalOptions.broadcastInvalidBlockProposal || block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint
1544
- }, blockPrefixRef);
1545
- // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
1546
- // so we avoid polluting our archive with a block that would fail.
1547
- // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
1548
- // If this throws, we abort the entire checkpoint.
1549
- await this.syncProposedBlockToArchiver(block, blockPrefixRef);
1599
+ const { proposal, blockPrefixRef } = await this.commitBuiltBlock(block, usedTxs, selection.range, consumption, blockProposalOptions);
1550
1600
  await this.notifyBlockReadyToBroadcast({
1551
1601
  block,
1552
1602
  blockNumber,
1553
1603
  indexWithinCheckpoint,
1604
+ timingInfo,
1554
1605
  inboxPrefixRef: blockPrefixRef,
1555
- consumedMessageCount: streamingState.cursor.totalMessageCount,
1556
- isStandalone: !timingInfo.isLastBlock,
1557
- remainingBuildSubslots: Math.max(0, maxBlocks - (timingInfo.index + 1)),
1558
- subslotIndex: timingInfo.index,
1559
- subslotDeadline: timingInfo.deadline,
1606
+ consumedMessageCount: consumption.consumedTotalMsgCount,
1560
1607
  blocksBuiltIncludingThis: blocksInCheckpoint.length,
1561
1608
  maxBlocksInCheckpoint: maxBlocks
1562
1609
  });
@@ -1577,31 +1624,6 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1577
1624
  // Wait until the next block's start time
1578
1625
  await this.waitUntilNextSubslot(timingInfo.deadline);
1579
1626
  }
1580
- // Streaming Inbox: the sub-slot schedule ran out mid-checkpoint, so the cursor may sit at a prefix that is not a
1581
- // live L1 bucket end, which no checkpoint can be published on. Resolve once and, if it is not one, build one more
1582
- // block rather than lose the slot; this is the only place the loop overrides the timetable. A cursor still at the
1583
- // checkpoint start needs nothing: the parent checkpoint already ended on a live bucket end.
1584
- if (ranOutOfSubslots && blocksInCheckpoint.length > 0 && streamingState.cursor.totalMessageCount > streamingState.checkpointStartTotalMsgCount) {
1585
- const forced = await this.buildForcedEndpointBlock(checkpointBuilder, streamingState, {
1586
- blockTimestamp: timestamp,
1587
- blockNumber: BlockNumber(initialBlockNumber + blocksInCheckpoint.length),
1588
- indexWithinCheckpoint: IndexWithinCheckpoint(blocksInCheckpoint.length),
1589
- txHashesAlreadyIncluded,
1590
- blockProposalOptions
1591
- });
1592
- if (forced !== undefined) {
1593
- if ('aborted' in forced) {
1594
- return {
1595
- aborted: true
1596
- };
1597
- }
1598
- blocksInCheckpoint.push(forced.block);
1599
- blockPendingBroadcast = forced.proposal;
1600
- // The tail consumed through its endpoint, so the checkpoint's final cursor is the tail's, not the one the
1601
- // loop stopped at. Both preflights read this state.
1602
- streamingState = forced.streamingState;
1603
- }
1604
- }
1605
1627
  this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
1606
1628
  slot: this.targetSlot,
1607
1629
  blocksBuilt: blocksInCheckpoint.length
@@ -1609,8 +1631,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1609
1631
  return {
1610
1632
  aborted: false,
1611
1633
  blocksInCheckpoint,
1612
- blockPendingBroadcast,
1613
- streamingState
1634
+ blockPendingBroadcast
1614
1635
  };
1615
1636
  }
1616
1637
  /**
@@ -1627,6 +1648,9 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1627
1648
  if (onCheckpointPhase === undefined) {
1628
1649
  return;
1629
1650
  }
1651
+ const { block, timingInfo } = opts;
1652
+ const subslotIndex = timingInfo.index;
1653
+ const subslotDeadline = timingInfo.deadline;
1630
1654
  const sendDeadline = this.timetable.getCheckpointProposalReceiveDeadline(this.targetSlot) - this.timetable.p2pPropagationTime;
1631
1655
  await onCheckpointPhase({
1632
1656
  phase: 'block-ready-to-broadcast',
@@ -1634,22 +1658,22 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1634
1658
  checkpointNumber: this.checkpointNumber,
1635
1659
  blockNumber: opts.blockNumber,
1636
1660
  indexWithinCheckpoint: opts.indexWithinCheckpoint,
1637
- blockHash: await opts.block.hash(),
1638
- isStandalone: opts.isStandalone,
1639
- remainingBuildSubslots: opts.remainingBuildSubslots,
1640
- subslotIndex: opts.subslotIndex,
1661
+ blockHash: await block.hash(),
1662
+ isStandalone: !timingInfo.isLastBlock,
1663
+ remainingBuildSubslots: Math.max(0, opts.maxBlocksInCheckpoint - (subslotIndex + 1)),
1664
+ subslotIndex,
1641
1665
  proposalSendDeadline: new Date(sendDeadline * 1000),
1642
1666
  consumedMessageCount: opts.consumedMessageCount,
1643
1667
  inboxPrefixRef: opts.inboxPrefixRef,
1644
1668
  schedule: {
1645
1669
  nowMs: ()=>this.dateProvider.now(),
1646
- selectNextBuildSubslot: (nowSeconds)=>this.selectNextBuildSubslot(nowSeconds, opts.subslotDeadline),
1670
+ selectNextBuildSubslot: (nowSeconds)=>this.selectNextBuildSubslot(nowSeconds, subslotDeadline),
1647
1671
  canBuildAnotherBlock: (nowSeconds)=>{
1648
1672
  if (opts.blocksBuiltIncludingThis >= opts.maxBlocksInCheckpoint) {
1649
1673
  return false;
1650
1674
  }
1651
- const next = this.selectNextBuildSubslot(nowSeconds, opts.subslotDeadline);
1652
- return next.canStart && next.index > opts.subslotIndex;
1675
+ const next = this.selectNextBuildSubslot(nowSeconds, subslotDeadline);
1676
+ return next.canStart && next.index > subslotIndex;
1653
1677
  },
1654
1678
  getProposalReceiveDeadlineSeconds: ()=>this.timetable.getCheckpointProposalReceiveDeadline(this.targetSlot),
1655
1679
  getProposalReceiveStartSeconds: ()=>this.timetable.getCheckpointProposalReceiveStart(this.targetSlot),
@@ -1670,86 +1694,57 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1670
1694
  * one, nothing is built and the checkpoint publishes as it stands. The block carries no transactions: it is
1671
1695
  * already past the schedule, so it must not spend its remaining time executing any.
1672
1696
  *
1673
- * Returns the block, its signed proposal and the consumption state the tail advanced to, `undefined` when no block
1674
- * was needed (the caller keeps the state it passed in), or an abort when the checkpoint has to be abandoned. The
1675
- * abort is already reported. `streamingState` is read, never modified.
1676
- */ async buildForcedEndpointBlock(checkpointBuilder, streamingState, opts) {
1677
- const { cursor, checkpointStartTotalMsgCount: checkpointStartCount } = streamingState;
1678
- const localSyncedCount = (await this.l1ToL2MessageSource.getSyncedMessagePosition()).totalMessageCount;
1679
- const upperBound = getEndpointUpperBound({
1680
- cursorCount: cursor.totalMessageCount,
1681
- localSyncedCount,
1682
- checkpointStartCount,
1683
- isFinalBlock: true,
1684
- caps: PROTOCOL_INBOX_CONSUMPTION_CAPS
1685
- });
1686
- const { deadline, pastLastBlockBuildTime } = this.getForcedEndpointBlockDeadline();
1687
- this.log.warn(`Ending checkpoint ${this.checkpointNumber} with a forced Inbox endpoint block`, {
1688
- slot: this.targetSlot,
1689
- checkpointNumber: this.checkpointNumber,
1697
+ * Returns the block and its signed proposal, `not-needed` when the cursor already sits on a live bucket end, or an
1698
+ * abort when the checkpoint has to be abandoned. The abort is already reported. The consumption cursor advances to
1699
+ * the endpoint only once the block has built.
1700
+ */ async buildForcedEndpointBlock(checkpointBuilder, consumption, opts) {
1701
+ const decision = await consumption.resolveForcedEndpoint({
1690
1702
  blockNumber: opts.blockNumber,
1691
- cursorTotalMsgCount: cursor.totalMessageCount,
1692
- upperBound,
1693
- deadline: deadline.toISOString(),
1694
- pastLastBlockBuildTime
1703
+ getDeadline: ()=>this.getForcedEndpointBlockDeadline()
1695
1704
  });
1696
- const resolved = await this.resolveEndpointWithinDeadline(cursor, upperBound, deadline.getTime() / 1000);
1697
- if (!resolved.ok) {
1698
- const reason = resolved.reason === 'local_prefix_changed' ? 'inbox_prefix_reorged' : 'inbox_completion_unresolved';
1699
- this.reportStreamingAbort(streamingState, reason, {
1705
+ if (decision.kind === 'abort') {
1706
+ this.reportStreamingAbort(consumption, decision.reason, {
1700
1707
  phase: 'forced_tail_block',
1701
- cause: resolved.reason,
1702
- upperBound,
1703
- endpointTotal: resolved.endpointTotal,
1704
- localSyncedCount
1708
+ ...decision.context
1705
1709
  });
1706
1710
  return {
1707
- aborted: true
1711
+ kind: 'aborted'
1708
1712
  };
1709
1713
  }
1710
- if (resolved.endpoint.totalMessageCount === cursor.totalMessageCount) {
1711
- this.log.verbose(`Checkpoint ${this.checkpointNumber} already ends at a live Inbox bucket end`, {
1712
- slot: this.targetSlot,
1713
- checkpointNumber: this.checkpointNumber,
1714
- cursorTotalMsgCount: cursor.totalMessageCount
1715
- });
1716
- return undefined;
1714
+ if (decision.kind === 'already-at-endpoint') {
1715
+ return {
1716
+ kind: 'not-needed'
1717
+ };
1717
1718
  }
1718
1719
  const buildResult = await this.buildSingleBlock(checkpointBuilder, {
1719
1720
  forceCreate: true,
1720
1721
  skipTransactions: true,
1721
1722
  blockTimestamp: opts.blockTimestamp,
1722
- buildDeadline: deadline,
1723
+ buildDeadline: decision.deadline,
1723
1724
  blockNumber: opts.blockNumber,
1724
1725
  indexWithinCheckpoint: opts.indexWithinCheckpoint,
1725
1726
  txHashesAlreadyIncluded: opts.txHashesAlreadyIncluded,
1726
- l1ToL2Messages: resolved.range.messages
1727
+ l1ToL2Messages: decision.range.messages
1727
1728
  });
1728
- if (!('block' in buildResult)) {
1729
- this.reportStreamingAbort(streamingState, 'inbox_completion_unresolved', {
1729
+ if (buildResult.kind !== 'built') {
1730
+ this.reportStreamingAbort(consumption, 'inbox_completion_unresolved', {
1730
1731
  phase: 'forced_tail_block',
1731
- cause: 'failure' in buildResult ? buildResult.failure : buildResult.error.message,
1732
- endpointTotalMsgCount: resolved.endpoint.totalMessageCount
1732
+ cause: buildResult.kind === 'skipped' ? buildResult.reason : buildResult.error.message,
1733
+ endpointTotalMsgCount: decision.range.end.totalMessageCount
1733
1734
  });
1734
1735
  return {
1735
- aborted: true
1736
+ kind: 'aborted'
1736
1737
  };
1737
1738
  }
1738
- const advancedState = {
1739
- ...streamingState,
1740
- cursor: resolved.range.end
1741
- };
1742
- const blockPrefixRef = InboxMessagePrefixRef.fromPosition(advancedState.cursor);
1743
- const proposal = await this.createBlockProposal(buildResult.block, buildResult.usedTxs, opts.blockProposalOptions, blockPrefixRef);
1744
- await this.syncProposedBlockToArchiver(buildResult.block, blockPrefixRef);
1739
+ const { proposal } = await this.commitBuiltBlock(buildResult.block, buildResult.usedTxs, decision.range, consumption, opts.blockProposalOptions);
1745
1740
  this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
1746
1741
  isFirstBlock: false,
1747
1742
  isLastBlock: true
1748
1743
  });
1749
1744
  return {
1745
+ kind: 'built',
1750
1746
  block: buildResult.block,
1751
- proposal,
1752
- streamingState: advancedState
1747
+ proposal
1753
1748
  };
1754
1749
  }
1755
1750
  /**
@@ -1771,6 +1766,28 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1771
1766
  pastLastBlockBuildTime: true
1772
1767
  };
1773
1768
  }
1769
+ /**
1770
+ * Commits the Inbox range a block was built over, then signs and stores the block. The loop and the forced tail
1771
+ * block share it; what to do with the signed proposal (gossip it or hold it for the checkpoint) stays theirs.
1772
+ */ async commitBuiltBlock(block, usedTxs, range, consumption, blockProposalOptions) {
1773
+ // Streaming Inbox: the block built successfully, so advance the cursor to the prefix it consumed through and
1774
+ // sign that prefix as this block's reference. A block that consumed nothing re-signs the cursor's prefix.
1775
+ const blockPrefixRef = consumption.commit(range);
1776
+ // Sign the block proposal. This will throw if HA signing fails.
1777
+ const proposal = await this.createBlockProposal(block, usedTxs, {
1778
+ ...blockProposalOptions,
1779
+ broadcastInvalidBlockProposal: blockProposalOptions.broadcastInvalidBlockProposal || block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint
1780
+ }, blockPrefixRef);
1781
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
1782
+ // so we avoid polluting our archive with a block that would fail.
1783
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
1784
+ // If this throws, we abort the entire checkpoint.
1785
+ await this.syncProposedBlockToArchiver(block, blockPrefixRef);
1786
+ return {
1787
+ proposal,
1788
+ blockPrefixRef
1789
+ };
1790
+ }
1774
1791
  /** Creates a block proposal for a given block via the validator client (unless in fisherman mode) */ createBlockProposal(block, usedTxs, blockProposalOptions, inboxPrefixRef) {
1775
1792
  if (this.config.fishermanMode) {
1776
1793
  this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
@@ -1779,210 +1796,26 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
1779
1796
  return this.validatorClient.createBlockProposal(block.header, this.checkpointNumber, block.indexWithinCheckpoint, block.archive.root, usedTxs, this.proposer, inboxPrefixRef, blockProposalOptions);
1780
1797
  }
1781
1798
  /**
1782
- * Resolves where a streaming-Inbox checkpoint's consumption starts: the parent checkpoint's consumed message
1783
- * prefix. The parent's cumulative consumed total is the L1-to-L2 message tree leaf count of the fork this
1784
- * checkpoint builds on (compact indexing makes leaf count equal cumulative message count), and the local message
1785
- * log serves the prefix hash at that count. Genesis is the `total = 0` case with a zero hash.
1786
- */ async resolveStreamingCheckpointStart(fork) {
1787
- const parentInfo = await fork.getTreeInfo(MerkleTreeId.L1_TO_L2_MESSAGE_TREE);
1788
- const parentTotalMsgCount = parentInfo.size;
1789
- const cursor = await this.l1ToL2MessageSource.getMessagePosition(parentTotalMsgCount);
1790
- if (cursor === undefined) {
1791
- throw new Error(`Streaming inbox: cannot resolve the Inbox message prefix at cumulative total ${parentTotalMsgCount} ` + `(checkpoint ${this.checkpointNumber}); local Inbox view has not synced it`);
1792
- }
1793
- return {
1794
- checkpointStartTotalMsgCount: parentTotalMsgCount,
1795
- cursor
1796
- };
1797
- }
1798
- /**
1799
- * Selects the message range this block consumes. Does not modify `state`; the caller records a state advanced to
1800
- * `range.end` only after the block builds successfully.
1801
- *
1802
- * Selection is greedy on the local log: every message the archiver has observed, up to the per-block and
1803
- * checkpoint caps. A block consults L1 only when it is the checkpoint's final block, whose position must be a live
1804
- * L1 bucket end, or when its prospective end would pass the threshold one bucket below the cap and could leave the
1805
- * last legal endpoint behind. The lookup is bounded by the checkpoint cap on a non-final block, so a mandatory
1806
- * bucket beyond this block's own reach is not stranded by a nearer endpoint, and additionally by one block's
1807
- * capacity on the final block. A non-final block then ends at the further of what the lookup allows and the safe
1808
- * local step, so consulting L1 never consumes less than staying below the threshold would have, and it may
1809
- * legitimately end inside a bucket. The final block instead ends exactly on the resolved boundary, so whenever the
1810
- * last live boundary within reach sits behind the safe local step it consumes fewer messages than the local log
1811
- * alone would allow. Nothing is retained: the next attempt decides again.
1812
- *
1813
- * An endpoint that cannot be resolved on a non-final block (local lag, no live endpoint yet) leaves the block with
1814
- * that safe local step and is retried on the next block; on the final block it abandons the checkpoint. A local
1815
- * prefix that no longer matches the cursor means the blocks already signed were built on messages the local log
1816
- * has since replaced, which also abandons the checkpoint.
1817
- */ async selectStreamingBundle(state, opts) {
1818
- const caps = PROTOCOL_INBOX_CONSUMPTION_CAPS;
1819
- const { cursor, checkpointStartTotalMsgCount: checkpointStartCount } = state;
1820
- const cursorCount = cursor.totalMessageCount;
1821
- const localSyncedCount = (await this.l1ToL2MessageSource.getSyncedMessagePosition()).totalMessageCount;
1822
- const greedyEnd = selectOrdinaryMessageEnd({
1823
- cursorCount,
1824
- localSyncedCount,
1825
- checkpointStartCount,
1826
- caps
1827
- });
1828
- if (!mustQueryEndpoint({
1829
- prospectiveEnd: greedyEnd,
1830
- checkpointStartCount,
1831
- isFinalBlock: opts.isFinalBlock,
1832
- caps
1833
- })) {
1834
- return this.readStreamingRange(state, greedyEnd);
1835
- }
1836
- const upperBound = getEndpointUpperBound({
1837
- cursorCount,
1838
- localSyncedCount,
1839
- checkpointStartCount,
1840
- isFinalBlock: opts.isFinalBlock,
1841
- caps
1842
- });
1843
- const resolved = await this.resolveEndpointWithinDeadline(cursor, upperBound, opts.buildDeadline);
1844
- const safeLocalEnd = selectSafeLocalEnd({
1845
- cursorCount,
1846
- localSyncedCount,
1847
- checkpointStartCount,
1848
- caps
1849
- });
1850
- if (!resolved.ok) {
1851
- if (resolved.reason === 'local_prefix_changed') {
1852
- return {
1853
- kind: 'abort',
1854
- reason: 'inbox_prefix_reorged',
1855
- context: {
1856
- upperBound
1857
- }
1858
- };
1859
- }
1860
- if (opts.isFinalBlock) {
1861
- return {
1862
- kind: 'abort',
1863
- reason: 'inbox_completion_unresolved',
1864
- context: {
1865
- cause: resolved.reason,
1866
- upperBound,
1867
- endpointTotal: resolved.endpointTotal,
1868
- localSyncedCount
1869
- }
1870
- };
1871
- }
1872
- this.log.warn(`Streaming Inbox endpoint not resolvable yet, taking the safe local step`, {
1873
- slot: this.targetSlot,
1874
- checkpointNumber: this.checkpointNumber,
1875
- cause: resolved.reason,
1876
- cursorTotalMsgCount: cursorCount,
1877
- localSyncedCount,
1878
- upperBound,
1879
- endpointTotal: resolved.endpointTotal,
1880
- safeLocalEnd
1881
- });
1882
- return this.readStreamingRange(state, safeLocalEnd);
1883
- }
1884
- const endpointTotal = resolved.endpoint.totalMessageCount;
1885
- const endpointEnd = minBigint(cursorCount + BigInt(caps.perBlockCap), endpointTotal);
1886
- // The final block has to land on the endpoint, so it takes it even when the safe local step reaches further; any
1887
- // other block takes the further of the two, so consulting L1 never consumes less than staying below the
1888
- // threshold would have.
1889
- const end = opts.isFinalBlock ? endpointEnd : maxBigint(safeLocalEnd, endpointEnd);
1890
- this.log.verbose(`Streaming Inbox resolved endpoint ${endpointTotal}, consuming through ${end}`, {
1891
- slot: this.targetSlot,
1892
- checkpointNumber: this.checkpointNumber,
1893
- cursorTotalMsgCount: cursorCount,
1894
- localSyncedCount,
1895
- upperBound,
1896
- endpointTotalMsgCount: endpointTotal,
1897
- bucketSeq: resolved.bucketSeq,
1898
- end
1899
- });
1900
- // An end short of or past the endpoint needs its own read, so the signed hash is the one at `end` and never the
1901
- // endpoint's; landing exactly on the endpoint reuses the snapshot the resolver already read and checked against
1902
- // the cursor's hash.
1903
- return end === endpointTotal ? {
1904
- kind: 'consume',
1905
- range: resolved.range
1906
- } : this.readStreamingRange(state, end);
1907
- }
1908
- /**
1909
- * Reads the messages from the cursor to `end` together with the positions at both ends from one snapshot of the
1910
- * local log, and checks that the log still starts where the cursor says: the blocks signed so far were built on
1911
- * that prefix, so a changed prefix (a content-changing L1 reorg) means the checkpoint cannot continue. A range the
1912
- * log can no longer serve whole is the same condition.
1913
- */ async readStreamingRange(state, end) {
1914
- const { cursor } = state;
1915
- let range;
1916
- try {
1917
- range = await this.l1ToL2MessageSource.getL1ToL2MessageRange(cursor.totalMessageCount, end);
1918
- } catch (err) {
1919
- return {
1920
- kind: 'abort',
1921
- reason: 'inbox_range_unavailable',
1922
- context: {
1923
- end,
1924
- error: err instanceof Error ? err.message : String(err)
1925
- }
1926
- };
1927
- }
1928
- if (!range.start.rollingHash.equals(cursor.rollingHash)) {
1929
- return {
1930
- kind: 'abort',
1931
- reason: 'inbox_prefix_reorged',
1932
- context: {
1933
- end,
1934
- localPrefixHash: range.start.rollingHash.toString()
1935
- }
1936
- };
1937
- }
1938
- return {
1939
- kind: 'consume',
1940
- range
1941
- };
1942
- }
1943
- /** Runs the single Inbox endpoint query of an endpoint block within the block's build deadline. */ resolveEndpointWithinDeadline(cursor, upperBound, buildDeadline) {
1944
- const remainingMs = buildDeadline * 1000 - this.dateProvider.now();
1945
- const timeoutMs = Math.max(1, Math.min(INBOX_ENDPOINT_READ_TIMEOUT_MS, remainingMs));
1946
- return executeTimeout(()=>resolveEndpoint({
1947
- inbox: this.inbox,
1948
- messageSource: this.l1ToL2MessageSource,
1949
- cursor,
1950
- upperBound
1951
- }), timeoutMs, `Inbox endpoint lookup at or before message total ${upperBound}`).catch((err)=>{
1952
- this.log.warn(`Inbox endpoint lookup failed, treating the endpoint as unresolved: ${err}`, {
1953
- slot: this.targetSlot,
1954
- checkpointNumber: this.checkpointNumber,
1955
- upperBound
1956
- });
1957
- return Promise.resolve({
1958
- ok: false,
1959
- reason: 'no_live_endpoint',
1960
- upperBound
1961
- });
1962
- });
1963
- }
1964
- /**
1965
1799
  * Reports that the streaming Inbox selection cannot complete this checkpoint and the slot is abandoned: the
1966
1800
  * checkpoint event, an operator warning and the failure metric. The blocks already signed are content-valid; only
1967
1801
  * the checkpoint that would end on them is unpublishable.
1968
- */ reportStreamingAbort(state, reason, extraContext = {}) {
1802
+ */ reportStreamingAbort(consumption, reason, extraContext = {}) {
1969
1803
  const context = {
1970
1804
  slot: this.targetSlot,
1971
1805
  checkpointNumber: this.checkpointNumber,
1972
- checkpointStartTotalMsgCount: state.checkpointStartTotalMsgCount,
1973
- consumedTotalMsgCount: state.cursor.totalMessageCount,
1974
- inboxRollingHash: state.cursor.rollingHash.toString(),
1806
+ ...consumption.toLogContext(),
1975
1807
  reason,
1976
1808
  ...extraContext
1977
1809
  };
1978
- this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, context);
1979
- this.log.warn(`Streaming Inbox consumption cannot complete this checkpoint; abandoning slot ${this.targetSlot}`, context);
1810
+ this.reportCheckpointFailure('build-failed', `Streaming Inbox consumption cannot complete this checkpoint; abandoning slot ${this.targetSlot}`, context, {
1811
+ level: 'warn'
1812
+ });
1980
1813
  this.metrics.recordCheckpointProposalFailed(reason);
1981
1814
  this.eventEmitter.emit('checkpoint-build-aborted', {
1982
1815
  slot: this.targetSlot,
1983
1816
  checkpointNumber: this.checkpointNumber,
1984
1817
  reason,
1985
- consumedTotalMsgCount: state.cursor.totalMessageCount
1818
+ consumedTotalMsgCount: consumption.consumedTotalMsgCount
1986
1819
  });
1987
1820
  }
1988
1821
  /**
@@ -2005,21 +1838,15 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2005
1838
  // Wait until we have enough txs to build the block
2006
1839
  const { canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
2007
1840
  if (!canStartBuilding) {
2008
- this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
2009
- reason: 'insufficient_txs',
2010
- blockNumber,
2011
- slot: this.targetSlot,
2012
- checkpointNumber: this.checkpointNumber,
2013
- indexWithinCheckpoint,
2014
- minTxs
2015
- });
2016
- this.log.verbose(`Not enough age-eligible txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (needs ${minTxs} eligible)`, {
1841
+ this.reportCheckpointFailure('block-build-failed', `Not enough age-eligible txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (needs ${minTxs} eligible)`, {
2017
1842
  reason: 'insufficient_txs',
2018
1843
  blockNumber,
2019
1844
  slot: this.targetSlot,
2020
1845
  checkpointNumber: this.checkpointNumber,
2021
1846
  indexWithinCheckpoint,
2022
1847
  minTxs
1848
+ }, {
1849
+ level: 'verbose'
2023
1850
  });
2024
1851
  this.eventEmitter.emit('block-tx-count-check-failed', {
2025
1852
  minTxs,
@@ -2027,7 +1854,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2027
1854
  });
2028
1855
  this.metrics.recordBlockProposalFailed('insufficient_txs');
2029
1856
  return {
2030
- failure: 'insufficient-txs'
1857
+ kind: 'skipped',
1858
+ reason: 'insufficient-txs'
2031
1859
  };
2032
1860
  }
2033
1861
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
@@ -2068,16 +1896,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2068
1896
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
2069
1897
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
2070
1898
  if (buildResult.status === 'insufficient-valid-txs') {
2071
- this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
2072
- reason: 'insufficient_valid_txs',
2073
- slot: this.targetSlot,
2074
- checkpointNumber: this.checkpointNumber,
2075
- blockNumber,
2076
- numTxs: buildResult.processedCount,
2077
- indexWithinCheckpoint,
2078
- minValidTxs
2079
- });
2080
- this.log.warn(`Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`, {
1899
+ this.reportCheckpointFailure('block-build-failed', `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`, {
2081
1900
  reason: 'insufficient_valid_txs',
2082
1901
  slot: this.targetSlot,
2083
1902
  checkpointNumber: this.checkpointNumber,
@@ -2085,6 +1904,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2085
1904
  numTxs: buildResult.processedCount,
2086
1905
  indexWithinCheckpoint,
2087
1906
  minValidTxs
1907
+ }, {
1908
+ level: 'warn'
2088
1909
  });
2089
1910
  this.eventEmitter.emit('block-build-failed', {
2090
1911
  reason: `Insufficient valid txs`,
@@ -2092,7 +1913,8 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2092
1913
  });
2093
1914
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
2094
1915
  return {
2095
- failure: 'insufficient-valid-txs'
1916
+ kind: 'skipped',
1917
+ reason: 'insufficient-valid-txs'
2096
1918
  };
2097
1919
  }
2098
1920
  // Block creation succeeded, emit stats and metrics
@@ -2124,6 +1946,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2124
1946
  });
2125
1947
  this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
2126
1948
  return {
1949
+ kind: 'built',
2127
1950
  block,
2128
1951
  usedTxs
2129
1952
  };
@@ -2132,21 +1955,19 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2132
1955
  reason: err.message,
2133
1956
  slot: this.targetSlot
2134
1957
  });
2135
- this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
2136
- reason: err instanceof Error ? err.message : String(err),
2137
- slot: this.targetSlot,
2138
- checkpointNumber: this.checkpointNumber,
2139
- blockNumber
2140
- });
2141
- this.log.error(`Error building block`, err, {
1958
+ this.reportCheckpointFailure('block-build-failed', `Error building block`, {
2142
1959
  reason: err instanceof Error ? err.message : String(err),
2143
1960
  slot: this.targetSlot,
2144
1961
  checkpointNumber: this.checkpointNumber,
2145
1962
  blockNumber
1963
+ }, {
1964
+ level: 'error',
1965
+ err
2146
1966
  });
2147
1967
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
2148
1968
  this.metrics.recordFailedBlock();
2149
1969
  return {
1970
+ kind: 'failed',
2150
1971
  error: err
2151
1972
  };
2152
1973
  }
@@ -2236,22 +2057,18 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2236
2057
  * Waits for enough attestations to be collected via p2p.
2237
2058
  * This is run after all blocks for the checkpoint have been built.
2238
2059
  */ async waitForAttestations(proposal) {
2239
- if (this.config.fishermanMode) {
2240
- this.log.debug('Skipping attestation collection in fisherman mode');
2241
- return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
2242
- }
2243
2060
  const slotNumber = proposal.slotNumber;
2244
- const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
2245
- if (!committee) {
2061
+ const lookup = requireStableCommittee(await this.epochCache.getCommittee(slotNumber));
2062
+ if (lookup.state === 'none') {
2246
2063
  throw new Error('No committee when collecting attestations');
2247
- } else if (committee.length === 0) {
2064
+ } else if (lookup.state === 'open') {
2248
2065
  this.log.verbose(`Attesting committee is empty`);
2249
2066
  return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
2250
- } else {
2251
- this.log.debug(`Attesting committee length is ${committee.length}`, {
2252
- committee
2253
- });
2254
2067
  }
2068
+ const { committee, seed, epoch } = lookup;
2069
+ this.log.debug(`Attesting committee length is ${committee.length}`, {
2070
+ committee
2071
+ });
2255
2072
  const numberOfRequiredAttestations = computeQuorum(committee.length);
2256
2073
  if (this.config.skipCollectingAttestations) {
2257
2074
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
@@ -2282,8 +2099,18 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2282
2099
  submittedCount: trimmed.length
2283
2100
  });
2284
2101
  // Manipulate the attestations if we've been configured to do so
2285
- if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation || this.config.injectYParityAttestation || this.config.shuffleAttestationOrdering) {
2286
- return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
2102
+ if (hasAttestationManipulation(this.config)) {
2103
+ return manipulateAttestations({
2104
+ config: this.config,
2105
+ epochCache: this.epochCache,
2106
+ signatureContext: this.getSignatureContext(),
2107
+ log: this.log,
2108
+ slotNumber: proposal.slotNumber,
2109
+ epoch,
2110
+ seed,
2111
+ committee,
2112
+ attestations: sorted
2113
+ });
2287
2114
  }
2288
2115
  return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
2289
2116
  } catch (err) {
@@ -2327,70 +2154,6 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2327
2154
  }
2328
2155
  });
2329
2156
  }
2330
- /** Breaks the attestations before publishing based on attack configs */ manipulateAttestations(slotNumber, epoch, seed, committee, attestations) {
2331
- // Compute the proposer index in the committee, since we dont want to tweak it.
2332
- // Otherwise, the L1 rollup contract will reject the block outright.
2333
- const proposerIndex = Number(this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)));
2334
- if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation) {
2335
- // Find non-empty attestations that are not from the proposer
2336
- const nonProposerIndices = [];
2337
- for(let i = 0; i < attestations.length; i++){
2338
- if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
2339
- nonProposerIndices.push(i);
2340
- }
2341
- }
2342
- if (nonProposerIndices.length > 0) {
2343
- const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
2344
- if (this.config.injectHighSValueAttestation) {
2345
- this.log.warn(`Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
2346
- unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
2347
- } else if (this.config.injectUnrecoverableSignatureAttestation) {
2348
- this.log.warn(`Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
2349
- unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
2350
- } else {
2351
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
2352
- unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
2353
- }
2354
- }
2355
- return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
2356
- }
2357
- if (this.config.injectYParityAttestation) {
2358
- // Force every non-proposer signed slot's recovery byte to yParity (v ∈ {0, 1}) form in the packed L1
2359
- // tuple, after packAttestations has canonicalized it. The proposer's own slot is left canonical so
2360
- // propose() still passes verifyProposer. Models a malicious proposer landing a checkpoint L1 accepts
2361
- // but that can never be proven (ECDSA.recover rejects v ∉ {27, 28}).
2362
- this.log.warn(`Injecting yParity attestations in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
2363
- return new MaliciousYParityCommitteeAttestationsAndSigners(attestations, proposerIndex, this.getSignatureContext());
2364
- }
2365
- if (this.config.shuffleAttestationOrdering) {
2366
- this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
2367
- const shuffled = [
2368
- ...attestations
2369
- ];
2370
- // Find two non-proposer positions that both have non-empty signatures to swap.
2371
- // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
2372
- // signers array stays correctly aligned with L1's committee reconstruction.
2373
- const swappable = [];
2374
- for(let k = 0; k < shuffled.length; k++){
2375
- if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
2376
- swappable.push(k);
2377
- }
2378
- }
2379
- if (swappable.length >= 2) {
2380
- const [i, j] = [
2381
- swappable[0],
2382
- swappable[1]
2383
- ];
2384
- [shuffled[i], shuffled[j]] = [
2385
- shuffled[j],
2386
- shuffled[i]
2387
- ];
2388
- }
2389
- const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
2390
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
2391
- }
2392
- return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
2393
- }
2394
2157
  async dropFailedTxsFromP2P(failedTxs) {
2395
2158
  if (failedTxs.length === 0) {
2396
2159
  return;
@@ -2431,6 +2194,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2431
2194
  slot: block.header.globalVariables.slotNumber
2432
2195
  });
2433
2196
  await this.blockSink.addBlock(block, inboxPrefixRef);
2197
+ this.unclaimedFirstBlockHash ??= await block.hash();
2434
2198
  }
2435
2199
  /**
2436
2200
  * Adds the proposed checkpoint to the archiver so the proposer's optimistic proposed-checkpoint
@@ -2441,7 +2205,7 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2441
2205
  * mode): the archiver derives the checkpoint archive from its stored blocks, so without them the
2442
2206
  * push would fail. All blocks were already added (and awaited) during block building, so this
2443
2207
  * needs no retry — they are guaranteed present by the time we get here.
2444
- */ async syncProposedCheckpointToArchiver(checkpoint, blockCount, feeAssetPriceModifier) {
2208
+ */ async syncProposedCheckpointToArchiver(checkpoint, proposal, blockCount, feeAssetPriceModifier) {
2445
2209
  if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
2446
2210
  return;
2447
2211
  }
@@ -2458,31 +2222,63 @@ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('Checkpoint
2458
2222
  startBlock,
2459
2223
  blockCount,
2460
2224
  totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
2461
- feeAssetPriceModifier
2225
+ feeAssetPriceModifier,
2226
+ signer: proposal.getSender()
2462
2227
  });
2228
+ this.unclaimedFirstBlockHash = undefined;
2229
+ }
2230
+ /**
2231
+ * Prunes this checkpoint's blocks from the local archiver once the job has given the checkpoint up after pushing
2232
+ * them. Until then the node serves them as its chain tip: world state applies them, the tx pool marks their txs
2233
+ * mined, and RPC users build txs on them, all of which the orphan prune would only undo seconds later. Pruning
2234
+ * every block after the parent rather than just the last one, since without the checkpoint none of them can land.
2235
+ *
2236
+ * Left to the orphan prune when the job was interrupted, since the sequencer is then stopping and the archiver sync
2237
+ * loop that runs the prune may be stopping with it, and when an HA peer holds one of the slot's duties, since the
2238
+ * peer may be proposing these very blocks and the orphan prune waits for its checkpoint proposal. Never throws: a
2239
+ * failed prune only leaves the blocks to the orphan prune.
2240
+ */ async pruneAbandonedCheckpointBlocks() {
2241
+ const firstBlockHash = this.unclaimedFirstBlockHash;
2242
+ if (firstBlockHash === undefined || this.interrupted || this.yieldedToHAPeer) {
2243
+ return;
2244
+ }
2245
+ this.unclaimedFirstBlockHash = undefined;
2246
+ const context = {
2247
+ slot: this.targetSlot,
2248
+ checkpointNumber: this.checkpointNumber,
2249
+ parentBlockNumber: this.syncedToBlockNumber,
2250
+ firstBlockHash: firstBlockHash.toString()
2251
+ };
2252
+ try {
2253
+ const prunedBlocks = await this.blockSink.pruneAbandonedProposedBlocks(this.syncedToBlockNumber, firstBlockHash);
2254
+ this.log.info(`Pruned the blocks of abandoned checkpoint ${this.checkpointNumber} from the local archiver`, {
2255
+ ...context,
2256
+ prunedBlocks
2257
+ });
2258
+ } catch (err) {
2259
+ this.log.warn(`Failed to prune the blocks of abandoned checkpoint ${this.checkpointNumber}; leaving them to the orphan prune`, {
2260
+ ...context,
2261
+ error: err instanceof Error ? err.message : String(err)
2262
+ });
2263
+ }
2463
2264
  }
2464
2265
  /** Runs fee analysis and logs checkpoint outcome as fisherman */ async handleCheckpointEndAsFisherman(checkpoint) {
2465
2266
  // Perform L1 fee analysis before clearing requests
2466
2267
  // The callback is invoked asynchronously after the next block is mined
2467
2268
  const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, (analysis)=>this.metrics.recordFishermanFeeAnalysis(analysis));
2468
- if (checkpoint) {
2469
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
2470
- ...checkpoint.toCheckpointInfo(),
2471
- ...checkpoint.getStats(),
2472
- feeAnalysisId: feeAnalysis?.id
2473
- });
2474
- } else {
2475
- this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
2476
- slot: this.targetSlot,
2477
- feeAnalysisId: feeAnalysis?.id
2478
- });
2479
- this.metrics.recordCheckpointProposalFailed('block_build_failed');
2480
- }
2269
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
2270
+ ...checkpoint.toCheckpointInfo(),
2271
+ ...checkpoint.getStats(),
2272
+ feeAnalysisId: feeAnalysis?.id
2273
+ });
2481
2274
  this.publisher.clearPendingRequests();
2482
2275
  }
2483
2276
  /**
2484
2277
  * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
2485
2278
  */ handleHASigningError(err, errorContext) {
2279
+ if (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError) {
2280
+ this.yieldedToHAPeer = true;
2281
+ }
2486
2282
  if (err instanceof DutyAlreadySignedError) {
2487
2283
  this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
2488
2284
  slot: this.targetSlot,