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

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 (96) hide show
  1. package/dest/client/sequencer-client.d.ts +12 -12
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +32 -25
  4. package/dest/config.d.ts +12 -5
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +73 -30
  7. package/dest/global_variable_builder/global_builder.d.ts +22 -13
  8. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  9. package/dest/global_variable_builder/global_builder.js +51 -41
  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 +7 -4
  14. package/dest/publisher/config.d.ts.map +1 -1
  15. package/dest/publisher/config.js +9 -3
  16. package/dest/publisher/sequencer-publisher-factory.d.ts +5 -4
  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 +15 -86
  22. package/dest/publisher/sequencer-publisher.d.ts +49 -41
  23. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  24. package/dest/publisher/sequencer-publisher.js +566 -114
  25. package/dest/sequencer/checkpoint_proposal_job.d.ts +79 -0
  26. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  27. package/dest/sequencer/checkpoint_proposal_job.js +1165 -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/config.d.ts +3 -2
  32. package/dest/sequencer/config.d.ts.map +1 -1
  33. package/dest/sequencer/events.d.ts +46 -0
  34. package/dest/sequencer/events.d.ts.map +1 -0
  35. package/dest/sequencer/events.js +1 -0
  36. package/dest/sequencer/index.d.ts +4 -2
  37. package/dest/sequencer/index.d.ts.map +1 -1
  38. package/dest/sequencer/index.js +3 -1
  39. package/dest/sequencer/metrics.d.ts +22 -2
  40. package/dest/sequencer/metrics.d.ts.map +1 -1
  41. package/dest/sequencer/metrics.js +125 -62
  42. package/dest/sequencer/sequencer.d.ts +107 -131
  43. package/dest/sequencer/sequencer.d.ts.map +1 -1
  44. package/dest/sequencer/sequencer.js +694 -605
  45. package/dest/sequencer/timetable.d.ts +54 -14
  46. package/dest/sequencer/timetable.d.ts.map +1 -1
  47. package/dest/sequencer/timetable.js +148 -59
  48. package/dest/sequencer/types.d.ts +3 -0
  49. package/dest/sequencer/types.d.ts.map +1 -0
  50. package/dest/sequencer/types.js +1 -0
  51. package/dest/sequencer/utils.d.ts +14 -8
  52. package/dest/sequencer/utils.d.ts.map +1 -1
  53. package/dest/sequencer/utils.js +7 -4
  54. package/dest/test/index.d.ts +4 -3
  55. package/dest/test/index.d.ts.map +1 -1
  56. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  57. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  58. package/dest/test/mock_checkpoint_builder.js +222 -0
  59. package/dest/test/utils.d.ts +53 -0
  60. package/dest/test/utils.d.ts.map +1 -0
  61. package/dest/test/utils.js +103 -0
  62. package/package.json +32 -30
  63. package/src/client/sequencer-client.ts +30 -41
  64. package/src/config.ts +78 -34
  65. package/src/global_variable_builder/global_builder.ts +65 -61
  66. package/src/index.ts +1 -7
  67. package/src/publisher/config.ts +12 -9
  68. package/src/publisher/sequencer-publisher-factory.ts +5 -4
  69. package/src/publisher/sequencer-publisher-metrics.ts +16 -72
  70. package/src/publisher/sequencer-publisher.ts +269 -146
  71. package/src/sequencer/README.md +531 -0
  72. package/src/sequencer/checkpoint_proposal_job.ts +845 -0
  73. package/src/sequencer/checkpoint_voter.ts +130 -0
  74. package/src/sequencer/config.ts +2 -1
  75. package/src/sequencer/events.ts +27 -0
  76. package/src/sequencer/index.ts +3 -1
  77. package/src/sequencer/metrics.ts +164 -70
  78. package/src/sequencer/sequencer.ts +437 -812
  79. package/src/sequencer/timetable.ts +173 -79
  80. package/src/sequencer/types.ts +6 -0
  81. package/src/sequencer/utils.ts +18 -9
  82. package/src/test/index.ts +3 -2
  83. package/src/test/mock_checkpoint_builder.ts +311 -0
  84. package/src/test/utils.ts +164 -0
  85. package/dest/sequencer/block_builder.d.ts +0 -27
  86. package/dest/sequencer/block_builder.d.ts.map +0 -1
  87. package/dest/sequencer/block_builder.js +0 -134
  88. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  89. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  90. package/dest/tx_validator/nullifier_cache.js +0 -24
  91. package/dest/tx_validator/tx_validator_factory.d.ts +0 -17
  92. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  93. package/dest/tx_validator/tx_validator_factory.js +0 -53
  94. package/src/sequencer/block_builder.ts +0 -222
  95. package/src/tx_validator/nullifier_cache.ts +0 -30
  96. package/src/tx_validator/tx_validator_factory.ts +0 -132
@@ -0,0 +1,845 @@
1
+ import { NUM_CHECKPOINT_END_MARKER_FIELDS, getNumBlockEndBlobFields } from '@aztec/blob-lib/encoding';
2
+ import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
3
+ import type { EpochCache } from '@aztec/epoch-cache';
4
+ import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
5
+ import { randomInt } from '@aztec/foundation/crypto/random';
6
+ import { Fr } from '@aztec/foundation/curves/bn254';
7
+ import { EthAddress } from '@aztec/foundation/eth-address';
8
+ import { Signature } from '@aztec/foundation/eth-signature';
9
+ import { filter } from '@aztec/foundation/iterator';
10
+ import type { Logger } from '@aztec/foundation/log';
11
+ import { sleep, sleepUntil } from '@aztec/foundation/sleep';
12
+ import { type DateProvider, Timer } from '@aztec/foundation/timer';
13
+ import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
14
+ import type { P2P } from '@aztec/p2p';
15
+ import type { SlasherClientInterface } from '@aztec/slasher';
16
+ import {
17
+ CommitteeAttestation,
18
+ CommitteeAttestationsAndSigners,
19
+ L2Block,
20
+ type L2BlockSink,
21
+ type L2BlockSource,
22
+ MaliciousCommitteeAttestationsAndSigners,
23
+ } from '@aztec/stdlib/block';
24
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
25
+ import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
26
+ import { Gas } from '@aztec/stdlib/gas';
27
+ import type {
28
+ PublicProcessorLimits,
29
+ ResolvedSequencerConfig,
30
+ WorldStateSynchronizer,
31
+ } from '@aztec/stdlib/interfaces/server';
32
+ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
33
+ import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
34
+ import { orderAttestations } from '@aztec/stdlib/p2p';
35
+ import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
36
+ import { type FailedTx, Tx } from '@aztec/stdlib/tx';
37
+ import { AttestationTimeoutError } from '@aztec/stdlib/validators';
38
+ import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
39
+ import { CheckpointBuilder, type FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec/validator-client';
40
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
41
+
42
+ import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
43
+ import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
44
+ import { CheckpointVoter } from './checkpoint_voter.js';
45
+ import { SequencerInterruptedError } from './errors.js';
46
+ import type { SequencerEvents } from './events.js';
47
+ import type { SequencerMetrics } from './metrics.js';
48
+ import type { SequencerTimetable } from './timetable.js';
49
+ import type { SequencerRollupConstants } from './types.js';
50
+ import { SequencerState } from './utils.js';
51
+
52
+ /** How much time to sleep while waiting for min transactions to accumulate for a block */
53
+ const TXS_POLLING_MS = 500;
54
+
55
+ /**
56
+ * Handles the execution of a checkpoint proposal after the initial preparation phase.
57
+ * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
58
+ * as well as enqueueing votes for slashing and governance proposals. This class is created from
59
+ * the Sequencer once the check for being the proposer for the slot has succeeded.
60
+ */
61
+ export class CheckpointProposalJob implements Traceable {
62
+ constructor(
63
+ private readonly epoch: EpochNumber,
64
+ private readonly slot: SlotNumber,
65
+ private readonly checkpointNumber: CheckpointNumber,
66
+ private readonly syncedToBlockNumber: BlockNumber,
67
+ // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
68
+ private readonly proposer: EthAddress | undefined,
69
+ private readonly publisher: SequencerPublisher,
70
+ private readonly attestorAddress: EthAddress,
71
+ private readonly invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
72
+ private readonly validatorClient: ValidatorClient,
73
+ private readonly globalsBuilder: GlobalVariableBuilder,
74
+ private readonly p2pClient: P2P,
75
+ private readonly worldState: WorldStateSynchronizer,
76
+ private readonly l1ToL2MessageSource: L1ToL2MessageSource,
77
+ private readonly l2BlockSource: L2BlockSource,
78
+ private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
79
+ private readonly blockSink: L2BlockSink,
80
+ private readonly l1Constants: SequencerRollupConstants,
81
+ protected config: ResolvedSequencerConfig,
82
+ protected timetable: SequencerTimetable,
83
+ private readonly slasherClient: SlasherClientInterface | undefined,
84
+ private readonly epochCache: EpochCache,
85
+ private readonly dateProvider: DateProvider,
86
+ private readonly metrics: SequencerMetrics,
87
+ private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
88
+ private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
89
+ protected readonly log: Logger,
90
+ public readonly tracer: Tracer,
91
+ ) {}
92
+
93
+ /**
94
+ * Executes the checkpoint proposal job.
95
+ * Returns the published checkpoint if successful, undefined otherwise.
96
+ */
97
+ @trackSpan('CheckpointProposalJob.execute')
98
+ public async execute(): Promise<Checkpoint | undefined> {
99
+ // Enqueue governance and slashing votes (returns promises that will be awaited later)
100
+ // In fisherman mode, we simulate slashing but don't actually publish to L1
101
+ // These are constant for the whole slot, so we only enqueue them once
102
+ const votesPromises = new CheckpointVoter(
103
+ this.slot,
104
+ this.publisher,
105
+ this.attestorAddress,
106
+ this.validatorClient,
107
+ this.slasherClient,
108
+ this.l1Constants,
109
+ this.config,
110
+ this.metrics,
111
+ this.log,
112
+ ).enqueueVotes();
113
+
114
+ // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
115
+ const checkpoint = await this.proposeCheckpoint();
116
+
117
+ // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
118
+ await Promise.all(votesPromises);
119
+
120
+ if (checkpoint) {
121
+ this.metrics.recordBlockProposalSuccess();
122
+ }
123
+
124
+ // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
125
+ if (this.config.fishermanMode) {
126
+ await this.handleCheckpointEndAsFisherman(checkpoint);
127
+ return;
128
+ }
129
+
130
+ // Then send everything to L1
131
+ const l1Response = await this.publisher.sendRequests();
132
+ const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
133
+ if (proposedAction) {
134
+ this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.slot });
135
+ const coinbase = checkpoint?.header.coinbase;
136
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
137
+ return checkpoint;
138
+ } else if (checkpoint) {
139
+ this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.slot });
140
+ return undefined;
141
+ }
142
+ }
143
+
144
+ @trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
145
+ return {
146
+ // nullish operator needed for tests
147
+ [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
148
+ [Attributes.SLOT_NUMBER]: this.slot,
149
+ };
150
+ })
151
+ private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
152
+ try {
153
+ // Get operator configured coinbase and fee recipient for this attestor
154
+ const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
155
+ const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
156
+
157
+ // Start the checkpoint
158
+ this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
159
+ this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
160
+
161
+ // Enqueues checkpoint invalidation (constant for the whole slot)
162
+ if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
163
+ this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
164
+ }
165
+
166
+ // Create checkpoint builder for the slot
167
+ const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
168
+ coinbase,
169
+ feeRecipient,
170
+ this.slot,
171
+ );
172
+
173
+ // Collect L1 to L2 messages for the checkpoint and compute their hash
174
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
175
+ const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
176
+
177
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
178
+ const previousCheckpoints = (await this.l2BlockSource.getCheckpointsForEpoch(this.epoch)).filter(
179
+ c => c.number < this.checkpointNumber,
180
+ );
181
+ const previousCheckpointOutHashes = previousCheckpoints.map(c => c.getCheckpointOutHash());
182
+
183
+ // Create a long-lived forked world state for the checkpoint builder
184
+ using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
185
+
186
+ // Create checkpoint builder for the entire slot
187
+ const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
188
+ this.checkpointNumber,
189
+ checkpointGlobalVariables,
190
+ l1ToL2Messages,
191
+ previousCheckpointOutHashes,
192
+ fork,
193
+ );
194
+
195
+ // Options for the validator client when creating block and checkpoint proposals
196
+ const blockProposalOptions: BlockProposalOptions = {
197
+ publishFullTxs: !!this.config.publishTxsWithProposals,
198
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
199
+ };
200
+
201
+ const checkpointProposalOptions: CheckpointProposalOptions = {
202
+ publishFullTxs: !!this.config.publishTxsWithProposals,
203
+ broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
204
+ };
205
+
206
+ let blocksInCheckpoint: L2Block[] = [];
207
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
208
+
209
+ try {
210
+ // Main loop: build blocks for the checkpoint
211
+ const result = await this.buildBlocksForCheckpoint(
212
+ checkpointBuilder,
213
+ checkpointGlobalVariables.timestamp,
214
+ inHash,
215
+ blockProposalOptions,
216
+ );
217
+ blocksInCheckpoint = result.blocksInCheckpoint;
218
+ blockPendingBroadcast = result.blockPendingBroadcast;
219
+ } catch (err) {
220
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
221
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
222
+ // which is normal for block building (may have picked different txs)
223
+ if (err instanceof DutyAlreadySignedError) {
224
+ this.log.info(`Checkpoint proposal for slot ${this.slot} already signed by another HA node, yielding`, {
225
+ slot: this.slot,
226
+ signedByNode: err.signedByNode,
227
+ });
228
+ return undefined;
229
+ }
230
+ if (err instanceof SlashingProtectionError) {
231
+ this.log.info(`Checkpoint proposal for slot ${this.slot} blocked by slashing protection, yielding`, {
232
+ slot: this.slot,
233
+ existingMessageHash: err.existingMessageHash,
234
+ attemptedMessageHash: err.attemptedMessageHash,
235
+ });
236
+ return undefined;
237
+ }
238
+ throw err;
239
+ }
240
+
241
+ if (blocksInCheckpoint.length === 0) {
242
+ this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
243
+ this.eventEmitter.emit('checkpoint-empty', { slot: this.slot });
244
+ return undefined;
245
+ }
246
+
247
+ // Assemble and broadcast the checkpoint proposal, including the last block that was not
248
+ // broadcasted yet, and wait to collect the committee attestations.
249
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
250
+ const checkpoint = await checkpointBuilder.completeCheckpoint();
251
+
252
+ // Do not collect attestations nor publish to L1 in fisherman mode
253
+ if (this.config.fishermanMode) {
254
+ this.log.info(
255
+ `Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` +
256
+ `Skipping proposal in fisherman mode.`,
257
+ {
258
+ slot: this.slot,
259
+ checkpoint: checkpoint.header.toInspect(),
260
+ blocksBuilt: blocksInCheckpoint.length,
261
+ },
262
+ );
263
+ this.metrics.recordCheckpointSuccess();
264
+ return checkpoint;
265
+ }
266
+
267
+ // Include the block pending broadcast in the checkpoint proposal if any
268
+ const lastBlock = blockPendingBroadcast && {
269
+ blockHeader: blockPendingBroadcast.block.header,
270
+ indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
271
+ txs: blockPendingBroadcast.txs,
272
+ };
273
+
274
+ // Create the checkpoint proposal and broadcast it
275
+ const proposal = await this.validatorClient.createCheckpointProposal(
276
+ checkpoint.header,
277
+ checkpoint.archive.root,
278
+ lastBlock,
279
+ this.proposer,
280
+ checkpointProposalOptions,
281
+ );
282
+
283
+ const blockProposedAt = this.dateProvider.now();
284
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
285
+
286
+ this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
287
+ const attestations = await this.waitForAttestations(proposal);
288
+ const blockAttestedAt = this.dateProvider.now();
289
+
290
+ this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
291
+
292
+ // Proposer must sign over the attestations before pushing them to L1
293
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
294
+ let attestationsSignature: Signature;
295
+ try {
296
+ attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
297
+ attestations,
298
+ signer,
299
+ this.slot,
300
+ this.checkpointNumber,
301
+ );
302
+ } catch (err) {
303
+ // We shouldn't really get here since we yield to another HA node
304
+ // as soon as we see these errors when creating block proposals.
305
+ if (err instanceof DutyAlreadySignedError) {
306
+ this.log.info(`Attestations signature for slot ${this.slot} already signed by another HA node, yielding`, {
307
+ slot: this.slot,
308
+ signedByNode: err.signedByNode,
309
+ });
310
+ return undefined;
311
+ }
312
+ if (err instanceof SlashingProtectionError) {
313
+ this.log.info(`Attestations signature for slot ${this.slot} blocked by slashing protection, yielding`, {
314
+ slot: this.slot,
315
+ existingMessageHash: err.existingMessageHash,
316
+ attemptedMessageHash: err.attemptedMessageHash,
317
+ });
318
+ return undefined;
319
+ }
320
+ throw err;
321
+ }
322
+
323
+ // Enqueue publishing the checkpoint to L1
324
+ this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
325
+ const aztecSlotDuration = this.l1Constants.slotDuration;
326
+ const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
327
+ const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
328
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
329
+ txTimeoutAt,
330
+ forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
331
+ });
332
+
333
+ return checkpoint;
334
+ } catch (err) {
335
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
336
+ // swallow this error. It's already been logged by a function deeper in the stack
337
+ return undefined;
338
+ }
339
+
340
+ this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
341
+ return undefined;
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Builds blocks for a checkpoint within the current slot.
347
+ */
348
+ @trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint')
349
+ private async buildBlocksForCheckpoint(
350
+ checkpointBuilder: CheckpointBuilder,
351
+ timestamp: bigint,
352
+ inHash: Fr,
353
+ blockProposalOptions: BlockProposalOptions,
354
+ ): Promise<{
355
+ blocksInCheckpoint: L2Block[];
356
+ blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
357
+ }> {
358
+ const blocksInCheckpoint: L2Block[] = [];
359
+ const txHashesAlreadyIncluded = new Set<string>();
360
+ const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
361
+
362
+ // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
363
+ let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
364
+
365
+ // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
366
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
367
+
368
+ while (true) {
369
+ const blocksBuilt = blocksInCheckpoint.length;
370
+ const indexWithinCheckpoint = blocksBuilt;
371
+ const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
372
+
373
+ const secondsIntoSlot = this.getSecondsIntoSlot();
374
+ const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
375
+
376
+ if (!timingInfo.canStart) {
377
+ this.log.debug(`Not enough time left in slot to start another block`, {
378
+ slot: this.slot,
379
+ blocksBuilt,
380
+ secondsIntoSlot,
381
+ });
382
+ break;
383
+ }
384
+
385
+ const buildResult = await this.buildSingleBlock(checkpointBuilder, {
386
+ // Create all blocks with the same timestamp
387
+ blockTimestamp: timestamp,
388
+ // Create an empty block if we haven't already and this is the last one
389
+ forceCreate: timingInfo.isLastBlock && blocksBuilt === 0 && this.config.buildCheckpointIfEmpty,
390
+ // Build deadline is only set if we are enforcing the timetable
391
+ buildDeadline: timingInfo.deadline
392
+ ? new Date((this.getSlotStartBuildTimestamp() + timingInfo.deadline) * 1000)
393
+ : undefined,
394
+ blockNumber,
395
+ indexWithinCheckpoint,
396
+ txHashesAlreadyIncluded,
397
+ remainingBlobFields,
398
+ });
399
+
400
+ if (!buildResult && timingInfo.isLastBlock) {
401
+ // If no block was produced due to not enough txs and this was the last subslot, exit
402
+ break;
403
+ } else if (!buildResult && timingInfo.deadline !== undefined) {
404
+ // But if there is still time for more blocks, wait until the next subslot and try again
405
+ await this.waitUntilNextSubslot(timingInfo.deadline);
406
+ continue;
407
+ } else if (!buildResult) {
408
+ // Exit if there is no possibility of building more blocks
409
+ break;
410
+ } else if ('error' in buildResult) {
411
+ // If there was an error building the block, just exit the loop and give up the rest of the slot
412
+ if (!(buildResult.error instanceof SequencerInterruptedError)) {
413
+ this.log.warn(`Halting block building for slot ${this.slot}`, {
414
+ slot: this.slot,
415
+ blocksBuilt,
416
+ error: buildResult.error,
417
+ });
418
+ }
419
+ break;
420
+ }
421
+
422
+ const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
423
+ blocksInCheckpoint.push(block);
424
+
425
+ // Update remaining blob fields for the next block
426
+ remainingBlobFields = newRemainingBlobFields;
427
+
428
+ // Sync the proposed block to the archiver to make it available
429
+ // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
430
+ // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
431
+ // Fire and forget - don't block the critical path, but log errors
432
+ this.syncProposedBlockToArchiver(block).catch(err => {
433
+ this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
434
+ });
435
+
436
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
437
+
438
+ // If this is the last block, exit the loop now so we start collecting attestations
439
+ if (timingInfo.isLastBlock) {
440
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
441
+ slot: this.slot,
442
+ blockNumber,
443
+ blocksBuilt,
444
+ });
445
+ blockPendingBroadcast = { block, txs: usedTxs };
446
+ break;
447
+ }
448
+
449
+ // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
450
+ // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
451
+ if (!this.config.fishermanMode) {
452
+ const proposal = await this.validatorClient.createBlockProposal(
453
+ block.header,
454
+ block.indexWithinCheckpoint,
455
+ inHash,
456
+ block.archive.root,
457
+ usedTxs,
458
+ this.proposer,
459
+ blockProposalOptions,
460
+ );
461
+ await this.p2pClient.broadcastProposal(proposal);
462
+ }
463
+
464
+ // Wait until the next block's start time
465
+ await this.waitUntilNextSubslot(timingInfo.deadline);
466
+ }
467
+
468
+ this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
469
+ slot: this.slot,
470
+ blocksBuilt: blocksInCheckpoint.length,
471
+ });
472
+
473
+ return { blocksInCheckpoint, blockPendingBroadcast };
474
+ }
475
+
476
+ /** Sleeps until it is time to produce the next block in the slot */
477
+ @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
478
+ private async waitUntilNextSubslot(nextSubslotStart: number) {
479
+ this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
480
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
481
+ await this.waitUntilTimeInSlot(nextSubslotStart);
482
+ }
483
+
484
+ /** Builds a single block. Called from the main block building loop. */
485
+ @trackSpan('CheckpointProposalJob.buildSingleBlock')
486
+ private async buildSingleBlock(
487
+ checkpointBuilder: CheckpointBuilder,
488
+ opts: {
489
+ forceCreate?: boolean;
490
+ blockTimestamp: bigint;
491
+ blockNumber: BlockNumber;
492
+ indexWithinCheckpoint: number;
493
+ buildDeadline: Date | undefined;
494
+ txHashesAlreadyIncluded: Set<string>;
495
+ remainingBlobFields: number;
496
+ },
497
+ ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
498
+ const {
499
+ blockTimestamp,
500
+ forceCreate,
501
+ blockNumber,
502
+ indexWithinCheckpoint,
503
+ buildDeadline,
504
+ txHashesAlreadyIncluded,
505
+ remainingBlobFields,
506
+ } = opts;
507
+
508
+ this.log.verbose(
509
+ `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
510
+ { ...checkpointBuilder.getConstantData(), ...opts },
511
+ );
512
+
513
+ try {
514
+ // Wait until we have enough txs to build the block
515
+ const minTxs = this.config.minTxsPerBlock;
516
+ const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
517
+ if (!canStartBuilding) {
518
+ this.log.warn(
519
+ `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
520
+ { blockNumber, slot: this.slot, indexWithinCheckpoint },
521
+ );
522
+ this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.slot });
523
+ this.metrics.recordBlockProposalFailed('insufficient_txs');
524
+ return undefined;
525
+ }
526
+
527
+ // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
528
+ // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
529
+ const pendingTxs = filter(
530
+ this.p2pClient.iteratePendingTxs(),
531
+ tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
532
+ );
533
+
534
+ this.log.debug(
535
+ `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
536
+ { slot: this.slot, blockNumber, indexWithinCheckpoint },
537
+ );
538
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
539
+
540
+ // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
541
+ const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
542
+ const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
543
+
544
+ const blockBuilderOptions: PublicProcessorLimits = {
545
+ maxTransactions: this.config.maxTxsPerBlock,
546
+ maxBlockSize: this.config.maxBlockSizeInBytes,
547
+ maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
548
+ maxBlobFields: maxBlobFieldsForTxs,
549
+ deadline: buildDeadline,
550
+ };
551
+
552
+ // Actually build the block by executing txs
553
+ const workTimer = new Timer();
554
+ const {
555
+ publicGas,
556
+ block,
557
+ publicProcessorDuration,
558
+ numTxs,
559
+ blockBuildingTimer,
560
+ usedTxs,
561
+ failedTxs,
562
+ usedTxBlobFields,
563
+ } = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
564
+ const blockBuildDuration = workTimer.ms();
565
+
566
+ // If any txs failed during execution, drop them from the mempool so we don't pick them up again
567
+ await this.dropFailedTxsFromP2P(failedTxs);
568
+
569
+ // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
570
+ // too long, then we may not get to minTxsPerBlock after executing public functions.
571
+ const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
572
+ if (!forceCreate && numTxs < minValidTxs) {
573
+ this.log.warn(
574
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
575
+ { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint },
576
+ );
577
+ this.eventEmitter.emit('block-tx-count-check-failed', {
578
+ minTxs: minValidTxs,
579
+ availableTxs: numTxs,
580
+ slot: this.slot,
581
+ });
582
+ this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
583
+ return undefined;
584
+ }
585
+
586
+ // Block creation succeeded, emit stats and metrics
587
+ const blockStats = {
588
+ eventName: 'l2-block-built',
589
+ duration: blockBuildDuration,
590
+ publicProcessDuration: publicProcessorDuration,
591
+ rollupCircuitsDuration: blockBuildingTimer.ms(),
592
+ ...block.getStats(),
593
+ } satisfies L2BlockBuiltStats;
594
+
595
+ const blockHash = await block.hash();
596
+ const txHashes = block.body.txEffects.map(tx => tx.txHash);
597
+ const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
598
+
599
+ this.log.info(
600
+ `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`,
601
+ { blockHash, txHashes, manaPerSec, ...blockStats },
602
+ );
603
+
604
+ this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
605
+ this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
606
+
607
+ return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
608
+ } catch (err: any) {
609
+ this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
610
+ this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
611
+ this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
612
+ this.metrics.recordFailedBlock();
613
+ return { error: err };
614
+ }
615
+ }
616
+
617
+ /** Waits until minTxs are available on the pool for building a block. */
618
+ @trackSpan('CheckpointProposalJob.waitForMinTxs')
619
+ private async waitForMinTxs(opts: {
620
+ forceCreate?: boolean;
621
+ blockNumber: BlockNumber;
622
+ indexWithinCheckpoint: number;
623
+ buildDeadline: Date | undefined;
624
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
625
+ const minTxs = this.config.minTxsPerBlock;
626
+ const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
627
+
628
+ // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
629
+ const startBuildingDeadline = buildDeadline
630
+ ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
631
+ : undefined;
632
+
633
+ let availableTxs = await this.p2pClient.getPendingTxCount();
634
+
635
+ while (!forceCreate && availableTxs < minTxs) {
636
+ // If we're past deadline, or we have no deadline, give up
637
+ const now = this.dateProvider.nowAsDate();
638
+ if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
639
+ return { canStartBuilding: false, availableTxs: availableTxs };
640
+ }
641
+
642
+ // Wait a bit before checking again
643
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
644
+ this.log.verbose(
645
+ `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
646
+ { blockNumber, slot: this.slot, indexWithinCheckpoint },
647
+ );
648
+ await sleep(TXS_POLLING_MS);
649
+ availableTxs = await this.p2pClient.getPendingTxCount();
650
+ }
651
+
652
+ return { canStartBuilding: true, availableTxs };
653
+ }
654
+
655
+ /**
656
+ * Waits for enough attestations to be collected via p2p.
657
+ * This is run after all blocks for the checkpoint have been built.
658
+ */
659
+ @trackSpan('CheckpointProposalJob.waitForAttestations')
660
+ private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
661
+ if (this.config.fishermanMode) {
662
+ this.log.debug('Skipping attestation collection in fisherman mode');
663
+ return CommitteeAttestationsAndSigners.empty();
664
+ }
665
+
666
+ const slotNumber = proposal.slotNumber;
667
+ const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
668
+
669
+ if (!committee) {
670
+ throw new Error('No committee when collecting attestations');
671
+ } else if (committee.length === 0) {
672
+ this.log.verbose(`Attesting committee is empty`);
673
+ return CommitteeAttestationsAndSigners.empty();
674
+ } else {
675
+ this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
676
+ }
677
+
678
+ const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
679
+
680
+ if (this.config.skipCollectingAttestations) {
681
+ this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
682
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
683
+ return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
684
+ }
685
+
686
+ const attestationTimeAllowed = this.config.enforceTimeTable
687
+ ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
688
+ : this.l1Constants.slotDuration;
689
+ const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
690
+
691
+ this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
692
+
693
+ const collectAttestationsTimer = new Timer();
694
+ let collectedAttestationsCount: number = 0;
695
+ try {
696
+ const attestations = await this.validatorClient.collectAttestations(
697
+ proposal,
698
+ numberOfRequiredAttestations,
699
+ attestationDeadline,
700
+ );
701
+
702
+ collectedAttestationsCount = attestations.length;
703
+
704
+ // Rollup contract requires that the signatures are provided in the order of the committee
705
+ const sorted = orderAttestations(attestations, committee);
706
+
707
+ // Manipulate the attestations if we've been configured to do so
708
+ if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
709
+ return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
710
+ }
711
+
712
+ return new CommitteeAttestationsAndSigners(sorted);
713
+ } catch (err) {
714
+ if (err && err instanceof AttestationTimeoutError) {
715
+ collectedAttestationsCount = err.collectedCount;
716
+ }
717
+ throw err;
718
+ } finally {
719
+ this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
720
+ }
721
+ }
722
+
723
+ /** Breaks the attestations before publishing based on attack configs */
724
+ private manipulateAttestations(
725
+ slotNumber: SlotNumber,
726
+ epoch: EpochNumber,
727
+ seed: bigint,
728
+ committee: EthAddress[],
729
+ attestations: CommitteeAttestation[],
730
+ ) {
731
+ // Compute the proposer index in the committee, since we dont want to tweak it.
732
+ // Otherwise, the L1 rollup contract will reject the block outright.
733
+ const proposerIndex = Number(
734
+ this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
735
+ );
736
+
737
+ if (this.config.injectFakeAttestation) {
738
+ // Find non-empty attestations that are not from the proposer
739
+ const nonProposerIndices: number[] = [];
740
+ for (let i = 0; i < attestations.length; i++) {
741
+ if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
742
+ nonProposerIndices.push(i);
743
+ }
744
+ }
745
+ if (nonProposerIndices.length > 0) {
746
+ const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
747
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
748
+ unfreeze(attestations[targetIndex]).signature = Signature.random();
749
+ }
750
+ return new CommitteeAttestationsAndSigners(attestations);
751
+ }
752
+
753
+ if (this.config.shuffleAttestationOrdering) {
754
+ this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
755
+
756
+ const shuffled = [...attestations];
757
+ const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
758
+ const valueI = shuffled[i];
759
+ const valueJ = shuffled[j];
760
+ shuffled[i] = valueJ;
761
+ shuffled[j] = valueI;
762
+
763
+ const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
764
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
765
+ }
766
+
767
+ return new CommitteeAttestationsAndSigners(attestations);
768
+ }
769
+
770
+ private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
771
+ if (failedTxs.length === 0) {
772
+ return;
773
+ }
774
+ const failedTxData = failedTxs.map(fail => fail.tx);
775
+ const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
776
+ this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
777
+ await this.p2pClient.deleteTxs(failedTxHashes);
778
+ }
779
+
780
+ /**
781
+ * Adds the proposed block to the archiver so it's available via P2P.
782
+ * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
783
+ * would never receive its own block without this explicit sync.
784
+ */
785
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
786
+ if (this.config.skipPushProposedBlocksToArchiver !== false) {
787
+ this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
788
+ blockNumber: block.number,
789
+ slot: block.header.globalVariables.slotNumber,
790
+ });
791
+ return;
792
+ }
793
+ this.log.debug(`Syncing proposed block ${block.number} to archiver`, {
794
+ blockNumber: block.number,
795
+ slot: block.header.globalVariables.slotNumber,
796
+ });
797
+ await this.blockSink.addBlock(block);
798
+ }
799
+
800
+ /** Runs fee analysis and logs checkpoint outcome as fisherman */
801
+ private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
802
+ // Perform L1 fee analysis before clearing requests
803
+ // The callback is invoked asynchronously after the next block is mined
804
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
805
+ this.metrics.recordFishermanFeeAnalysis(analysis),
806
+ );
807
+
808
+ if (checkpoint) {
809
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
810
+ ...checkpoint.toCheckpointInfo(),
811
+ ...checkpoint.getStats(),
812
+ feeAnalysisId: feeAnalysis?.id,
813
+ });
814
+ } else {
815
+ this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
816
+ slot: this.slot,
817
+ feeAnalysisId: feeAnalysis?.id,
818
+ });
819
+ this.metrics.recordBlockProposalFailed('block_build_failed');
820
+ }
821
+
822
+ this.publisher.clearPendingRequests();
823
+ }
824
+
825
+ /** Waits until a specific time within the current slot */
826
+ @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
827
+ protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
828
+ const slotStartTimestamp = this.getSlotStartBuildTimestamp();
829
+ const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
830
+ await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
831
+ }
832
+
833
+ private getSlotStartBuildTimestamp(): number {
834
+ return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
835
+ }
836
+
837
+ private getSecondsIntoSlot(): number {
838
+ const slotStartTimestamp = this.getSlotStartBuildTimestamp();
839
+ return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
840
+ }
841
+
842
+ public getPublisher() {
843
+ return this.publisher;
844
+ }
845
+ }