@aztec/sequencer-client 0.0.1-commit.b655e406 → 0.0.1-commit.b8a057fa

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 (165) hide show
  1. package/README.md +281 -21
  2. package/dest/client/index.d.ts +1 -1
  3. package/dest/client/sequencer-client.d.ts +41 -18
  4. package/dest/client/sequencer-client.d.ts.map +1 -1
  5. package/dest/client/sequencer-client.js +88 -42
  6. package/dest/config.d.ts +41 -8
  7. package/dest/config.d.ts.map +1 -1
  8. package/dest/config.js +153 -53
  9. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  10. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  11. package/dest/global_variable_builder/fee_predictor.js +138 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  13. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  14. package/dest/global_variable_builder/fee_provider.js +80 -0
  15. package/dest/global_variable_builder/global_builder.d.ts +20 -29
  16. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  17. package/dest/global_variable_builder/global_builder.js +28 -72
  18. package/dest/global_variable_builder/index.d.ts +4 -2
  19. package/dest/global_variable_builder/index.d.ts.map +1 -1
  20. package/dest/global_variable_builder/index.js +2 -0
  21. package/dest/index.d.ts +2 -3
  22. package/dest/index.d.ts.map +1 -1
  23. package/dest/index.js +1 -2
  24. package/dest/publisher/config.d.ts +59 -20
  25. package/dest/publisher/config.d.ts.map +1 -1
  26. package/dest/publisher/config.js +134 -34
  27. package/dest/publisher/index.d.ts +2 -1
  28. package/dest/publisher/index.d.ts.map +1 -1
  29. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  30. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  31. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  32. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  33. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  34. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  35. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +98 -0
  36. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  37. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
  38. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  39. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  40. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
  41. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  42. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  43. package/dest/publisher/l1_tx_failed_store/index.js +3 -0
  44. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  45. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  46. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  47. package/dest/publisher/sequencer-publisher-factory.d.ts +15 -8
  48. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  49. package/dest/publisher/sequencer-publisher-factory.js +28 -4
  50. package/dest/publisher/sequencer-publisher-metrics.d.ts +3 -3
  51. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  52. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  53. package/dest/publisher/sequencer-publisher.d.ts +164 -96
  54. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  55. package/dest/publisher/sequencer-publisher.js +1305 -416
  56. package/dest/publisher/write_json.d.ts +11 -0
  57. package/dest/publisher/write_json.d.ts.map +1 -0
  58. package/dest/publisher/write_json.js +57 -0
  59. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  60. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  61. package/dest/sequencer/automine/automine_factory.js +85 -0
  62. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  63. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  64. package/dest/sequencer/automine/automine_sequencer.js +690 -0
  65. package/dest/sequencer/automine/index.d.ts +3 -0
  66. package/dest/sequencer/automine/index.d.ts.map +1 -0
  67. package/dest/sequencer/automine/index.js +2 -0
  68. package/dest/sequencer/checkpoint_proposal_job.d.ts +158 -0
  69. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  70. package/dest/sequencer/checkpoint_proposal_job.js +1801 -0
  71. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  72. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  73. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  74. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  75. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  76. package/dest/sequencer/checkpoint_voter.js +106 -0
  77. package/dest/sequencer/config.d.ts +3 -2
  78. package/dest/sequencer/config.d.ts.map +1 -1
  79. package/dest/sequencer/errors.d.ts +1 -1
  80. package/dest/sequencer/errors.d.ts.map +1 -1
  81. package/dest/sequencer/events.d.ts +103 -0
  82. package/dest/sequencer/events.d.ts.map +1 -0
  83. package/dest/sequencer/events.js +1 -0
  84. package/dest/sequencer/index.d.ts +4 -2
  85. package/dest/sequencer/index.d.ts.map +1 -1
  86. package/dest/sequencer/index.js +3 -1
  87. package/dest/sequencer/metrics.d.ts +48 -4
  88. package/dest/sequencer/metrics.d.ts.map +1 -1
  89. package/dest/sequencer/metrics.js +257 -50
  90. package/dest/sequencer/requests_tracker.d.ts +22 -0
  91. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  92. package/dest/sequencer/requests_tracker.js +33 -0
  93. package/dest/sequencer/sequencer.d.ts +253 -148
  94. package/dest/sequencer/sequencer.d.ts.map +1 -1
  95. package/dest/sequencer/sequencer.js +1208 -598
  96. package/dest/sequencer/types.d.ts +3 -0
  97. package/dest/sequencer/types.d.ts.map +1 -0
  98. package/dest/sequencer/types.js +1 -0
  99. package/dest/sequencer/utils.d.ts +14 -8
  100. package/dest/sequencer/utils.d.ts.map +1 -1
  101. package/dest/sequencer/utils.js +7 -4
  102. package/dest/test/index.d.ts +8 -9
  103. package/dest/test/index.d.ts.map +1 -1
  104. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  105. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  106. package/dest/test/mock_checkpoint_builder.js +231 -0
  107. package/dest/test/utils.d.ts +67 -0
  108. package/dest/test/utils.d.ts.map +1 -0
  109. package/dest/test/utils.js +122 -0
  110. package/package.json +34 -30
  111. package/src/client/sequencer-client.ts +118 -66
  112. package/src/config.ts +181 -62
  113. package/src/global_variable_builder/README.md +44 -0
  114. package/src/global_variable_builder/fee_predictor.ts +182 -0
  115. package/src/global_variable_builder/fee_provider.ts +97 -0
  116. package/src/global_variable_builder/global_builder.ts +45 -106
  117. package/src/global_variable_builder/index.ts +3 -1
  118. package/src/index.ts +1 -7
  119. package/src/publisher/config.ts +190 -46
  120. package/src/publisher/index.ts +3 -0
  121. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  122. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  123. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +164 -0
  124. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
  125. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  126. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  127. package/src/publisher/sequencer-publisher-factory.ts +45 -14
  128. package/src/publisher/sequencer-publisher-metrics.ts +19 -71
  129. package/src/publisher/sequencer-publisher.ts +1109 -538
  130. package/src/publisher/write_json.ts +78 -0
  131. package/src/sequencer/README.md +243 -0
  132. package/src/sequencer/automine/README.md +60 -0
  133. package/src/sequencer/automine/automine_factory.ts +152 -0
  134. package/src/sequencer/automine/automine_sequencer.ts +796 -0
  135. package/src/sequencer/automine/index.ts +6 -0
  136. package/src/sequencer/checkpoint_proposal_job.ts +1652 -0
  137. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  138. package/src/sequencer/checkpoint_voter.ts +119 -0
  139. package/src/sequencer/config.ts +2 -1
  140. package/src/sequencer/events.ts +88 -0
  141. package/src/sequencer/index.ts +3 -1
  142. package/src/sequencer/metrics.ts +330 -62
  143. package/src/sequencer/requests_tracker.ts +43 -0
  144. package/src/sequencer/sequencer.ts +1033 -777
  145. package/src/sequencer/types.ts +6 -0
  146. package/src/sequencer/utils.ts +18 -9
  147. package/src/test/index.ts +7 -8
  148. package/src/test/mock_checkpoint_builder.ts +323 -0
  149. package/src/test/utils.ts +218 -0
  150. package/dest/sequencer/block_builder.d.ts +0 -27
  151. package/dest/sequencer/block_builder.d.ts.map +0 -1
  152. package/dest/sequencer/block_builder.js +0 -130
  153. package/dest/sequencer/timetable.d.ts +0 -50
  154. package/dest/sequencer/timetable.d.ts.map +0 -1
  155. package/dest/sequencer/timetable.js +0 -137
  156. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  157. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  158. package/dest/tx_validator/nullifier_cache.js +0 -24
  159. package/dest/tx_validator/tx_validator_factory.d.ts +0 -17
  160. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  161. package/dest/tx_validator/tx_validator_factory.js +0 -53
  162. package/src/sequencer/block_builder.ts +0 -218
  163. package/src/sequencer/timetable.ts +0 -188
  164. package/src/tx_validator/nullifier_cache.ts +0 -30
  165. package/src/tx_validator/tx_validator_factory.ts +0 -132
@@ -1,497 +1,804 @@
1
- import { L2Block } from '@aztec/aztec.js/block';
2
- import { BLOBS_PER_BLOCK, FIELDS_PER_BLOB, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
3
- import type { EpochCache } from '@aztec/epoch-cache';
4
- import { FormattedViemError, NoCommitteeError, type RollupContract } from '@aztec/ethereum';
5
- import { omit, pick } from '@aztec/foundation/collection';
6
- import { randomInt } from '@aztec/foundation/crypto';
1
+ import { getKzg } from '@aztec/blob-lib';
2
+ import { type EpochCache, PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
3
+ import { NoCommitteeError, type RollupContract } from '@aztec/ethereum/contracts';
4
+ import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
5
+ import { merge, omit, pick } from '@aztec/foundation/collection';
6
+ import { Fr } from '@aztec/foundation/curves/bn254';
7
7
  import { EthAddress } from '@aztec/foundation/eth-address';
8
- import { Signature } from '@aztec/foundation/eth-signature';
9
- import { Fr } from '@aztec/foundation/fields';
10
- import { createLogger } from '@aztec/foundation/log';
8
+ import { type Logger, createLogger } from '@aztec/foundation/log';
11
9
  import { RunningPromise } from '@aztec/foundation/running-promise';
12
- import { type DateProvider, Timer } from '@aztec/foundation/timer';
13
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
10
+ import type { DateProvider } from '@aztec/foundation/timer';
11
+ import type { TypedEventEmitter } from '@aztec/foundation/types';
14
12
  import type { P2P } from '@aztec/p2p';
15
13
  import type { SlasherClientInterface } from '@aztec/slasher';
16
- import {
17
- CommitteeAttestation,
18
- CommitteeAttestationsAndSigners,
19
- type L2BlockSource,
20
- type ValidateBlockResult,
14
+ import type {
15
+ BlockData,
16
+ L2BlockSink,
17
+ L2BlockSource,
18
+ ProposedCheckpointSink,
19
+ ValidateCheckpointResult,
21
20
  } from '@aztec/stdlib/block';
22
- import { type L1RollupConstants, getSlotAtTimestamp, getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
23
- import { Gas } from '@aztec/stdlib/gas';
24
21
  import {
25
- type IFullNodeBlockBuilder,
26
- type PublicProcessorLimits,
22
+ type Checkpoint,
23
+ type ProposedCheckpointData,
24
+ buildCheckpointSimulationOverridesPlan,
25
+ } from '@aztec/stdlib/checkpoint';
26
+ import type { ChainConfig } from '@aztec/stdlib/config';
27
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
28
+ import {
29
+ MIN_PER_BLOCK_ALLOCATION_MULTIPLIER,
30
+ MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER,
31
+ computeNetworkTxGasLimits,
32
+ } from '@aztec/stdlib/gas';
33
+ import {
34
+ type ResolvedSequencerConfig,
35
+ type SequencerConfig,
27
36
  SequencerConfigSchema,
28
37
  type WorldStateSynchronizer,
29
38
  } from '@aztec/stdlib/interfaces/server';
30
39
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
31
- import type { BlockProposalOptions } from '@aztec/stdlib/p2p';
32
- import { orderAttestations } from '@aztec/stdlib/p2p';
33
- import { CheckpointHeader } from '@aztec/stdlib/rollup';
40
+ import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
34
41
  import { pickFromSchema } from '@aztec/stdlib/schemas';
35
- import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
36
- import { MerkleTreeId } from '@aztec/stdlib/trees';
37
- import { ContentCommitment, type FailedTx, GlobalVariables, Tx } from '@aztec/stdlib/tx';
38
- import { AttestationTimeoutError } from '@aztec/stdlib/validators';
42
+ import { ProposerTimetable, buildProposerTimetable } from '@aztec/stdlib/timetable';
39
43
  import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
40
- import type { ValidatorClient } from '@aztec/validator-client';
44
+ import { FullNodeCheckpointsBuilder, NodeKeystoreAdapter, type ValidatorClient } from '@aztec/validator-client';
41
45
 
42
46
  import EventEmitter from 'node:events';
43
- import type { TypedDataDefinition } from 'viem';
44
47
 
48
+ import { DefaultSequencerConfig } from '../config.js';
45
49
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
46
50
  import type { SequencerPublisherFactory } from '../publisher/sequencer-publisher-factory.js';
47
- import type { Action, InvalidateBlockRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
48
- import type { SequencerConfig } from './config.js';
49
- import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
51
+ import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
52
+ import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
53
+ import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
54
+ import { CheckpointVoter } from './checkpoint_voter.js';
55
+ import { SequencerInterruptedError } from './errors.js';
56
+ import type { SequencerEvents } from './events.js';
50
57
  import { SequencerMetrics } from './metrics.js';
51
- import { SequencerTimetable } from './timetable.js';
52
- import { SequencerState, type SequencerStateWithSlot } from './utils.js';
58
+ import { RequestsTracker } from './requests_tracker.js';
59
+ import type { SequencerRollupConstants } from './types.js';
60
+ import { SequencerState } from './utils.js';
53
61
 
54
62
  export { SequencerState };
55
63
 
56
- type SequencerRollupConstants = Pick<L1RollupConstants, 'ethereumSlotDuration' | 'l1GenesisTime' | 'slotDuration'>;
57
-
58
- export type SequencerEvents = {
59
- ['state-changed']: (args: {
60
- oldState: SequencerState;
61
- newState: SequencerState;
62
- secondsIntoSlot?: number;
63
- slotNumber?: bigint;
64
- }) => void;
65
- ['proposer-rollup-check-failed']: (args: { reason: string }) => void;
66
- ['tx-count-check-failed']: (args: { minTxs: number; availableTxs: number }) => void;
67
- ['block-build-failed']: (args: { reason: string }) => void;
68
- ['block-publish-failed']: (args: {
69
- successfulActions?: Action[];
70
- failedActions?: Action[];
71
- sentActions?: Action[];
72
- expiredActions?: Action[];
73
- }) => void;
74
- ['block-published']: (args: { blockNumber: number; slot: number }) => void;
64
+ /** Slot snapshot used to prepare a checkpoint proposal. */
65
+ type SequencerSlotContext = {
66
+ slot: SlotNumber;
67
+ targetSlot: SlotNumber;
68
+ epoch: EpochNumber;
69
+ targetEpoch: EpochNumber;
70
+ ts: bigint;
71
+ nowSeconds: bigint;
75
72
  };
76
73
 
77
74
  /**
78
75
  * Sequencer client
79
- * - Wins a period of time to become the sequencer (depending on finalized protocol).
80
- * - Chooses a set of txs from the tx pool to be in the rollup.
81
- * - Simulate the rollup of txs.
82
- * - Adds proof requests to the request pool (not for this milestone).
83
- * - Receives results to those proofs from the network (repeats as necessary) (not for this milestone).
84
- * - Publishes L1 tx(s) to the rollup contract via RollupPublisher.
76
+ * - Checks whether it is elected as proposer for the next slot
77
+ * - Builds multiple blocks and broadcasts them
78
+ * - Collects attestations for the checkpoint
79
+ * - Publishes the checkpoint to L1
80
+ * - Votes for proposals and slashes on L1
85
81
  */
86
82
  export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<SequencerEvents>) {
87
- private runningPromise?: RunningPromise;
88
- private pollingIntervalMs: number = 1000;
89
- private maxTxsPerBlock = 32;
90
- private minTxsPerBlock = 1;
91
- private maxL1TxInclusionTimeIntoSlot = 0;
83
+ protected runningPromise?: RunningPromise;
92
84
  private state = SequencerState.STOPPED;
93
- private maxBlockSizeInBytes: number = 1024 * 1024;
94
- private maxBlockGas: Gas = new Gas(100e9, 100e9);
85
+ private stateSlotNumber: SlotNumber | undefined;
86
+ /** Wall-clock time (ms, via the date provider) at which the current state was entered. */
87
+ private stateEnteredAtMs: number;
95
88
  private metrics: SequencerMetrics;
89
+ private checkpointProposalJobMetrics: CheckpointProposalJobMetrics;
90
+ private readonly stateLog: Logger;
91
+
92
+ /** The last slot for which we attempted to perform our fallback duties (votes and/or prune) with degraded block production */
93
+ private lastSlotForFallbackAction: SlotNumber | undefined;
96
94
 
97
- private lastBlockPublished: L2Block | undefined;
95
+ /** The (checkpoint, slot) of the last invalidation request we successfully simulated, to prevent
96
+ * re-simulating and re-submitting the same invalidation across the many ticks within a single slot. */
97
+ private lastInvalidationAttempt: { slot: SlotNumber; checkpointNumber: CheckpointNumber } | undefined;
98
98
 
99
- private governanceProposerPayload: EthAddress | undefined;
99
+ /** The last slot for which we logged "no committee" warning, to avoid spam */
100
+ private lastSlotForNoCommitteeWarning: SlotNumber | undefined;
100
101
 
101
- /** The last slot for which we attempted to vote when sync failed, to prevent duplicate attempts. */
102
- private lastSlotForVoteWhenSyncFailed: bigint | undefined;
102
+ /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */
103
+ protected lastSlotForCheckpointProposalJob: SlotNumber | undefined;
103
104
 
104
- /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */
105
- protected timetable!: SequencerTimetable;
106
- protected enforceTimeTable: boolean = false;
105
+ /** Last successful checkpoint proposed */
106
+ private lastCheckpointProposed: Checkpoint | undefined;
107
107
 
108
- // This shouldn't be here as this gets re-created each time we build/propose a block.
109
- // But we have a number of tests that abuse/rely on this class having a permanent publisher.
110
- // As long as those tests only configure a single publisher they will continue to work.
111
- // This will get re-assigned every time the sequencer goes to build a new block to a publisher that is valid
112
- // for the block proposer.
113
- protected publisher: SequencerPublisher | undefined;
108
+ /** The last epoch for which we logged strategy comparison in fisherman mode. */
109
+ private lastEpochForStrategyComparison: EpochNumber | undefined;
110
+
111
+ /** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */
112
+ protected lastCheckpointProposalJob: CheckpointProposalJob | undefined;
113
+
114
+ /**
115
+ * In-flight fire-and-forget requests that {@link stop} interrupts and drains, and {@link pause} awaits
116
+ * untouched: the checkpoint proposal jobs' backgrounded L1 submissions (each job is handed this shared
117
+ * tracker) plus the sequencer's own fallback submissions (votes/prune when we cannot build, or
118
+ * escape-hatch votes). Each fallback send is gated by its wrapper publisher's interruptible target-slot
119
+ * sleep; the tracked interrupt wakes that sleep so the send short-circuits without publishing. A wrapper
120
+ * is created for a single send and is never restarted, so once interrupted its sleeper can never publish
121
+ * a stale-slot tx, even after the pooled publishers are restarted by a later {@link start}.
122
+ */
123
+ protected readonly pendingRequests = new RequestsTracker();
124
+
125
+ /** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */
126
+ protected timetable!: ProposerTimetable;
127
+
128
+ /** Config for the sequencer */
129
+ protected config: ResolvedSequencerConfig = DefaultSequencerConfig;
130
+ private readonly signatureContext: CoordinationSignatureContext;
114
131
 
115
132
  constructor(
116
133
  protected publisherFactory: SequencerPublisherFactory,
117
- protected validatorClient: ValidatorClient | undefined, // During migration the validator client can be inactive
134
+ protected validatorClient: ValidatorClient,
118
135
  protected globalsBuilder: GlobalVariableBuilder,
119
136
  protected p2pClient: P2P,
120
137
  protected worldState: WorldStateSynchronizer,
121
138
  protected slasherClient: SlasherClientInterface | undefined,
122
- protected l2BlockSource: L2BlockSource,
139
+ protected l2BlockSource: L2BlockSource & L2BlockSink & ProposedCheckpointSink,
123
140
  protected l1ToL2MessageSource: L1ToL2MessageSource,
124
- protected blockBuilder: IFullNodeBlockBuilder,
141
+ protected checkpointsBuilder: FullNodeCheckpointsBuilder,
125
142
  protected l1Constants: SequencerRollupConstants,
126
143
  protected dateProvider: DateProvider,
127
144
  protected epochCache: EpochCache,
128
145
  protected rollupContract: RollupContract,
129
- protected config: SequencerConfig,
146
+ config: SequencerConfig & Pick<ChainConfig, 'l1ChainId' | 'rollupAddress'>,
130
147
  protected telemetry: TelemetryClient = getTelemetryClient(),
131
148
  protected log = createLogger('sequencer'),
132
149
  ) {
133
150
  super();
151
+ this.stateLog = log.createChild('state');
152
+ this.stateEnteredAtMs = this.dateProvider.now();
134
153
 
154
+ // Add [FISHERMAN] prefix to logger if in fisherman mode
155
+ if (config.fishermanMode) {
156
+ this.log = log.createChild('[FISHERMAN]');
157
+ }
158
+
159
+ this.signatureContext = {
160
+ chainId: config.l1ChainId,
161
+ rollupAddress: config.rollupAddress,
162
+ };
135
163
  this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
136
- // Initialize config
137
- this.updateConfig(this.config);
164
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
165
+ this.updateConfig(config);
138
166
  }
139
167
 
140
- get tracer(): Tracer {
141
- return this.metrics.tracer;
168
+ /**
169
+ * Updates sequencer config by the defined values and rebuilds the timetable.
170
+ *
171
+ * The merged config is validated against a candidate before being committed: {@link buildTimetable} may
172
+ * reject the candidate (invalid timing geometry, or per-block allocation multipliers below the network
173
+ * minimums). On rejection we leave `this.config` and `this.timetable` untouched and rethrow, so a bad update
174
+ * never leaves the sequencer running with a rejected config and a stale timetable.
175
+ */
176
+ public updateConfig(config: Partial<SequencerConfig>) {
177
+ const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
178
+ const candidate = merge(this.config, filteredConfig);
179
+ let timetable: ProposerTimetable;
180
+ try {
181
+ timetable = this.buildTimetable(candidate);
182
+ } catch (err) {
183
+ this.log.warn(`Rejecting sequencer config update: ${(err as Error).message}`, {
184
+ rejectedConfig: omit(filteredConfig, 'txPublicSetupAllowListExtend'),
185
+ });
186
+ throw err;
187
+ }
188
+ this.config = candidate;
189
+ this.timetable = timetable;
190
+ this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
142
191
  }
143
192
 
144
- public getValidatorAddresses() {
145
- return this.validatorClient?.getValidatorAddresses();
146
- }
193
+ /**
194
+ * Builds the proposer timetable from the given config and L1 constants via the shared
195
+ * {@link buildProposerTimetable} helper, so the sequencer derives the same blocks-per-checkpoint as the p2p
196
+ * layer and `getNodeInfo`. The fast local/e2e profile and budget clamping happen inside
197
+ * {@link ProposerTimetable}.
198
+ *
199
+ * Throws if the timing geometry is invalid or the per-block allocation multipliers are below the network
200
+ * minimums; callers must treat a throw as a rejected config and not commit it.
201
+ */
202
+ private buildTimetable(config: ResolvedSequencerConfig): ProposerTimetable {
203
+ const timetable = buildProposerTimetable(config, this.l1Constants);
204
+
205
+ const maxNumberOfBlocks = timetable.getMaxBlocksPerCheckpoint();
206
+ this.log.info(`Sequencer timetable initialized with ${maxNumberOfBlocks} blocks per slot`, {
207
+ aztecSlotDuration: timetable.aztecSlotDuration,
208
+ ethereumSlotDuration: timetable.ethereumSlotDuration,
209
+ blockDuration: timetable.blockDuration,
210
+ minBlockDuration: timetable.minBlockDuration,
211
+ p2pPropagationTime: timetable.p2pPropagationTime,
212
+ checkpointProposalPrepareTime: timetable.checkpointProposalPrepareTime,
213
+ maxNumberOfBlocks,
214
+ });
147
215
 
148
- public getConfig() {
149
- return this.config;
216
+ this.assertConfigMeetsNetworkTxLimits(config, maxNumberOfBlocks);
217
+
218
+ return timetable;
150
219
  }
151
220
 
152
221
  /**
153
- * Updates sequencer config by the defined values in the config on input.
154
- * @param config - New parameters.
222
+ * Checks this node's configured per-block allocation against the network admission limit. A node
223
+ * advertises and admits txs up to the limit derived from the network-minimum multipliers (see
224
+ * {@link computeNetworkTxGasLimits}).
225
+ *
226
+ * Fails startup (and runtime config updates) only when the configured per-block allocation *multipliers*
227
+ * (`perBlockAllocationMultiplier` / `perBlockDAAllocationMultiplier`) are below the network minimums: such
228
+ * a node would accept txs over RPC/gossip that its builder can never pack into a block regardless of block
229
+ * size. Operators may configure a higher (more generous) multiplier, but not a lower one.
230
+ *
231
+ * When the multipliers meet the floor but an absolute per-block gas cap (`maxDABlockGas` / `maxL2BlockGas`)
232
+ * shrinks the builder's effective grant below the network limit, this is legitimate operator
233
+ * restrictiveness — the node simply builds smaller blocks and such txs stay in the pool for other
234
+ * proposers — so we only log a warning rather than failing startup. Restrictive tx-count caps
235
+ * (`maxTxsPerBlock` / `maxTxsPerCheckpoint`) can likewise make the builder skip admitted txs; they are
236
+ * intentionally not modeled here for the same reason.
155
237
  */
156
- public updateConfig(config: SequencerConfig) {
157
- this.log.info(
158
- `Sequencer config set`,
159
- omit(pickFromSchema(config, SequencerConfigSchema), 'txPublicSetupAllowList'),
160
- );
161
-
162
- if (config.transactionPollingIntervalMS !== undefined) {
163
- this.pollingIntervalMs = config.transactionPollingIntervalMS;
164
- }
165
- if (config.maxTxsPerBlock !== undefined) {
166
- this.maxTxsPerBlock = config.maxTxsPerBlock;
167
- }
168
- if (config.minTxsPerBlock !== undefined) {
169
- this.minTxsPerBlock = config.minTxsPerBlock;
170
- }
171
- if (config.maxDABlockGas !== undefined) {
172
- this.maxBlockGas = new Gas(config.maxDABlockGas, this.maxBlockGas.l2Gas);
173
- }
174
- if (config.maxL2BlockGas !== undefined) {
175
- this.maxBlockGas = new Gas(this.maxBlockGas.daGas, config.maxL2BlockGas);
176
- }
177
- if (config.maxBlockSizeInBytes !== undefined) {
178
- this.maxBlockSizeInBytes = config.maxBlockSizeInBytes;
238
+ private assertConfigMeetsNetworkTxLimits(config: ResolvedSequencerConfig, maxBlocksPerCheckpoint: number) {
239
+ // Mirror CheckpointBuilder.capLimitsByCheckpointBudgets: DA falls back to the general multiplier.
240
+ const l2Multiplier = config.perBlockAllocationMultiplier;
241
+ const daMultiplier = config.perBlockDAAllocationMultiplier ?? l2Multiplier;
242
+
243
+ // The allocation is monotonic in the multiplier, so a multiplier at or above the network minimum
244
+ // guarantees the builder grants at least the network admission limit. Checking the multipliers directly
245
+ // is sufficient (and strictly more conservative than modeling the resulting gas grant).
246
+ if (daMultiplier < MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER) {
247
+ throw new Error(
248
+ `perBlockDAAllocationMultiplier (${daMultiplier}) is below the network minimum ` +
249
+ `${MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
250
+ );
179
251
  }
180
- if (config.governanceProposerPayload) {
181
- this.governanceProposerPayload = config.governanceProposerPayload;
252
+ if (l2Multiplier < MIN_PER_BLOCK_ALLOCATION_MULTIPLIER) {
253
+ throw new Error(
254
+ `perBlockAllocationMultiplier (${l2Multiplier}) is below the network minimum ` +
255
+ `${MIN_PER_BLOCK_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
256
+ );
182
257
  }
183
- if (config.maxL1TxInclusionTimeIntoSlot !== undefined) {
184
- this.maxL1TxInclusionTimeIntoSlot = config.maxL1TxInclusionTimeIntoSlot;
258
+
259
+ // Absolute per-block gas caps below the network admission limit are legitimate operator restrictiveness:
260
+ // the node simply builds smaller blocks and such txs stay in the pool for other proposers. Warn only.
261
+ const networkLimit = computeNetworkTxGasLimits({
262
+ maxBlocksPerCheckpoint,
263
+ manaCheckpointBudget: this.l1Constants.rollupManaLimit,
264
+ });
265
+ if (config.maxDABlockGas !== undefined && config.maxDABlockGas < networkLimit.daGas) {
266
+ this.log.warn(
267
+ `Sequencer maxDABlockGas (${config.maxDABlockGas}) is below the network DA admission limit ` +
268
+ `(${networkLimit.daGas}): txs declaring more DA gas are admitted over RPC/gossip but will be skipped ` +
269
+ `by this proposer's own blocks and left in the pool for other proposers.`,
270
+ { maxDABlockGas: config.maxDABlockGas, networkDaGas: networkLimit.daGas, maxBlocksPerCheckpoint },
271
+ );
185
272
  }
186
- if (config.enforceTimeTable !== undefined) {
187
- this.enforceTimeTable = config.enforceTimeTable;
273
+ if (config.maxL2BlockGas !== undefined && config.maxL2BlockGas < networkLimit.l2Gas) {
274
+ this.log.warn(
275
+ `Sequencer maxL2BlockGas (${config.maxL2BlockGas}) is below the network L2 admission limit ` +
276
+ `(${networkLimit.l2Gas}): txs declaring more L2 gas are admitted over RPC/gossip but will be skipped ` +
277
+ `by this proposer's own blocks and left in the pool for other proposers.`,
278
+ { maxL2BlockGas: config.maxL2BlockGas, networkL2Gas: networkLimit.l2Gas, maxBlocksPerCheckpoint },
279
+ );
188
280
  }
189
-
190
- this.setTimeTable();
191
-
192
- // TODO: Just read everything from the config object as needed instead of copying everything into local vars.
193
-
194
- // Update all values on this.config that are populated in the config object.
195
- Object.assign(this.config, config);
196
281
  }
197
282
 
198
- private setTimeTable() {
199
- this.timetable = new SequencerTimetable(
200
- {
201
- ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
202
- aztecSlotDuration: this.aztecSlotDuration,
203
- maxL1TxInclusionTimeIntoSlot: this.maxL1TxInclusionTimeIntoSlot,
204
- attestationPropagationTime: this.config.attestationPropagationTime,
205
- enforce: this.enforceTimeTable,
206
- },
207
- this.metrics,
208
- this.log,
209
- );
210
- }
211
-
212
- public async init() {
213
- this.publisher = (await this.publisherFactory.create(undefined)).publisher;
283
+ /** Initializes the sequencer (precomputes tables). Takes about 3s. */
284
+ public init() {
285
+ getKzg();
214
286
  }
215
287
 
216
288
  /**
217
- * Starts the sequencer and moves to IDLE state.
289
+ * Starts (or restarts) the sequencer and moves it to the IDLE state. Idempotent: a start while already
290
+ * running is a no-op, so it never orphans the previous poll loop. A start while STOPPING throws, since the
291
+ * in-flight stop would mark the fresh loop's state STOPPED and orphan it — silently doing nothing would
292
+ * leave the caller believing the sequencer is running when it is on its way to STOPPED. Safe to call after
293
+ * a previous {@link stop} has resolved; the caller must also restart the publishers (see
294
+ * {@link SequencerClient.start}) so L1 publishing is re-enabled.
218
295
  */
219
296
  public start() {
220
- this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.pollingIntervalMs);
297
+ if (this.state === SequencerState.STOPPING) {
298
+ throw new Error('Cannot start sequencer while it is stopping');
299
+ }
300
+ if (this.runningPromise?.isRunning()) {
301
+ this.log.warn('Attempted to start sequencer that is already running');
302
+ return;
303
+ }
304
+ this.runningPromise = new RunningPromise(
305
+ this.safeWork.bind(this),
306
+ this.log,
307
+ this.config.sequencerPollingIntervalMS,
308
+ );
221
309
  this.setState(SequencerState.IDLE, undefined, { force: true });
222
310
  this.runningPromise.start();
223
311
  this.log.info('Started sequencer');
224
312
  }
225
313
 
314
+ /** Triggers an immediate run of the sequencer, bypassing the polling interval. */
315
+ public trigger() {
316
+ return this.runningPromise?.trigger();
317
+ }
318
+
226
319
  /**
227
- * Stops the sequencer from processing txs and moves to STOPPED state.
320
+ * Stops the sequencer from building blocks and moves it to STOPPED state, interrupting the in-flight
321
+ * work() iteration and its pending L1 submissions for a fast shutdown, then draining before returning.
322
+ * Idempotent: a second call while already stopped or stopping is a no-op. Lifecycle calls are expected
323
+ * to be serialized by the caller. For a restartable pause that lets in-flight work finish untouched
324
+ * (e.g. around a test clock warp), use {@link pause} instead.
228
325
  */
229
326
  public async stop(): Promise<void> {
327
+ if (this.state === SequencerState.STOPPED || this.state === SequencerState.STOPPING) {
328
+ this.log.debug(`Sequencer already ${this.state.toLowerCase()}, ignoring stop`);
329
+ return;
330
+ }
230
331
  this.log.info(`Stopping sequencer`);
231
332
  this.setState(SequencerState.STOPPING, undefined, { force: true });
232
- this.publisher?.interrupt();
333
+ this.lastCheckpointProposalJob?.interrupt();
334
+ await this.publisherFactory.stopAll();
335
+ // Stop the poll loop and await the in-flight work() iteration. work() registers its fire-and-forget
336
+ // requests synchronously before returning, so once the loop has stopped, pendingRequests holds every
337
+ // request that will ever exist. Interrupting any earlier could miss a request registered by the last
338
+ // in-flight iteration.
233
339
  await this.runningPromise?.stop();
340
+ this.pendingRequests.interruptRequests();
341
+ await this.pendingRequests.awaitRequests();
234
342
  this.setState(SequencerState.STOPPED, undefined, { force: true });
235
343
  this.log.info('Stopped sequencer');
236
344
  }
237
345
 
238
346
  /**
239
- * Returns the current state of the sequencer.
240
- * @returns An object with a state entry with one of SequencerState.
347
+ * Gracefully pauses block production so the sequencer can later be resumed with {@link start}: halts the
348
+ * poll loop and waits for the in-flight work() iteration and every pending L1 submission / fallback send
349
+ * to finish, without interrupting them. No interrupt lands mid-build, so no spurious checkpoint-error is
350
+ * emitted and no enqueued checkpoint is dropped. Deliberately does not stop inner services (validator/HA
351
+ * signer, publishers), so the slashing-protection store stays open and the sequencer stays restartable.
352
+ * Used by tests that pause sequencers around an L1 clock warp. Idempotent.
241
353
  */
354
+ public async pause(): Promise<void> {
355
+ if (!this.runningPromise?.isRunning()) {
356
+ this.log.debug('Sequencer not running, ignoring pause');
357
+ return;
358
+ }
359
+ this.log.info('Pausing sequencer');
360
+ // Halt the poll loop and let the in-flight iteration finish naturally — no interrupt, and no STOPPING
361
+ // state, since entering STOPPING would make the iteration's own setState calls throw and fail it.
362
+ // work() registers its fire-and-forget requests synchronously before returning, so once the loop has
363
+ // stopped pendingRequests holds every request that will ever exist; awaiting it lets them all finish.
364
+ await this.runningPromise.stop();
365
+ await this.pendingRequests.awaitRequests();
366
+ this.log.info('Paused sequencer');
367
+ }
368
+
369
+ /** Main sequencer loop with a try/catch */
370
+ protected async safeWork() {
371
+ try {
372
+ await this.work();
373
+ } catch (err) {
374
+ this.emit('checkpoint-error', { error: err as Error });
375
+ throw err;
376
+ } finally {
377
+ this.setState(SequencerState.IDLE, undefined);
378
+ }
379
+ }
380
+
381
+ /** Returns the current state of the sequencer. */
242
382
  public status() {
243
383
  return { state: this.state };
244
384
  }
245
385
 
246
386
  /**
247
- * @notice Performs most of the sequencer duties:
248
- * - Checks if we are up to date
249
- * - If we are and we are the sequencer, collect txs and build a block
250
- * - Collect attestations for the block
251
- * - Submit block
252
- * - If our block for some reason is not included, revert the state
387
+ * Main sequencer loop:
388
+ * - Checks if we are up to date
389
+ * - If we are and we are the sequencer, collect txs and build blocks
390
+ * - Build multiple blocks per slot when configured
391
+ * - Collect attestations for the final block
392
+ * - Submit checkpoint
253
393
  */
394
+ @trackSpan('Sequencer.work')
254
395
  protected async work() {
255
396
  this.setState(SequencerState.SYNCHRONIZING, undefined);
256
- const { slot, ts, now } = this.epochCache.getEpochAndSlotInNextL1Slot();
397
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
257
398
 
258
- // Check we have not already published a block for this slot (cheapest check)
259
- if (this.lastBlockPublished && this.lastBlockPublished.header.getSlot() >= slot) {
260
- this.log.debug(
261
- `Cannot propose block at next L2 slot ${slot} since that slot was taken by our own block ${this.lastBlockPublished.number}`,
262
- );
399
+ // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
400
+ const checkpointProposalJob = await this.prepareCheckpointProposal(
401
+ slot,
402
+ targetSlot,
403
+ epoch,
404
+ targetEpoch,
405
+ ts,
406
+ nowSeconds,
407
+ );
408
+ if (!checkpointProposalJob) {
263
409
  return;
264
410
  }
265
411
 
266
- // Check all components are synced to latest as seen by the archiver (queries all subsystems)
412
+ // Track the job so we can await its pending L1 submission during shutdown
413
+ this.lastCheckpointProposalJob = checkpointProposalJob;
414
+
415
+ // Execute the checkpoint proposal job
416
+ const checkpoint = await checkpointProposalJob.execute();
417
+
418
+ // Update last checkpoint proposed (currently unused)
419
+ if (checkpoint) {
420
+ this.lastCheckpointProposed = checkpoint;
421
+ }
422
+
423
+ // Log fee strategy comparison if on fisherman (uses target epoch since we mirror the proposer's perspective)
424
+ if (
425
+ this.config.fishermanMode &&
426
+ (this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)
427
+ ) {
428
+ this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
429
+ this.lastEpochForStrategyComparison = targetEpoch;
430
+ }
431
+
432
+ return checkpoint;
433
+ }
434
+
435
+ /** Returns slot and target slot from a single clock snapshot. */
436
+ protected getSlotContextInNextL1Slot(): SequencerSlotContext {
437
+ const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
438
+ const targetSlot = SlotNumber(slot + PROPOSER_PIPELINING_SLOT_OFFSET);
439
+ return { slot, targetSlot, epoch, targetEpoch: getEpochAtSlot(targetSlot, this.l1Constants), ts, nowSeconds };
440
+ }
441
+
442
+ /**
443
+ * Prepares the checkpoint proposal by performing all necessary checks and setup.
444
+ * This is the initial step in the main loop.
445
+ * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
446
+ */
447
+ @trackSpan('Sequencer.prepareCheckpointProposal')
448
+ protected async prepareCheckpointProposal(
449
+ slot: SlotNumber,
450
+ targetSlot: SlotNumber,
451
+ epoch: EpochNumber,
452
+ targetEpoch: EpochNumber,
453
+ ts: bigint,
454
+ nowSeconds: bigint,
455
+ ): Promise<CheckpointProposalJob | undefined> {
456
+ // Check we have not already processed this target slot (cheapest check).
457
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot) {
458
+ this.log.trace(`Target slot ${targetSlot} has already been processed`);
459
+ return undefined;
460
+ }
461
+
462
+ // But if we have already proposed for this slot, then we definitely have to skip it, automining or not
463
+ if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= targetSlot) {
464
+ this.log.trace(
465
+ `Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`,
466
+ );
467
+ return undefined;
468
+ }
469
+
470
+ // Test-only: skip proposing for explicitly paused slots. Attestation paths run in the validator
471
+ // client and are not gated by this hook, so paused proposers still attest to others' proposals.
472
+ if (this.config.pauseProposingForSlots?.some(s => s === targetSlot)) {
473
+ this.log.warn(`Skipping proposal for paused slot ${targetSlot} (test-only pauseProposingForSlots hook)`, {
474
+ targetSlot,
475
+ });
476
+ return undefined;
477
+ }
478
+
479
+ // Cheap proposer check first: most nodes are not the proposer for most slots, so gate the
480
+ // expensive multi-subsystem checkSync (and the rest of the build path) behind it. Computed once
481
+ // here and reused for the escape-hatch voting path below. No setState/timing gate on this path:
482
+ // the build-start deadline gate runs only on the proposer build path after a successful checkSync.
483
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
484
+
485
+ // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
486
+ // Still perform governance/slashing voting (as proposer) once per slot.
487
+ // When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
488
+ const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
489
+
490
+ if (isEscapeHatchOpen) {
491
+ if (canPropose) {
492
+ await this.tryVoteWhenEscapeHatchOpen({ slot, targetSlot, proposer });
493
+ } else {
494
+ this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
495
+ slot,
496
+ epoch,
497
+ proposer,
498
+ });
499
+ }
500
+ return undefined;
501
+ }
502
+
503
+ // If we are not the proposer, check whether we should invalidate an invalid pending chain (a
504
+ // liveness backstop) and bail before any sync work or build-timing gate. This reads only the
505
+ // archiver's pending-chain validation status, which is authoritative on its own, instead of
506
+ // running the full sync check. Wrapped in try/catch because this leaner path skips the broader
507
+ // proposed-checkpoint/tip coherence screen that checkSync applied, so transient archiver
508
+ // incoherence surfaces as a quiet skip rather than a work-loop error.
509
+ if (!canPropose) {
510
+ try {
511
+ const pendingChainValidationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
512
+ await this.considerInvalidatingCheckpoint(pendingChainValidationStatus, slot);
513
+ } catch (err) {
514
+ this.log.warn(`Failed to consider invalidating checkpoint`, { err, slot, targetSlot });
515
+ }
516
+ return undefined;
517
+ }
518
+
519
+ // Explicit build-loop entry gate: if we are past the latest useful block-building start for the
520
+ // target slot, abandon building for this slot. The proposer prioritizes the ideal L1-publish path
521
+ // and does not plan around the late consensus-handoff path. This is the proposer build path's
522
+ // timing gate; it runs only after we know we are the synced proposer, so non-proposer invalidation
523
+ // and escape-hatch voting (which returned above) are never gated by build timing. Vote-only paths
524
+ // still run when block building is abandoned.
525
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
526
+ const nowForStartGate = this.dateProvider.now() / 1000;
527
+ if (nowForStartGate > startDeadline) {
528
+ this.log.debug(`Past start deadline for slot ${targetSlot}, abandoning block building`, {
529
+ targetSlot,
530
+ nowForStartGate,
531
+ startDeadline,
532
+ });
533
+ // Mark the slot as attempted so a deadline abort is not retried within the same slot. Vote-only actions
534
+ // still need to run because sync can succeed even when it is too late to start building a checkpoint.
535
+ await this.tryVoteAndPruneWhenCannotBuild({ slot, targetSlot });
536
+ this.lastSlotForCheckpointProposalJob = targetSlot;
537
+ return undefined;
538
+ }
539
+
540
+ // We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
541
+ // Now run the full sync check before building.
267
542
  const syncedTo = await this.checkSync({ ts, slot });
268
543
  if (!syncedTo) {
269
- await this.tryVoteWhenSyncFails({ slot, ts });
270
- return;
544
+ return undefined;
271
545
  }
272
546
 
273
- const chainTipArchive = syncedTo.archive;
274
- const newBlockNumber = syncedTo.blockNumber + 1;
275
-
276
- const syncLogData = {
277
- now,
278
- syncedToL1Ts: syncedTo.l1Timestamp,
279
- syncedToL2Slot: getSlotAtTimestamp(syncedTo.l1Timestamp, this.l1Constants),
280
- nextL2Slot: slot,
281
- nextL2SlotTs: ts,
282
- l1SlotDuration: this.l1Constants.ethereumSlotDuration,
283
- newBlockNumber,
547
+ // Next checkpoint follows from the last synced one
548
+ const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
549
+
550
+ const logCtx = {
551
+ nowSeconds,
552
+ syncedToL2Slot: syncedTo.syncedL2Slot,
553
+ slot,
554
+ targetSlot,
555
+ slotTs: ts,
556
+ checkpointNumber,
284
557
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex'),
285
558
  };
286
559
 
287
- // Check that we are a proposer for the next slot
288
- this.setState(SequencerState.PROPOSER_CHECK, slot);
289
- const [canPropose, proposer] = await this.checkCanPropose(slot);
560
+ // We are the synced proposer within the build window; enter the proposer-check state and build.
561
+ this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
290
562
 
291
- // If we are not a proposer, check if we should invalidate a invalid block, and bail
292
- if (!canPropose) {
293
- await this.considerInvalidatingBlock(syncedTo, slot);
294
- return;
563
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
564
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
565
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
566
+ if (checkpointNumber > confirmedCkpt + 2) {
567
+ this.log.verbose(
568
+ `Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`,
569
+ );
570
+ return undefined;
295
571
  }
296
572
 
297
- // Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
298
- if (syncedTo.block && syncedTo.block.header.getSlot() >= slot) {
573
+ // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
574
+ if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
299
575
  this.log.warn(
300
- `Cannot propose block at next L2 slot ${slot} since that slot was taken by block ${syncedTo.blockNumber}`,
301
- { ...syncLogData, block: syncedTo.block.header.toInspect() },
576
+ `Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`,
577
+ { ...logCtx, block: syncedTo.blockData.header.toInspect() },
302
578
  );
303
- return;
579
+ this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
580
+ return undefined;
304
581
  }
305
582
 
306
583
  // We now need to get ourselves a publisher.
307
584
  // The returned attestor will be the one we provided if we provided one.
308
585
  // Otherwise it will be a valid attestor for the returned publisher.
309
- const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
586
+ // In fisherman mode, pass undefined to use the fisherman's own keystore instead of the actual proposer's
587
+ const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
588
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
310
589
  this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
311
- this.publisher = publisher;
312
590
 
313
- const coinbase = this.validatorClient!.getCoinbaseForAttestor(attestorAddress);
314
- const feeRecipient = this.validatorClient!.getFeeRecipientForAttestor(attestorAddress);
591
+ // Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
592
+ // Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
593
+ // will invalidate the currently invalid checkpoint on L1.
594
+ const invalidateCheckpoint =
595
+ syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid
596
+ ? undefined
597
+ : await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
598
+
599
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
600
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
601
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
602
+ let archiveForCheck = syncedTo.archive;
603
+
604
+ if (syncedTo.hasProposedCheckpoint) {
605
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
606
+ this.log.verbose(
607
+ `Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`,
608
+ { targetSlot, parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1) },
609
+ );
610
+ // Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
611
+ // own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
612
+ // view and can transiently diverge from the proposed parent (e.g. before the proposed
613
+ // parent's blocks have been applied locally); diverging here would cause the canProposeAt
614
+ // override to set archives[pending] to one value while we present another for comparison.
615
+ archiveForCheck = syncedTo.proposedCheckpointData!.archive.root;
616
+ } else if (invalidateCheckpoint) {
617
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
618
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
619
+ archiveForCheck = invalidateCheckpoint.lastArchive;
620
+ this.metrics.recordPipelineDepth(0);
621
+ } else {
622
+ this.metrics.recordPipelineDepth(0);
623
+ }
624
+
625
+ // Build the simulation plan: pending/proven override from pipelining or invalidation (or the
626
+ // current snapshot when neither applies, to short-circuit any pending prune in simulation),
627
+ // plus the parent checkpoint cell and fee header when pipelining.
628
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
629
+ checkpointNumber,
630
+ proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
631
+ invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
632
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
633
+ rollup: this.rollupContract,
634
+ signatureContext: this.signatureContext,
635
+ log: this.log,
636
+ });
637
+
638
+ // The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
639
+ // so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
640
+ // simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
641
+ // actually fire at the target slot without it — so observers can spot "we are building
642
+ // optimistically across a pruning boundary" in the logs.
643
+ const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
644
+ if (provenOverride !== undefined && (await this.l2BlockSource.isPruneDueAtSlot(targetSlot))) {
645
+ this.log.warn(
646
+ `Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`,
647
+ { checkpointNumber, slot, targetSlot, provenOverride },
648
+ );
649
+ }
315
650
 
316
- // Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
317
- const invalidateBlock = await publisher.simulateInvalidateBlock(syncedTo.pendingChainValidationStatus);
651
+ this.emit('preparing-checkpoint', {
652
+ targetSlot,
653
+ checkpointNumber,
654
+ hadProposedParent: syncedTo.hasProposedCheckpoint,
655
+ provenOverride,
656
+ simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending,
657
+ });
318
658
 
319
- // Check with the rollup if we can indeed propose at the next L2 slot. This check should not fail
320
- // if all the previous checks are good, but we do it just in case.
321
- const canProposeCheck = await publisher.canProposeAtNextEthBlock(
322
- chainTipArchive,
659
+ const canProposeCheck = await publisher.canProposeAt(
660
+ archiveForCheck,
323
661
  proposer ?? EthAddress.ZERO,
324
- invalidateBlock,
662
+ simulationOverridesPlan,
325
663
  );
326
664
 
665
+ const proposeContext = {
666
+ hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
667
+ proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
668
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
669
+ isInvalidating: !!invalidateCheckpoint,
670
+ invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
671
+ archiveForCheck: archiveForCheck.toString(),
672
+ overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
673
+ overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
674
+ overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader,
675
+ };
676
+
327
677
  if (canProposeCheck === undefined) {
328
678
  this.log.warn(
329
- `Cannot propose block ${newBlockNumber} at slot ${slot} due to failed rollup contract check`,
330
- syncLogData,
679
+ `Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`,
680
+ { ...logCtx, ...proposeContext },
331
681
  );
332
- this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed' });
333
- return;
334
- } else if (canProposeCheck.slot !== slot) {
682
+ this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed', slot });
683
+ this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
684
+ return undefined;
685
+ }
686
+
687
+ if (canProposeCheck.slot !== targetSlot) {
335
688
  this.log.warn(
336
- `Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${slot} but got ${canProposeCheck.slot}.`,
337
- { ...syncLogData, rollup: canProposeCheck, newBlockNumber, expectedSlot: slot },
689
+ `Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${targetSlot} but got ${canProposeCheck.slot}.`,
690
+ { ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: targetSlot },
338
691
  );
339
- this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch' });
340
- return;
341
- } else if (canProposeCheck.blockNumber !== BigInt(newBlockNumber)) {
692
+ this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch', slot });
693
+ this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
694
+ return undefined;
695
+ }
696
+
697
+ if (canProposeCheck.checkpointNumber !== checkpointNumber) {
342
698
  this.log.warn(
343
- `Cannot propose block due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected block ${newBlockNumber} but got ${canProposeCheck.blockNumber}.`,
344
- { ...syncLogData, rollup: canProposeCheck, newBlockNumber, expectedSlot: slot },
699
+ `Cannot propose due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected checkpoint ${checkpointNumber} but got ${canProposeCheck.checkpointNumber}.`,
700
+ { ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: slot },
345
701
  );
346
- this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch' });
347
- return;
702
+ this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch', slot });
703
+ this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
704
+ return undefined;
348
705
  }
349
706
 
350
- this.log.debug(`Can propose block ${newBlockNumber} at slot ${slot} as ${proposer}`, { ...syncLogData });
351
-
352
- const newGlobalVariables = await this.globalsBuilder.buildGlobalVariables(
353
- newBlockNumber,
354
- coinbase,
355
- feeRecipient,
356
- slot,
357
- );
707
+ this.lastSlotForCheckpointProposalJob = targetSlot;
358
708
 
359
- // Enqueue governance and slashing votes (returns promises that will be awaited later)
360
- const votesPromises = this.enqueueGovernanceAndSlashingVotes(
361
- publisher,
362
- attestorAddress,
363
- slot,
364
- newGlobalVariables.timestamp,
709
+ await this.p2pClient.prepareForSlot(targetSlot);
710
+ this.log.info(
711
+ `Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`,
712
+ {
713
+ ...logCtx,
714
+ ...proposeContext,
715
+ proposer,
716
+ },
365
717
  );
366
718
 
367
- // Enqueues block invalidation
368
- if (invalidateBlock && !this.config.skipInvalidateBlockAsProposer) {
369
- publisher.enqueueInvalidateBlock(invalidateBlock);
370
- }
371
-
372
- // Actual block building
373
- this.setState(SequencerState.INITIALIZING_PROPOSAL, slot);
374
- const block: L2Block | undefined = await this.tryBuildBlockAndEnqueuePublish(
375
- slot,
719
+ // Create and return the checkpoint proposal job
720
+ return this.createCheckpointProposalJob(
721
+ targetSlot,
722
+ targetEpoch,
723
+ checkpointNumber,
724
+ syncedTo.blockNumber,
725
+ syncedTo.checkpointedCheckpointNumber,
376
726
  proposer,
377
- newBlockNumber,
378
727
  publisher,
379
- newGlobalVariables,
380
- chainTipArchive,
381
- invalidateBlock,
728
+ attestorAddress,
729
+ invalidateCheckpoint,
730
+ syncedTo.proposedCheckpointData,
382
731
  );
383
-
384
- // Wait until the voting promises have resolved, so all requests are enqueued
385
- await Promise.all(votesPromises);
386
-
387
- // And send the tx to L1
388
- const l1Response = await publisher.sendRequests();
389
- const proposedBlock = l1Response?.successfulActions.find(a => a === 'propose');
390
- if (proposedBlock) {
391
- this.lastBlockPublished = block;
392
- this.emit('block-published', { blockNumber: newBlockNumber, slot: Number(slot) });
393
- await this.metrics.incFilledSlot(publisher.getSenderAddress().toString(), coinbase);
394
- } else if (block) {
395
- this.emit('block-publish-failed', l1Response ?? {});
396
- }
397
-
398
- this.setState(SequencerState.IDLE, undefined);
399
732
  }
400
733
 
401
- /** Tries building a block proposal, and if successful, enqueues it for publishing. */
402
- private async tryBuildBlockAndEnqueuePublish(
403
- slot: bigint,
734
+ protected createCheckpointProposalJob(
735
+ targetSlot: SlotNumber,
736
+ targetEpoch: EpochNumber,
737
+ checkpointNumber: CheckpointNumber,
738
+ syncedToBlockNumber: BlockNumber,
739
+ checkpointedCheckpointNumber: CheckpointNumber,
404
740
  proposer: EthAddress | undefined,
405
- newBlockNumber: number,
406
741
  publisher: SequencerPublisher,
407
- newGlobalVariables: GlobalVariables,
408
- chainTipArchive: Fr,
409
- invalidateBlock: InvalidateBlockRequest | undefined,
410
- ) {
411
- this.log.verbose(`Preparing proposal for block ${newBlockNumber} at slot ${slot}`, {
742
+ attestorAddress: EthAddress,
743
+ invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
744
+ proposedCheckpointData?: ProposedCheckpointData,
745
+ ): CheckpointProposalJob {
746
+ return new CheckpointProposalJob(
747
+ targetSlot,
748
+ targetEpoch,
749
+ checkpointNumber,
750
+ syncedToBlockNumber,
751
+ checkpointedCheckpointNumber,
412
752
  proposer,
413
- publisher: publisher.getSenderAddress(),
414
- globalVariables: newGlobalVariables.toInspect(),
415
- chainTipArchive,
416
- blockNumber: newBlockNumber,
417
- slot,
418
- });
419
-
420
- const proposalHeader = CheckpointHeader.from({
421
- ...newGlobalVariables,
422
- timestamp: newGlobalVariables.timestamp,
423
- lastArchiveRoot: chainTipArchive,
424
- contentCommitment: ContentCommitment.empty(),
425
- totalManaUsed: Fr.ZERO,
426
- });
427
-
428
- let block: L2Block | undefined;
429
-
430
- const pendingTxCount = await this.p2pClient.getPendingTxCount();
431
- if (pendingTxCount >= this.minTxsPerBlock) {
432
- // We don't fetch exactly maxTxsPerBlock txs here because we may not need all of them if we hit a limit before,
433
- // and also we may need to fetch more if we don't have enough valid txs.
434
- const pendingTxs = this.p2pClient.iteratePendingTxs();
435
- try {
436
- block = await this.buildBlockAndEnqueuePublish(
437
- pendingTxs,
438
- proposalHeader,
439
- newGlobalVariables,
440
- proposer,
441
- invalidateBlock,
442
- publisher,
443
- );
444
- } catch (err: any) {
445
- this.emit('block-build-failed', { reason: err.message });
446
- if (err instanceof FormattedViemError) {
447
- this.log.verbose(`Unable to build/enqueue block ${err.message}`);
448
- } else {
449
- this.log.error(`Error building/enqueuing block`, err, { blockNumber: newBlockNumber, slot });
450
- }
451
- }
452
- } else {
453
- this.log.verbose(
454
- `Not enough txs to build block ${newBlockNumber} at slot ${slot} (got ${pendingTxCount} txs, need ${this.minTxsPerBlock})`,
455
- { chainTipArchive, blockNumber: newBlockNumber, slot },
456
- );
457
- this.emit('tx-count-check-failed', { minTxs: this.minTxsPerBlock, availableTxs: pendingTxCount });
458
- }
459
- return block;
753
+ publisher,
754
+ attestorAddress,
755
+ invalidateCheckpoint,
756
+ this.validatorClient,
757
+ this.globalsBuilder,
758
+ this.p2pClient,
759
+ this.worldState,
760
+ this.l1ToL2MessageSource,
761
+ this.l2BlockSource,
762
+ this.checkpointsBuilder,
763
+ this.l2BlockSource,
764
+ this.l1Constants,
765
+ this.signatureContext,
766
+ this.config,
767
+ this.timetable,
768
+ this.slasherClient,
769
+ this.epochCache,
770
+ this.dateProvider,
771
+ this.metrics,
772
+ this.checkpointProposalJobMetrics.createRecorder(),
773
+ this,
774
+ this.pendingRequests,
775
+ this.setState.bind(this),
776
+ this.tracer,
777
+ this.log.getBindings(),
778
+ proposedCheckpointData,
779
+ );
460
780
  }
461
781
 
462
- @trackSpan('Sequencer.work')
463
- protected async safeWork() {
464
- try {
465
- await this.work();
466
- } catch (err) {
467
- if (err instanceof SequencerTooSlowError) {
468
- // Log as warn only if we had to abort halfway through the block proposal
469
- const logLvl = [SequencerState.INITIALIZING_PROPOSAL, SequencerState.PROPOSER_CHECK].includes(err.proposedState)
470
- ? ('debug' as const)
471
- : ('warn' as const);
472
- this.log[logLvl](err.message, { now: this.dateProvider.nowInSeconds() });
473
- } else {
474
- // Re-throw other errors
475
- throw err;
476
- }
477
- } finally {
478
- this.setState(SequencerState.IDLE, undefined);
479
- }
782
+ /**
783
+ * Returns the current sequencer state.
784
+ */
785
+ public getState(): SequencerState {
786
+ return this.state;
480
787
  }
481
788
 
482
789
  /**
483
- * Sets the sequencer state and checks if we have enough time left in the slot to transition to the new state.
790
+ * Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
791
+ * records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
484
792
  * @param proposedState - The new state to transition to.
485
- * @param slotNumber - The current slot number.
793
+ * @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
794
+ * and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
486
795
  * @param force - Whether to force the transition even if the sequencer is stopped.
487
796
  */
488
- setState(proposedState: SequencerStateWithSlot, slotNumber: bigint, opts?: { force?: boolean }): void;
489
- setState(
490
- proposedState: Exclude<SequencerState, SequencerStateWithSlot>,
491
- slotNumber?: undefined,
492
- opts?: { force?: boolean },
493
- ): void;
494
- setState(proposedState: SequencerState, slotNumber: bigint | undefined, opts: { force?: boolean } = {}): void {
797
+ protected setState(
798
+ proposedState: SequencerState,
799
+ slotNumber: SlotNumber | undefined,
800
+ opts: { force?: boolean } = {},
801
+ ): void {
495
802
  if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
496
803
  this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
497
804
  throw new SequencerInterruptedError();
@@ -500,325 +807,56 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
500
807
  this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
501
808
  return;
502
809
  }
503
- let secondsIntoSlot = undefined;
504
- if (slotNumber !== undefined) {
505
- secondsIntoSlot = this.getSecondsIntoSlot(slotNumber);
506
- this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
507
- }
810
+ const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
811
+
812
+ const oldState = this.state;
813
+ const oldStateSlotNumber = this.stateSlotNumber;
814
+ const stateChanged = proposedState !== oldState;
815
+ // Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
816
+ // calls, read from the date provider so it tracks simulated time under a test/manual clock.
817
+ const transitionAtMs = this.dateProvider.now();
818
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
508
819
 
509
820
  const boringStates = [SequencerState.IDLE, SequencerState.SYNCHRONIZING];
510
821
  const logLevel =
511
- boringStates.includes(proposedState) && boringStates.includes(this.state)
512
- ? ('trace' as const)
513
- : ('debug' as const);
514
- this.log[logLevel](`Transitioning from ${this.state} to ${proposedState}`, { slotNumber, secondsIntoSlot });
515
-
516
- this.emit('state-changed', {
517
- oldState: this.state,
822
+ boringStates.includes(proposedState) && boringStates.includes(oldState) ? ('trace' as const) : ('debug' as const);
823
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
824
+ oldState,
518
825
  newState: proposedState,
519
- secondsIntoSlot,
520
826
  slotNumber,
827
+ stateSlotNumber: oldStateSlotNumber,
828
+ secondsIntoBuildFrame,
829
+ ...(stateChanged && { stateDurationMs: Math.ceil(stateDurationMs) }),
521
830
  });
522
- this.state = proposedState;
523
- }
524
-
525
- private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
526
- if (failedTxs.length === 0) {
527
- return;
528
- }
529
- const failedTxData = failedTxs.map(fail => fail.tx);
530
- const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
531
- this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
532
- await this.p2pClient.deleteTxs(failedTxHashes);
533
- }
534
-
535
- protected getBlockBuilderOptions(slot: number): PublicProcessorLimits {
536
- // Deadline for processing depends on whether we're proposing a block
537
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
538
- const processingEndTimeWithinSlot = this.timetable.getBlockProposalExecTimeEnd(secondsIntoSlot);
539
-
540
- // Deadline is only set if enforceTimeTable is enabled.
541
- const deadline = this.enforceTimeTable
542
- ? new Date((this.getSlotStartBuildTimestamp(slot) + processingEndTimeWithinSlot) * 1000)
543
- : undefined;
544
- return {
545
- maxTransactions: this.maxTxsPerBlock,
546
- maxBlockSize: this.maxBlockSizeInBytes,
547
- maxBlockGas: this.maxBlockGas,
548
- maxBlobFields: BLOBS_PER_BLOCK * FIELDS_PER_BLOB,
549
- deadline,
550
- };
551
- }
552
-
553
- /**
554
- * @notice Build and propose a block to the chain
555
- *
556
- * @dev MUST throw instead of exiting early to ensure that world-state
557
- * is being rolled back if the block is dropped.
558
- *
559
- * @param pendingTxs - Iterable of pending transactions to construct the block from
560
- * @param proposalHeader - The partial header constructed for the proposal
561
- * @param newGlobalVariables - The global variables for the new block
562
- * @param proposerAddress - The address of the proposer
563
- */
564
- @trackSpan('Sequencer.buildBlockAndEnqueuePublish', (_validTxs, _proposalHeader, newGlobalVariables) => ({
565
- [Attributes.BLOCK_NUMBER]: newGlobalVariables.blockNumber,
566
- }))
567
- private async buildBlockAndEnqueuePublish(
568
- pendingTxs: Iterable<Tx> | AsyncIterable<Tx>,
569
- proposalHeader: CheckpointHeader,
570
- newGlobalVariables: GlobalVariables,
571
- proposerAddress: EthAddress | undefined,
572
- invalidateBlock: InvalidateBlockRequest | undefined,
573
- publisher: SequencerPublisher,
574
- ): Promise<L2Block> {
575
- await publisher.validateBlockHeader(proposalHeader, invalidateBlock);
576
-
577
- const blockNumber = newGlobalVariables.blockNumber;
578
- const slot = proposalHeader.slotNumber.toBigInt();
579
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(blockNumber);
580
-
581
- const workTimer = new Timer();
582
- this.setState(SequencerState.CREATING_BLOCK, slot);
583
-
584
- try {
585
- const blockBuilderOptions = this.getBlockBuilderOptions(Number(slot));
586
- const buildBlockRes = await this.blockBuilder.buildBlock(
587
- pendingTxs,
588
- l1ToL2Messages,
589
- newGlobalVariables,
590
- blockBuilderOptions,
591
- );
592
- const { publicGas, block, publicProcessorDuration, numTxs, numMsgs, blockBuildingTimer, usedTxs, failedTxs } =
593
- buildBlockRes;
594
- const blockBuildDuration = workTimer.ms();
595
- await this.dropFailedTxsFromP2P(failedTxs);
596
-
597
- const minTxsPerBlock = this.minTxsPerBlock;
598
- if (numTxs < minTxsPerBlock) {
599
- this.log.warn(
600
- `Block ${blockNumber} has too few txs to be proposed (got ${numTxs} but required ${minTxsPerBlock})`,
601
- { slot, blockNumber, numTxs },
602
- );
603
- throw new Error(`Block has too few successful txs to be proposed`);
604
- }
605
-
606
- // TODO(@PhilWindle) We should probably periodically check for things like another
607
- // block being published before ours instead of just waiting on our block
608
- await publisher.validateBlockHeader(block.getCheckpointHeader(), invalidateBlock);
609
-
610
- const blockStats: L2BlockBuiltStats = {
611
- eventName: 'l2-block-built',
612
- creator: proposerAddress?.toString() ?? publisher.getSenderAddress().toString(),
613
- duration: workTimer.ms(),
614
- publicProcessDuration: publicProcessorDuration,
615
- rollupCircuitsDuration: blockBuildingTimer.ms(),
616
- ...block.getStats(),
617
- };
618
-
619
- const blockHash = await block.hash();
620
- const txHashes = block.body.txEffects.map(tx => tx.txHash);
621
- this.log.info(
622
- `Built block ${block.number} for slot ${slot} with ${numTxs} txs and ${numMsgs} messages. ${
623
- publicGas.l2Gas / workTimer.s()
624
- } mana/s`,
625
- {
626
- blockHash,
627
- globalVariables: block.header.globalVariables.toInspect(),
628
- txHashes,
629
- ...blockStats,
630
- },
631
- );
632
-
633
- this.log.debug('Collecting attestations');
634
- const attestations = await this.collectAttestations(block, usedTxs, proposerAddress);
635
- if (attestations !== undefined) {
636
- this.log.verbose(`Collected ${attestations.length} attestations`, { blockHash, blockNumber });
637
- }
638
-
639
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(attestations ?? []);
640
- const attestationsAndSignersSignature = this.validatorClient
641
- ? await this.validatorClient.signAttestationsAndSigners(
642
- attestationsAndSigners,
643
- proposerAddress ?? publisher.getSenderAddress(),
644
- )
645
- : Signature.empty();
646
-
647
- await this.enqueuePublishL2Block(
648
- block,
649
- attestationsAndSigners,
650
- attestationsAndSignersSignature,
651
- invalidateBlock,
652
- publisher,
653
- );
654
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
655
- return block;
656
- } catch (err) {
657
- this.metrics.recordFailedBlock();
658
- throw err;
659
- }
660
- }
661
-
662
- @trackSpan('Sequencer.collectAttestations', (block, txHashes) => ({
663
- [Attributes.BLOCK_NUMBER]: block.number,
664
- [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
665
- [Attributes.BLOCK_TXS_COUNT]: txHashes.length,
666
- }))
667
- protected async collectAttestations(
668
- block: L2Block,
669
- txs: Tx[],
670
- proposerAddress: EthAddress | undefined,
671
- ): Promise<CommitteeAttestation[] | undefined> {
672
- const { committee } = await this.epochCache.getCommittee(block.header.getSlot());
673
-
674
- // We checked above that the committee is defined, so this should never happen.
675
- if (!committee) {
676
- throw new Error('No committee when collecting attestations');
677
- }
678
-
679
- if (committee.length === 0) {
680
- this.log.verbose(`Attesting committee is empty`);
681
- return undefined;
682
- } else {
683
- this.log.debug(`Attesting committee length is ${committee.length}`);
684
- }
685
-
686
- if (!this.validatorClient) {
687
- const msg = 'Missing validator client: Cannot collect attestations';
688
- this.log.error(msg);
689
- throw new Error(msg);
690
- }
691
-
692
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
693
-
694
- const slotNumber = block.header.globalVariables.slotNumber.toBigInt();
695
- this.setState(SequencerState.COLLECTING_ATTESTATIONS, slotNumber);
696
-
697
- this.log.debug('Creating block proposal for validators');
698
- const blockProposalOptions: BlockProposalOptions = {
699
- publishFullTxs: !!this.config.publishTxsWithProposals,
700
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
701
- };
702
- const proposal = await this.validatorClient.createBlockProposal(
703
- block.header.globalVariables.blockNumber,
704
- block.getCheckpointHeader(),
705
- block.archive.root,
706
- block.header.state,
707
- txs,
708
- proposerAddress,
709
- blockProposalOptions,
710
- );
711
-
712
- if (!proposal) {
713
- throw new Error(`Failed to create block proposal`);
714
- }
715
-
716
- if (this.config.skipCollectingAttestations) {
717
- this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
718
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
719
- return orderAttestations(attestations ?? [], committee);
720
- }
721
-
722
- this.log.debug('Broadcasting block proposal to validators');
723
- await this.validatorClient.broadcastBlockProposal(proposal);
724
831
 
725
- const attestationTimeAllowed = this.enforceTimeTable
726
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_BLOCK)!
727
- : this.aztecSlotDuration;
728
-
729
- this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
730
-
731
- const timer = new Timer();
732
- let collectedAttestationsCount: number = 0;
733
- try {
734
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
735
- const attestations = await this.validatorClient.collectAttestations(
736
- proposal,
737
- numberOfRequiredAttestations,
738
- attestationDeadline,
739
- );
740
-
741
- collectedAttestationsCount = attestations.length;
742
-
743
- // note: the smart contract requires that the signatures are provided in the order of the committee
744
- const sorted = orderAttestations(attestations, committee);
745
- if (this.config.injectFakeAttestation) {
746
- const nonEmpty = sorted.filter(a => !a.signature.isEmpty());
747
- const randomIndex = randomInt(nonEmpty.length);
748
- this.log.warn(`Injecting fake attestation in block ${block.number}`);
749
- unfreeze(nonEmpty[randomIndex]).signature = Signature.random();
750
- }
751
- return sorted;
752
- } catch (err) {
753
- if (err && err instanceof AttestationTimeoutError) {
754
- collectedAttestationsCount = err.collectedCount;
755
- }
756
- throw err;
757
- } finally {
758
- this.metrics.recordCollectedAttestations(collectedAttestationsCount, timer.ms());
759
- }
760
- }
761
-
762
- /**
763
- * Publishes the L2Block to the rollup contract.
764
- * @param block - The L2Block to be published.
765
- */
766
- @trackSpan('Sequencer.enqueuePublishL2Block', block => ({
767
- [Attributes.BLOCK_NUMBER]: block.number,
768
- }))
769
- protected async enqueuePublishL2Block(
770
- block: L2Block,
771
- attestationsAndSigners: CommitteeAttestationsAndSigners,
772
- attestationsAndSignersSignature: Signature,
773
- invalidateBlock: InvalidateBlockRequest | undefined,
774
- publisher: SequencerPublisher,
775
- ): Promise<void> {
776
- // Publishes new block to the network and awaits the tx to be mined
777
- this.setState(SequencerState.PUBLISHING_BLOCK, block.header.globalVariables.slotNumber.toBigInt());
778
-
779
- // Time out tx at the end of the slot
780
- const slot = block.header.globalVariables.slotNumber.toNumber();
781
- const txTimeoutAt = new Date((this.getSlotStartBuildTimestamp(slot) + this.aztecSlotDuration) * 1000);
782
-
783
- const enqueued = await publisher.enqueueProposeL2Block(
784
- block,
785
- attestationsAndSigners,
786
- attestationsAndSignersSignature,
787
- {
788
- txTimeoutAt,
789
- forcePendingBlockNumber: invalidateBlock?.forcePendingBlockNumber,
790
- },
791
- );
792
-
793
- if (!enqueued) {
794
- throw new Error(`Failed to enqueue publish of block ${block.number}`);
832
+ this.emit('state-changed', {
833
+ oldState,
834
+ newState: proposedState,
835
+ secondsIntoBuildFrame,
836
+ targetSlot: slotNumber,
837
+ });
838
+ if (stateChanged) {
839
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
840
+ this.stateEnteredAtMs = transitionAtMs;
841
+ this.stateSlotNumber = slotNumber;
795
842
  }
843
+ this.state = proposedState;
796
844
  }
797
845
 
798
846
  /**
799
847
  * Returns whether all dependencies have caught up.
800
848
  * We don't check against the previous block submitted since it may have been reorg'd out.
801
849
  */
802
- protected async checkSync(args: { ts: bigint; slot: bigint }): Promise<
803
- | {
804
- block?: L2Block;
805
- blockNumber: number;
806
- archive: Fr;
807
- l1Timestamp: bigint;
808
- pendingChainValidationStatus: ValidateBlockResult;
809
- }
810
- | undefined
811
- > {
812
- // Check that the archiver and dependencies have synced to the previous L1 slot at least
813
- // TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
814
- // cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
815
- const l1Timestamp = await this.l2BlockSource.getL1Timestamp();
816
- const { slot, ts } = args;
817
- if (l1Timestamp === undefined || l1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration) < ts) {
850
+ protected async checkSync(args: { ts: bigint; slot: SlotNumber }): Promise<SequencerSyncCheckResult | undefined> {
851
+ // Check that the archiver has fully synced the L2 slot before the one we want to propose in.
852
+ // The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
853
+ // See getSyncedL2SlotNumber for how missed L1 blocks are handled.
854
+ const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
855
+ const { slot } = args;
856
+ if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
818
857
  this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
819
858
  slot,
820
- ts,
821
- l1Timestamp,
859
+ syncedL2Slot,
822
860
  });
823
861
  return undefined;
824
862
  }
@@ -828,111 +866,117 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
828
866
  number: syncSummary.latestBlockNumber,
829
867
  hash: syncSummary.latestBlockHash,
830
868
  })),
831
- this.l2BlockSource.getL2Tips().then(t => t.latest),
869
+ this.l2BlockSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
832
870
  this.p2pClient.getStatus().then(p2p => p2p.syncedToL2Block),
833
- this.l1ToL2MessageSource.getL2Tips().then(t => t.latest),
871
+ this.l1ToL2MessageSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
834
872
  this.l2BlockSource.getPendingChainValidationStatus(),
873
+ this.l2BlockSource.getProposedCheckpointData(),
835
874
  ] as const);
836
875
 
837
- const [worldState, l2BlockSource, p2p, l1ToL2MessageSource, pendingChainValidationStatus] = syncedBlocks;
876
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] =
877
+ syncedBlocks;
838
878
 
839
- // The archiver reports 'undefined' hash for the genesis block
840
- // because it doesn't have access to world state to compute it (facepalm)
841
879
  const result =
842
- l2BlockSource.hash === undefined
843
- ? worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSource.number === 0
844
- : worldState.hash === l2BlockSource.hash &&
845
- p2p.hash === l2BlockSource.hash &&
846
- l1ToL2MessageSource.hash === l2BlockSource.hash;
880
+ worldState.hash === l2Tips.proposed.hash &&
881
+ p2p.hash === l2Tips.proposed.hash &&
882
+ l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash &&
883
+ l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash &&
884
+ l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
847
885
 
848
886
  if (!result) {
849
- this.log.debug(`Sequencer sync check failed`, { worldState, l2BlockSource, p2p, l1ToL2MessageSource });
887
+ this.log.debug(`Sequencer sync check failed`, {
888
+ worldState,
889
+ l2BlockSource: l2Tips.proposed,
890
+ p2p,
891
+ l1ToL2MessageSourceTips,
892
+ });
850
893
  return undefined;
851
894
  }
852
895
 
853
- // Special case for genesis state
854
896
  const blockNumber = worldState.number;
855
- if (blockNumber < INITIAL_L2_BLOCK_NUM) {
856
- const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
857
- return { blockNumber: INITIAL_L2_BLOCK_NUM - 1, archive, l1Timestamp, pendingChainValidationStatus };
897
+ const blockData = await this.l2BlockSource.getBlockData({ number: blockNumber });
898
+ if (!blockData) {
899
+ this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
900
+ blockNumber,
901
+ l2Tips,
902
+ syncedL2Slot,
903
+ ...args,
904
+ });
905
+ return undefined;
858
906
  }
859
907
 
860
- const block = await this.l2BlockSource.getBlock(blockNumber);
861
- if (!block) {
862
- // this shouldn't really happen because a moment ago we checked that all components were in sync
863
- this.log.error(`Failed to get L2 block ${blockNumber} from the archiver with all components in sync`);
908
+ // Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
909
+ // proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
910
+ // our world-state tip past the checkpointed tip while the proposing node never published the
911
+ // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
912
+ // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
913
+ // once their build slot ends; this guard is the correctness barrier during the grace window before.
914
+ // `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
915
+ // the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
916
+ // on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
917
+ if (
918
+ blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number &&
919
+ proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber
920
+ ) {
921
+ const logCtx = {
922
+ blockCheckpointNumber: blockData.checkpointNumber,
923
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
924
+ proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
925
+ blockNumber: blockData.header.getBlockNumber(),
926
+ blockSlot: blockData.header.getSlot(),
927
+ syncedL2Slot,
928
+ ...args,
929
+ };
930
+
931
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
932
+ return undefined;
933
+ }
934
+
935
+ const hasProposedCheckpoint = proposedCheckpointData !== undefined;
936
+
937
+ // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
938
+ // The checkpoint number to build is derived as blockData.checkpointNumber + 1
939
+ if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
940
+ this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
941
+ proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
942
+ blockCheckpointNumber: blockData.checkpointNumber,
943
+ syncedL2Slot,
944
+ ...args,
945
+ });
864
946
  return undefined;
865
947
  }
866
948
 
867
949
  return {
868
- block,
869
- blockNumber: block.number,
870
- archive: block.archive.root,
871
- l1Timestamp,
950
+ blockData,
951
+ blockNumber: blockData.header.getBlockNumber(),
952
+ checkpointNumber: blockData.checkpointNumber,
953
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
954
+ archive: blockData.archive.root,
955
+ hasProposedCheckpoint,
956
+ proposedCheckpointData,
957
+ syncedL2Slot,
872
958
  pendingChainValidationStatus,
873
959
  };
874
960
  }
875
961
 
876
- /**
877
- * Enqueues governance and slashing votes with the publisher. Does not block.
878
- * @param publisher - The publisher to enqueue votes with
879
- * @param attestorAddress - The attestor address to use for signing
880
- * @param slot - The slot number
881
- * @param timestamp - The timestamp for the votes
882
- * @param context - Optional context for logging (e.g., block number)
883
- * @returns A tuple of [governanceEnqueued, slashingEnqueued]
884
- */
885
- protected enqueueGovernanceAndSlashingVotes(
886
- publisher: SequencerPublisher,
887
- attestorAddress: EthAddress,
888
- slot: bigint,
889
- timestamp: bigint,
890
- ): [Promise<boolean> | undefined, Promise<boolean> | undefined] {
891
- try {
892
- const signerFn = (msg: TypedDataDefinition) =>
893
- this.validatorClient!.signWithAddress(attestorAddress, msg).then(s => s.toString());
894
-
895
- const enqueueGovernancePromise =
896
- this.governanceProposerPayload && !this.governanceProposerPayload.isZero()
897
- ? publisher
898
- .enqueueGovernanceCastSignal(this.governanceProposerPayload, slot, timestamp, attestorAddress, signerFn)
899
- .catch(err => {
900
- this.log.error(`Error enqueuing governance vote`, err, { slot });
901
- return false;
902
- })
903
- : undefined;
904
-
905
- const enqueueSlashingPromise = this.slasherClient
906
- ? this.slasherClient
907
- .getProposerActions(slot)
908
- .then(actions => publisher.enqueueSlashingActions(actions, slot, timestamp, attestorAddress, signerFn))
909
- .catch(err => {
910
- this.log.error(`Error enqueuing slashing actions`, err, { slot });
911
- return false;
912
- })
913
- : undefined;
914
-
915
- return [enqueueGovernancePromise, enqueueSlashingPromise];
916
- } catch (err) {
917
- this.log.error(`Error enqueueing governance and slashing votes`, err);
918
- return [undefined, undefined];
919
- }
920
- }
921
-
922
962
  /**
923
963
  * Checks if we are the proposer for the next slot.
924
964
  * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
925
965
  */
926
- protected async checkCanPropose(slot: bigint): Promise<[boolean, EthAddress | undefined]> {
966
+ protected async checkCanPropose(targetSlot: SlotNumber): Promise<[boolean, EthAddress | undefined]> {
927
967
  let proposer: EthAddress | undefined;
968
+
928
969
  try {
929
- proposer = await this.epochCache.getProposerAttesterAddressInSlot(slot);
970
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
930
971
  } catch (e) {
931
972
  if (e instanceof NoCommitteeError) {
932
- this.log.warn(`Cannot propose at next L2 slot ${slot} since the committee does not exist on L1`);
973
+ if (this.lastSlotForNoCommitteeWarning !== targetSlot) {
974
+ this.lastSlotForNoCommitteeWarning = targetSlot;
975
+ this.log.warn(`Cannot propose at target slot ${targetSlot} since the committee does not exist on L1`);
976
+ }
933
977
  return [false, undefined];
934
978
  }
935
- this.log.error(`Error getting proposer for slot ${slot}`, e);
979
+ this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
936
980
  return [false, undefined];
937
981
  }
938
982
 
@@ -940,59 +984,65 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
940
984
  if (proposer === undefined) {
941
985
  return [true, undefined];
942
986
  }
987
+ // In fisherman mode, just return the current proposer
988
+ if (this.config.fishermanMode) {
989
+ return [true, proposer];
990
+ }
943
991
 
944
- const validatorAddresses = this.validatorClient!.getValidatorAddresses();
992
+ const validatorAddresses = this.validatorClient.getValidatorAddresses();
945
993
  const weAreProposer = validatorAddresses.some(addr => addr.equals(proposer));
946
994
 
947
995
  if (!weAreProposer) {
948
- this.log.debug(`Cannot propose at slot ${slot} since we are not a proposer`, { validatorAddresses, proposer });
996
+ this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
997
+ targetSlot,
998
+ validatorAddresses,
999
+ proposer,
1000
+ });
949
1001
  return [false, proposer];
950
1002
  }
951
1003
 
1004
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
1005
+ targetSlot,
1006
+ proposer,
1007
+ });
952
1008
  return [true, proposer];
953
1009
  }
954
1010
 
955
1011
  /**
956
- * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
957
- * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
1012
+ * Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
1013
+ * block-building window. This allows the sequencer to participate in governance/slashing votes even when it
1014
+ * cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
958
1015
  */
959
- protected async tryVoteWhenSyncFails(args: { slot: bigint; ts: bigint }): Promise<void> {
960
- const { slot, ts } = args;
1016
+ @trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
1017
+ protected async tryVoteAndPruneWhenCannotBuild(args: { slot: SlotNumber; targetSlot: SlotNumber }): Promise<void> {
1018
+ const { slot, targetSlot } = args;
961
1019
 
962
1020
  // Prevent duplicate attempts in the same slot
963
- if (this.lastSlotForVoteWhenSyncFailed === slot) {
964
- this.log.debug(`Already attempted to vote in slot ${slot} (skipping)`);
1021
+ if (this.lastSlotForFallbackAction === slot) {
1022
+ this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
965
1023
  return;
966
1024
  }
967
1025
 
968
- // Check if we're past the max time for initializing a proposal
969
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
970
- const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_PROPOSAL);
971
-
972
- // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
973
- // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
974
- if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
975
- this.log.trace(`Not attempting to vote since there is still for block building`, {
976
- secondsIntoSlot,
977
- maxAllowedTime,
978
- });
979
- return;
980
- }
1026
+ // Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
1027
+ // Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
1028
+ // build-start deadline can miss the whole fallback window when the target advances with the clock.
1029
+ const nowSeconds = this.dateProvider.now() / 1000;
1030
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
981
1031
 
982
- this.log.debug(`Sync for slot ${slot} failed, checking for voting opportunities`, {
983
- secondsIntoSlot,
984
- maxAllowedTime,
1032
+ this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
1033
+ nowSeconds,
1034
+ startDeadline,
985
1035
  });
986
1036
 
987
1037
  // Check if we're a proposer or proposal is open
988
- const [canPropose, proposer] = await this.checkCanPropose(slot);
1038
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
989
1039
  if (!canPropose) {
990
- this.log.debug(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
1040
+ this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
991
1041
  return;
992
1042
  }
993
1043
 
994
1044
  // Mark this slot as attempted
995
- this.lastSlotForVoteWhenSyncFailed = slot;
1045
+ this.lastSlotForFallbackAction = slot;
996
1046
 
997
1047
  // Get a publisher for voting
998
1048
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
@@ -1002,17 +1052,122 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1002
1052
  slot,
1003
1053
  });
1004
1054
 
1005
- // Enqueue governance and slashing votes using the shared helper method
1006
- const votesPromises = this.enqueueGovernanceAndSlashingVotes(publisher, attestorAddress, slot, ts);
1007
- await Promise.all(votesPromises);
1055
+ // Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
1056
+ const voter = new CheckpointVoter(
1057
+ targetSlot,
1058
+ publisher,
1059
+ attestorAddress,
1060
+ this.validatorClient,
1061
+ this.slasherClient,
1062
+ this.l1Constants,
1063
+ this.config,
1064
+ this.metrics,
1065
+ this.log,
1066
+ );
1067
+ const votesPromises = voter.enqueueVotes();
1068
+ const votes = await Promise.all(votesPromises);
1069
+
1070
+ // Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
1071
+ // recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
1072
+ const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
1073
+
1074
+ // Bail if nothing to do
1075
+ if (votes.every(p => !p) && !pruneEnqueued) {
1076
+ this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
1077
+ return;
1078
+ }
1079
+
1080
+ const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
1081
+ this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
1082
+ slot,
1083
+ pruneEnqueued,
1084
+ governanceVoteEnqueued: !!governanceVoteEnqueued,
1085
+ slashingVoteEnqueued: !!slashingVoteEnqueued,
1086
+ });
1087
+
1088
+ // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
1089
+ // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
1090
+ // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
1091
+ // work loop while waiting for the target slot to start, but track it so stop() can drain it.
1092
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1093
+ this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, { slot });
1094
+ });
1095
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
1096
+ }
1097
+
1098
+ private async tryEnqueuePruneIfPrunable(targetSlot: SlotNumber, publisher: SequencerPublisher): Promise<boolean> {
1099
+ try {
1100
+ return await publisher.enqueuePruneIfPrunable(targetSlot);
1101
+ } catch (err) {
1102
+ this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, { targetSlot });
1103
+ return false;
1104
+ }
1105
+ }
1106
+
1107
+ /**
1108
+ * Tries to vote on slashing actions and governance proposals when escape hatch is open.
1109
+ * This allows the sequencer to participate in voting without performing checkpoint proposal work.
1110
+ */
1111
+ @trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
1112
+ protected async tryVoteWhenEscapeHatchOpen(args: {
1113
+ slot: SlotNumber;
1114
+ targetSlot: SlotNumber;
1115
+ proposer: EthAddress | undefined;
1116
+ }): Promise<void> {
1117
+ const { slot, targetSlot, proposer } = args;
1118
+
1119
+ // Prevent duplicate attempts in the same slot
1120
+ if (this.lastSlotForFallbackAction === slot) {
1121
+ this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
1122
+ return;
1123
+ }
1124
+
1125
+ // Mark this slot as attempted
1126
+ this.lastSlotForFallbackAction = slot;
1127
+
1128
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
1129
+
1130
+ this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
1131
+ slot,
1132
+ targetSlot,
1133
+ attestorAddress,
1134
+ });
1135
+
1136
+ // Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
1137
+ // Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
1138
+ // L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
1139
+ // sign for `targetSlot` and delay submission to the start of `targetSlot`.
1140
+ const voter = new CheckpointVoter(
1141
+ targetSlot,
1142
+ publisher,
1143
+ attestorAddress,
1144
+ this.validatorClient,
1145
+ this.slasherClient,
1146
+ this.l1Constants,
1147
+ this.config,
1148
+ this.metrics,
1149
+ this.log,
1150
+ );
1008
1151
 
1009
- if (votesPromises.every(p => !p)) {
1010
- this.log.debug(`No votes to enqueue for slot ${slot}`);
1152
+ const votesPromises = voter.enqueueVotes();
1153
+ const votes = await Promise.all(votesPromises);
1154
+
1155
+ if (votes.every(p => !p)) {
1156
+ this.log.debug(`No votes to enqueue for slot ${slot} (escape hatch open)`);
1011
1157
  return;
1012
1158
  }
1013
1159
 
1014
- this.log.info(`Voting in slot ${slot} despite sync failure`, { slot });
1015
- await publisher.sendRequests();
1160
+ this.log.info(`Voting in slot ${slot} (escape hatch open)`, { slot, targetSlot });
1161
+ // Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
1162
+ // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1163
+ // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1164
+ // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1165
+ // waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
1166
+ // stop() can drain it.
1167
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1168
+ this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, { slot, targetSlot });
1169
+ });
1170
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
1016
1171
  }
1017
1172
 
1018
1173
  /**
@@ -1020,29 +1175,44 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1020
1175
  * has been there without being invalidated and whether the sequencer is in the committee or not. We always
1021
1176
  * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
1022
1177
  * and if they fail, any sequencer will try as well.
1178
+ * @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
1179
+ * @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
1023
1180
  */
1024
- protected async considerInvalidatingBlock(
1025
- syncedTo: NonNullable<Awaited<ReturnType<Sequencer['checkSync']>>>,
1026
- currentSlot: bigint,
1181
+ protected async considerInvalidatingCheckpoint(
1182
+ pendingChainValidationStatus: ValidateCheckpointResult,
1183
+ currentSlot: SlotNumber,
1027
1184
  ): Promise<void> {
1028
- const { pendingChainValidationStatus, l1Timestamp } = syncedTo;
1029
1185
  if (pendingChainValidationStatus.valid) {
1030
1186
  return;
1031
1187
  }
1032
1188
 
1033
- const { publisher } = await this.publisherFactory.create(undefined);
1034
- const invalidBlockNumber = pendingChainValidationStatus.block.blockNumber;
1035
- const invalidBlockTimestamp = pendingChainValidationStatus.block.timestamp;
1036
- const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidBlockTimestamp);
1037
- const ourValidatorAddresses = this.validatorClient!.getValidatorAddresses();
1189
+ const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1190
+
1191
+ // Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
1192
+ // The guard is keyed by (checkpoint, slot) so a different invalid checkpoint surfacing later in
1193
+ // the same slot is not suppressed — and is set only after a request is successfully simulated below,
1194
+ // so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
1195
+ if (
1196
+ this.lastInvalidationAttempt?.slot === currentSlot &&
1197
+ this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber
1198
+ ) {
1199
+ this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
1200
+ currentSlot,
1201
+ invalidCheckpointNumber,
1202
+ });
1203
+ return;
1204
+ }
1205
+
1206
+ const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
1207
+ const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
1208
+ const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
1038
1209
 
1039
1210
  const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } =
1040
1211
  this.config;
1041
1212
 
1042
1213
  const logData = {
1043
- invalidL1Timestamp: invalidBlockTimestamp,
1044
- l1Timestamp,
1045
- invalidBlock: pendingChainValidationStatus.block,
1214
+ invalidL1Timestamp: invalidCheckpointTimestamp,
1215
+ invalidCheckpoint: pendingChainValidationStatus.checkpoint,
1046
1216
  secondsBeforeInvalidatingBlockAsCommitteeMember,
1047
1217
  secondsBeforeInvalidatingBlockAsNonCommitteeMember,
1048
1218
  ourValidatorAddresses,
@@ -1070,41 +1240,127 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1070
1240
  return;
1071
1241
  }
1072
1242
 
1073
- const invalidateBlock = await publisher.simulateInvalidateBlock(pendingChainValidationStatus);
1074
- if (!invalidateBlock) {
1075
- this.log.warn(`Failed to simulate invalidate block`, logData);
1243
+ let validatorToUse: EthAddress;
1244
+ if (invalidateAsCommitteeMember) {
1245
+ // When invalidating as a committee member, use first validator that's actually in the committee
1246
+ const { committee } = await this.epochCache.getCommittee(currentSlot);
1247
+ if (committee) {
1248
+ const committeeSet = new Set(committee.map(addr => addr.toString()));
1249
+ validatorToUse =
1250
+ ourValidatorAddresses.find(addr => committeeSet.has(addr.toString())) ?? ourValidatorAddresses[0];
1251
+ } else {
1252
+ validatorToUse = ourValidatorAddresses[0];
1253
+ }
1254
+ } else {
1255
+ // When invalidating as a non-committee member, use the first validator
1256
+ validatorToUse = ourValidatorAddresses[0];
1257
+ }
1258
+
1259
+ const { publisher } = await this.publisherFactory.create(validatorToUse);
1260
+
1261
+ const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(pendingChainValidationStatus);
1262
+ if (!invalidateCheckpoint) {
1263
+ this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
1076
1264
  return;
1077
1265
  }
1078
1266
 
1267
+ // We produced a valid invalidation request; record it so further ticks within this slot skip the
1268
+ // committee lookup, simulation, and submission above for this same invalid checkpoint.
1269
+ this.lastInvalidationAttempt = { slot: currentSlot, checkpointNumber: invalidCheckpointNumber };
1270
+
1079
1271
  this.log.info(
1080
1272
  invalidateAsCommitteeMember
1081
- ? `Invalidating block ${invalidBlockNumber} as committee member`
1082
- : `Invalidating block ${invalidBlockNumber} as non-committee member`,
1273
+ ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member`
1274
+ : `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`,
1083
1275
  logData,
1084
1276
  );
1085
1277
 
1086
- publisher.enqueueInvalidateBlock(invalidateBlock);
1087
- await publisher.sendRequests();
1278
+ publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
1279
+
1280
+ if (!this.config.fishermanMode) {
1281
+ await publisher.sendRequests();
1282
+ } else {
1283
+ this.log.info('Invalidating checkpoint in fisherman mode, clearing pending requests');
1284
+ publisher.clearPendingRequests();
1285
+ }
1088
1286
  }
1089
1287
 
1090
- private getSlotStartBuildTimestamp(slotNumber: number | bigint): number {
1091
- return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
1288
+ private logStrategyComparison(epoch: EpochNumber, publisher: SequencerPublisher): void {
1289
+ const feeAnalyzer = publisher.getL1FeeAnalyzer();
1290
+ if (!feeAnalyzer) {
1291
+ return;
1292
+ }
1293
+
1294
+ const comparison = feeAnalyzer.getStrategyComparison();
1295
+ if (comparison.length === 0) {
1296
+ this.log.debug(`No strategy data available yet for epoch ${epoch}`);
1297
+ return;
1298
+ }
1299
+
1300
+ this.log.info(`L1 Fee Strategy Performance Report - End of Epoch ${epoch}`, {
1301
+ epoch: Number(epoch),
1302
+ totalAnalyses: comparison[0]?.totalAnalyses,
1303
+ strategies: comparison.map(s => ({
1304
+ id: s.strategyId,
1305
+ name: s.strategyName,
1306
+ inclusionRate: `${(s.inclusionRate * 100).toFixed(1)}%`,
1307
+ inclusionCount: `${s.inclusionCount}/${s.totalAnalyses}`,
1308
+ avgCostEth: s.avgEstimatedCostEth.toFixed(6),
1309
+ totalCostEth: s.totalEstimatedCostEth.toFixed(6),
1310
+ avgOverpaymentEth: s.avgOverpaymentEth.toFixed(6),
1311
+ totalOverpaymentEth: s.totalOverpaymentEth.toFixed(6),
1312
+ avgPriorityFeeDeltaGwei: s.avgPriorityFeeDeltaGwei.toFixed(2),
1313
+ })),
1314
+ });
1092
1315
  }
1093
1316
 
1094
- private getSecondsIntoSlot(slotNumber: number | bigint): number {
1095
- const slotStartTimestamp = this.getSlotStartBuildTimestamp(slotNumber);
1096
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1317
+ /**
1318
+ * Wall-clock seconds elapsed since the build-frame start of the given target slot
1319
+ * (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
1320
+ */
1321
+ private getSecondsIntoBuildFrame(targetSlot: SlotNumber): number {
1322
+ const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
1323
+ return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
1097
1324
  }
1098
1325
 
1099
- get aztecSlotDuration() {
1326
+ public get aztecSlotDuration() {
1100
1327
  return this.l1Constants.slotDuration;
1101
1328
  }
1102
1329
 
1103
- get maxL2BlockGas(): number | undefined {
1330
+ public get maxL2BlockGas(): number | undefined {
1104
1331
  return this.config.maxL2BlockGas;
1105
1332
  }
1106
1333
 
1107
1334
  public getSlasherClient(): SlasherClientInterface | undefined {
1108
1335
  return this.slasherClient;
1109
1336
  }
1337
+
1338
+ public get tracer(): Tracer {
1339
+ return this.metrics.tracer;
1340
+ }
1341
+
1342
+ public getValidatorAddresses() {
1343
+ return this.validatorClient?.getValidatorAddresses();
1344
+ }
1345
+
1346
+ /** Updates the publisher factory's node keystore adapter after a keystore reload. */
1347
+ public updatePublisherNodeKeyStore(adapter: NodeKeystoreAdapter): void {
1348
+ this.publisherFactory.updateNodeKeyStore(adapter);
1349
+ }
1350
+
1351
+ public getConfig() {
1352
+ return this.config;
1353
+ }
1110
1354
  }
1355
+
1356
+ type SequencerSyncCheckResult = {
1357
+ blockData?: BlockData;
1358
+ checkpointNumber: CheckpointNumber;
1359
+ checkpointedCheckpointNumber: CheckpointNumber;
1360
+ blockNumber: BlockNumber;
1361
+ archive: Fr;
1362
+ hasProposedCheckpoint: boolean;
1363
+ proposedCheckpointData?: ProposedCheckpointData;
1364
+ syncedL2Slot: SlotNumber;
1365
+ pendingChainValidationStatus: ValidateCheckpointResult;
1366
+ };