@aztec/sequencer-client 3.0.3 → 4.0.0-devnet.1-patch.1

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 (93) hide show
  1. package/dest/client/sequencer-client.d.ts +11 -11
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +29 -25
  4. package/dest/config.d.ts +7 -2
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +66 -28
  7. package/dest/global_variable_builder/global_builder.d.ts +19 -11
  8. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  9. package/dest/global_variable_builder/global_builder.js +48 -39
  10. package/dest/index.d.ts +2 -3
  11. package/dest/index.d.ts.map +1 -1
  12. package/dest/index.js +1 -2
  13. package/dest/publisher/config.d.ts +3 -3
  14. package/dest/publisher/config.d.ts.map +1 -1
  15. package/dest/publisher/config.js +2 -2
  16. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -3
  17. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  18. package/dest/publisher/sequencer-publisher-factory.js +1 -1
  19. package/dest/publisher/sequencer-publisher-metrics.d.ts +3 -3
  20. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  21. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  22. package/dest/publisher/sequencer-publisher.d.ts +43 -39
  23. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  24. package/dest/publisher/sequencer-publisher.js +599 -130
  25. package/dest/sequencer/checkpoint_proposal_job.d.ts +102 -0
  26. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  27. package/dest/sequencer/checkpoint_proposal_job.js +1191 -0
  28. package/dest/sequencer/checkpoint_voter.d.ts +35 -0
  29. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  30. package/dest/sequencer/checkpoint_voter.js +109 -0
  31. package/dest/sequencer/events.d.ts +46 -0
  32. package/dest/sequencer/events.d.ts.map +1 -0
  33. package/dest/sequencer/events.js +1 -0
  34. package/dest/sequencer/index.d.ts +4 -2
  35. package/dest/sequencer/index.d.ts.map +1 -1
  36. package/dest/sequencer/index.js +3 -1
  37. package/dest/sequencer/metrics.d.ts +22 -2
  38. package/dest/sequencer/metrics.d.ts.map +1 -1
  39. package/dest/sequencer/metrics.js +143 -70
  40. package/dest/sequencer/sequencer.d.ts +107 -129
  41. package/dest/sequencer/sequencer.d.ts.map +1 -1
  42. package/dest/sequencer/sequencer.js +677 -603
  43. package/dest/sequencer/timetable.d.ts +51 -14
  44. package/dest/sequencer/timetable.d.ts.map +1 -1
  45. package/dest/sequencer/timetable.js +145 -59
  46. package/dest/sequencer/types.d.ts +3 -0
  47. package/dest/sequencer/types.d.ts.map +1 -0
  48. package/dest/sequencer/types.js +1 -0
  49. package/dest/sequencer/utils.d.ts +14 -8
  50. package/dest/sequencer/utils.d.ts.map +1 -1
  51. package/dest/sequencer/utils.js +7 -4
  52. package/dest/test/index.d.ts +3 -2
  53. package/dest/test/index.d.ts.map +1 -1
  54. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  55. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  56. package/dest/test/mock_checkpoint_builder.js +220 -0
  57. package/dest/test/utils.d.ts +53 -0
  58. package/dest/test/utils.d.ts.map +1 -0
  59. package/dest/test/utils.js +103 -0
  60. package/package.json +30 -28
  61. package/src/client/sequencer-client.ts +27 -35
  62. package/src/config.ts +73 -27
  63. package/src/global_variable_builder/global_builder.ts +57 -51
  64. package/src/index.ts +1 -7
  65. package/src/publisher/config.ts +3 -3
  66. package/src/publisher/sequencer-publisher-factory.ts +3 -3
  67. package/src/publisher/sequencer-publisher-metrics.ts +19 -71
  68. package/src/publisher/sequencer-publisher.ts +284 -161
  69. package/src/sequencer/README.md +531 -0
  70. package/src/sequencer/checkpoint_proposal_job.ts +877 -0
  71. package/src/sequencer/checkpoint_voter.ts +130 -0
  72. package/src/sequencer/events.ts +27 -0
  73. package/src/sequencer/index.ts +3 -1
  74. package/src/sequencer/metrics.ts +189 -77
  75. package/src/sequencer/sequencer.ts +416 -805
  76. package/src/sequencer/timetable.ts +175 -80
  77. package/src/sequencer/types.ts +6 -0
  78. package/src/sequencer/utils.ts +18 -9
  79. package/src/test/index.ts +2 -1
  80. package/src/test/mock_checkpoint_builder.ts +309 -0
  81. package/src/test/utils.ts +164 -0
  82. package/dest/sequencer/block_builder.d.ts +0 -28
  83. package/dest/sequencer/block_builder.d.ts.map +0 -1
  84. package/dest/sequencer/block_builder.js +0 -127
  85. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  86. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  87. package/dest/tx_validator/nullifier_cache.js +0 -24
  88. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  89. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  90. package/dest/tx_validator/tx_validator_factory.js +0 -53
  91. package/src/sequencer/block_builder.ts +0 -214
  92. package/src/tx_validator/nullifier_cache.ts +0 -30
  93. package/src/tx_validator/tx_validator_factory.ts +0 -133
@@ -1,245 +1,158 @@
1
- import { L2Block } from '@aztec/aztec.js/block';
2
1
  import { getKzg } from '@aztec/blob-lib';
3
- import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
4
3
  import type { EpochCache } from '@aztec/epoch-cache';
5
4
  import { NoCommitteeError, type RollupContract } from '@aztec/ethereum/contracts';
6
- import { FormattedViemError } from '@aztec/ethereum/utils';
7
5
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
8
- import { omit, pick } from '@aztec/foundation/collection';
9
- import { randomInt } from '@aztec/foundation/crypto/random';
6
+ import { merge, omit, pick } from '@aztec/foundation/collection';
10
7
  import { Fr } from '@aztec/foundation/curves/bn254';
11
8
  import { EthAddress } from '@aztec/foundation/eth-address';
12
- import { Signature } from '@aztec/foundation/eth-signature';
13
9
  import { createLogger } from '@aztec/foundation/log';
14
10
  import { RunningPromise } from '@aztec/foundation/running-promise';
15
- import { type DateProvider, Timer } from '@aztec/foundation/timer';
16
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
11
+ import type { DateProvider } from '@aztec/foundation/timer';
12
+ import type { TypedEventEmitter } from '@aztec/foundation/types';
17
13
  import type { P2P } from '@aztec/p2p';
18
14
  import type { SlasherClientInterface } from '@aztec/slasher';
15
+ import type { L2Block, L2BlockSink, L2BlockSource, ValidateCheckpointResult } from '@aztec/stdlib/block';
16
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
17
+ import { getSlotAtTimestamp, getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
19
18
  import {
20
- CommitteeAttestation,
21
- CommitteeAttestationsAndSigners,
22
- type L2BlockSource,
23
- MaliciousCommitteeAttestationsAndSigners,
24
- type ValidateBlockResult,
25
- } from '@aztec/stdlib/block';
26
- import { type L1RollupConstants, getSlotAtTimestamp, getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
27
- import { Gas } from '@aztec/stdlib/gas';
28
- import {
29
- type IFullNodeBlockBuilder,
30
- type PublicProcessorLimits,
19
+ type ResolvedSequencerConfig,
20
+ type SequencerConfig,
31
21
  SequencerConfigSchema,
32
22
  type WorldStateSynchronizer,
33
23
  } from '@aztec/stdlib/interfaces/server';
34
24
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
35
- import type { BlockProposalOptions } from '@aztec/stdlib/p2p';
36
- import { orderAttestations } from '@aztec/stdlib/p2p';
37
- import { CheckpointHeader } from '@aztec/stdlib/rollup';
38
25
  import { pickFromSchema } from '@aztec/stdlib/schemas';
39
- import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
40
26
  import { MerkleTreeId } from '@aztec/stdlib/trees';
41
- import { ContentCommitment, type FailedTx, GlobalVariables, Tx } from '@aztec/stdlib/tx';
42
- import { AttestationTimeoutError } from '@aztec/stdlib/validators';
43
27
  import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
44
- import type { ValidatorClient } from '@aztec/validator-client';
28
+ import { FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec/validator-client';
45
29
 
46
30
  import EventEmitter from 'node:events';
47
- import type { TypedDataDefinition } from 'viem';
48
31
 
32
+ import { DefaultSequencerConfig } from '../config.js';
49
33
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
50
34
  import type { SequencerPublisherFactory } from '../publisher/sequencer-publisher-factory.js';
51
- import type { Action, InvalidateBlockRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
52
- import type { SequencerConfig } from './config.js';
35
+ import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
36
+ import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
37
+ import { CheckpointVoter } from './checkpoint_voter.js';
53
38
  import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
39
+ import type { SequencerEvents } from './events.js';
54
40
  import { SequencerMetrics } from './metrics.js';
55
41
  import { SequencerTimetable } from './timetable.js';
56
- import { SequencerState, type SequencerStateWithSlot } from './utils.js';
42
+ import type { SequencerRollupConstants } from './types.js';
43
+ import { SequencerState } from './utils.js';
57
44
 
58
45
  export { SequencerState };
59
46
 
60
- type SequencerRollupConstants = Pick<L1RollupConstants, 'ethereumSlotDuration' | 'l1GenesisTime' | 'slotDuration'>;
61
-
62
- export type SequencerEvents = {
63
- ['state-changed']: (args: {
64
- oldState: SequencerState;
65
- newState: SequencerState;
66
- secondsIntoSlot?: number;
67
- slotNumber?: SlotNumber;
68
- }) => void;
69
- ['proposer-rollup-check-failed']: (args: { reason: string }) => void;
70
- ['tx-count-check-failed']: (args: { minTxs: number; availableTxs: number }) => void;
71
- ['block-build-failed']: (args: { reason: string }) => void;
72
- ['block-publish-failed']: (args: {
73
- successfulActions?: Action[];
74
- failedActions?: Action[];
75
- sentActions?: Action[];
76
- expiredActions?: Action[];
77
- }) => void;
78
- ['block-published']: (args: { blockNumber: BlockNumber; slot: number }) => void;
79
- };
80
-
81
47
  /**
82
48
  * Sequencer client
83
- * - Wins a period of time to become the sequencer (depending on finalized protocol).
84
- * - Chooses a set of txs from the tx pool to be in the rollup.
85
- * - Simulate the rollup of txs.
86
- * - Adds proof requests to the request pool (not for this milestone).
87
- * - Receives results to those proofs from the network (repeats as necessary) (not for this milestone).
88
- * - Publishes L1 tx(s) to the rollup contract via RollupPublisher.
49
+ * - Checks whether it is elected as proposer for the next slot
50
+ * - Builds multiple blocks and broadcasts them
51
+ * - Collects attestations for the checkpoint
52
+ * - Publishes the checkpoint to L1
53
+ * - Votes for proposals and slashes on L1
89
54
  */
90
55
  export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<SequencerEvents>) {
91
56
  private runningPromise?: RunningPromise;
92
- private pollingIntervalMs: number = 1000;
93
- private maxTxsPerBlock = 32;
94
- private minTxsPerBlock = 1;
95
- private maxL1TxInclusionTimeIntoSlot = 0;
96
57
  private state = SequencerState.STOPPED;
97
- private maxBlockSizeInBytes: number = 1024 * 1024;
98
- private maxBlockGas: Gas = new Gas(100e9, 100e9);
99
58
  private metrics: SequencerMetrics;
100
59
 
101
- private lastBlockPublished: L2Block | undefined;
60
+ /** The last slot for which we attempted to perform our voting duties with degraded block production */
61
+ private lastSlotForFallbackVote: SlotNumber | undefined;
102
62
 
103
- private governanceProposerPayload: EthAddress | undefined;
63
+ /** The last slot for which we logged "no committee" warning, to avoid spam */
64
+ private lastSlotForNoCommitteeWarning: SlotNumber | undefined;
104
65
 
105
- /** The last slot for which we attempted to vote when sync failed, to prevent duplicate attempts. */
106
- private lastSlotForVoteWhenSyncFailed: SlotNumber | undefined;
66
+ /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */
67
+ private lastSlotForCheckpointProposalJob: SlotNumber | undefined;
107
68
 
108
- /** The last slot for which we built a validation block in fisherman mode, to prevent duplicate attempts. */
109
- private lastSlotForValidationBlock: SlotNumber | undefined;
69
+ /** Last successful checkpoint proposed */
70
+ private lastCheckpointProposed: Checkpoint | undefined;
71
+
72
+ /** The last epoch for which we logged strategy comparison in fisherman mode. */
73
+ private lastEpochForStrategyComparison: EpochNumber | undefined;
110
74
 
111
75
  /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */
112
76
  protected timetable!: SequencerTimetable;
113
- protected enforceTimeTable: boolean = false;
114
77
 
115
78
  // This shouldn't be here as this gets re-created each time we build/propose a block.
116
79
  // But we have a number of tests that abuse/rely on this class having a permanent publisher.
117
80
  // As long as those tests only configure a single publisher they will continue to work.
118
81
  // This will get re-assigned every time the sequencer goes to build a new block to a publisher that is valid
119
82
  // for the block proposer.
83
+ // TODO(palla/mbps): Remove this field and fix tests
120
84
  protected publisher: SequencerPublisher | undefined;
121
85
 
86
+ /** Config for the sequencer */
87
+ protected config: ResolvedSequencerConfig = DefaultSequencerConfig;
88
+
122
89
  constructor(
123
90
  protected publisherFactory: SequencerPublisherFactory,
124
- protected validatorClient: ValidatorClient | undefined, // During migration the validator client can be inactive
91
+ protected validatorClient: ValidatorClient,
125
92
  protected globalsBuilder: GlobalVariableBuilder,
126
93
  protected p2pClient: P2P,
127
94
  protected worldState: WorldStateSynchronizer,
128
95
  protected slasherClient: SlasherClientInterface | undefined,
129
- protected l2BlockSource: L2BlockSource,
96
+ protected l2BlockSource: L2BlockSource & L2BlockSink,
130
97
  protected l1ToL2MessageSource: L1ToL2MessageSource,
131
- protected blockBuilder: IFullNodeBlockBuilder,
98
+ protected checkpointsBuilder: FullNodeCheckpointsBuilder,
132
99
  protected l1Constants: SequencerRollupConstants,
133
100
  protected dateProvider: DateProvider,
134
101
  protected epochCache: EpochCache,
135
102
  protected rollupContract: RollupContract,
136
- protected config: SequencerConfig,
103
+ config: SequencerConfig,
137
104
  protected telemetry: TelemetryClient = getTelemetryClient(),
138
105
  protected log = createLogger('sequencer'),
139
106
  ) {
140
107
  super();
141
108
 
142
109
  // Add [FISHERMAN] prefix to logger if in fisherman mode
143
- if (this.config.fishermanMode) {
110
+ if (config.fishermanMode) {
144
111
  this.log = log.createChild('[FISHERMAN]');
145
112
  }
146
113
 
147
114
  this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
148
- // Initialize config
149
- this.updateConfig(this.config);
150
- }
151
-
152
- get tracer(): Tracer {
153
- return this.metrics.tracer;
154
- }
155
-
156
- public getValidatorAddresses() {
157
- return this.validatorClient?.getValidatorAddresses();
158
- }
159
-
160
- public getConfig() {
161
- return this.config;
115
+ this.updateConfig(config);
162
116
  }
163
117
 
164
- /**
165
- * Updates sequencer config by the defined values in the config on input.
166
- * @param config - New parameters.
167
- */
168
- public updateConfig(config: SequencerConfig) {
169
- this.log.info(
170
- `Sequencer config set`,
171
- omit(pickFromSchema(config, SequencerConfigSchema), 'txPublicSetupAllowList'),
172
- );
173
-
174
- if (config.transactionPollingIntervalMS !== undefined) {
175
- this.pollingIntervalMs = config.transactionPollingIntervalMS;
176
- }
177
- if (config.maxTxsPerBlock !== undefined) {
178
- this.maxTxsPerBlock = config.maxTxsPerBlock;
179
- }
180
- if (config.minTxsPerBlock !== undefined) {
181
- this.minTxsPerBlock = config.minTxsPerBlock;
182
- }
183
- if (config.maxDABlockGas !== undefined) {
184
- this.maxBlockGas = new Gas(config.maxDABlockGas, this.maxBlockGas.l2Gas);
185
- }
186
- if (config.maxL2BlockGas !== undefined) {
187
- this.maxBlockGas = new Gas(this.maxBlockGas.daGas, config.maxL2BlockGas);
188
- }
189
- if (config.maxBlockSizeInBytes !== undefined) {
190
- this.maxBlockSizeInBytes = config.maxBlockSizeInBytes;
191
- }
192
- if (config.governanceProposerPayload) {
193
- this.governanceProposerPayload = config.governanceProposerPayload;
194
- }
195
- if (config.maxL1TxInclusionTimeIntoSlot !== undefined) {
196
- this.maxL1TxInclusionTimeIntoSlot = config.maxL1TxInclusionTimeIntoSlot;
197
- }
198
- if (config.enforceTimeTable !== undefined) {
199
- this.enforceTimeTable = config.enforceTimeTable;
200
- }
201
-
202
- this.setTimeTable();
203
-
204
- // TODO: Just read everything from the config object as needed instead of copying everything into local vars.
205
-
206
- // Update all values on this.config that are populated in the config object.
207
- Object.assign(this.config, config);
208
- }
209
-
210
- private setTimeTable() {
118
+ /** Updates sequencer config by the defined values and updates the timetable */
119
+ public updateConfig(config: Partial<SequencerConfig>) {
120
+ const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
121
+ this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowList'));
122
+ this.config = merge(this.config, filteredConfig);
211
123
  this.timetable = new SequencerTimetable(
212
124
  {
213
125
  ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
214
126
  aztecSlotDuration: this.aztecSlotDuration,
215
- maxL1TxInclusionTimeIntoSlot: this.maxL1TxInclusionTimeIntoSlot,
216
- attestationPropagationTime: this.config.attestationPropagationTime,
217
- enforce: this.enforceTimeTable,
127
+ l1PublishingTime: this.l1PublishingTime,
128
+ p2pPropagationTime: this.config.attestationPropagationTime,
129
+ blockDurationMs: this.config.blockDurationMs,
130
+ enforce: this.config.enforceTimeTable,
218
131
  },
219
132
  this.metrics,
220
133
  this.log,
221
134
  );
222
135
  }
223
136
 
137
+ /** Initializes the sequencer (precomputes tables and creates a publisher). Takes about 3s. */
224
138
  public async init() {
225
- // Takes ~3s to precompute some tables.
226
139
  getKzg();
227
140
  this.publisher = (await this.publisherFactory.create(undefined)).publisher;
228
141
  }
229
142
 
230
- /**
231
- * Starts the sequencer and moves to IDLE state.
232
- */
143
+ /** Starts the sequencer and moves to IDLE state. */
233
144
  public start() {
234
- this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.pollingIntervalMs);
145
+ this.runningPromise = new RunningPromise(
146
+ this.safeWork.bind(this),
147
+ this.log,
148
+ this.config.sequencerPollingIntervalMS,
149
+ );
235
150
  this.setState(SequencerState.IDLE, undefined, { force: true });
236
151
  this.runningPromise.start();
237
152
  this.log.info('Started sequencer');
238
153
  }
239
154
 
240
- /**
241
- * Stops the sequencer from processing txs and moves to STOPPED state.
242
- */
155
+ /** Stops the sequencer from building blocks and moves to STOPPED state. */
243
156
  public async stop(): Promise<void> {
244
157
  this.log.info(`Stopping sequencer`);
245
158
  this.setState(SequencerState.STOPPING, undefined, { force: true });
@@ -249,52 +162,140 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
249
162
  this.log.info('Stopped sequencer');
250
163
  }
251
164
 
252
- /**
253
- * Returns the current state of the sequencer.
254
- * @returns An object with a state entry with one of SequencerState.
255
- */
165
+ /** Main sequencer loop with a try/catch */
166
+ protected async safeWork() {
167
+ try {
168
+ await this.work();
169
+ } catch (err) {
170
+ this.emit('checkpoint-error', { error: err as Error });
171
+ if (err instanceof SequencerTooSlowError) {
172
+ // TODO(palla/mbps): Add missing states
173
+ // Log as warn only if we had to abort halfway through the block proposal
174
+ const logLvl = [SequencerState.INITIALIZING_CHECKPOINT, SequencerState.PROPOSER_CHECK].includes(
175
+ err.proposedState,
176
+ )
177
+ ? ('debug' as const)
178
+ : ('warn' as const);
179
+ this.log[logLvl](err.message, { now: this.dateProvider.nowInSeconds() });
180
+ } else {
181
+ // Re-throw other errors
182
+ throw err;
183
+ }
184
+ } finally {
185
+ this.setState(SequencerState.IDLE, undefined);
186
+ }
187
+ }
188
+
189
+ /** Returns the current state of the sequencer. */
256
190
  public status() {
257
191
  return { state: this.state };
258
192
  }
259
193
 
260
194
  /**
261
- * @notice Performs most of the sequencer duties:
262
- * - Checks if we are up to date
263
- * - If we are and we are the sequencer, collect txs and build a block
264
- * - Collect attestations for the block
265
- * - Submit block
266
- * - If our block for some reason is not included, revert the state
195
+ * Main sequencer loop:
196
+ * - Checks if we are up to date
197
+ * - If we are and we are the sequencer, collect txs and build blocks
198
+ * - Build multiple blocks per slot when configured
199
+ * - Collect attestations for the final block
200
+ * - Submit checkpoint
267
201
  */
202
+ @trackSpan('Sequencer.work')
268
203
  protected async work() {
269
204
  this.setState(SequencerState.SYNCHRONIZING, undefined);
270
- const { slot, ts, now } = this.epochCache.getEpochAndSlotInNextL1Slot();
205
+ const { slot, ts, now, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
271
206
 
272
- // Check we have not already published a block for this slot (cheapest check)
273
- if (this.lastBlockPublished && this.lastBlockPublished.header.getSlot() >= slot) {
274
- this.log.debug(
275
- `Cannot propose block at next L2 slot ${slot} since that slot was taken by our own block ${this.lastBlockPublished.number}`,
276
- );
207
+ // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
208
+ const checkpointProposalJob = await this.prepareCheckpointProposal(epoch, slot, ts, now);
209
+ if (!checkpointProposalJob) {
277
210
  return;
278
211
  }
279
212
 
213
+ // Execute the checkpoint proposal job
214
+ const checkpoint = await checkpointProposalJob.execute();
215
+
216
+ // Update last checkpoint proposed (currently unused)
217
+ if (checkpoint) {
218
+ this.lastCheckpointProposed = checkpoint;
219
+ }
220
+
221
+ // Log fee strategy comparison if on fisherman
222
+ if (
223
+ this.config.fishermanMode &&
224
+ (this.lastEpochForStrategyComparison === undefined || epoch > this.lastEpochForStrategyComparison)
225
+ ) {
226
+ this.logStrategyComparison(epoch, checkpointProposalJob.getPublisher());
227
+ this.lastEpochForStrategyComparison = epoch;
228
+ }
229
+
230
+ return checkpoint;
231
+ }
232
+
233
+ /**
234
+ * Prepares the checkpoint proposal by performing all necessary checks and setup.
235
+ * This is the initial step in the main loop.
236
+ * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
237
+ */
238
+ @trackSpan('Sequencer.prepareCheckpointProposal')
239
+ private async prepareCheckpointProposal(
240
+ epoch: EpochNumber,
241
+ slot: SlotNumber,
242
+ ts: bigint,
243
+ now: bigint,
244
+ ): Promise<CheckpointProposalJob | undefined> {
245
+ // Check we have not already processed this slot (cheapest check)
246
+ // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
247
+ // running against actual time (eg when we use sandbox-style automining)
248
+ if (
249
+ this.lastSlotForCheckpointProposalJob &&
250
+ this.lastSlotForCheckpointProposalJob >= slot &&
251
+ this.config.enforceTimeTable
252
+ ) {
253
+ this.log.trace(`Slot ${slot} has already been processed`);
254
+ return undefined;
255
+ }
256
+
257
+ // But if we have already proposed for this slot, the we definitely have to skip it, automining or not
258
+ if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= slot) {
259
+ this.log.trace(`Slot ${slot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`);
260
+ return undefined;
261
+ }
262
+
280
263
  // Check all components are synced to latest as seen by the archiver (queries all subsystems)
281
264
  const syncedTo = await this.checkSync({ ts, slot });
282
265
  if (!syncedTo) {
283
266
  await this.tryVoteWhenSyncFails({ slot, ts });
284
- return;
267
+ return undefined;
285
268
  }
286
269
 
287
- const chainTipArchive = syncedTo.archive;
288
- const newBlockNumber = BlockNumber(syncedTo.blockNumber + 1);
270
+ // If escape hatch is open for this epoch, do not start checkpoint proposal work and do not attempt invalidations.
271
+ // Still perform governance/slashing voting (as proposer) once per slot.
272
+ const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(epoch);
289
273
 
290
- const syncLogData = {
274
+ if (isEscapeHatchOpen) {
275
+ this.setState(SequencerState.PROPOSER_CHECK, slot);
276
+ const [canPropose, proposer] = await this.checkCanPropose(slot);
277
+ if (canPropose) {
278
+ await this.tryVoteWhenEscapeHatchOpen({ slot, proposer });
279
+ } else {
280
+ this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
281
+ slot,
282
+ epoch,
283
+ proposer,
284
+ });
285
+ }
286
+ return undefined;
287
+ }
288
+
289
+ // Next checkpoint follows from the last synced one
290
+ const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
291
+
292
+ const logCtx = {
291
293
  now,
292
294
  syncedToL1Ts: syncedTo.l1Timestamp,
293
295
  syncedToL2Slot: getSlotAtTimestamp(syncedTo.l1Timestamp, this.l1Constants),
294
- nextL2Slot: slot,
295
- nextL2SlotTs: ts,
296
- l1SlotDuration: this.l1Constants.ethereumSlotDuration,
297
- newBlockNumber,
296
+ slot,
297
+ slotTs: ts,
298
+ checkpointNumber,
298
299
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex'),
299
300
  };
300
301
 
@@ -302,269 +303,147 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
302
303
  this.setState(SequencerState.PROPOSER_CHECK, slot);
303
304
  const [canPropose, proposer] = await this.checkCanPropose(slot);
304
305
 
305
- // If we are not a proposer check if we should invalidate a invalid block, and bail
306
+ // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
306
307
  if (!canPropose) {
307
- await this.considerInvalidatingBlock(syncedTo, slot);
308
- return;
309
- }
310
-
311
- // In fisherman mode, check if we've already validated this slot to prevent duplicate attempts
312
- if (this.config.fishermanMode) {
313
- if (this.lastSlotForValidationBlock === slot) {
314
- this.log.trace(`Already validated block building for slot ${slot} (skipping)`, { slot });
315
- return;
316
- }
317
- this.log.debug(
318
- `Building validation block for slot ${slot} (actual proposer: ${proposer?.toString() ?? 'none'})`,
319
- { slot, proposer: proposer?.toString() },
320
- );
321
- // Mark this slot as being validated
322
- this.lastSlotForValidationBlock = slot;
308
+ await this.considerInvalidatingCheckpoint(syncedTo, slot);
309
+ return undefined;
323
310
  }
324
311
 
325
312
  // Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
326
313
  if (syncedTo.block && syncedTo.block.header.getSlot() >= slot) {
327
314
  this.log.warn(
328
315
  `Cannot propose block at next L2 slot ${slot} since that slot was taken by block ${syncedTo.blockNumber}`,
329
- { ...syncLogData, block: syncedTo.block.header.toInspect() },
316
+ { ...logCtx, block: syncedTo.block.header.toInspect() },
330
317
  );
331
318
  this.metrics.recordBlockProposalPrecheckFailed('slot_already_taken');
332
- return;
319
+ return undefined;
333
320
  }
334
321
 
335
322
  // We now need to get ourselves a publisher.
336
323
  // The returned attestor will be the one we provided if we provided one.
337
324
  // Otherwise it will be a valid attestor for the returned publisher.
338
325
  // In fisherman mode, pass undefined to use the fisherman's own keystore instead of the actual proposer's
339
- const { attestorAddress, publisher } = await this.publisherFactory.create(
340
- this.config.fishermanMode ? undefined : proposer,
341
- );
326
+ const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
327
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
342
328
  this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
343
329
  this.publisher = publisher;
344
330
 
345
331
  // In fisherman mode, set the actual proposer's address for simulations
346
- if (this.config.fishermanMode) {
347
- if (proposer) {
348
- publisher.setProposerAddressForSimulation(proposer);
349
- this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
350
- }
332
+ if (this.config.fishermanMode && proposer) {
333
+ publisher.setProposerAddressForSimulation(proposer);
334
+ this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
351
335
  }
352
336
 
353
- // Get proposer credentials
354
- const coinbase = this.validatorClient!.getCoinbaseForAttestor(attestorAddress);
355
- const feeRecipient = this.validatorClient!.getFeeRecipientForAttestor(attestorAddress);
356
-
357
337
  // Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
358
- const invalidateBlock = await publisher.simulateInvalidateBlock(syncedTo.pendingChainValidationStatus);
338
+ const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
359
339
 
360
- // Check with the rollup if we can indeed propose at the next L2 slot. This check should not fail
340
+ // Check with the rollup contract if we can indeed propose at the next L2 slot. This check should not fail
361
341
  // if all the previous checks are good, but we do it just in case.
362
342
  const canProposeCheck = await publisher.canProposeAtNextEthBlock(
363
- chainTipArchive,
343
+ syncedTo.archive,
364
344
  proposer ?? EthAddress.ZERO,
365
- invalidateBlock,
345
+ invalidateCheckpoint,
366
346
  );
367
347
 
368
348
  if (canProposeCheck === undefined) {
369
349
  this.log.warn(
370
- `Cannot propose block ${newBlockNumber} at slot ${slot} due to failed rollup contract check`,
371
- syncLogData,
350
+ `Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`,
351
+ logCtx,
372
352
  );
373
- this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed' });
353
+ this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed', slot });
374
354
  this.metrics.recordBlockProposalPrecheckFailed('rollup_contract_check_failed');
375
- return;
376
- } else if (canProposeCheck.slot !== slot) {
355
+ return undefined;
356
+ }
357
+
358
+ if (canProposeCheck.slot !== slot) {
377
359
  this.log.warn(
378
360
  `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}.`,
379
- { ...syncLogData, rollup: canProposeCheck, newBlockNumber, expectedSlot: slot },
361
+ { ...logCtx, rollup: canProposeCheck, expectedSlot: slot },
380
362
  );
381
- this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch' });
363
+ this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch', slot });
382
364
  this.metrics.recordBlockProposalPrecheckFailed('slot_mismatch');
383
- return;
384
- } else if (canProposeCheck.checkpointNumber !== CheckpointNumber.fromBlockNumber(newBlockNumber)) {
365
+ return undefined;
366
+ }
367
+
368
+ if (canProposeCheck.checkpointNumber !== checkpointNumber) {
385
369
  this.log.warn(
386
- `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.checkpointNumber}.`,
387
- { ...syncLogData, rollup: canProposeCheck, newBlockNumber, expectedSlot: slot },
370
+ `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}.`,
371
+ { ...logCtx, rollup: canProposeCheck, expectedSlot: slot },
388
372
  );
389
- this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch' });
373
+ this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch', slot });
390
374
  this.metrics.recordBlockProposalPrecheckFailed('block_number_mismatch');
391
- return;
375
+ return undefined;
392
376
  }
393
377
 
394
- this.log.debug(`Can propose block ${newBlockNumber} at slot ${slot} as ${proposer}`, { ...syncLogData });
378
+ this.lastSlotForCheckpointProposalJob = slot;
379
+ await this.p2pClient.prepareForSlot(slot);
380
+ this.log.info(`Preparing checkpoint proposal ${checkpointNumber} at slot ${slot}`, { ...logCtx, proposer });
395
381
 
396
- const newGlobalVariables = await this.globalsBuilder.buildGlobalVariables(
397
- newBlockNumber,
398
- coinbase,
399
- feeRecipient,
400
- slot,
401
- );
402
-
403
- // Enqueue governance and slashing votes (returns promises that will be awaited later)
404
- // In fisherman mode, we simulate slashing but don't actually publish to L1
405
- const votesPromises = this.enqueueGovernanceAndSlashingVotes(
406
- publisher,
407
- attestorAddress,
408
- slot,
409
- newGlobalVariables.timestamp,
410
- );
411
-
412
- // Enqueues block invalidation
413
- if (invalidateBlock && !this.config.skipInvalidateBlockAsProposer) {
414
- publisher.enqueueInvalidateBlock(invalidateBlock);
415
- }
416
-
417
- // Actual block building
418
- this.setState(SequencerState.INITIALIZING_PROPOSAL, slot);
419
- this.metrics.incOpenSlot(slot, proposer?.toString() ?? 'unknown');
420
- const block: L2Block | undefined = await this.tryBuildBlockAndEnqueuePublish(
382
+ // Create and return the checkpoint proposal job
383
+ return this.createCheckpointProposalJob(
384
+ epoch,
421
385
  slot,
386
+ checkpointNumber,
387
+ syncedTo.blockNumber,
422
388
  proposer,
423
- newBlockNumber,
424
389
  publisher,
425
- newGlobalVariables,
426
- chainTipArchive,
427
- invalidateBlock,
390
+ attestorAddress,
391
+ invalidateCheckpoint,
428
392
  );
429
-
430
- // Wait until the voting promises have resolved, so all requests are enqueued
431
- await Promise.all(votesPromises);
432
-
433
- // In fisherman mode, we don't publish to L1
434
- if (this.config.fishermanMode) {
435
- // Clear pending requests
436
- publisher.clearPendingRequests();
437
-
438
- if (block) {
439
- this.log.info(`Validation block building SUCCEEDED for slot ${slot}`, {
440
- blockNumber: newBlockNumber,
441
- slot: Number(slot),
442
- archive: block.archive.toString(),
443
- txCount: block.body.txEffects.length,
444
- });
445
- this.lastBlockPublished = block;
446
- this.metrics.recordBlockProposalSuccess();
447
- } else {
448
- // Block building failed in fisherman mode
449
- this.log.warn(`Validation block building FAILED for slot ${slot}`, {
450
- blockNumber: newBlockNumber,
451
- slot: Number(slot),
452
- });
453
- this.metrics.recordBlockProposalFailed('block_build_failed');
454
- }
455
- } else {
456
- // Normal mode: send the tx to L1
457
- const l1Response = await publisher.sendRequests();
458
- const proposedBlock = l1Response?.successfulActions.find(a => a === 'propose');
459
- if (proposedBlock) {
460
- this.lastBlockPublished = block;
461
- this.emit('block-published', { blockNumber: newBlockNumber, slot: Number(slot) });
462
- await this.metrics.incFilledSlot(publisher.getSenderAddress().toString(), coinbase);
463
- } else if (block) {
464
- this.emit('block-publish-failed', l1Response ?? {});
465
- }
466
- }
467
-
468
- this.setState(SequencerState.IDLE, undefined);
469
393
  }
470
394
 
471
- /** Tries building a block proposal, and if successful, enqueues it for publishing. */
472
- private async tryBuildBlockAndEnqueuePublish(
395
+ protected createCheckpointProposalJob(
396
+ epoch: EpochNumber,
473
397
  slot: SlotNumber,
398
+ checkpointNumber: CheckpointNumber,
399
+ syncedToBlockNumber: BlockNumber,
474
400
  proposer: EthAddress | undefined,
475
- newBlockNumber: BlockNumber,
476
401
  publisher: SequencerPublisher,
477
- newGlobalVariables: GlobalVariables,
478
- chainTipArchive: Fr,
479
- invalidateBlock: InvalidateBlockRequest | undefined,
480
- ) {
481
- this.log.verbose(`Preparing proposal for block ${newBlockNumber} at slot ${slot}`, {
482
- proposer,
483
- publisher: publisher.getSenderAddress(),
484
- globalVariables: newGlobalVariables.toInspect(),
485
- chainTipArchive,
486
- blockNumber: newBlockNumber,
402
+ attestorAddress: EthAddress,
403
+ invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
404
+ ): CheckpointProposalJob {
405
+ return new CheckpointProposalJob(
406
+ epoch,
487
407
  slot,
488
- });
489
-
490
- const proposalHeader = CheckpointHeader.from({
491
- ...newGlobalVariables,
492
- timestamp: newGlobalVariables.timestamp,
493
- lastArchiveRoot: chainTipArchive,
494
- blockHeadersHash: Fr.ZERO,
495
- contentCommitment: ContentCommitment.empty(),
496
- totalManaUsed: Fr.ZERO,
497
- });
498
-
499
- let block: L2Block | undefined;
500
-
501
- const pendingTxCount = await this.p2pClient.getPendingTxCount();
502
- if (pendingTxCount >= this.minTxsPerBlock) {
503
- // We don't fetch exactly maxTxsPerBlock txs here because we may not need all of them if we hit a limit before,
504
- // and also we may need to fetch more if we don't have enough valid txs.
505
- const pendingTxs = this.p2pClient.iteratePendingTxs();
506
- try {
507
- block = await this.buildBlockAndEnqueuePublish(
508
- pendingTxs,
509
- proposalHeader,
510
- newGlobalVariables,
511
- proposer,
512
- invalidateBlock,
513
- publisher,
514
- );
515
- } catch (err: any) {
516
- this.emit('block-build-failed', { reason: err.message });
517
- if (err instanceof FormattedViemError) {
518
- this.log.verbose(`Unable to build/enqueue block ${err.message}`);
519
- } else {
520
- this.log.error(`Error building/enqueuing block`, err, { blockNumber: newBlockNumber, slot });
521
- }
522
- this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
523
- }
524
- } else {
525
- this.log.verbose(
526
- `Not enough txs to build block ${newBlockNumber} at slot ${slot} (got ${pendingTxCount} txs, need ${this.minTxsPerBlock})`,
527
- { chainTipArchive, blockNumber: newBlockNumber, slot },
528
- );
529
- this.emit('tx-count-check-failed', { minTxs: this.minTxsPerBlock, availableTxs: pendingTxCount });
530
- this.metrics.recordBlockProposalFailed('insufficient_txs');
531
- }
532
- return block;
533
- }
534
-
535
- @trackSpan('Sequencer.work')
536
- protected async safeWork() {
537
- try {
538
- await this.work();
539
- } catch (err) {
540
- if (err instanceof SequencerTooSlowError) {
541
- // Log as warn only if we had to abort halfway through the block proposal
542
- const logLvl = [SequencerState.INITIALIZING_PROPOSAL, SequencerState.PROPOSER_CHECK].includes(err.proposedState)
543
- ? ('debug' as const)
544
- : ('warn' as const);
545
- this.log[logLvl](err.message, { now: this.dateProvider.nowInSeconds() });
546
- } else {
547
- // Re-throw other errors
548
- throw err;
549
- }
550
- } finally {
551
- this.setState(SequencerState.IDLE, undefined);
552
- }
408
+ checkpointNumber,
409
+ syncedToBlockNumber,
410
+ proposer,
411
+ publisher,
412
+ attestorAddress,
413
+ invalidateCheckpoint,
414
+ this.validatorClient,
415
+ this.globalsBuilder,
416
+ this.p2pClient,
417
+ this.worldState,
418
+ this.l1ToL2MessageSource,
419
+ this.l2BlockSource,
420
+ this.checkpointsBuilder,
421
+ this.l2BlockSource,
422
+ this.l1Constants,
423
+ this.config,
424
+ this.timetable,
425
+ this.slasherClient,
426
+ this.epochCache,
427
+ this.dateProvider,
428
+ this.metrics,
429
+ this,
430
+ this.setState.bind(this),
431
+ this.tracer,
432
+ this.log.getBindings(),
433
+ );
553
434
  }
554
435
 
555
436
  /**
556
- * Sets the sequencer state and checks if we have enough time left in the slot to transition to the new state.
437
+ * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
557
438
  * @param proposedState - The new state to transition to.
558
439
  * @param slotNumber - The current slot number.
559
440
  * @param force - Whether to force the transition even if the sequencer is stopped.
560
441
  */
561
- setState(proposedState: SequencerStateWithSlot, slotNumber: SlotNumber, opts?: { force?: boolean }): void;
562
- setState(
563
- proposedState: Exclude<SequencerState, SequencerStateWithSlot>,
564
- slotNumber?: undefined,
565
- opts?: { force?: boolean },
566
- ): void;
567
- setState(proposedState: SequencerState, slotNumber: SlotNumber | undefined, opts: { force?: boolean } = {}): void {
442
+ protected setState(
443
+ proposedState: SequencerState,
444
+ slotNumber: SlotNumber | undefined,
445
+ opts: { force?: boolean } = {},
446
+ ): void {
568
447
  if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
569
448
  this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
570
449
  throw new SequencerInterruptedError();
@@ -590,352 +469,16 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
590
469
  oldState: this.state,
591
470
  newState: proposedState,
592
471
  secondsIntoSlot,
593
- slotNumber,
472
+ slot: slotNumber,
594
473
  });
595
474
  this.state = proposedState;
596
475
  }
597
476
 
598
- private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
599
- if (failedTxs.length === 0) {
600
- return;
601
- }
602
- const failedTxData = failedTxs.map(fail => fail.tx);
603
- const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
604
- this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
605
- await this.p2pClient.deleteTxs(failedTxHashes);
606
- }
607
-
608
- protected getBlockBuilderOptions(slot: SlotNumber): PublicProcessorLimits {
609
- // Deadline for processing depends on whether we're proposing a block
610
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
611
- const processingEndTimeWithinSlot = this.timetable.getBlockProposalExecTimeEnd(secondsIntoSlot);
612
-
613
- // Deadline is only set if enforceTimeTable is enabled.
614
- const deadline = this.enforceTimeTable
615
- ? new Date((this.getSlotStartBuildTimestamp(slot) + processingEndTimeWithinSlot) * 1000)
616
- : undefined;
617
- return {
618
- maxTransactions: this.maxTxsPerBlock,
619
- maxBlockSize: this.maxBlockSizeInBytes,
620
- maxBlockGas: this.maxBlockGas,
621
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
622
- deadline,
623
- };
624
- }
625
-
626
- /**
627
- * @notice Build and propose a block to the chain
628
- *
629
- * @dev MUST throw instead of exiting early to ensure that world-state
630
- * is being rolled back if the block is dropped.
631
- *
632
- * @param pendingTxs - Iterable of pending transactions to construct the block from
633
- * @param proposalHeader - The partial header constructed for the proposal
634
- * @param newGlobalVariables - The global variables for the new block
635
- * @param proposerAddress - The address of the proposer
636
- */
637
- @trackSpan('Sequencer.buildBlockAndEnqueuePublish', (_validTxs, _proposalHeader, newGlobalVariables) => ({
638
- [Attributes.BLOCK_NUMBER]: newGlobalVariables.blockNumber,
639
- }))
640
- private async buildBlockAndEnqueuePublish(
641
- pendingTxs: Iterable<Tx> | AsyncIterable<Tx>,
642
- proposalHeader: CheckpointHeader,
643
- newGlobalVariables: GlobalVariables,
644
- proposerAddress: EthAddress | undefined,
645
- invalidateBlock: InvalidateBlockRequest | undefined,
646
- publisher: SequencerPublisher,
647
- ): Promise<L2Block> {
648
- await publisher.validateBlockHeader(proposalHeader, invalidateBlock);
649
-
650
- const blockNumber = newGlobalVariables.blockNumber;
651
- const checkpointNumber = CheckpointNumber.fromBlockNumber(blockNumber);
652
- const slot = proposalHeader.slotNumber;
653
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
654
-
655
- const workTimer = new Timer();
656
- this.setState(SequencerState.CREATING_BLOCK, slot);
657
-
658
- try {
659
- const blockBuilderOptions = this.getBlockBuilderOptions(slot);
660
- const buildBlockRes = await this.blockBuilder.buildBlock(
661
- pendingTxs,
662
- l1ToL2Messages,
663
- newGlobalVariables,
664
- blockBuilderOptions,
665
- );
666
- const { publicGas, block, publicProcessorDuration, numTxs, numMsgs, blockBuildingTimer, usedTxs, failedTxs } =
667
- buildBlockRes;
668
- const blockBuildDuration = workTimer.ms();
669
- await this.dropFailedTxsFromP2P(failedTxs);
670
-
671
- const minTxsPerBlock = this.minTxsPerBlock;
672
- if (numTxs < minTxsPerBlock) {
673
- this.log.warn(
674
- `Block ${blockNumber} has too few txs to be proposed (got ${numTxs} but required ${minTxsPerBlock})`,
675
- { slot, blockNumber, numTxs },
676
- );
677
- throw new Error(`Block has too few successful txs to be proposed`);
678
- }
679
-
680
- // TODO(@PhilWindle) We should probably periodically check for things like another
681
- // block being published before ours instead of just waiting on our block
682
- await publisher.validateBlockHeader(block.getCheckpointHeader(), invalidateBlock);
683
-
684
- const blockStats: L2BlockBuiltStats = {
685
- eventName: 'l2-block-built',
686
- creator: proposerAddress?.toString() ?? publisher.getSenderAddress().toString(),
687
- duration: workTimer.ms(),
688
- publicProcessDuration: publicProcessorDuration,
689
- rollupCircuitsDuration: blockBuildingTimer.ms(),
690
- ...block.getStats(),
691
- };
692
-
693
- const blockHash = await block.hash();
694
- const txHashes = block.body.txEffects.map(tx => tx.txHash);
695
- this.log.info(
696
- `Built block ${block.number} for slot ${slot} with ${numTxs} txs and ${numMsgs} messages. ${
697
- publicGas.l2Gas / workTimer.s()
698
- } mana/s`,
699
- {
700
- blockHash,
701
- globalVariables: block.header.globalVariables.toInspect(),
702
- txHashes,
703
- ...blockStats,
704
- },
705
- );
706
-
707
- // In fisherman mode, skip attestation collection
708
- let attestationsAndSigners: CommitteeAttestationsAndSigners;
709
- if (this.config.fishermanMode) {
710
- this.log.debug('Skipping attestation collection');
711
- attestationsAndSigners = CommitteeAttestationsAndSigners.empty();
712
- } else {
713
- this.log.debug('Collecting attestations');
714
- attestationsAndSigners = await this.collectAttestations(block, usedTxs, proposerAddress);
715
- this.log.verbose(
716
- `Collected ${attestationsAndSigners.attestations.length} attestations for block ${blockNumber} at slot ${slot}`,
717
- { blockHash, blockNumber, slot },
718
- );
719
- }
720
-
721
- // In fisherman mode, skip attestation signing
722
- const attestationsAndSignersSignature =
723
- this.config.fishermanMode || !this.validatorClient
724
- ? Signature.empty()
725
- : await this.validatorClient.signAttestationsAndSigners(
726
- attestationsAndSigners,
727
- proposerAddress ?? publisher.getSenderAddress(),
728
- );
729
-
730
- await this.enqueuePublishL2Block(
731
- block,
732
- attestationsAndSigners,
733
- attestationsAndSignersSignature,
734
- invalidateBlock,
735
- publisher,
736
- );
737
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
738
- return block;
739
- } catch (err) {
740
- this.metrics.recordFailedBlock();
741
- throw err;
742
- }
743
- }
744
-
745
- @trackSpan('Sequencer.collectAttestations', (block, txHashes) => ({
746
- [Attributes.BLOCK_NUMBER]: block.number,
747
- [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
748
- [Attributes.BLOCK_TXS_COUNT]: txHashes.length,
749
- }))
750
- protected async collectAttestations(
751
- block: L2Block,
752
- txs: Tx[],
753
- proposerAddress: EthAddress | undefined,
754
- ): Promise<CommitteeAttestationsAndSigners> {
755
- const { committee, seed, epoch } = await this.epochCache.getCommittee(block.slot);
756
-
757
- // We checked above that the committee is defined, so this should never happen.
758
- if (!committee) {
759
- throw new Error('No committee when collecting attestations');
760
- }
761
-
762
- if (committee.length === 0) {
763
- this.log.verbose(`Attesting committee is empty`);
764
- return CommitteeAttestationsAndSigners.empty();
765
- } else {
766
- this.log.debug(`Attesting committee length is ${committee.length}`);
767
- }
768
-
769
- if (!this.validatorClient) {
770
- throw new Error('Missing validator client: Cannot collect attestations');
771
- }
772
-
773
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
774
-
775
- const slotNumber = block.header.globalVariables.slotNumber;
776
- this.setState(SequencerState.COLLECTING_ATTESTATIONS, slotNumber);
777
-
778
- this.log.debug('Creating block proposal for validators');
779
- const blockProposalOptions: BlockProposalOptions = {
780
- publishFullTxs: !!this.config.publishTxsWithProposals,
781
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
782
- };
783
- const proposal = await this.validatorClient.createBlockProposal(
784
- block.header.globalVariables.blockNumber,
785
- block.getCheckpointHeader(),
786
- block.archive.root,
787
- txs,
788
- proposerAddress,
789
- blockProposalOptions,
790
- );
791
-
792
- if (!proposal) {
793
- throw new Error(`Failed to create block proposal`);
794
- }
795
-
796
- if (this.config.skipCollectingAttestations) {
797
- this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
798
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
799
- return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
800
- }
801
-
802
- this.log.debug('Broadcasting block proposal to validators');
803
- await this.validatorClient.broadcastBlockProposal(proposal);
804
-
805
- const attestationTimeAllowed = this.enforceTimeTable
806
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_BLOCK)!
807
- : this.aztecSlotDuration;
808
-
809
- this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
810
-
811
- const timer = new Timer();
812
- let collectedAttestationsCount: number = 0;
813
- try {
814
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
815
- const attestations = await this.validatorClient.collectAttestations(
816
- proposal,
817
- numberOfRequiredAttestations,
818
- attestationDeadline,
819
- );
820
-
821
- collectedAttestationsCount = attestations.length;
822
-
823
- // note: the smart contract requires that the signatures are provided in the order of the committee
824
- const sorted = orderAttestations(attestations, committee);
825
-
826
- // manipulate the attestations if we've been configured to do so
827
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
828
- return this.manipulateAttestations(block, epoch, seed, committee, sorted);
829
- }
830
-
831
- return new CommitteeAttestationsAndSigners(sorted);
832
- } catch (err) {
833
- if (err && err instanceof AttestationTimeoutError) {
834
- collectedAttestationsCount = err.collectedCount;
835
- }
836
- throw err;
837
- } finally {
838
- this.metrics.recordCollectedAttestations(collectedAttestationsCount, timer.ms());
839
- }
840
- }
841
-
842
- /** Breaks the attestations before publishing based on attack configs */
843
- private manipulateAttestations(
844
- block: L2Block,
845
- epoch: EpochNumber,
846
- seed: bigint,
847
- committee: EthAddress[],
848
- attestations: CommitteeAttestation[],
849
- ) {
850
- // Compute the proposer index in the committee, since we dont want to tweak it.
851
- // Otherwise, the L1 rollup contract will reject the block outright.
852
- const proposerIndex = Number(
853
- this.epochCache.computeProposerIndex(block.slot, epoch, seed, BigInt(committee.length)),
854
- );
855
-
856
- if (this.config.injectFakeAttestation) {
857
- // Find non-empty attestations that are not from the proposer
858
- const nonProposerIndices: number[] = [];
859
- for (let i = 0; i < attestations.length; i++) {
860
- if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
861
- nonProposerIndices.push(i);
862
- }
863
- }
864
- if (nonProposerIndices.length > 0) {
865
- const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
866
- this.log.warn(`Injecting fake attestation in block ${block.number} at index ${targetIndex}`);
867
- unfreeze(attestations[targetIndex]).signature = Signature.random();
868
- }
869
- return new CommitteeAttestationsAndSigners(attestations);
870
- }
871
-
872
- if (this.config.shuffleAttestationOrdering) {
873
- this.log.warn(`Shuffling attestation ordering in block ${block.number} (proposer index ${proposerIndex})`);
874
-
875
- const shuffled = [...attestations];
876
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
877
- const valueI = shuffled[i];
878
- const valueJ = shuffled[j];
879
- shuffled[i] = valueJ;
880
- shuffled[j] = valueI;
881
-
882
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
883
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
884
- }
885
-
886
- return new CommitteeAttestationsAndSigners(attestations);
887
- }
888
-
889
- /**
890
- * Publishes the L2Block to the rollup contract.
891
- * @param block - The L2Block to be published.
892
- */
893
- @trackSpan('Sequencer.enqueuePublishL2Block', block => ({
894
- [Attributes.BLOCK_NUMBER]: block.number,
895
- }))
896
- protected async enqueuePublishL2Block(
897
- block: L2Block,
898
- attestationsAndSigners: CommitteeAttestationsAndSigners,
899
- attestationsAndSignersSignature: Signature,
900
- invalidateBlock: InvalidateBlockRequest | undefined,
901
- publisher: SequencerPublisher,
902
- ): Promise<void> {
903
- // Publishes new block to the network and awaits the tx to be mined
904
- this.setState(SequencerState.PUBLISHING_BLOCK, block.header.globalVariables.slotNumber);
905
-
906
- // Time out tx at the end of the slot
907
- const slot = block.header.globalVariables.slotNumber;
908
- const txTimeoutAt = new Date((this.getSlotStartBuildTimestamp(slot) + this.aztecSlotDuration) * 1000);
909
-
910
- const enqueued = await publisher.enqueueProposeL2Block(
911
- block,
912
- attestationsAndSigners,
913
- attestationsAndSignersSignature,
914
- {
915
- txTimeoutAt,
916
- forcePendingBlockNumber: invalidateBlock?.forcePendingBlockNumber,
917
- },
918
- );
919
-
920
- if (!enqueued) {
921
- throw new Error(`Failed to enqueue publish of block ${block.number}`);
922
- }
923
- }
924
-
925
477
  /**
926
478
  * Returns whether all dependencies have caught up.
927
479
  * We don't check against the previous block submitted since it may have been reorg'd out.
928
480
  */
929
- protected async checkSync(args: { ts: bigint; slot: SlotNumber }): Promise<
930
- | {
931
- block?: L2Block;
932
- blockNumber: BlockNumber;
933
- archive: Fr;
934
- l1Timestamp: bigint;
935
- pendingChainValidationStatus: ValidateBlockResult;
936
- }
937
- | undefined
938
- > {
481
+ protected async checkSync(args: { ts: bigint; slot: SlotNumber }): Promise<SequencerSyncCheckResult | undefined> {
939
482
  // Check that the archiver and dependencies have synced to the previous L1 slot at least
940
483
  // TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
941
484
  // cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
@@ -955,9 +498,9 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
955
498
  number: syncSummary.latestBlockNumber,
956
499
  hash: syncSummary.latestBlockHash,
957
500
  })),
958
- this.l2BlockSource.getL2Tips().then(t => t.latest),
501
+ this.l2BlockSource.getL2Tips().then(t => t.proposed),
959
502
  this.p2pClient.getStatus().then(p2p => p2p.syncedToL2Block),
960
- this.l1ToL2MessageSource.getL2Tips().then(t => t.latest),
503
+ this.l1ToL2MessageSource.getL2Tips().then(t => t.proposed),
961
504
  this.l2BlockSource.getPendingChainValidationStatus(),
962
505
  ] as const);
963
506
 
@@ -965,6 +508,7 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
965
508
 
966
509
  // Handle zero as a special case, since the block hash won't match across services if we're changing the prefilled data for the genesis block,
967
510
  // as the world state can compute the new genesis block hash, but other components use the hardcoded constant.
511
+ // TODO(palla/mbps): Fix the above. All components should be able to handle dynamic genesis block hashes.
968
512
  const result =
969
513
  (l2BlockSource.number === 0 && worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSource.number === 0) ||
970
514
  (worldState.hash === l2BlockSource.hash &&
@@ -980,10 +524,16 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
980
524
  const blockNumber = worldState.number;
981
525
  if (blockNumber < INITIAL_L2_BLOCK_NUM) {
982
526
  const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
983
- return { blockNumber: BlockNumber(INITIAL_L2_BLOCK_NUM - 1), archive, l1Timestamp, pendingChainValidationStatus };
527
+ return {
528
+ checkpointNumber: CheckpointNumber.ZERO,
529
+ blockNumber: BlockNumber.ZERO,
530
+ archive,
531
+ l1Timestamp,
532
+ pendingChainValidationStatus,
533
+ };
984
534
  }
985
535
 
986
- const block = await this.l2BlockSource.getBlock(blockNumber);
536
+ const block = await this.l2BlockSource.getL2Block(blockNumber);
987
537
  if (!block) {
988
538
  // this shouldn't really happen because a moment ago we checked that all components were in sync
989
539
  this.log.error(`Failed to get L2 block ${blockNumber} from the archiver with all components in sync`);
@@ -993,69 +543,13 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
993
543
  return {
994
544
  block,
995
545
  blockNumber: block.number,
546
+ checkpointNumber: block.checkpointNumber,
996
547
  archive: block.archive.root,
997
548
  l1Timestamp,
998
549
  pendingChainValidationStatus,
999
550
  };
1000
551
  }
1001
552
 
1002
- /**
1003
- * Enqueues governance and slashing votes with the publisher. Does not block.
1004
- * @param publisher - The publisher to enqueue votes with
1005
- * @param attestorAddress - The attestor address to use for signing
1006
- * @param slot - The slot number
1007
- * @param timestamp - The timestamp for the votes
1008
- * @param context - Optional context for logging (e.g., block number)
1009
- * @returns A tuple of [governanceEnqueued, slashingEnqueued]
1010
- */
1011
- protected enqueueGovernanceAndSlashingVotes(
1012
- publisher: SequencerPublisher,
1013
- attestorAddress: EthAddress,
1014
- slot: SlotNumber,
1015
- timestamp: bigint,
1016
- ): [Promise<boolean> | undefined, Promise<boolean> | undefined] {
1017
- try {
1018
- const signerFn = (msg: TypedDataDefinition) =>
1019
- this.validatorClient!.signWithAddress(attestorAddress, msg).then(s => s.toString());
1020
-
1021
- const enqueueGovernancePromise =
1022
- this.governanceProposerPayload && !this.governanceProposerPayload.isZero()
1023
- ? publisher
1024
- .enqueueGovernanceCastSignal(this.governanceProposerPayload, slot, timestamp, attestorAddress, signerFn)
1025
- .catch(err => {
1026
- this.log.error(`Error enqueuing governance vote`, err, { slot });
1027
- return false;
1028
- })
1029
- : undefined;
1030
-
1031
- const enqueueSlashingPromise = this.slasherClient
1032
- ? this.slasherClient
1033
- .getProposerActions(slot)
1034
- .then(actions => {
1035
- // Record metrics for fisherman mode
1036
- if (this.config.fishermanMode && actions.length > 0) {
1037
- this.log.debug(`Fisherman mode: simulating ${actions.length} slashing action(s) for slot ${slot}`, {
1038
- slot,
1039
- actionCount: actions.length,
1040
- });
1041
- this.metrics.recordSlashingAttempt(actions.length);
1042
- }
1043
- // Enqueue the actions to fully simulate L1 tx building (they won't be sent in fisherman mode)
1044
- return publisher.enqueueSlashingActions(actions, slot, timestamp, attestorAddress, signerFn);
1045
- })
1046
- .catch(err => {
1047
- this.log.error(`Error enqueuing slashing actions`, err, { slot });
1048
- return false;
1049
- })
1050
- : undefined;
1051
-
1052
- return [enqueueGovernancePromise, enqueueSlashingPromise];
1053
- } catch (err) {
1054
- this.log.error(`Error enqueueing governance and slashing votes`, err);
1055
- return [undefined, undefined];
1056
- }
1057
- }
1058
-
1059
553
  /**
1060
554
  * Checks if we are the proposer for the next slot.
1061
555
  * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
@@ -1067,7 +561,10 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1067
561
  proposer = await this.epochCache.getProposerAttesterAddressInSlot(slot);
1068
562
  } catch (e) {
1069
563
  if (e instanceof NoCommitteeError) {
1070
- this.log.warn(`Cannot propose at next L2 slot ${slot} since the committee does not exist on L1`);
564
+ if (this.lastSlotForNoCommitteeWarning !== slot) {
565
+ this.lastSlotForNoCommitteeWarning = slot;
566
+ this.log.warn(`Cannot propose at next L2 slot ${slot} since the committee does not exist on L1`);
567
+ }
1071
568
  return [false, undefined];
1072
569
  }
1073
570
  this.log.error(`Error getting proposer for slot ${slot}`, e);
@@ -1083,7 +580,7 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1083
580
  return [true, proposer];
1084
581
  }
1085
582
 
1086
- const validatorAddresses = this.validatorClient!.getValidatorAddresses();
583
+ const validatorAddresses = this.validatorClient.getValidatorAddresses();
1087
584
  const weAreProposer = validatorAddresses.some(addr => addr.equals(proposer));
1088
585
 
1089
586
  if (!weAreProposer) {
@@ -1098,30 +595,31 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1098
595
  * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
1099
596
  * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
1100
597
  */
598
+ @trackSpan('Seqeuencer.tryVoteWhenSyncFails', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
1101
599
  protected async tryVoteWhenSyncFails(args: { slot: SlotNumber; ts: bigint }): Promise<void> {
1102
- const { slot, ts } = args;
600
+ const { slot } = args;
1103
601
 
1104
602
  // Prevent duplicate attempts in the same slot
1105
- if (this.lastSlotForVoteWhenSyncFailed === slot) {
1106
- this.log.debug(`Already attempted to vote in slot ${slot} (skipping)`);
603
+ if (this.lastSlotForFallbackVote === slot) {
604
+ this.log.trace(`Already attempted to vote in slot ${slot} (skipping)`);
1107
605
  return;
1108
606
  }
1109
607
 
1110
608
  // Check if we're past the max time for initializing a proposal
1111
609
  const secondsIntoSlot = this.getSecondsIntoSlot(slot);
1112
- const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_PROPOSAL);
610
+ const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_CHECKPOINT);
1113
611
 
1114
612
  // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
1115
613
  // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
1116
614
  if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
1117
- this.log.trace(`Not attempting to vote since there is still for block building`, {
615
+ this.log.trace(`Not attempting to vote since there is still time for block building`, {
1118
616
  secondsIntoSlot,
1119
617
  maxAllowedTime,
1120
618
  });
1121
619
  return;
1122
620
  }
1123
621
 
1124
- this.log.debug(`Sync for slot ${slot} failed, checking for voting opportunities`, {
622
+ this.log.trace(`Sync for slot ${slot} failed, checking for voting opportunities`, {
1125
623
  secondsIntoSlot,
1126
624
  maxAllowedTime,
1127
625
  });
@@ -1129,12 +627,12 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1129
627
  // Check if we're a proposer or proposal is open
1130
628
  const [canPropose, proposer] = await this.checkCanPropose(slot);
1131
629
  if (!canPropose) {
1132
- this.log.debug(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
630
+ this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
1133
631
  return;
1134
632
  }
1135
633
 
1136
634
  // Mark this slot as attempted
1137
- this.lastSlotForVoteWhenSyncFailed = slot;
635
+ this.lastSlotForFallbackVote = slot;
1138
636
 
1139
637
  // Get a publisher for voting
1140
638
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
@@ -1144,11 +642,22 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1144
642
  slot,
1145
643
  });
1146
644
 
1147
- // Enqueue governance and slashing votes using the shared helper method
1148
- const votesPromises = this.enqueueGovernanceAndSlashingVotes(publisher, attestorAddress, slot, ts);
1149
- await Promise.all(votesPromises);
645
+ // Enqueue governance and slashing votes
646
+ const voter = new CheckpointVoter(
647
+ slot,
648
+ publisher,
649
+ attestorAddress,
650
+ this.validatorClient,
651
+ this.slasherClient,
652
+ this.l1Constants,
653
+ this.config,
654
+ this.metrics,
655
+ this.log,
656
+ );
657
+ const votesPromises = voter.enqueueVotes();
658
+ const votes = await Promise.all(votesPromises);
1150
659
 
1151
- if (votesPromises.every(p => !p)) {
660
+ if (votes.every(p => !p)) {
1152
661
  this.log.debug(`No votes to enqueue for slot ${slot}`);
1153
662
  return;
1154
663
  }
@@ -1157,14 +666,62 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1157
666
  await publisher.sendRequests();
1158
667
  }
1159
668
 
669
+ /**
670
+ * Tries to vote on slashing actions and governance proposals when escape hatch is open.
671
+ * This allows the sequencer to participate in voting without performing checkpoint proposal work.
672
+ */
673
+ @trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
674
+ protected async tryVoteWhenEscapeHatchOpen(args: {
675
+ slot: SlotNumber;
676
+ proposer: EthAddress | undefined;
677
+ }): Promise<void> {
678
+ const { slot, proposer } = args;
679
+
680
+ // Prevent duplicate attempts in the same slot
681
+ if (this.lastSlotForFallbackVote === slot) {
682
+ this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
683
+ return;
684
+ }
685
+
686
+ // Mark this slot as attempted
687
+ this.lastSlotForFallbackVote = slot;
688
+
689
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
690
+
691
+ this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, { slot, attestorAddress });
692
+
693
+ const voter = new CheckpointVoter(
694
+ slot,
695
+ publisher,
696
+ attestorAddress,
697
+ this.validatorClient,
698
+ this.slasherClient,
699
+ this.l1Constants,
700
+ this.config,
701
+ this.metrics,
702
+ this.log,
703
+ );
704
+
705
+ const votesPromises = voter.enqueueVotes();
706
+ const votes = await Promise.all(votesPromises);
707
+
708
+ if (votes.every(p => !p)) {
709
+ this.log.debug(`No votes to enqueue for slot ${slot} (escape hatch open)`);
710
+ return;
711
+ }
712
+
713
+ this.log.info(`Voting in slot ${slot} (escape hatch open)`, { slot });
714
+ await publisher.sendRequests();
715
+ }
716
+
1160
717
  /**
1161
718
  * Considers invalidating a block if the pending chain is invalid. Depends on how long the invalid block
1162
719
  * has been there without being invalidated and whether the sequencer is in the committee or not. We always
1163
720
  * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
1164
721
  * and if they fail, any sequencer will try as well.
1165
722
  */
1166
- protected async considerInvalidatingBlock(
1167
- syncedTo: NonNullable<Awaited<ReturnType<Sequencer['checkSync']>>>,
723
+ protected async considerInvalidatingCheckpoint(
724
+ syncedTo: SequencerSyncCheckResult,
1168
725
  currentSlot: SlotNumber,
1169
726
  ): Promise<void> {
1170
727
  const { pendingChainValidationStatus, l1Timestamp } = syncedTo;
@@ -1172,18 +729,18 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1172
729
  return;
1173
730
  }
1174
731
 
1175
- const invalidBlockNumber = pendingChainValidationStatus.block.blockNumber;
1176
- const invalidBlockTimestamp = pendingChainValidationStatus.block.timestamp;
1177
- const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidBlockTimestamp);
1178
- const ourValidatorAddresses = this.validatorClient!.getValidatorAddresses();
732
+ const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
733
+ const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
734
+ const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
735
+ const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
1179
736
 
1180
737
  const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } =
1181
738
  this.config;
1182
739
 
1183
740
  const logData = {
1184
- invalidL1Timestamp: invalidBlockTimestamp,
741
+ invalidL1Timestamp: invalidCheckpointTimestamp,
1185
742
  l1Timestamp,
1186
- invalidBlock: pendingChainValidationStatus.block,
743
+ invalidCheckpoint: pendingChainValidationStatus.checkpoint,
1187
744
  secondsBeforeInvalidatingBlockAsCommitteeMember,
1188
745
  secondsBeforeInvalidatingBlockAsNonCommitteeMember,
1189
746
  ourValidatorAddresses,
@@ -1229,29 +786,58 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1229
786
 
1230
787
  const { publisher } = await this.publisherFactory.create(validatorToUse);
1231
788
 
1232
- const invalidateBlock = await publisher.simulateInvalidateBlock(pendingChainValidationStatus);
1233
- if (!invalidateBlock) {
1234
- this.log.warn(`Failed to simulate invalidate block`, logData);
789
+ const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(pendingChainValidationStatus);
790
+ if (!invalidateCheckpoint) {
791
+ this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
1235
792
  return;
1236
793
  }
1237
794
 
1238
795
  this.log.info(
1239
796
  invalidateAsCommitteeMember
1240
- ? `Invalidating block ${invalidBlockNumber} as committee member`
1241
- : `Invalidating block ${invalidBlockNumber} as non-committee member`,
797
+ ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member`
798
+ : `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`,
1242
799
  logData,
1243
800
  );
1244
801
 
1245
- publisher.enqueueInvalidateBlock(invalidateBlock);
802
+ publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
1246
803
 
1247
804
  if (!this.config.fishermanMode) {
1248
805
  await publisher.sendRequests();
1249
806
  } else {
1250
- this.log.info('Invalidating block in fisherman mode, clearing pending requests');
807
+ this.log.info('Invalidating checkpoint in fisherman mode, clearing pending requests');
1251
808
  publisher.clearPendingRequests();
1252
809
  }
1253
810
  }
1254
811
 
812
+ private logStrategyComparison(epoch: EpochNumber, publisher: SequencerPublisher): void {
813
+ const feeAnalyzer = publisher.getL1FeeAnalyzer();
814
+ if (!feeAnalyzer) {
815
+ return;
816
+ }
817
+
818
+ const comparison = feeAnalyzer.getStrategyComparison();
819
+ if (comparison.length === 0) {
820
+ this.log.debug(`No strategy data available yet for epoch ${epoch}`);
821
+ return;
822
+ }
823
+
824
+ this.log.info(`L1 Fee Strategy Performance Report - End of Epoch ${epoch}`, {
825
+ epoch: Number(epoch),
826
+ totalAnalyses: comparison[0]?.totalAnalyses,
827
+ strategies: comparison.map(s => ({
828
+ id: s.strategyId,
829
+ name: s.strategyName,
830
+ inclusionRate: `${(s.inclusionRate * 100).toFixed(1)}%`,
831
+ inclusionCount: `${s.inclusionCount}/${s.totalAnalyses}`,
832
+ avgCostEth: s.avgEstimatedCostEth.toFixed(6),
833
+ totalCostEth: s.totalEstimatedCostEth.toFixed(6),
834
+ avgOverpaymentEth: s.avgOverpaymentEth.toFixed(6),
835
+ totalOverpaymentEth: s.totalOverpaymentEth.toFixed(6),
836
+ avgPriorityFeeDeltaGwei: s.avgPriorityFeeDeltaGwei.toFixed(2),
837
+ })),
838
+ });
839
+ }
840
+
1255
841
  private getSlotStartBuildTimestamp(slotNumber: SlotNumber): number {
1256
842
  return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
1257
843
  }
@@ -1261,15 +847,40 @@ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<Sequ
1261
847
  return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1262
848
  }
1263
849
 
1264
- get aztecSlotDuration() {
850
+ public get aztecSlotDuration() {
1265
851
  return this.l1Constants.slotDuration;
1266
852
  }
1267
853
 
1268
- get maxL2BlockGas(): number | undefined {
854
+ public get maxL2BlockGas(): number | undefined {
1269
855
  return this.config.maxL2BlockGas;
1270
856
  }
1271
857
 
1272
858
  public getSlasherClient(): SlasherClientInterface | undefined {
1273
859
  return this.slasherClient;
1274
860
  }
861
+
862
+ public get tracer(): Tracer {
863
+ return this.metrics.tracer;
864
+ }
865
+
866
+ public getValidatorAddresses() {
867
+ return this.validatorClient?.getValidatorAddresses();
868
+ }
869
+
870
+ public getConfig() {
871
+ return this.config;
872
+ }
873
+
874
+ private get l1PublishingTime(): number {
875
+ return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
876
+ }
1275
877
  }
878
+
879
+ type SequencerSyncCheckResult = {
880
+ block?: L2Block;
881
+ checkpointNumber: CheckpointNumber;
882
+ blockNumber: BlockNumber;
883
+ archive: Fr;
884
+ l1Timestamp: bigint;
885
+ pendingChainValidationStatus: ValidateCheckpointResult;
886
+ };