@aztec-labs/sequencer-client 6.0.0-nightly.20260829

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +307 -0
  2. package/dest/client/index.d.ts +2 -0
  3. package/dest/client/index.d.ts.map +1 -0
  4. package/dest/client/index.js +1 -0
  5. package/dest/client/sequencer-client.d.ts +94 -0
  6. package/dest/client/sequencer-client.d.ts.map +1 -0
  7. package/dest/client/sequencer-client.js +177 -0
  8. package/dest/config.d.ts +56 -0
  9. package/dest/config.d.ts.map +1 -0
  10. package/dest/config.js +251 -0
  11. package/dest/global_variable_builder/fee_predictor.d.ts +49 -0
  12. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_predictor.js +127 -0
  14. package/dest/global_variable_builder/fee_provider.d.ts +28 -0
  15. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  16. package/dest/global_variable_builder/fee_provider.js +87 -0
  17. package/dest/global_variable_builder/global_builder.d.ts +28 -0
  18. package/dest/global_variable_builder/global_builder.d.ts.map +1 -0
  19. package/dest/global_variable_builder/global_builder.js +40 -0
  20. package/dest/global_variable_builder/index.d.ts +4 -0
  21. package/dest/global_variable_builder/index.d.ts.map +1 -0
  22. package/dest/global_variable_builder/index.js +3 -0
  23. package/dest/index.d.ts +7 -0
  24. package/dest/index.d.ts.map +1 -0
  25. package/dest/index.js +8 -0
  26. package/dest/publisher/config.d.ts +68 -0
  27. package/dest/publisher/config.d.ts.map +1 -0
  28. package/dest/publisher/config.js +137 -0
  29. package/dest/publisher/index.d.ts +5 -0
  30. package/dest/publisher/index.d.ts.map +1 -0
  31. package/dest/publisher/index.js +4 -0
  32. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  33. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  34. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  35. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  36. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  37. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  38. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +101 -0
  39. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  40. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
  41. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  42. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  43. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
  44. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  45. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  46. package/dest/publisher/l1_tx_failed_store/index.js +3 -0
  47. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  48. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  49. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  50. package/dest/publisher/sequencer-publisher-factory.d.ts +50 -0
  51. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  52. package/dest/publisher/sequencer-publisher-factory.js +75 -0
  53. package/dest/publisher/sequencer-publisher-metrics.d.ts +26 -0
  54. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -0
  55. package/dest/publisher/sequencer-publisher-metrics.js +101 -0
  56. package/dest/publisher/sequencer-publisher.d.ts +254 -0
  57. package/dest/publisher/sequencer-publisher.d.ts.map +1 -0
  58. package/dest/publisher/sequencer-publisher.js +1784 -0
  59. package/dest/publisher/write_json.d.ts +11 -0
  60. package/dest/publisher/write_json.d.ts.map +1 -0
  61. package/dest/publisher/write_json.js +57 -0
  62. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  63. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  64. package/dest/sequencer/automine/automine_factory.js +85 -0
  65. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  66. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  67. package/dest/sequencer/automine/automine_sequencer.js +732 -0
  68. package/dest/sequencer/automine/index.d.ts +3 -0
  69. package/dest/sequencer/automine/index.d.ts.map +1 -0
  70. package/dest/sequencer/automine/index.js +2 -0
  71. package/dest/sequencer/checkpoint_proposal_job.d.ts +169 -0
  72. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  73. package/dest/sequencer/checkpoint_proposal_job.js +1961 -0
  74. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  75. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  76. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  77. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  78. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  79. package/dest/sequencer/checkpoint_voter.js +106 -0
  80. package/dest/sequencer/config.d.ts +8 -0
  81. package/dest/sequencer/config.d.ts.map +1 -0
  82. package/dest/sequencer/config.js +1 -0
  83. package/dest/sequencer/errors.d.ts +11 -0
  84. package/dest/sequencer/errors.d.ts.map +1 -0
  85. package/dest/sequencer/errors.js +15 -0
  86. package/dest/sequencer/events.d.ts +103 -0
  87. package/dest/sequencer/events.d.ts.map +1 -0
  88. package/dest/sequencer/events.js +1 -0
  89. package/dest/sequencer/inbox_bucket_selector.d.ts +88 -0
  90. package/dest/sequencer/inbox_bucket_selector.d.ts.map +1 -0
  91. package/dest/sequencer/inbox_bucket_selector.js +80 -0
  92. package/dest/sequencer/index.d.ts +6 -0
  93. package/dest/sequencer/index.d.ts.map +1 -0
  94. package/dest/sequencer/index.js +5 -0
  95. package/dest/sequencer/metrics.d.ts +75 -0
  96. package/dest/sequencer/metrics.d.ts.map +1 -0
  97. package/dest/sequencer/metrics.js +343 -0
  98. package/dest/sequencer/missing_committee.d.ts +72 -0
  99. package/dest/sequencer/missing_committee.d.ts.map +1 -0
  100. package/dest/sequencer/missing_committee.js +139 -0
  101. package/dest/sequencer/requests_tracker.d.ts +22 -0
  102. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  103. package/dest/sequencer/requests_tracker.js +33 -0
  104. package/dest/sequencer/sequencer.d.ts +326 -0
  105. package/dest/sequencer/sequencer.d.ts.map +1 -0
  106. package/dest/sequencer/sequencer.js +1495 -0
  107. package/dest/sequencer/types.d.ts +3 -0
  108. package/dest/sequencer/types.d.ts.map +1 -0
  109. package/dest/sequencer/types.js +1 -0
  110. package/dest/sequencer/utils.d.ts +30 -0
  111. package/dest/sequencer/utils.d.ts.map +1 -0
  112. package/dest/sequencer/utils.js +18 -0
  113. package/dest/test/index.d.ts +23 -0
  114. package/dest/test/index.d.ts.map +1 -0
  115. package/dest/test/index.js +6 -0
  116. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  117. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  118. package/dest/test/mock_checkpoint_builder.js +230 -0
  119. package/dest/test/utils.d.ts +67 -0
  120. package/dest/test/utils.d.ts.map +1 -0
  121. package/dest/test/utils.js +121 -0
  122. package/package.json +118 -0
  123. package/src/client/index.ts +1 -0
  124. package/src/client/sequencer-client.ts +281 -0
  125. package/src/config.ts +309 -0
  126. package/src/global_variable_builder/README.md +44 -0
  127. package/src/global_variable_builder/fee_predictor.ts +176 -0
  128. package/src/global_variable_builder/fee_provider.ts +104 -0
  129. package/src/global_variable_builder/global_builder.ts +68 -0
  130. package/src/global_variable_builder/index.ts +3 -0
  131. package/src/index.ts +15 -0
  132. package/src/publisher/config.ts +220 -0
  133. package/src/publisher/index.ts +8 -0
  134. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  135. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  136. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +166 -0
  137. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
  138. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  139. package/src/publisher/sequencer-bundle-simulator.ts +253 -0
  140. package/src/publisher/sequencer-publisher-factory.ts +121 -0
  141. package/src/publisher/sequencer-publisher-metrics.ts +145 -0
  142. package/src/publisher/sequencer-publisher.ts +1719 -0
  143. package/src/publisher/write_json.ts +77 -0
  144. package/src/sequencer/README.md +243 -0
  145. package/src/sequencer/automine/README.md +60 -0
  146. package/src/sequencer/automine/automine_factory.ts +156 -0
  147. package/src/sequencer/automine/automine_sequencer.ts +841 -0
  148. package/src/sequencer/automine/index.ts +6 -0
  149. package/src/sequencer/checkpoint_proposal_job.ts +1889 -0
  150. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  151. package/src/sequencer/checkpoint_voter.ts +118 -0
  152. package/src/sequencer/config.ts +9 -0
  153. package/src/sequencer/errors.ts +21 -0
  154. package/src/sequencer/events.ts +93 -0
  155. package/src/sequencer/inbox_bucket_selector.ts +160 -0
  156. package/src/sequencer/index.ts +5 -0
  157. package/src/sequencer/metrics.ts +463 -0
  158. package/src/sequencer/missing_committee.ts +192 -0
  159. package/src/sequencer/requests_tracker.ts +43 -0
  160. package/src/sequencer/sequencer.ts +1401 -0
  161. package/src/sequencer/types.ts +6 -0
  162. package/src/sequencer/utils.ts +42 -0
  163. package/src/test/index.ts +26 -0
  164. package/src/test/mock_checkpoint_builder.ts +324 -0
  165. package/src/test/utils.ts +215 -0
@@ -0,0 +1,1889 @@
1
+ import { MAX_L1_TO_L2_MSGS_PER_BLOCK, MAX_L1_TO_L2_MSGS_PER_CHECKPOINT } from '@aztec-labs/constants';
2
+ import { type EpochCache, PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec-labs/epoch-cache';
3
+ import type { SimulationOverridesPlan } from '@aztec-labs/ethereum/contracts';
4
+ import {
5
+ BlockNumber,
6
+ CheckpointNumber,
7
+ EpochNumber,
8
+ IndexWithinCheckpoint,
9
+ SlotNumber,
10
+ } from '@aztec-labs/foundation/branded-types';
11
+ import { randomInt } from '@aztec-labs/foundation/crypto/random';
12
+ import {
13
+ flipSignature,
14
+ generateRecoverableSignature,
15
+ generateUnrecoverableSignature,
16
+ } from '@aztec-labs/foundation/crypto/secp256k1-signer';
17
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
18
+ import { InterruptError, TimeoutError } from '@aztec-labs/foundation/error';
19
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
20
+ import { Signature } from '@aztec-labs/foundation/eth-signature';
21
+ import { filter } from '@aztec-labs/foundation/iterator';
22
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec-labs/foundation/log';
23
+ import { InterruptibleSleep } from '@aztec-labs/foundation/sleep';
24
+ import { type DateProvider, Timer } from '@aztec-labs/foundation/timer';
25
+ import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec-labs/foundation/types';
26
+ import type { P2P } from '@aztec-labs/p2p';
27
+ import type { SlasherClientInterface } from '@aztec-labs/slasher';
28
+ import {
29
+ CommitteeAttestation,
30
+ CommitteeAttestationsAndSigners,
31
+ L2Block,
32
+ type L2BlockSink,
33
+ type L2BlockSource,
34
+ MaliciousCommitteeAttestationsAndSigners,
35
+ MaliciousYParityCommitteeAttestationsAndSigners,
36
+ type ProposedCheckpointSink,
37
+ type ValidateCheckpointResult,
38
+ } from '@aztec-labs/stdlib/block';
39
+ import {
40
+ type Checkpoint,
41
+ type ProposedCheckpointData,
42
+ buildCheckpointSimulationOverridesPlan,
43
+ getPreviousCheckpointInboxRollingHash,
44
+ getPreviousCheckpointOutHashes,
45
+ validateCheckpoint,
46
+ } from '@aztec-labs/stdlib/checkpoint';
47
+ import { computeQuorum, getTimestampForSlot } from '@aztec-labs/stdlib/epoch-helpers';
48
+ import { Gas } from '@aztec-labs/stdlib/gas';
49
+ import {
50
+ type BlockBuilderOptions,
51
+ InsufficientValidTxsError,
52
+ type MerkleTreeWriteOperations,
53
+ type ResolvedSequencerConfig,
54
+ type WorldStateSynchronizer,
55
+ } from '@aztec-labs/stdlib/interfaces/server';
56
+ import {
57
+ type InboxBucket,
58
+ InboxBucketRef,
59
+ type L1ToL2MessageSource,
60
+ getInboxCutoffTimestamp,
61
+ isInboxConsumptionSufficient,
62
+ } from '@aztec-labs/stdlib/messaging';
63
+ import type {
64
+ BlockProposal,
65
+ BlockProposalOptions,
66
+ CheckpointAttestation,
67
+ CheckpointProposal,
68
+ CheckpointProposalOptions,
69
+ CoordinationSignatureContext,
70
+ } from '@aztec-labs/stdlib/p2p';
71
+ import { orderAttestations, trimAttestations } from '@aztec-labs/stdlib/p2p';
72
+ import type { L2BlockBuiltStats } from '@aztec-labs/stdlib/stats';
73
+ import type { ProposerTimetable } from '@aztec-labs/stdlib/timetable';
74
+ import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
75
+ import { type FailedTx, Tx } from '@aztec-labs/stdlib/tx';
76
+ import { AttestationTimeoutError } from '@aztec-labs/stdlib/validators';
77
+ import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec-labs/telemetry-client';
78
+ import { CheckpointBuilder, type FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec-labs/validator-client';
79
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec-labs/validator-ha-signer/errors';
80
+
81
+ import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
82
+ import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
83
+ import type { CheckpointProposalJobMetricsRecorder } from './checkpoint_proposal_job_metrics.js';
84
+ import { CheckpointVoter } from './checkpoint_voter.js';
85
+ import { SequencerInterruptedError } from './errors.js';
86
+ import type { SequencerEvents } from './events.js';
87
+ import {
88
+ type ConsumedBucketCursor,
89
+ type InboxBucketSelection,
90
+ selectInboxBucketForBlock,
91
+ } from './inbox_bucket_selector.js';
92
+ import type { SequencerMetrics } from './metrics.js';
93
+ import type { RequestsTracker } from './requests_tracker.js';
94
+ import type { SequencerRollupConstants } from './types.js';
95
+ import { SequencerState } from './utils.js';
96
+
97
+ /** How much time to sleep while waiting for min transactions to accumulate for a block */
98
+ const TXS_POLLING_MS = 500;
99
+ const ARCHIVER_SYNC_POLLING_MS = 200;
100
+
101
+ /** Result from proposeCheckpoint when a checkpoint was successfully built and broadcast. */
102
+ type CheckpointProposalBroadcast = {
103
+ checkpoint: Checkpoint;
104
+ proposal: CheckpointProposal;
105
+ blockProposedAt: number;
106
+ /**
107
+ * Sequence number of the last Inbox bucket the checkpoint consumed through — the L1 `propose` lookup aid, which
108
+ * must resolve to the bucket whose rolling hash the checkpoint header committed to. Taken from the streaming
109
+ * consumption cursor rather than the held last-block proposal, which is absent when the checkpoint's final block
110
+ * fails to build after earlier blocks already consumed messages.
111
+ */
112
+ bucketHint: bigint;
113
+ };
114
+
115
+ /** Result after attestation collection and signing, ready for L1 submission. */
116
+ type CheckpointProposalResult = {
117
+ checkpoint: Checkpoint;
118
+ attestations: CommitteeAttestationsAndSigners;
119
+ attestationsSignature: Signature;
120
+ /** Sequence number of the Inbox bucket the checkpoint's rolling hash corresponds to; the L1 `propose` lookup aid. */
121
+ bucketHint: bigint;
122
+ };
123
+
124
+ /**
125
+ * Running state of streaming Inbox message selection across the blocks of one checkpoint.
126
+ * Consumption starts from the parent checkpoint's last-consumed bucket and advances one block at a time.
127
+ */
128
+ type StreamingCheckpointState = {
129
+ /** Cumulative Inbox message count consumed as of the parent checkpoint; the per-checkpoint cap origin (fixed). */
130
+ checkpointStartTotalMsgCount: bigint;
131
+ /** The last bucket consumed so far (parent checkpoint's at the first block); advances as blocks consume. */
132
+ parent: ConsumedBucketCursor;
133
+ /** Reference to the last consumed bucket; reused by blocks that consume nothing. */
134
+ lastBucketRef: InboxBucketRef;
135
+ };
136
+
137
+ /**
138
+ * Handles the execution of a checkpoint proposal after the initial preparation phase.
139
+ * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
140
+ * as well as enqueueing votes for slashing and governance proposals. This class is created from
141
+ * the Sequencer once the check for being the proposer for the slot has succeeded.
142
+ */
143
+ export class CheckpointProposalJob implements Traceable {
144
+ protected readonly log: Logger;
145
+ private readonly checkpointEventLog: Logger;
146
+
147
+ private readonly interruptibleSleep = new InterruptibleSleep();
148
+ private interrupted = false;
149
+
150
+ /**
151
+ * Chain state overrides built once per slot in proposeCheckpoint after the checkpoint is
152
+ * complete. Carries the pending parent override (archive + slot + fee header) for pipelining,
153
+ * or the invalidation pending override when rolling back. Consumed by
154
+ * publisher.validateCheckpointHeader before broadcast.
155
+ */
156
+ private checkpointSimulationOverridesPlan?: SimulationOverridesPlan;
157
+
158
+ private getSignatureContext(): CoordinationSignatureContext {
159
+ return this.signatureContext;
160
+ }
161
+
162
+ constructor(
163
+ private readonly targetSlot: SlotNumber,
164
+ private readonly targetEpoch: EpochNumber,
165
+ private readonly checkpointNumber: CheckpointNumber,
166
+ private readonly syncedToBlockNumber: BlockNumber,
167
+ private readonly checkpointedCheckpointNumber: CheckpointNumber,
168
+ // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
169
+ private readonly proposer: EthAddress | undefined,
170
+ private readonly publisher: SequencerPublisher,
171
+ private readonly attestorAddress: EthAddress,
172
+ private readonly invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
173
+ private readonly validatorClient: ValidatorClient,
174
+ private readonly globalsBuilder: GlobalVariableBuilder,
175
+ private readonly p2pClient: P2P,
176
+ private readonly worldState: WorldStateSynchronizer,
177
+ private readonly l1ToL2MessageSource: L1ToL2MessageSource,
178
+ private readonly l2BlockSource: L2BlockSource,
179
+ private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
180
+ private readonly blockSink: L2BlockSink & ProposedCheckpointSink,
181
+ private readonly l1Constants: SequencerRollupConstants,
182
+ private readonly signatureContext: CoordinationSignatureContext,
183
+ protected config: ResolvedSequencerConfig,
184
+ protected timetable: ProposerTimetable,
185
+ private readonly slasherClient: SlasherClientInterface | undefined,
186
+ private readonly epochCache: EpochCache,
187
+ private readonly dateProvider: DateProvider,
188
+ private readonly metrics: SequencerMetrics,
189
+ private readonly checkpointMetrics: CheckpointProposalJobMetricsRecorder,
190
+ protected readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
191
+ // Shared with the owning sequencer, which drains it during shutdown; the fire-and-forget L1
192
+ // submission this job backgrounds is tracked here rather than in a job-local tracker.
193
+ protected readonly pendingRequests: RequestsTracker,
194
+ private readonly setStateFn: (state: SequencerState, slot: SlotNumber) => void,
195
+ public readonly tracer: Tracer,
196
+ bindings?: LoggerBindings,
197
+ private readonly proposedCheckpointData?: ProposedCheckpointData,
198
+ ) {
199
+ this.log = createLogger('sequencer:checkpoint-proposal', {
200
+ ...bindings,
201
+ instanceId: `slot-${this.getBuildSlot()}`,
202
+ });
203
+ this.checkpointEventLog = createLogger('sequencer:checkpoint-events', {
204
+ ...bindings,
205
+ instanceId: `slot-${this.getBuildSlot()}`,
206
+ });
207
+ }
208
+
209
+ /**
210
+ * The wall-clock slot during which this job builds, i.e. the slot one before {@link targetSlot} under
211
+ * proposer pipelining. Also the slot of the parent checkpoint this job builds on top of.
212
+ */
213
+ private getBuildSlot(): SlotNumber {
214
+ return SlotNumber(this.targetSlot - PROPOSER_PIPELINING_SLOT_OFFSET);
215
+ }
216
+
217
+ /**
218
+ * Sets the sequencer state for this job, reporting the target slot the checkpoint is being proposed for
219
+ * (not the wall-clock build slot). The slot is informational on the event payload/metrics; the job knows
220
+ * its own target slot, so callers only pass the state.
221
+ */
222
+ private setState(state: SequencerState): void {
223
+ this.setStateFn(state, this.targetSlot);
224
+ }
225
+
226
+ /** Interrupts job-owned waits, including the publisher's send-at-slot sleep, so shutdown can finish. */
227
+ public interrupt(): void {
228
+ this.interrupted = true;
229
+ this.interruptibleSleep.interrupt(true);
230
+ this.publisher.interrupt();
231
+ }
232
+
233
+ private async awaitInterruptibleSleep(ms: number): Promise<void> {
234
+ if (this.interrupted) {
235
+ throw new SequencerInterruptedError();
236
+ }
237
+ if (ms <= 0) {
238
+ return;
239
+ }
240
+ try {
241
+ await this.interruptibleSleep.sleep(ms);
242
+ } catch (err) {
243
+ if (err instanceof InterruptError) {
244
+ throw new SequencerInterruptedError();
245
+ }
246
+ throw err;
247
+ }
248
+ }
249
+
250
+ private logCheckpointEvent(eventName: string, message: string, fields: Record<string, unknown>): void {
251
+ this.checkpointEventLog.debug(message, {
252
+ eventName: `sequencer-checkpoint-${eventName}`,
253
+ ...fields,
254
+ });
255
+ }
256
+
257
+ /**
258
+ * Executes the checkpoint proposal job.
259
+ * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
260
+ * Attestation collection, signing, and L1 submission are backgrounded so the
261
+ * work loop can return to IDLE immediately for consecutive slot proposals.
262
+ * Returns the built checkpoint if successful, undefined otherwise.
263
+ */
264
+ @trackSpan('CheckpointProposalJob.execute')
265
+ public async execute(): Promise<Checkpoint | undefined> {
266
+ // Enqueue governance and slashing votes (returns promises that will be awaited later)
267
+ // In fisherman mode, we simulate slashing but don't actually publish to L1
268
+ // These are constant for the whole slot, so we only enqueue them once
269
+ const votesPromises = new CheckpointVoter(
270
+ this.targetSlot,
271
+ this.publisher,
272
+ this.attestorAddress,
273
+ this.validatorClient,
274
+ this.slasherClient,
275
+ this.l1Constants,
276
+ this.config,
277
+ this.metrics,
278
+ this.log,
279
+ ).enqueueVotes();
280
+
281
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
282
+ // Returns after broadcast — attestation collection is deferred.
283
+ const broadcast = await this.proposeCheckpoint();
284
+
285
+ if (!broadcast) {
286
+ await Promise.all(votesPromises);
287
+ // Still submit votes even without a checkpoint.
288
+ // Under proposer pipelining, vote-offenses signatures are EIP-712-bound to `targetSlot`
289
+ // (the pipelined slot in which the multicall is expected to mine). Submitting at the
290
+ // wall-clock time would let the multicall mine in a different L2 slot, causing
291
+ // signature verification to fail silently inside Multicall3. Delay submission to the
292
+ // start of `targetSlot` so the tx mines in the slot the vote was signed for.
293
+ if (!this.config.fishermanMode) {
294
+ this.pendingRequests.trackRequest(this.publisher.sendRequestsAt(this.targetSlot), () => this.interrupt());
295
+ }
296
+ return undefined;
297
+ }
298
+
299
+ const { checkpoint } = broadcast;
300
+ this.metrics.recordCheckpointProposalSuccess();
301
+
302
+ // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
303
+ if (this.config.fishermanMode) {
304
+ await this.handleCheckpointEndAsFisherman(checkpoint);
305
+ return checkpoint;
306
+ }
307
+
308
+ // Background the attestation → signing → L1 pipeline so the work loop is unblocked
309
+ this.pendingRequests.trackRequest(this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises), () =>
310
+ this.interrupt(),
311
+ );
312
+
313
+ // Return the built checkpoint immediately — the work loop is now unblocked
314
+ return checkpoint;
315
+ }
316
+
317
+ /**
318
+ * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
319
+ * Runs as a fire-and-forget task tracked in the sequencer's shared tracker so the work loop is unblocked.
320
+ */
321
+ private async waitForAttestationsAndEnqueueSubmissionAsync(
322
+ broadcast: CheckpointProposalBroadcast,
323
+ votesPromises: Promise<unknown>[],
324
+ ): Promise<void> {
325
+ const { checkpoint } = broadcast;
326
+ // The bucket the checkpoint consumed through, from the streaming cursor. Sourcing it from the held last-block
327
+ // proposal is wrong: when the checkpoint's final block fails to build after earlier blocks already consumed
328
+ // messages, no block is held, so the hint would fall back to genesis bucket 0 while the header commits to a
329
+ // non-genesis rolling hash, which L1 rejects with Rollup__InvalidInboxRollingHash.
330
+ const bucketHint = broadcast.bucketHint;
331
+
332
+ try {
333
+ // Wait for all votes actions, enqueued at the beginning, to resolve
334
+ await Promise.all(votesPromises);
335
+
336
+ // Try to collect attestations from the committee
337
+ const signedAttestations = await this.getSignedCommitteeAttestations(broadcast);
338
+
339
+ // Wait for the previous checkpoint to land on L1 before submitting, so we can check it
340
+ // matches the proposed checkpoint we used as parent, and has valid attestations.
341
+ if (signedAttestations && (await this.waitForValidParentCheckpointOnL1())) {
342
+ await this.enqueueCheckpointForSubmission({ checkpoint, ...signedAttestations, bucketHint });
343
+ }
344
+
345
+ // If we failed to collect attestations, at least check if we need to issue an invalidation
346
+ if (!signedAttestations && (await this.waitForSyncedL2SlotNumber(this.getBuildSlot()))) {
347
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
348
+ if (!validationStatus.valid) {
349
+ this.log.warn(
350
+ `Checkpoint ${validationStatus.checkpoint.checkpointNumber} has invalid attestations, enqueuing invalidation in spite of attestation collection failure`,
351
+ { checkpoint: validationStatus.checkpoint, reason: validationStatus.reason },
352
+ );
353
+ await this.enqueueInvalidation(validationStatus);
354
+ }
355
+ }
356
+
357
+ // Send whatever was enqueued: votes + (propose | invalidation | nothing).
358
+ const l1Response = await this.publisher.sendRequestsAt(this.targetSlot);
359
+ const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
360
+ if (proposedAction) {
361
+ this.logCheckpointEvent('published', `Checkpoint published for slot ${this.targetSlot}`, {
362
+ slot: this.targetSlot,
363
+ checkpointNumber: this.checkpointNumber,
364
+ successfulActions: l1Response?.successfulActions,
365
+ sentActions: l1Response?.sentActions,
366
+ });
367
+ this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
368
+ const coinbase = checkpoint.header.coinbase;
369
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
370
+ } else {
371
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
372
+ slot: this.targetSlot,
373
+ checkpointNumber: this.checkpointNumber,
374
+ successfulActions: l1Response?.successfulActions,
375
+ failedActions: l1Response?.failedActions,
376
+ sentActions: l1Response?.sentActions,
377
+ expiredActions: l1Response?.expiredActions,
378
+ reason: 'propose_action_not_successful',
379
+ });
380
+ this.log.warn(`Checkpoint publish failed for slot ${this.targetSlot}`, {
381
+ slot: this.targetSlot,
382
+ checkpointNumber: this.checkpointNumber,
383
+ successfulActions: l1Response?.successfulActions,
384
+ failedActions: l1Response?.failedActions,
385
+ sentActions: l1Response?.sentActions,
386
+ expiredActions: l1Response?.expiredActions,
387
+ reason: 'propose_action_not_successful',
388
+ });
389
+ this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
390
+ this.metrics.recordPipelineDiscard();
391
+ }
392
+ } catch (err) {
393
+ if (err instanceof SequencerInterruptedError) {
394
+ return;
395
+ }
396
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
397
+ slot: this.targetSlot,
398
+ checkpointNumber: this.checkpointNumber,
399
+ reason: err instanceof Error ? err.message : String(err),
400
+ });
401
+ this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err, {
402
+ slot: this.targetSlot,
403
+ checkpointNumber: this.checkpointNumber,
404
+ reason: err instanceof Error ? err.message : String(err),
405
+ });
406
+ this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
407
+ this.metrics.recordPipelineDiscard();
408
+ }
409
+ }
410
+
411
+ /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */
412
+ private async enqueueCheckpointForSubmission(result: CheckpointProposalResult): Promise<void> {
413
+ const { checkpoint, attestations, attestationsSignature, bucketHint } = result;
414
+
415
+ this.setState(SequencerState.PUBLISHING_CHECKPOINT);
416
+ // Latest L1 block the propose can still land in for the target slot: the last Ethereum block inside
417
+ // the target slot (`target_slot_start + S - E`). This is one ethereum slot later than
418
+ // `attestation_deadline` (= last_ethereum_block_in_target_slot - E), which bounds when validators must
419
+ // have signed, not when the proposer must have sent. Using the attestation deadline here is too tight:
420
+ // attestations are collected up to (and, when not enforcing, past) it, so the propose tx would be
421
+ // enqueued already expired and time out before it can mine.
422
+ const lastL1BlockInTargetSlot =
423
+ Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) +
424
+ this.l1Constants.slotDuration -
425
+ this.l1Constants.ethereumSlotDuration;
426
+ const txTimeoutAt = new Date(lastL1BlockInTargetSlot * 1000);
427
+
428
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
429
+ if (
430
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
431
+ this.config.skipPublishingCheckpointsPercent > 0
432
+ ) {
433
+ const roll = Math.max(0, randomInt(100));
434
+ if (roll < this.config.skipPublishingCheckpointsPercent) {
435
+ this.log.warn(
436
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${roll}`,
437
+ );
438
+ return;
439
+ }
440
+ }
441
+
442
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, bucketHint, {
443
+ txTimeoutAt,
444
+ });
445
+ }
446
+
447
+ /**
448
+ * Wait until the archiver syncs past the given L2 slot number.
449
+ * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
450
+ * L1 submission window and is no longer useful.
451
+ */
452
+ private async waitForSyncedL2SlotNumber(waitForSlot: SlotNumber): Promise<boolean> {
453
+ const targetSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
454
+ const targetSlotEndMs = (targetSlotStart + this.l1Constants.slotDuration) * 1000;
455
+ const syncDelayTolerance = this.l1Constants.ethereumSlotDuration * 2 * 1000;
456
+ const timeoutSeconds = Math.max(0.1, (targetSlotEndMs + syncDelayTolerance - this.dateProvider.now()) / 1000);
457
+
458
+ try {
459
+ const timer = new Timer();
460
+ while (true) {
461
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
462
+ if (syncedSlot !== undefined && syncedSlot >= waitForSlot) {
463
+ return true;
464
+ }
465
+ if (timeoutSeconds && timer.s() > timeoutSeconds) {
466
+ throw new TimeoutError(`Timeout awaiting archiver sync past slot ${waitForSlot}`);
467
+ }
468
+ await this.awaitInterruptibleSleep(ARCHIVER_SYNC_POLLING_MS);
469
+ }
470
+ } catch (err) {
471
+ if (err instanceof SequencerInterruptedError) {
472
+ throw err;
473
+ }
474
+ this.log.warn(
475
+ `Archiver did not sync L1 past slot ${waitForSlot} before slot ${this.targetSlot} expired, discarding pipelined work`,
476
+ { checkpointNumber: this.checkpointNumber },
477
+ );
478
+ this.emitPipelinedCheckpointDiscarded('archiver-sync-timeout');
479
+ return false;
480
+ }
481
+ }
482
+
483
+ /**
484
+ * Waits for the parent checkpoint to land on L1 before submitting a pipelined checkpoint.
485
+ * Polls until the archiver has synced L1 past the parent's slot, then verifies:
486
+ * - If we built on a proposed parent: it must have landed on L1 with matching hash and valid attestations.
487
+ * - If we built without a proposed parent: no new checkpoint must have appeared for that slot.
488
+ * If the parent has invalid attestations, enqueues an invalidation. Returns whether to proceed with the proposal.
489
+ */
490
+ protected async waitForValidParentCheckpointOnL1(): Promise<boolean> {
491
+ if (this.config.skipWaitForValidParentCheckpointOnL1) {
492
+ this.log.warn(`Skipping waitForValidParentCheckpointOnL1 due to test configuration`, {
493
+ checkpointNumber: this.checkpointNumber,
494
+ });
495
+ return true;
496
+ }
497
+
498
+ const parentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 1);
499
+
500
+ // Wait until archiver has synced L1 past the parent's slot (the build slot, one before targetSlot)
501
+ if (!(await this.waitForSyncedL2SlotNumber(this.getBuildSlot()))) {
502
+ return false;
503
+ }
504
+
505
+ const tips = await this.l2BlockSource.getL2Tips();
506
+ const checkpointedNumber = tips.checkpointed.checkpoint.number;
507
+
508
+ // We built on top of a proposed checkpoint. Verify it landed on L1 as expected.
509
+ if (this.proposedCheckpointData) {
510
+ // After syncing from L1 we see the chain tip has invalid attestations. This means the parent checkpoint was posted
511
+ // with invalid attestations, or it built on top of something with invalid attestations and didnt invalidate them.
512
+ // Either way, we thought our parent would be valid, so we have to throw away our work. But at least we'll try and
513
+ // invalidate on L1 so we clean up the chain for the next proposer. And we'll slash them, but that's handled elsewhere.
514
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
515
+ if (!validationStatus.valid) {
516
+ this.log.warn(
517
+ `Parent checkpoint ${parentCheckpointNumber} has invalid attestations, discarding pipelined work`,
518
+ { checkpointNumber: this.checkpointNumber, reason: validationStatus.reason },
519
+ );
520
+ this.emitPipelinedCheckpointDiscarded('parent-invalid-attestations');
521
+ await this.enqueueInvalidation(validationStatus);
522
+ return false;
523
+ }
524
+
525
+ // The pending chain is valid. But did the parent checkpoint land on L1 at all?
526
+ if (checkpointedNumber < parentCheckpointNumber) {
527
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} did not land on L1, discarding pipelined work`, {
528
+ checkpointNumber: this.checkpointNumber,
529
+ checkpointedNumber,
530
+ });
531
+ this.emitPipelinedCheckpointDiscarded('parent-not-on-l1');
532
+ return false;
533
+ }
534
+
535
+ // It landed. But is it the one we were expecting?
536
+ const expectedHash = this.proposedCheckpointData.header.hash().toString();
537
+ if (tips.checkpointed.checkpoint.hash !== expectedHash) {
538
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} hash mismatch on L1, discarding pipelined work`, {
539
+ checkpointNumber: this.checkpointNumber,
540
+ expectedHash,
541
+ actualHash: tips.checkpointed.checkpoint.hash,
542
+ });
543
+ this.emitPipelinedCheckpointDiscarded('parent-hash-mismatch');
544
+ return false;
545
+ }
546
+
547
+ return true;
548
+ } else {
549
+ // We didn't see a proposed checkpoint at build time, so we built on checkpointed parent from two slots ago.
550
+ // But if a new checkpoint for the previous slot appeared on L1 in the meantime, our checkpoint assumed the wrong parent,
551
+ // so we have to discard our work. This can happen if we're somehow cut off from p2p and fail to see the checkpoint
552
+ // proposal for the previous slot.
553
+ if (checkpointedNumber > parentCheckpointNumber) {
554
+ this.log.warn(
555
+ `Unexpected checkpoint ${checkpointedNumber} landed on L1 after we built on top of parent ${parentCheckpointNumber}, discarding pipelined work`,
556
+ { checkpointNumber: this.checkpointNumber, checkpointedNumber },
557
+ );
558
+ this.emitPipelinedCheckpointDiscarded('unexpected-parent-appeared');
559
+ return false;
560
+ }
561
+
562
+ return true;
563
+ }
564
+ }
565
+
566
+ /** Emits the pipelined-checkpoint-discarded event and records the metric. */
567
+ private emitPipelinedCheckpointDiscarded(reason: string): void {
568
+ this.metrics.recordPipelineParentCheckpointMismatch(reason);
569
+ this.eventEmitter.emit('pipelined-checkpoint-discarded', {
570
+ slot: this.targetSlot,
571
+ checkpointNumber: this.checkpointNumber,
572
+ reason,
573
+ });
574
+ }
575
+
576
+ /** Simulates and enqueues an invalidation request for the invalid parent checkpoint. */
577
+ private async enqueueInvalidation(validationStatus: ValidateCheckpointResult): Promise<void> {
578
+ if (this.config.skipInvalidateBlockAsProposer) {
579
+ this.log.warn(`Skipping checkpoint invalidation as proposer due to test configuration`);
580
+ return;
581
+ }
582
+ const invalidateRequest = await this.publisher.simulateInvalidateCheckpoint(validationStatus);
583
+ if (invalidateRequest) {
584
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
585
+ const txTimeoutAt = new Date((submissionSlotStart + this.l1Constants.slotDuration) * 1000);
586
+ this.publisher.enqueueInvalidateCheckpoint(invalidateRequest, { txTimeoutAt });
587
+ } else {
588
+ this.log.info(`Invalidation simulation returned undefined, checkpoint may have been removed already`, {
589
+ checkpointNumber: this.checkpointNumber,
590
+ });
591
+ }
592
+ }
593
+
594
+ @trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
595
+ return {
596
+ // nullish operator needed for tests
597
+ [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
598
+ [Attributes.SLOT_NUMBER]: this.targetSlot,
599
+ };
600
+ })
601
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
602
+ try {
603
+ const now = this.dateProvider.now();
604
+ if (this.proposedCheckpointData) {
605
+ // Measure against the wall-clock slot whose build window we are currently using.
606
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
607
+ // target-slot boundary a full slot away from the actual build start time.
608
+ const slotBoundaryMs = Number(getTimestampForSlot(this.getBuildSlot(), this.l1Constants)) * 1000;
609
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
610
+ }
611
+ this.checkpointMetrics.startCheckpointTiming(now);
612
+
613
+ // Get operator configured coinbase and fee recipient for this attestor
614
+ const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
615
+ const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
616
+
617
+ // Start the checkpoint
618
+ this.setState(SequencerState.INITIALIZING_CHECKPOINT);
619
+ this.logCheckpointEvent('slot-started', `Starting checkpoint proposal for slot ${this.targetSlot}`, {
620
+ buildSlot: this.getBuildSlot(),
621
+ submissionSlot: this.targetSlot,
622
+ slot: this.targetSlot,
623
+ checkpointNumber: this.checkpointNumber,
624
+ proposer: this.proposer?.toString(),
625
+ attestorAddress: this.attestorAddress.toString(),
626
+ publisherAddress: this.publisher.getSenderAddress().toString(),
627
+ coinbase: coinbase.toString(),
628
+ });
629
+ this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
630
+
631
+ // Enqueues checkpoint invalidation (constant for the whole slot)
632
+ if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
633
+ this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
634
+ }
635
+
636
+ // Build the simulation plan for this slot. When pipelining, this overrides L1's view of
637
+ // pending/archive/fee-header to "as if the proposed parent had landed", so both the
638
+ // mana-min-fee simulation (in the globals builder) and the pre-broadcast
639
+ // validateCheckpointHeader see the chain tip the eventual L1 send will see.
640
+ this.checkpointSimulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
641
+ checkpointNumber: this.checkpointNumber,
642
+ proposedCheckpointData: this.proposedCheckpointData,
643
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
644
+ checkpointedCheckpointNumber: this.checkpointedCheckpointNumber,
645
+ rollup: this.publisher.rollupContract,
646
+ signatureContext: this.signatureContext,
647
+ log: this.log,
648
+ });
649
+
650
+ const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
651
+ coinbase,
652
+ feeRecipient,
653
+ this.targetSlot,
654
+ this.checkpointSimulationOverridesPlan,
655
+ );
656
+
657
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
658
+ // Under pipelining the parent checkpoint may not be on L1 yet at build time, so the helper
659
+ // splices in the parent's checkpointOutHash from the locally-known proposed checkpoint so
660
+ // the resulting `epochOutHash` matches what validators (and L1) compute once the parent
661
+ // lands on L1.
662
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
663
+ blockSource: this.l2BlockSource,
664
+ epoch: this.targetEpoch,
665
+ checkpointNumber: this.checkpointNumber,
666
+ l1Constants: this.epochCache.getL1Constants(),
667
+ pipeliningEnabled: true,
668
+ proposedCheckpointData: this.proposedCheckpointData,
669
+ log: this.log,
670
+ });
671
+
672
+ // Chain start for this checkpoint's inbox rolling hash: the parent checkpoint's `inboxRollingHash`. Unlike the
673
+ // epoch out-hash tree, the chain is continuous across epochs, so this is always the immediately preceding
674
+ // checkpoint's value (or zero at genesis).
675
+ const previousInboxRollingHash = await getPreviousCheckpointInboxRollingHash({
676
+ blockSource: this.l2BlockSource,
677
+ checkpointNumber: this.checkpointNumber,
678
+ proposedCheckpointData: this.proposedCheckpointData,
679
+ log: this.log,
680
+ });
681
+
682
+ // Anchor the modifier to the predicted parent fee header: L1 will apply it against
683
+ // that, not against the latest published checkpoint (which lags by one under pipelining).
684
+ const predictedParentEthPerFeeAssetE12 =
685
+ this.checkpointSimulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
686
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12);
687
+
688
+ // Create a long-lived forked world state for the checkpoint builder
689
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
690
+
691
+ // Streaming Inbox: the consumption cursor starts at the parent state this checkpoint builds on. The fork's
692
+ // L1-to-L2 tree leaf count is the parent's cumulative consumed total (compact indexing), which resolves the
693
+ // parent's last-consumed bucket.
694
+ const streamingState = await this.resolveStreamingCheckpointStart(fork);
695
+
696
+ // Create checkpoint builder for the entire slot
697
+ const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
698
+ this.checkpointNumber,
699
+ checkpointGlobalVariables,
700
+ feeAssetPriceModifier,
701
+ previousCheckpointOutHashes,
702
+ previousInboxRollingHash,
703
+ fork,
704
+ this.log.getBindings(),
705
+ );
706
+
707
+ // Options for the validator client when creating block and checkpoint proposals
708
+ const blockProposalOptions: BlockProposalOptions = {
709
+ publishFullTxs: !!this.config.publishTxsWithProposals,
710
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
711
+ };
712
+
713
+ const checkpointProposalOptions: CheckpointProposalOptions = {
714
+ publishFullTxs: !!this.config.publishTxsWithProposals,
715
+ broadcastInvalidCheckpointProposal:
716
+ this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal,
717
+ };
718
+
719
+ let blocksInCheckpoint: L2Block[] = [];
720
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
721
+ const checkpointBuildTimer = new Timer();
722
+
723
+ try {
724
+ // Main loop: build blocks for the checkpoint
725
+ const result = await this.buildBlocksForCheckpoint(
726
+ checkpointBuilder,
727
+ checkpointGlobalVariables.timestamp,
728
+ blockProposalOptions,
729
+ streamingState,
730
+ );
731
+ blocksInCheckpoint = result.blocksInCheckpoint;
732
+ blockPendingBroadcast = result.blockPendingBroadcast;
733
+ } catch (err) {
734
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
735
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
736
+ // which is normal for block building (may have picked different txs)
737
+ if (this.handleHASigningError(err, 'Block proposal')) {
738
+ return undefined;
739
+ }
740
+ throw err;
741
+ }
742
+
743
+ if (blocksInCheckpoint.length === 0) {
744
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
745
+ slot: this.targetSlot,
746
+ checkpointNumber: this.checkpointNumber,
747
+ reason: 'no_blocks_built',
748
+ });
749
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
750
+ slot: this.targetSlot,
751
+ checkpointNumber: this.checkpointNumber,
752
+ reason: 'no_blocks_built',
753
+ });
754
+ this.eventEmitter.emit('checkpoint-empty', { slot: this.targetSlot });
755
+ return undefined;
756
+ }
757
+
758
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
759
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
760
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
761
+ slot: this.targetSlot,
762
+ checkpointNumber: this.checkpointNumber,
763
+ blocksBuilt: blocksInCheckpoint.length,
764
+ minBlocksForCheckpoint,
765
+ reason: 'min_blocks_not_met',
766
+ });
767
+ this.log.warn(
768
+ `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
769
+ {
770
+ slot: this.targetSlot,
771
+ checkpointNumber: this.checkpointNumber,
772
+ blocksBuilt: blocksInCheckpoint.length,
773
+ minBlocksForCheckpoint,
774
+ reason: 'min_blocks_not_met',
775
+ },
776
+ );
777
+ return undefined;
778
+ }
779
+
780
+ // Streaming Inbox censorship floor: re-derive the mandatory-consumption verdict from the final consumed
781
+ // position, independently of the per-block selection that produced it. Runs before the checkpoint is assembled,
782
+ // so the held last block and the checkpoint proposal are both still ungossiped and the propose tx is never
783
+ // sent for a checkpoint L1 would revert and validators would refuse to attest.
784
+ const consumption = await this.checkCheckpointConsumption(streamingState);
785
+ if (!consumption.sufficient) {
786
+ const { cutoffTimestamp, nextBucket } = consumption;
787
+ const context = {
788
+ slot: this.targetSlot,
789
+ checkpointNumber: this.checkpointNumber,
790
+ blocksBuilt: blocksInCheckpoint.length,
791
+ blocksRemaining: this.config.maxBlocksPerCheckpoint - blocksInCheckpoint.length,
792
+ checkpointStartTotalMsgCount: streamingState.checkpointStartTotalMsgCount,
793
+ consumedBucketSeq: streamingState.parent.seq,
794
+ consumedTotalMsgCount: streamingState.parent.totalMsgCount,
795
+ unconsumedBucketSeq: nextBucket?.seq,
796
+ unconsumedBucketTotalMsgCount: nextBucket?.totalMsgCount,
797
+ cutoffTimestamp,
798
+ reason: 'inbox_consumption_insufficient',
799
+ };
800
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, context);
801
+ this.log.warn(
802
+ `Checkpoint leaves a mandatory Inbox bucket unconsumed, skipping proposal; the streaming backlog does not ` +
803
+ `fit ${this.config.maxBlocksPerCheckpoint} blocks per checkpoint`,
804
+ context,
805
+ );
806
+ this.metrics.recordCheckpointProposalFailed('inbox_consumption_insufficient');
807
+ return undefined;
808
+ }
809
+
810
+ // Assemble and broadcast the checkpoint proposal, including the last block that was not
811
+ // broadcasted yet, and wait to collect the committee attestations.
812
+ this.setState(SequencerState.ASSEMBLING_CHECKPOINT);
813
+ const checkpoint = await checkpointBuilder.completeCheckpoint();
814
+
815
+ // Final validation: per-block limits are only checked if the operator set them explicitly.
816
+ // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
817
+ try {
818
+ validateCheckpoint(checkpoint, {
819
+ rollupManaLimit: this.l1Constants.rollupManaLimit,
820
+ maxL2BlockGas: this.config.maxL2BlockGas,
821
+ maxDABlockGas: this.config.maxDABlockGas,
822
+ maxTxsPerBlock: this.config.maxTxsPerBlock,
823
+ maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
824
+ });
825
+ } catch (err) {
826
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
827
+ slot: this.targetSlot,
828
+ checkpointNumber: this.checkpointNumber,
829
+ blocksBuilt: blocksInCheckpoint.length,
830
+ reason: 'invalid_checkpoint',
831
+ checkpoint: checkpoint.header.toInspect(),
832
+ });
833
+ this.log.error(`Built an invalid checkpoint at slot ${this.targetSlot} (skipping proposal)`, err, {
834
+ slot: this.targetSlot,
835
+ checkpointNumber: this.checkpointNumber,
836
+ blocksBuilt: blocksInCheckpoint.length,
837
+ reason: 'invalid_checkpoint',
838
+ checkpoint: checkpoint.header.toInspect(),
839
+ });
840
+ return undefined;
841
+ }
842
+
843
+ // Record checkpoint-level build metrics
844
+ this.checkpointMetrics.recordCheckpointBuild(
845
+ checkpointBuildTimer.ms(),
846
+ blocksInCheckpoint.length,
847
+ checkpoint.getStats().txCount,
848
+ Number(checkpoint.header.totalManaUsed.toBigInt()),
849
+ );
850
+ this.logCheckpointEvent('built', `Checkpoint built for slot ${this.targetSlot}`, {
851
+ slot: this.targetSlot,
852
+ buildSlot: this.getBuildSlot(),
853
+ checkpointNumber: this.checkpointNumber,
854
+ proposer: this.proposer?.toString(),
855
+ attestorAddress: this.attestorAddress.toString(),
856
+ publisherAddress: this.publisher.getSenderAddress().toString(),
857
+ blocksBuilt: blocksInCheckpoint.length,
858
+ txCount: checkpoint.getStats().txCount,
859
+ totalMana: Number(checkpoint.header.totalManaUsed.toBigInt()),
860
+ });
861
+
862
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
863
+ if (this.config.fishermanMode) {
864
+ this.log.info(
865
+ `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
866
+ `Skipping proposal in fisherman mode.`,
867
+ {
868
+ slot: this.targetSlot,
869
+ checkpoint: checkpoint.header.toInspect(),
870
+ blocksBuilt: blocksInCheckpoint.length,
871
+ },
872
+ );
873
+ this.metrics.recordCheckpointSuccess();
874
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
875
+ return {
876
+ checkpoint,
877
+ proposal: undefined!,
878
+ blockProposedAt: this.dateProvider.now(),
879
+ bucketHint: streamingState.lastBucketRef.bucketSeq,
880
+ };
881
+ }
882
+
883
+ // Validate the header against L1 state before broadcasting.
884
+ // If this fails the slot is aborted before any gossip work; state drift between here
885
+ // and the eventual L1 send is caught by the bundle simulate at send time.
886
+ try {
887
+ await this.publisher.validateCheckpointHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
888
+ } catch (err) {
889
+ this.log.error(`Pre-broadcast header validation failed for slot ${this.targetSlot}; aborting`, err, {
890
+ slot: this.targetSlot,
891
+ checkpointNumber: this.checkpointNumber,
892
+ });
893
+ this.metrics.recordCheckpointProposalFailed('header_validation_failed');
894
+ this.eventEmitter.emit('header-validation-failed', {
895
+ slot: this.targetSlot,
896
+ checkpointNumber: this.checkpointNumber,
897
+ reason: err instanceof Error ? err.message : String(err),
898
+ });
899
+ return undefined;
900
+ }
901
+
902
+ // Create the checkpoint proposal and broadcast it
903
+ const proposal = await this.validatorClient.createCheckpointProposal(
904
+ checkpoint.header,
905
+ checkpoint.archive.root,
906
+ this.checkpointNumber,
907
+ feeAssetPriceModifier,
908
+ blockPendingBroadcast,
909
+ this.proposer,
910
+ checkpointProposalOptions,
911
+ );
912
+
913
+ // Advance our own optimistic proposed-checkpoint tip locally before gossiping. Gossipsub
914
+ // doesn't echo our own messages back, so this is how the proposer makes its own proposed
915
+ // checkpoint visible for pipelining the next slot. Built from local checkpoint data — never
916
+ // from the broadcast proposal archive, which may be deliberately corrupted under test flags.
917
+ // Fail closed: if this throws, the outer catch aborts the slot before gossiping.
918
+ await this.syncProposedCheckpointToArchiver(checkpoint, blocksInCheckpoint.length, feeAssetPriceModifier);
919
+
920
+ const blockProposedAt = this.dateProvider.now();
921
+ if (this.config.skipBroadcastCheckpointProposal) {
922
+ // Test-only: suppress the CheckpointProposal so peers never see a proposed checkpoint for
923
+ // this slot, but still broadcast the held last block standalone so peers' archivers ingest
924
+ // it as a proposed-but-uncheckpointed tip — the exact orphan-block state that
925
+ // pruneOrphanProposedBlocks / checkSync must handle.
926
+ if (blockPendingBroadcast && !this.config.skipBroadcastProposals) {
927
+ await this.p2pClient.broadcastProposal(blockPendingBroadcast);
928
+ }
929
+ } else if (!this.config.skipBroadcastProposals) {
930
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
931
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
932
+ }
933
+
934
+ // Return immediately after broadcast — attestation collection happens in the background. The bucket hint is
935
+ // the streaming cursor's final consumed bucket, which matches the header's rolling hash whether or not a last
936
+ // block was held for broadcast.
937
+ return { checkpoint, proposal, blockProposedAt, bucketHint: streamingState.lastBucketRef.bucketSeq };
938
+ } catch (err) {
939
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
940
+ // swallow this error. It's already been logged by a function deeper in the stack
941
+ return undefined;
942
+ }
943
+
944
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
945
+ return undefined;
946
+ }
947
+ }
948
+
949
+ /**
950
+ * Builds blocks for a checkpoint within the current slot.
951
+ */
952
+ @trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint')
953
+ private async buildBlocksForCheckpoint(
954
+ checkpointBuilder: CheckpointBuilder,
955
+ timestamp: bigint,
956
+ blockProposalOptions: BlockProposalOptions,
957
+ streamingState?: StreamingCheckpointState,
958
+ ): Promise<{
959
+ blocksInCheckpoint: L2Block[];
960
+ blockPendingBroadcast: BlockProposal | undefined;
961
+ }> {
962
+ const blocksInCheckpoint: L2Block[] = [];
963
+ const txHashesAlreadyIncluded = new Set<string>();
964
+ const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
965
+
966
+ // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
967
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
968
+
969
+ while (true) {
970
+ const blocksBuilt = blocksInCheckpoint.length;
971
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
972
+ const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
973
+
974
+ if (blocksBuilt >= this.config.maxBlocksPerCheckpoint) {
975
+ this.log.debug(`Reached max blocks per checkpoint`, {
976
+ slot: this.targetSlot,
977
+ blocksBuilt,
978
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint,
979
+ });
980
+ break;
981
+ }
982
+
983
+ const nowSeconds = this.dateProvider.now() / 1000;
984
+ const timingInfo = this.timetable.selectNextSubslot(this.targetSlot, nowSeconds);
985
+
986
+ if (!timingInfo.canStart) {
987
+ this.log.debug(`Not enough time left in slot to start another block`, {
988
+ slot: this.targetSlot,
989
+ blocksBuilt,
990
+ nowSeconds,
991
+ });
992
+ break;
993
+ }
994
+
995
+ // Streaming Inbox: select this block's message bundle against the current (not-yet-advanced) consumption
996
+ // cursor. The state is only advanced once the block builds successfully, so a failed build (retried in a
997
+ // later sub-slot) re-derives the bundle rather than losing it. The builder inserts the bundle and rolls it
998
+ // back with the fork on failure. The censorship cutoff floor must apply on whichever block ends the
999
+ // checkpoint, which includes the block that reaches the per-checkpoint block cap, not just the timetable's
1000
+ // last sub-slot.
1001
+ const isCheckpointFinalBlock = timingInfo.isLastBlock || blocksBuilt + 1 >= this.config.maxBlocksPerCheckpoint;
1002
+ const selection = streamingState
1003
+ ? await this.selectStreamingBundle(streamingState, isCheckpointFinalBlock, nowSeconds)
1004
+ : undefined;
1005
+
1006
+ // No checkpoint ending on this block can satisfy the censorship floor, so building it would only waste the
1007
+ // sub-slot: stop here and let the post-loop consumption check abort the checkpoint before anything is gossiped.
1008
+ if (selection?.insufficientFinalBlockCapacity) {
1009
+ this.log.warn(
1010
+ `Streaming Inbox backlog does not fit the checkpoint's remaining blocks; stopping block building`,
1011
+ {
1012
+ slot: this.targetSlot,
1013
+ checkpointNumber: this.checkpointNumber,
1014
+ blocksBuilt,
1015
+ blockNumber,
1016
+ },
1017
+ );
1018
+ break;
1019
+ }
1020
+
1021
+ const streamingBundle = streamingState ? (selection && selection.consume ? selection.bundle : []) : undefined;
1022
+
1023
+ const buildResult = await this.buildSingleBlock(checkpointBuilder, {
1024
+ // Create all blocks with the same timestamp
1025
+ blockTimestamp: timestamp,
1026
+ // Create an empty block if we haven't already and this is the last one
1027
+ forceCreate: timingInfo.isLastBlock && blocksBuilt === 0 && this.config.buildCheckpointIfEmpty,
1028
+ buildDeadline: new Date(timingInfo.deadline * 1000),
1029
+ blockNumber,
1030
+ indexWithinCheckpoint,
1031
+ txHashesAlreadyIncluded,
1032
+ l1ToL2Messages: streamingBundle,
1033
+ });
1034
+
1035
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
1036
+ if ('failure' in buildResult) {
1037
+ // If this was the last subslot, we're done.
1038
+ if (timingInfo.isLastBlock) {
1039
+ break;
1040
+ }
1041
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
1042
+ await this.waitUntilNextSubslot(timingInfo.deadline);
1043
+ continue;
1044
+ }
1045
+
1046
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
1047
+ // We don't want to risk building more blocks if something went wrong.
1048
+ if ('error' in buildResult) {
1049
+ if (!(buildResult.error instanceof SequencerInterruptedError)) {
1050
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
1051
+ slot: this.targetSlot,
1052
+ blocksBuilt,
1053
+ error: buildResult.error,
1054
+ });
1055
+ }
1056
+ break;
1057
+ }
1058
+
1059
+ const { block, usedTxs } = buildResult;
1060
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
1061
+ isFirstBlock: blocksBuilt === 0,
1062
+ isLastBlock: timingInfo.isLastBlock,
1063
+ });
1064
+
1065
+ blocksInCheckpoint.push(block);
1066
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
1067
+
1068
+ // Streaming Inbox: the block built successfully, so advance the consumption cursor and carry this block's
1069
+ // rolling-hash bucket reference. A block that consumed nothing reuses the parent bucket reference.
1070
+ let blockBucketRef: InboxBucketRef | undefined = undefined;
1071
+ if (streamingState && selection) {
1072
+ if (selection.consume) {
1073
+ streamingState.parent = { seq: selection.bucket.seq, totalMsgCount: selection.bucket.totalMsgCount };
1074
+ streamingState.lastBucketRef = InboxBucketRef.fromBucket(selection.bucket);
1075
+ }
1076
+ blockBucketRef = streamingState.lastBucketRef;
1077
+ }
1078
+
1079
+ // Sign the block proposal. This will throw if HA signing fails.
1080
+ const proposal = await this.createBlockProposal(
1081
+ block,
1082
+ usedTxs,
1083
+ {
1084
+ ...blockProposalOptions,
1085
+ broadcastInvalidBlockProposal:
1086
+ blockProposalOptions.broadcastInvalidBlockProposal ||
1087
+ block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint,
1088
+ },
1089
+ blockBucketRef,
1090
+ );
1091
+
1092
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
1093
+ // so we avoid polluting our archive with a block that would fail.
1094
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
1095
+ // If this throws, we abort the entire checkpoint.
1096
+ await this.syncProposedBlockToArchiver(block);
1097
+
1098
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
1099
+ if (timingInfo.isLastBlock) {
1100
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
1101
+ slot: this.targetSlot,
1102
+ blockNumber,
1103
+ blocksBuilt,
1104
+ });
1105
+
1106
+ blockPendingBroadcast = proposal;
1107
+ break;
1108
+ }
1109
+
1110
+ // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
1111
+ if (proposal && !this.config.skipBroadcastProposals) {
1112
+ await this.p2pClient.broadcastProposal(proposal);
1113
+ }
1114
+
1115
+ // Wait until the next block's start time
1116
+ await this.waitUntilNextSubslot(timingInfo.deadline);
1117
+ }
1118
+
1119
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
1120
+ slot: this.targetSlot,
1121
+ blocksBuilt: blocksInCheckpoint.length,
1122
+ });
1123
+
1124
+ return { blocksInCheckpoint, blockPendingBroadcast };
1125
+ }
1126
+
1127
+ /** Creates a block proposal for a given block via the validator client (unless in fisherman mode) */
1128
+ private createBlockProposal(
1129
+ block: L2Block,
1130
+ usedTxs: Tx[],
1131
+ blockProposalOptions: BlockProposalOptions,
1132
+ bucketRef?: InboxBucketRef,
1133
+ ): Promise<BlockProposal | undefined> {
1134
+ if (this.config.fishermanMode) {
1135
+ this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
1136
+ return Promise.resolve(undefined);
1137
+ }
1138
+ return this.validatorClient.createBlockProposal(
1139
+ block.header,
1140
+ this.checkpointNumber,
1141
+ block.indexWithinCheckpoint,
1142
+ block.archive.root,
1143
+ usedTxs,
1144
+ this.proposer,
1145
+ blockProposalOptions,
1146
+ bucketRef,
1147
+ );
1148
+ }
1149
+
1150
+ /**
1151
+ * Resolves where a streaming-Inbox checkpoint's consumption starts: the parent checkpoint's last-consumed bucket.
1152
+ * The parent's cumulative consumed total is the L1-to-L2 message tree leaf count of the fork
1153
+ * this checkpoint builds on (compact indexing makes leaf count equal cumulative message count), which resolves the
1154
+ * parent bucket by total. Genesis is the `total = 0` case, resolving the genesis bucket 0.
1155
+ */
1156
+ private async resolveStreamingCheckpointStart(fork: MerkleTreeWriteOperations): Promise<StreamingCheckpointState> {
1157
+ const parentInfo = await fork.getTreeInfo(MerkleTreeId.L1_TO_L2_MESSAGE_TREE);
1158
+ const parentTotalMsgCount = parentInfo.size;
1159
+ const parentBucket = await this.l1ToL2MessageSource.getInboxBucketByTotalMsgCount(parentTotalMsgCount);
1160
+ if (parentBucket === undefined) {
1161
+ throw new Error(
1162
+ `Streaming inbox: cannot resolve parent Inbox bucket for cumulative total ${parentTotalMsgCount} ` +
1163
+ `(checkpoint ${this.checkpointNumber}); local Inbox view has not synced it`,
1164
+ );
1165
+ }
1166
+ return {
1167
+ checkpointStartTotalMsgCount: parentTotalMsgCount,
1168
+ parent: { seq: parentBucket.seq, totalMsgCount: parentBucket.totalMsgCount },
1169
+ lastBucketRef: InboxBucketRef.fromBucket(parentBucket),
1170
+ };
1171
+ }
1172
+
1173
+ /**
1174
+ * Whether the checkpoint's final consumed position satisfies the streaming-Inbox censorship floor, mirroring the
1175
+ * mandatory-consumption assert in `ProposeLib.validateInboxConsumption`: the first bucket left unconsumed must be
1176
+ * absent, past the cutoff, or a cap-escape. The bucket and cutoff the verdict was taken against are returned for
1177
+ * diagnostics.
1178
+ *
1179
+ * Derived from the consumption cursor rather than from the per-block selections that advanced it, so a selector that
1180
+ * stops short of a mandatory bucket is caught here regardless of how it reported the shortfall.
1181
+ */
1182
+ private async checkCheckpointConsumption(
1183
+ state: StreamingCheckpointState,
1184
+ ): Promise<{ sufficient: boolean; nextBucket: InboxBucket | undefined; cutoffTimestamp: bigint }> {
1185
+ const nextBucket = await this.l1ToL2MessageSource.getInboxBucket(state.parent.seq + 1n);
1186
+ const cutoffTimestamp = getInboxCutoffTimestamp(this.targetSlot, this.l1Constants);
1187
+ const sufficient = isInboxConsumptionSufficient({
1188
+ nextBucket,
1189
+ cutoffTimestamp,
1190
+ checkpointStartTotalMsgCount: state.checkpointStartTotalMsgCount,
1191
+ perCheckpointCap: MAX_L1_TO_L2_MSGS_PER_CHECKPOINT,
1192
+ });
1193
+ return { sufficient, nextBucket, cutoffTimestamp };
1194
+ }
1195
+
1196
+ /**
1197
+ * Selects this block's streaming-Inbox message bundle against the current consumption cursor, mirroring the L1
1198
+ * predicate in `ProposeLib.validateInboxConsumption`. Does not mutate the cursor; the caller
1199
+ * advances it only after the block builds successfully.
1200
+ */
1201
+ private selectStreamingBundle(
1202
+ state: StreamingCheckpointState,
1203
+ isLastBlock: boolean,
1204
+ nowSeconds: number,
1205
+ ): Promise<InboxBucketSelection> {
1206
+ const cutoffTimestamp = getInboxCutoffTimestamp(this.targetSlot, this.l1Constants);
1207
+ return selectInboxBucketForBlock({
1208
+ messageSource: this.l1ToL2MessageSource,
1209
+ now: BigInt(Math.floor(nowSeconds)),
1210
+ minBucketAgeSeconds: BigInt(this.l1Constants.ethereumSlotDuration),
1211
+ parent: state.parent,
1212
+ checkpointStartTotalMsgCount: state.checkpointStartTotalMsgCount,
1213
+ perBlockCap: MAX_L1_TO_L2_MSGS_PER_BLOCK,
1214
+ perCheckpointCap: MAX_L1_TO_L2_MSGS_PER_CHECKPOINT,
1215
+ isLastBlock,
1216
+ cutoffTimestamp,
1217
+ });
1218
+ }
1219
+
1220
+ /**
1221
+ * Sleeps until it is time to produce the next block in the slot.
1222
+ * @param nextSubslotStart - Absolute wall-clock timestamp in seconds of the previous sub-slot deadline.
1223
+ */
1224
+ @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
1225
+ protected async waitUntilNextSubslot(nextSubslotStart: number) {
1226
+ this.setState(SequencerState.WAITING_UNTIL_NEXT_BLOCK);
1227
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s`, {
1228
+ slot: this.targetSlot,
1229
+ });
1230
+ await this.awaitInterruptibleSleep(Math.max(0, nextSubslotStart * 1000 - this.dateProvider.now()));
1231
+ }
1232
+
1233
+ /** Builds a single block. Called from the main block building loop. */
1234
+ @trackSpan('CheckpointProposalJob.buildSingleBlock')
1235
+ protected async buildSingleBlock(
1236
+ checkpointBuilder: CheckpointBuilder,
1237
+ opts: {
1238
+ forceCreate?: boolean;
1239
+ blockTimestamp: bigint;
1240
+ blockNumber: BlockNumber;
1241
+ indexWithinCheckpoint: IndexWithinCheckpoint;
1242
+ buildDeadline: Date | undefined;
1243
+ txHashesAlreadyIncluded: Set<string>;
1244
+ /** Streaming Inbox message bundle for this block's L1-to-L2 tree; undefined when it consumes nothing. */
1245
+ l1ToL2Messages?: Fr[];
1246
+ },
1247
+ ): Promise<
1248
+ { block: L2Block; usedTxs: Tx[] } | { failure: 'insufficient-txs' | 'insufficient-valid-txs' } | { error: Error }
1249
+ > {
1250
+ const {
1251
+ blockTimestamp,
1252
+ forceCreate,
1253
+ blockNumber,
1254
+ indexWithinCheckpoint,
1255
+ buildDeadline,
1256
+ txHashesAlreadyIncluded,
1257
+ l1ToL2Messages,
1258
+ } = opts;
1259
+
1260
+ this.log.verbose(
1261
+ `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot}`,
1262
+ { ...checkpointBuilder.getConstantData(), ...opts },
1263
+ );
1264
+
1265
+ try {
1266
+ // Wait until we have enough txs to build the block
1267
+ const { canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
1268
+ if (!canStartBuilding) {
1269
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1270
+ reason: 'insufficient_txs',
1271
+ blockNumber,
1272
+ slot: this.targetSlot,
1273
+ checkpointNumber: this.checkpointNumber,
1274
+ indexWithinCheckpoint,
1275
+ minTxs,
1276
+ });
1277
+ this.log.verbose(
1278
+ `Not enough age-eligible txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (needs ${minTxs} eligible)`,
1279
+ {
1280
+ reason: 'insufficient_txs',
1281
+ blockNumber,
1282
+ slot: this.targetSlot,
1283
+ checkpointNumber: this.checkpointNumber,
1284
+ indexWithinCheckpoint,
1285
+ minTxs,
1286
+ },
1287
+ );
1288
+ this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, slot: this.targetSlot });
1289
+ this.metrics.recordBlockProposalFailed('insufficient_txs');
1290
+ return { failure: 'insufficient-txs' };
1291
+ }
1292
+
1293
+ // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
1294
+ // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
1295
+ // Block building only executes txs, so we skip loading their proofs unless these same tx objects get attached
1296
+ // to the broadcasted proposals via publishTxsWithProposals.
1297
+ const pendingTxs = filter(
1298
+ this.p2pClient.iterateEligiblePendingTxs({ includeProof: !!this.config.publishTxsWithProposals }),
1299
+ tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
1300
+ );
1301
+
1302
+ this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot}`, {
1303
+ slot: this.targetSlot,
1304
+ blockNumber,
1305
+ indexWithinCheckpoint,
1306
+ });
1307
+ this.setState(SequencerState.CREATING_BLOCK);
1308
+
1309
+ // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
1310
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
1311
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
1312
+ // A zero-tx block is proven by the no-txs block-root circuit at any index, but one carrying neither txs
1313
+ // nor messages past the first block is pure padding, so the floor for minValidTxs is 1 there.
1314
+ const configuredMinValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
1315
+ const minValidTxs =
1316
+ indexWithinCheckpoint > 0 && (l1ToL2Messages?.length ?? 0) === 0
1317
+ ? Math.max(configuredMinValidTxs, 1)
1318
+ : configuredMinValidTxs;
1319
+ const blockBuilderOptions: BlockBuilderOptions = {
1320
+ maxTransactions: this.config.maxTxsPerBlock,
1321
+ maxBlockGas:
1322
+ this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined
1323
+ ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity)
1324
+ : undefined,
1325
+ deadline: buildDeadline,
1326
+ isBuildingProposal: true,
1327
+ minValidTxs,
1328
+ maxBlocksPerCheckpoint: this.timetable.getMaxBlocksPerCheckpoint(),
1329
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
1330
+ perBlockDAAllocationMultiplier: this.config.perBlockDAAllocationMultiplier,
1331
+ l1ToL2Messages,
1332
+ };
1333
+
1334
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
1335
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
1336
+ // updated for blocks that will be discarded.
1337
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
1338
+ checkpointBuilder,
1339
+ pendingTxs,
1340
+ blockNumber,
1341
+ blockTimestamp,
1342
+ blockBuilderOptions,
1343
+ );
1344
+
1345
+ // If any txs failed during execution, drop them from the mempool so we don't pick them up again
1346
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
1347
+
1348
+ if (buildResult.status === 'insufficient-valid-txs') {
1349
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1350
+ reason: 'insufficient_valid_txs',
1351
+ slot: this.targetSlot,
1352
+ checkpointNumber: this.checkpointNumber,
1353
+ blockNumber,
1354
+ numTxs: buildResult.processedCount,
1355
+ indexWithinCheckpoint,
1356
+ minValidTxs,
1357
+ });
1358
+ this.log.warn(
1359
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`,
1360
+ {
1361
+ reason: 'insufficient_valid_txs',
1362
+ slot: this.targetSlot,
1363
+ checkpointNumber: this.checkpointNumber,
1364
+ blockNumber,
1365
+ numTxs: buildResult.processedCount,
1366
+ indexWithinCheckpoint,
1367
+ minValidTxs,
1368
+ },
1369
+ );
1370
+ this.eventEmitter.emit('block-build-failed', {
1371
+ reason: `Insufficient valid txs`,
1372
+ slot: this.targetSlot,
1373
+ });
1374
+ this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
1375
+ return { failure: 'insufficient-valid-txs' };
1376
+ }
1377
+
1378
+ // Block creation succeeded, emit stats and metrics
1379
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
1380
+
1381
+ const blockStats = {
1382
+ eventName: 'l2-block-built',
1383
+ duration: blockBuildDuration,
1384
+ publicProcessDuration: publicProcessorDuration,
1385
+ ...block.getStats(),
1386
+ } satisfies L2BlockBuiltStats;
1387
+
1388
+ const blockHash = await block.hash();
1389
+ const txHashes = block.body.txEffects.map(tx => tx.txHash);
1390
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
1391
+
1392
+ this.log.info(
1393
+ `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot} with ${numTxs} txs`,
1394
+ { blockHash, txHashes, manaPerSec, ...blockStats },
1395
+ );
1396
+
1397
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
1398
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
1399
+ this.eventEmitter.emit('block-proposed', {
1400
+ blockNumber: block.number,
1401
+ blockHash,
1402
+ checkpointNumber: this.checkpointNumber,
1403
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1404
+ slot: this.targetSlot,
1405
+ buildSlot: this.getBuildSlot(),
1406
+ });
1407
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
1408
+
1409
+ return { block, usedTxs };
1410
+ } catch (err: any) {
1411
+ this.eventEmitter.emit('block-build-failed', {
1412
+ reason: err.message,
1413
+ slot: this.targetSlot,
1414
+ });
1415
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1416
+ reason: err instanceof Error ? err.message : String(err),
1417
+ slot: this.targetSlot,
1418
+ checkpointNumber: this.checkpointNumber,
1419
+ blockNumber,
1420
+ });
1421
+ this.log.error(`Error building block`, err, {
1422
+ reason: err instanceof Error ? err.message : String(err),
1423
+ slot: this.targetSlot,
1424
+ checkpointNumber: this.checkpointNumber,
1425
+ blockNumber,
1426
+ });
1427
+ this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
1428
+ this.metrics.recordFailedBlock();
1429
+ return { error: err };
1430
+ }
1431
+ }
1432
+
1433
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
1434
+ private async buildSingleBlockWithCheckpointBuilder(
1435
+ checkpointBuilder: CheckpointBuilder,
1436
+ pendingTxs: AsyncIterable<Tx>,
1437
+ blockNumber: BlockNumber,
1438
+ blockTimestamp: bigint,
1439
+ blockBuilderOptions: BlockBuilderOptions,
1440
+ ) {
1441
+ try {
1442
+ const workTimer = new Timer();
1443
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
1444
+ const blockBuildDuration = workTimer.ms();
1445
+ return { ...result, blockBuildDuration, status: 'success' as const };
1446
+ } catch (err: unknown) {
1447
+ if (isErrorClass(err, InsufficientValidTxsError)) {
1448
+ return {
1449
+ failedTxs: err.failedTxs,
1450
+ processedCount: err.processedCount,
1451
+ status: 'insufficient-valid-txs' as const,
1452
+ };
1453
+ }
1454
+ throw err;
1455
+ }
1456
+ }
1457
+
1458
+ /** Waits until minTxs are available on the pool for building a block. */
1459
+ @trackSpan('CheckpointProposalJob.waitForMinTxs')
1460
+ private async waitForMinTxs(opts: {
1461
+ forceCreate?: boolean;
1462
+ blockNumber: BlockNumber;
1463
+ indexWithinCheckpoint: IndexWithinCheckpoint;
1464
+ buildDeadline: Date | undefined;
1465
+ /** Streaming Inbox message bundle this block consumes; a non-empty bundle permits a zero-tx (message-only) block. */
1466
+ l1ToL2Messages?: Fr[];
1467
+ }): Promise<{ canStartBuilding: boolean; minTxs: number }> {
1468
+ const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
1469
+
1470
+ // A non-empty streaming Inbox bundle is work on its own: the block must be produced even with zero txs,
1471
+ // regardless of minTxsPerBlock, so the messages get inserted (message-only block).
1472
+ // Without a bundle, a non-first block needs at least one tx to avoid empty filler blocks even when
1473
+ // minTxsPerBlock is zero.
1474
+ const hasStreamingBundle = (opts.l1ToL2Messages?.length ?? 0) > 0;
1475
+ const minTxs = hasStreamingBundle
1476
+ ? 0
1477
+ : indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0
1478
+ ? 1
1479
+ : this.config.minTxsPerBlock;
1480
+
1481
+ // Latest time to keep waiting for txs: wait_for_txs_deadline = block_build_deadline(k) - min_block_duration.
1482
+ const startBuildingDeadline = buildDeadline
1483
+ ? new Date(buildDeadline.getTime() - this.timetable.minBlockDuration * 1000)
1484
+ : undefined;
1485
+
1486
+ // Gate on age-eligible txs so we don't start building on txs the builder would then filter out for being
1487
+ // too fresh. hasEligiblePendingTxs early-exits once minTxs are eligible instead of counting the whole pool.
1488
+ while (!forceCreate && !(await this.p2pClient.hasEligiblePendingTxs(minTxs))) {
1489
+ // If we're past deadline, or we have no deadline, give up
1490
+ const now = this.dateProvider.nowAsDate();
1491
+ if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
1492
+ return { canStartBuilding: false, minTxs };
1493
+ }
1494
+
1495
+ // Wait a bit before checking again
1496
+ this.setState(SequencerState.WAITING_FOR_TXS);
1497
+ this.log.verbose(
1498
+ `Waiting for ${minTxs} age-eligible txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot}`,
1499
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint, minTxs },
1500
+ );
1501
+ await this.waitForTxsPollingInterval();
1502
+ }
1503
+
1504
+ return { canStartBuilding: true, minTxs };
1505
+ }
1506
+
1507
+ private async getSignedCommitteeAttestations(
1508
+ broadcast: CheckpointProposalBroadcast,
1509
+ ): Promise<{ attestations: CommitteeAttestationsAndSigners; attestationsSignature: Signature } | undefined> {
1510
+ const { proposal, blockProposedAt } = broadcast;
1511
+ this.setState(SequencerState.COLLECTING_ATTESTATIONS);
1512
+ const attestations = await this.waitForAttestations(proposal);
1513
+ if (!attestations) {
1514
+ return undefined;
1515
+ }
1516
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
1517
+
1518
+ // Proposer must sign over the attestations before pushing them to L1
1519
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1520
+ try {
1521
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
1522
+ attestations,
1523
+ signer,
1524
+ this.targetSlot,
1525
+ this.checkpointNumber,
1526
+ );
1527
+ return { attestations, attestationsSignature };
1528
+ } catch (err) {
1529
+ if (this.handleHASigningError(err, 'Attestations signature')) {
1530
+ return;
1531
+ }
1532
+ this.log.error(`Error signing attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1533
+ return undefined;
1534
+ }
1535
+ }
1536
+
1537
+ /**
1538
+ * Waits for enough attestations to be collected via p2p.
1539
+ * This is run after all blocks for the checkpoint have been built.
1540
+ */
1541
+ @trackSpan('CheckpointProposalJob.waitForAttestations')
1542
+ private async waitForAttestations(
1543
+ proposal: CheckpointProposal,
1544
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
1545
+ if (this.config.fishermanMode) {
1546
+ this.log.debug('Skipping attestation collection in fisherman mode');
1547
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1548
+ }
1549
+
1550
+ const slotNumber = proposal.slotNumber;
1551
+ const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
1552
+
1553
+ if (!committee) {
1554
+ throw new Error('No committee when collecting attestations');
1555
+ } else if (committee.length === 0) {
1556
+ this.log.verbose(`Attesting committee is empty`);
1557
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1558
+ } else {
1559
+ this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
1560
+ }
1561
+
1562
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
1563
+
1564
+ if (this.config.skipCollectingAttestations) {
1565
+ this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
1566
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
1567
+ this.logCheckpointAttestations('collected', committee, attestations ?? [], numberOfRequiredAttestations, {
1568
+ reason: 'collect_own_only',
1569
+ });
1570
+ return new CommitteeAttestationsAndSigners(
1571
+ orderAttestations(attestations ?? [], committee),
1572
+ this.getSignatureContext(),
1573
+ );
1574
+ }
1575
+
1576
+ // Hard attestation-collection cutoff = the single consensus attestation_deadline (target_slot_start + S - 2E).
1577
+ const attestationDeadlineSeconds = this.timetable.getAttestationDeadline(this.targetSlot);
1578
+ const attestationDeadline = new Date(attestationDeadlineSeconds * 1000);
1579
+
1580
+ this.metrics.recordRequiredAttestations(
1581
+ numberOfRequiredAttestations,
1582
+ Math.max(0, attestationDeadline.getTime() - this.dateProvider.now()),
1583
+ );
1584
+
1585
+ const collectAttestationsTimer = new Timer();
1586
+ let collectedAttestationsCount: number = 0;
1587
+ try {
1588
+ const attestations = await this.validatorClient.collectAttestations(
1589
+ proposal,
1590
+ numberOfRequiredAttestations,
1591
+ attestationDeadline,
1592
+ this.checkpointNumber,
1593
+ );
1594
+
1595
+ collectedAttestationsCount = attestations.length;
1596
+
1597
+ // Trim attestations to minimum required to save L1 calldata gas
1598
+ const localAddresses = this.validatorClient.getValidatorAddresses();
1599
+ const trimmed = trimAttestations(
1600
+ attestations,
1601
+ numberOfRequiredAttestations,
1602
+ this.attestorAddress,
1603
+ localAddresses,
1604
+ );
1605
+ if (trimmed.length < attestations.length) {
1606
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
1607
+ }
1608
+
1609
+ // Rollup contract requires that the signatures are provided in the order of the committee
1610
+ const sorted = orderAttestations(trimmed, committee);
1611
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1612
+ submittedCount: trimmed.length,
1613
+ });
1614
+
1615
+ // Manipulate the attestations if we've been configured to do so
1616
+ if (
1617
+ this.config.injectFakeAttestation ||
1618
+ this.config.injectHighSValueAttestation ||
1619
+ this.config.injectUnrecoverableSignatureAttestation ||
1620
+ this.config.injectYParityAttestation ||
1621
+ this.config.shuffleAttestationOrdering
1622
+ ) {
1623
+ return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
1624
+ }
1625
+
1626
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
1627
+ } catch (err) {
1628
+ if (err && err instanceof AttestationTimeoutError) {
1629
+ collectedAttestationsCount = err.collectedCount;
1630
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1631
+ collectedCount: collectedAttestationsCount,
1632
+ reason: 'timeout',
1633
+ });
1634
+ this.log.error(
1635
+ `Timeout while waiting for attestations for checkpoint proposal at slot ${proposal.slotNumber} (collected ${collectedAttestationsCount}/${numberOfRequiredAttestations})`,
1636
+ err,
1637
+ );
1638
+ } else {
1639
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1640
+ collectedCount: collectedAttestationsCount,
1641
+ reason: err instanceof Error ? err.message : String(err),
1642
+ });
1643
+ this.log.error(`Error collecting attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1644
+ }
1645
+ return undefined;
1646
+ } finally {
1647
+ this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
1648
+ }
1649
+ }
1650
+
1651
+ private logCheckpointAttestations(
1652
+ status: 'collected' | 'failed',
1653
+ committee: EthAddress[],
1654
+ attestations: CheckpointAttestation[] | undefined,
1655
+ requiredAttestations: number,
1656
+ opts: { collectedCount?: number; submittedCount?: number; reason?: string } = {},
1657
+ ) {
1658
+ const signedValidators =
1659
+ attestations
1660
+ ?.map(attestation => attestation.getSender()?.toString())
1661
+ .filter((address): address is `0x${string}` => address !== undefined) ?? [];
1662
+ const collectedCount = opts.collectedCount ?? new Set(signedValidators).size;
1663
+ const missingValidatorCount = status === 'failed' ? Math.max(0, requiredAttestations - collectedCount) : undefined;
1664
+ this.logCheckpointEvent(`attestations-${status}`, `Checkpoint attestations ${status} for slot ${this.targetSlot}`, {
1665
+ slot: this.targetSlot,
1666
+ checkpointNumber: this.checkpointNumber,
1667
+ committeeSize: committee.length,
1668
+ requiredAttestations,
1669
+ collectedAttestations: collectedCount,
1670
+ ...(opts.submittedCount !== undefined && { submittedAttestations: opts.submittedCount }),
1671
+ ...(missingValidatorCount !== undefined && { missingValidatorCount }),
1672
+ ...(opts.reason !== undefined && { reason: opts.reason }),
1673
+ });
1674
+ }
1675
+
1676
+ /** Breaks the attestations before publishing based on attack configs */
1677
+ private manipulateAttestations(
1678
+ slotNumber: SlotNumber,
1679
+ epoch: EpochNumber,
1680
+ seed: bigint,
1681
+ committee: EthAddress[],
1682
+ attestations: CommitteeAttestation[],
1683
+ ) {
1684
+ // Compute the proposer index in the committee, since we dont want to tweak it.
1685
+ // Otherwise, the L1 rollup contract will reject the block outright.
1686
+ const proposerIndex = Number(
1687
+ this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
1688
+ );
1689
+
1690
+ if (
1691
+ this.config.injectFakeAttestation ||
1692
+ this.config.injectHighSValueAttestation ||
1693
+ this.config.injectUnrecoverableSignatureAttestation
1694
+ ) {
1695
+ // Find non-empty attestations that are not from the proposer
1696
+ const nonProposerIndices: number[] = [];
1697
+ for (let i = 0; i < attestations.length; i++) {
1698
+ if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
1699
+ nonProposerIndices.push(i);
1700
+ }
1701
+ }
1702
+ if (nonProposerIndices.length > 0) {
1703
+ const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
1704
+ if (this.config.injectHighSValueAttestation) {
1705
+ this.log.warn(
1706
+ `Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
1707
+ );
1708
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
1709
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
1710
+ this.log.warn(
1711
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
1712
+ );
1713
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
1714
+ } else {
1715
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1716
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
1717
+ }
1718
+ }
1719
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1720
+ }
1721
+
1722
+ if (this.config.injectYParityAttestation) {
1723
+ // Force every non-proposer signed slot's recovery byte to yParity (v ∈ {0, 1}) form in the packed L1
1724
+ // tuple, after packAttestations has canonicalized it. The proposer's own slot is left canonical so
1725
+ // propose() still passes verifyProposer. Models a malicious proposer landing a checkpoint L1 accepts
1726
+ // but that can never be proven (ECDSA.recover rejects v ∉ {27, 28}).
1727
+ this.log.warn(`Injecting yParity attestations in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
1728
+ return new MaliciousYParityCommitteeAttestationsAndSigners(
1729
+ attestations,
1730
+ proposerIndex,
1731
+ this.getSignatureContext(),
1732
+ );
1733
+ }
1734
+
1735
+ if (this.config.shuffleAttestationOrdering) {
1736
+ this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
1737
+
1738
+ const shuffled = [...attestations];
1739
+
1740
+ // Find two non-proposer positions that both have non-empty signatures to swap.
1741
+ // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
1742
+ // signers array stays correctly aligned with L1's committee reconstruction.
1743
+ const swappable: number[] = [];
1744
+ for (let k = 0; k < shuffled.length; k++) {
1745
+ if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
1746
+ swappable.push(k);
1747
+ }
1748
+ }
1749
+ if (swappable.length >= 2) {
1750
+ const [i, j] = [swappable[0], swappable[1]];
1751
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
1752
+ }
1753
+
1754
+ const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
1755
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
1756
+ }
1757
+
1758
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1759
+ }
1760
+
1761
+ private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
1762
+ if (failedTxs.length === 0) {
1763
+ return;
1764
+ }
1765
+ const failedTxData = failedTxs.map(fail => fail.tx);
1766
+ const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
1767
+ const failures = failedTxs.map(fail => ({ txHash: fail.tx.getTxHash().toString(), reason: fail.error.message }));
1768
+ this.log.warn(
1769
+ `Dropping ${failedTxs.length} txs from mempool due to failures during block building for slot ${this.targetSlot}`,
1770
+ { slot: this.targetSlot, checkpointNumber: this.checkpointNumber, failures },
1771
+ );
1772
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
1773
+ }
1774
+
1775
+ /**
1776
+ * Adds the proposed block to the archiver so it's available via P2P.
1777
+ * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1778
+ * would never receive its own block without this explicit sync.
1779
+ *
1780
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1781
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1782
+ * whenever the real proposer's block arrives from L1.
1783
+ */
1784
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
1785
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1786
+ this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1787
+ blockNumber: block.number,
1788
+ slot: block.header.globalVariables.slotNumber,
1789
+ });
1790
+ return;
1791
+ }
1792
+ this.log.debug(`Syncing proposed block ${block.number} to archiver`, {
1793
+ blockNumber: block.number,
1794
+ slot: block.header.globalVariables.slotNumber,
1795
+ });
1796
+ await this.blockSink.addBlock(block);
1797
+ }
1798
+
1799
+ /**
1800
+ * Adds the proposed checkpoint to the archiver so the proposer's optimistic proposed-checkpoint
1801
+ * tip advances locally. Gossip doesn't echo our own messages back, so without this the proposer
1802
+ * would never see its own proposed checkpoint and couldn't pipeline the next slot.
1803
+ *
1804
+ * Skipped whenever proposed blocks aren't pushed (`skipPushProposedBlocksToArchiver`, fisherman
1805
+ * mode): the archiver derives the checkpoint archive from its stored blocks, so without them the
1806
+ * push would fail. All blocks were already added (and awaited) during block building, so this
1807
+ * needs no retry — they are guaranteed present by the time we get here.
1808
+ */
1809
+ private async syncProposedCheckpointToArchiver(
1810
+ checkpoint: Checkpoint,
1811
+ blockCount: number,
1812
+ feeAssetPriceModifier: bigint,
1813
+ ): Promise<void> {
1814
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1815
+ return;
1816
+ }
1817
+ const startBlock = BlockNumber(this.syncedToBlockNumber + 1);
1818
+ this.log.debug(`Syncing proposed checkpoint ${this.checkpointNumber} to archiver`, {
1819
+ checkpointNumber: this.checkpointNumber,
1820
+ slot: this.targetSlot,
1821
+ startBlock,
1822
+ blockCount,
1823
+ });
1824
+ await this.blockSink.addProposedCheckpoint({
1825
+ header: checkpoint.header,
1826
+ checkpointNumber: this.checkpointNumber,
1827
+ startBlock,
1828
+ blockCount,
1829
+ totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
1830
+ feeAssetPriceModifier,
1831
+ });
1832
+ }
1833
+
1834
+ /** Runs fee analysis and logs checkpoint outcome as fisherman */
1835
+ private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
1836
+ // Perform L1 fee analysis before clearing requests
1837
+ // The callback is invoked asynchronously after the next block is mined
1838
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, analysis =>
1839
+ this.metrics.recordFishermanFeeAnalysis(analysis),
1840
+ );
1841
+
1842
+ if (checkpoint) {
1843
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
1844
+ ...checkpoint.toCheckpointInfo(),
1845
+ ...checkpoint.getStats(),
1846
+ feeAnalysisId: feeAnalysis?.id,
1847
+ });
1848
+ } else {
1849
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1850
+ slot: this.targetSlot,
1851
+ feeAnalysisId: feeAnalysis?.id,
1852
+ });
1853
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
1854
+ }
1855
+
1856
+ this.publisher.clearPendingRequests();
1857
+ }
1858
+
1859
+ /**
1860
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
1861
+ */
1862
+ private handleHASigningError(err: any, errorContext: string): boolean {
1863
+ if (err instanceof DutyAlreadySignedError) {
1864
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1865
+ slot: this.targetSlot,
1866
+ signedByNode: err.signedByNode,
1867
+ });
1868
+ return true;
1869
+ }
1870
+ if (err instanceof SlashingProtectionError) {
1871
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1872
+ slot: this.targetSlot,
1873
+ existingMessageHash: err.existingMessageHash,
1874
+ attemptedMessageHash: err.attemptedMessageHash,
1875
+ });
1876
+ return true;
1877
+ }
1878
+ return false;
1879
+ }
1880
+
1881
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
1882
+ protected async waitForTxsPollingInterval(): Promise<void> {
1883
+ await this.awaitInterruptibleSleep(TXS_POLLING_MS);
1884
+ }
1885
+
1886
+ public getPublisher() {
1887
+ return this.publisher;
1888
+ }
1889
+ }