@aztec/sequencer-client 0.0.1-commit.03f7ef2 → 0.0.1-commit.04d373f

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 (145) hide show
  1. package/README.md +282 -21
  2. package/dest/client/sequencer-client.d.ts +20 -11
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +67 -33
  5. package/dest/config.d.ts +29 -7
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +82 -37
  8. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  9. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  10. package/dest/global_variable_builder/fee_predictor.js +128 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_provider.js +58 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +14 -16
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +16 -50
  17. package/dest/global_variable_builder/index.d.ts +4 -2
  18. package/dest/global_variable_builder/index.d.ts.map +1 -1
  19. package/dest/global_variable_builder/index.js +2 -0
  20. package/dest/index.d.ts +2 -3
  21. package/dest/index.d.ts.map +1 -1
  22. package/dest/index.js +1 -2
  23. package/dest/publisher/config.d.ts +47 -17
  24. package/dest/publisher/config.d.ts.map +1 -1
  25. package/dest/publisher/config.js +121 -42
  26. package/dest/publisher/index.d.ts +2 -1
  27. package/dest/publisher/index.d.ts.map +1 -1
  28. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  29. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  31. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  32. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  33. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  34. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  35. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  36. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  37. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  38. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  39. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  40. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  41. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  42. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  43. package/dest/publisher/sequencer-publisher-factory.d.ts +12 -6
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +27 -3
  46. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  47. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  49. package/dest/publisher/sequencer-publisher.d.ts +108 -81
  50. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  51. package/dest/publisher/sequencer-publisher.js +876 -403
  52. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  53. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  54. package/dest/sequencer/automine/automine_factory.js +84 -0
  55. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  56. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  57. package/dest/sequencer/automine/automine_sequencer.js +506 -0
  58. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  59. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  60. package/dest/sequencer/chain_state_overrides.js +98 -0
  61. package/dest/sequencer/checkpoint_proposal_job.d.ts +87 -16
  62. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  63. package/dest/sequencer/checkpoint_proposal_job.js +1331 -203
  64. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  65. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  66. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  67. package/dest/sequencer/checkpoint_voter.d.ts +3 -3
  68. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  69. package/dest/sequencer/checkpoint_voter.js +34 -13
  70. package/dest/sequencer/events.d.ts +47 -2
  71. package/dest/sequencer/events.d.ts.map +1 -1
  72. package/dest/sequencer/index.d.ts +3 -3
  73. package/dest/sequencer/index.d.ts.map +1 -1
  74. package/dest/sequencer/index.js +2 -2
  75. package/dest/sequencer/metrics.d.ts +23 -8
  76. package/dest/sequencer/metrics.d.ts.map +1 -1
  77. package/dest/sequencer/metrics.js +158 -143
  78. package/dest/sequencer/sequencer.d.ts +92 -29
  79. package/dest/sequencer/sequencer.d.ts.map +1 -1
  80. package/dest/sequencer/sequencer.js +818 -157
  81. package/dest/sequencer/timetable.d.ts +17 -6
  82. package/dest/sequencer/timetable.d.ts.map +1 -1
  83. package/dest/sequencer/timetable.js +51 -46
  84. package/dest/sequencer/types.d.ts +2 -2
  85. package/dest/sequencer/types.d.ts.map +1 -1
  86. package/dest/test/index.d.ts +4 -7
  87. package/dest/test/index.d.ts.map +1 -1
  88. package/dest/test/mock_checkpoint_builder.d.ts +29 -17
  89. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  90. package/dest/test/mock_checkpoint_builder.js +86 -34
  91. package/dest/test/utils.d.ts +13 -9
  92. package/dest/test/utils.d.ts.map +1 -1
  93. package/dest/test/utils.js +31 -20
  94. package/package.json +29 -28
  95. package/src/client/sequencer-client.ts +94 -38
  96. package/src/config.ts +107 -46
  97. package/src/global_variable_builder/README.md +44 -0
  98. package/src/global_variable_builder/fee_predictor.ts +172 -0
  99. package/src/global_variable_builder/fee_provider.ts +75 -0
  100. package/src/global_variable_builder/global_builder.ts +26 -63
  101. package/src/global_variable_builder/index.ts +3 -1
  102. package/src/index.ts +5 -4
  103. package/src/publisher/config.ts +157 -45
  104. package/src/publisher/index.ts +3 -0
  105. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  106. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  107. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  108. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  109. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  110. package/src/publisher/sequencer-publisher-factory.ts +39 -10
  111. package/src/publisher/sequencer-publisher-metrics.ts +17 -69
  112. package/src/publisher/sequencer-publisher.ts +611 -521
  113. package/src/sequencer/README.md +152 -450
  114. package/src/sequencer/automine/README.md +46 -0
  115. package/src/sequencer/automine/automine_factory.ts +145 -0
  116. package/src/sequencer/automine/automine_sequencer.ts +592 -0
  117. package/src/sequencer/chain_state_overrides.ts +162 -0
  118. package/src/sequencer/checkpoint_proposal_job.ts +1138 -230
  119. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  120. package/src/sequencer/checkpoint_voter.ts +31 -17
  121. package/src/sequencer/events.ts +50 -2
  122. package/src/sequencer/index.ts +2 -2
  123. package/src/sequencer/metrics.ts +168 -151
  124. package/src/sequencer/sequencer.ts +535 -162
  125. package/src/sequencer/timetable.ts +70 -57
  126. package/src/sequencer/types.ts +1 -1
  127. package/src/test/index.ts +3 -6
  128. package/src/test/mock_checkpoint_builder.ts +149 -73
  129. package/src/test/utils.ts +78 -30
  130. package/dest/sequencer/block_builder.d.ts +0 -26
  131. package/dest/sequencer/block_builder.d.ts.map +0 -1
  132. package/dest/sequencer/block_builder.js +0 -129
  133. package/dest/sequencer/checkpoint_builder.d.ts +0 -63
  134. package/dest/sequencer/checkpoint_builder.d.ts.map +0 -1
  135. package/dest/sequencer/checkpoint_builder.js +0 -131
  136. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  137. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  138. package/dest/tx_validator/nullifier_cache.js +0 -24
  139. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  140. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  141. package/dest/tx_validator/tx_validator_factory.js +0 -53
  142. package/src/sequencer/block_builder.ts +0 -217
  143. package/src/sequencer/checkpoint_builder.ts +0 -217
  144. package/src/tx_validator/nullifier_cache.ts +0 -30
  145. package/src/tx_validator/tx_validator_factory.ts +0 -133
@@ -1,42 +1,74 @@
1
- import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
2
1
  import type { EpochCache } from '@aztec/epoch-cache';
3
- import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { SimulationOverridesPlan } from '@aztec/ethereum/contracts';
3
+ import {
4
+ BlockNumber,
5
+ CheckpointNumber,
6
+ EpochNumber,
7
+ IndexWithinCheckpoint,
8
+ SlotNumber,
9
+ } from '@aztec/foundation/branded-types';
4
10
  import { randomInt } from '@aztec/foundation/crypto/random';
11
+ import {
12
+ flipSignature,
13
+ generateRecoverableSignature,
14
+ generateUnrecoverableSignature,
15
+ } from '@aztec/foundation/crypto/secp256k1-signer';
16
+ import { Fr } from '@aztec/foundation/curves/bn254';
5
17
  import { EthAddress } from '@aztec/foundation/eth-address';
6
18
  import { Signature } from '@aztec/foundation/eth-signature';
7
19
  import { filter } from '@aztec/foundation/iterator';
8
- import type { Logger } from '@aztec/foundation/log';
20
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
21
+ import { retryUntil } from '@aztec/foundation/retry';
9
22
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
10
23
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
11
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
24
+ import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
12
25
  import type { P2P } from '@aztec/p2p';
13
26
  import type { SlasherClientInterface } from '@aztec/slasher';
14
27
  import {
15
28
  CommitteeAttestation,
16
29
  CommitteeAttestationsAndSigners,
17
- L2BlockNew,
30
+ L2Block,
31
+ type L2BlockSink,
32
+ type L2BlockSource,
18
33
  MaliciousCommitteeAttestationsAndSigners,
34
+ type ProposedCheckpointSink,
35
+ type ValidateCheckpointResult,
19
36
  } from '@aztec/stdlib/block';
20
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
21
- import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
37
+ import {
38
+ type Checkpoint,
39
+ type ProposedCheckpointData,
40
+ getPreviousCheckpointOutHashes,
41
+ validateCheckpoint,
42
+ } from '@aztec/stdlib/checkpoint';
43
+ import { computeQuorum, getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
22
44
  import { Gas } from '@aztec/stdlib/gas';
23
- import type {
24
- PublicProcessorLimits,
25
- ResolvedSequencerConfig,
26
- WorldStateSynchronizer,
45
+ import {
46
+ type BlockBuilderOptions,
47
+ InsufficientValidTxsError,
48
+ type ResolvedSequencerConfig,
49
+ type WorldStateSynchronizer,
27
50
  } from '@aztec/stdlib/interfaces/server';
28
- import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
29
- import type { BlockProposal, BlockProposalOptions } from '@aztec/stdlib/p2p';
30
- import { orderAttestations } from '@aztec/stdlib/p2p';
31
- import { CheckpointHeader } from '@aztec/stdlib/rollup';
51
+ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
52
+ import type {
53
+ BlockProposal,
54
+ BlockProposalOptions,
55
+ CheckpointAttestation,
56
+ CheckpointProposal,
57
+ CheckpointProposalOptions,
58
+ CoordinationSignatureContext,
59
+ } from '@aztec/stdlib/p2p';
60
+ import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
32
61
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
33
62
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
34
63
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
35
- import type { ValidatorClient } from '@aztec/validator-client';
64
+ import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
65
+ import { CheckpointBuilder, type FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec/validator-client';
66
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
36
67
 
37
68
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
38
- import type { InvalidateBlockRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
39
- import { CheckpointBuilder, type FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
69
+ import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
70
+ import { buildCheckpointSimulationOverridesPlan } from './chain_state_overrides.js';
71
+ import type { CheckpointProposalJobMetricsRecorder } from './checkpoint_proposal_job_metrics.js';
40
72
  import { CheckpointVoter } from './checkpoint_voter.js';
41
73
  import { SequencerInterruptedError } from './errors.js';
42
74
  import type { SequencerEvents } from './events.js';
@@ -48,50 +80,117 @@ import { SequencerState } from './utils.js';
48
80
  /** How much time to sleep while waiting for min transactions to accumulate for a block */
49
81
  const TXS_POLLING_MS = 500;
50
82
 
83
+ /** Result from proposeCheckpoint when a checkpoint was successfully built and broadcast. */
84
+ type CheckpointProposalBroadcast = {
85
+ checkpoint: Checkpoint;
86
+ proposal: CheckpointProposal;
87
+ blockProposedAt: number;
88
+ };
89
+
90
+ /** Result after attestation collection and signing, ready for L1 submission. */
91
+ type CheckpointProposalResult = {
92
+ checkpoint: Checkpoint;
93
+ attestations: CommitteeAttestationsAndSigners;
94
+ attestationsSignature: Signature;
95
+ };
96
+
51
97
  /**
52
98
  * Handles the execution of a checkpoint proposal after the initial preparation phase.
53
99
  * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
54
100
  * as well as enqueueing votes for slashing and governance proposals. This class is created from
55
101
  * the Sequencer once the check for being the proposer for the slot has succeeded.
56
102
  */
57
- export class CheckpointProposalJob {
103
+ export class CheckpointProposalJob implements Traceable {
104
+ protected readonly log: Logger;
105
+ private readonly checkpointEventLog: Logger;
106
+
107
+ /** Tracks the fire-and-forget L1 submission promise so it can be awaited during shutdown. */
108
+ private pendingL1Submission: Promise<void> | undefined;
109
+
110
+ /**
111
+ * Chain state overrides built once per slot in proposeCheckpoint after the checkpoint is
112
+ * complete. Carries the pending parent override (archive + slot + fee header) for pipelining,
113
+ * or the invalidation pending override when rolling back. Consumed by
114
+ * publisher.validateBlockHeader before broadcast.
115
+ */
116
+ private checkpointSimulationOverridesPlan?: SimulationOverridesPlan;
117
+
118
+ private getSignatureContext(): CoordinationSignatureContext {
119
+ return this.signatureContext;
120
+ }
121
+
58
122
  constructor(
59
- private readonly slot: SlotNumber,
123
+ private readonly slotNow: SlotNumber,
124
+ private readonly targetSlot: SlotNumber,
125
+ private readonly targetEpoch: EpochNumber,
60
126
  private readonly checkpointNumber: CheckpointNumber,
61
127
  private readonly syncedToBlockNumber: BlockNumber,
128
+ private readonly checkpointedCheckpointNumber: CheckpointNumber,
62
129
  // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
63
130
  private readonly proposer: EthAddress | undefined,
64
131
  private readonly publisher: SequencerPublisher,
65
132
  private readonly attestorAddress: EthAddress,
66
- private readonly invalidateBlock: InvalidateBlockRequest | undefined,
133
+ private readonly invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
67
134
  private readonly validatorClient: ValidatorClient,
68
135
  private readonly globalsBuilder: GlobalVariableBuilder,
69
136
  private readonly p2pClient: P2P,
70
137
  private readonly worldState: WorldStateSynchronizer,
71
138
  private readonly l1ToL2MessageSource: L1ToL2MessageSource,
139
+ private readonly l2BlockSource: L2BlockSource,
72
140
  private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
141
+ private readonly blockSink: L2BlockSink & ProposedCheckpointSink,
73
142
  private readonly l1Constants: SequencerRollupConstants,
143
+ private readonly signatureContext: CoordinationSignatureContext,
74
144
  protected config: ResolvedSequencerConfig,
75
145
  protected timetable: SequencerTimetable,
76
146
  private readonly slasherClient: SlasherClientInterface | undefined,
77
147
  private readonly epochCache: EpochCache,
78
148
  private readonly dateProvider: DateProvider,
79
149
  private readonly metrics: SequencerMetrics,
80
- private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
150
+ private readonly checkpointMetrics: CheckpointProposalJobMetricsRecorder,
151
+ protected readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
81
152
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
82
- protected readonly log: Logger,
83
- ) {}
153
+ public readonly tracer: Tracer,
154
+ bindings?: LoggerBindings,
155
+ private readonly proposedCheckpointData?: ProposedCheckpointData,
156
+ ) {
157
+ this.log = createLogger('sequencer:checkpoint-proposal', {
158
+ ...bindings,
159
+ instanceId: `slot-${this.slotNow}`,
160
+ });
161
+ this.checkpointEventLog = createLogger('sequencer:checkpoint-events', {
162
+ ...bindings,
163
+ instanceId: `slot-${this.slotNow}`,
164
+ });
165
+ }
166
+
167
+ /** Awaits the pending L1 submission if one is in progress. Call during shutdown. */
168
+ public async awaitPendingSubmission(): Promise<void> {
169
+ this.log.info('Awaiting pending L1 payload submission');
170
+ await this.pendingL1Submission;
171
+ }
172
+
173
+ private logCheckpointEvent(eventName: string, message: string, fields: Record<string, unknown>): void {
174
+ this.checkpointEventLog.debug(message, {
175
+ eventName: `sequencer-checkpoint-${eventName}`,
176
+ ...fields,
177
+ });
178
+ }
84
179
 
85
180
  /**
86
181
  * Executes the checkpoint proposal job.
87
- * Returns the published checkpoint if successful, undefined otherwise.
182
+ * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
183
+ * Attestation collection, signing, and L1 submission are backgrounded so the
184
+ * work loop can return to IDLE immediately for consecutive slot proposals.
185
+ * Returns the built checkpoint if successful, undefined otherwise.
88
186
  */
187
+ @trackSpan('CheckpointProposalJob.execute')
89
188
  public async execute(): Promise<Checkpoint | undefined> {
90
189
  // Enqueue governance and slashing votes (returns promises that will be awaited later)
91
190
  // In fisherman mode, we simulate slashing but don't actually publish to L1
92
191
  // These are constant for the whole slot, so we only enqueue them once
93
192
  const votesPromises = new CheckpointVoter(
94
- this.slot,
193
+ this.targetSlot,
95
194
  this.publisher,
96
195
  this.attestorAddress,
97
196
  this.validatorClient,
@@ -102,66 +201,407 @@ export class CheckpointProposalJob {
102
201
  this.log,
103
202
  ).enqueueVotes();
104
203
 
105
- // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
106
- const checkpoint = await this.proposeCheckpoint();
204
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
205
+ // Returns after broadcast — attestation collection is deferred.
206
+ const broadcast = await this.proposeCheckpoint();
207
+
208
+ if (!broadcast) {
209
+ await Promise.all(votesPromises);
210
+ // Still submit votes even without a checkpoint.
211
+ // Under proposer pipelining, vote-offenses signatures are EIP-712-bound to `targetSlot`
212
+ // (the pipelined slot in which the multicall is expected to mine). Submitting at the
213
+ // wall-clock time would let the multicall mine in a different L2 slot, causing
214
+ // signature verification to fail silently inside Multicall3. Delay submission to the
215
+ // start of `targetSlot` so the tx mines in the slot the vote was signed for.
216
+ if (!this.config.fishermanMode) {
217
+ this.pendingL1Submission = this.publisher.sendRequestsAt(this.targetSlot).then(() => {});
218
+ }
219
+ return undefined;
220
+ }
107
221
 
108
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
109
- await Promise.all(votesPromises);
222
+ const { checkpoint } = broadcast;
223
+ this.metrics.recordCheckpointProposalSuccess();
110
224
 
111
225
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
112
226
  if (this.config.fishermanMode) {
113
227
  await this.handleCheckpointEndAsFisherman(checkpoint);
114
- return;
228
+ return checkpoint;
115
229
  }
116
230
 
117
- // Then send everything to L1
118
- const l1Response = await this.publisher.sendRequests();
119
- const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
120
- if (proposedAction) {
121
- this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.slot });
122
- const coinbase = checkpoint?.header.coinbase;
123
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
124
- return checkpoint;
125
- } else if (checkpoint) {
126
- this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.slot });
127
- return undefined;
231
+ // Background the attestation signing → L1 pipeline so the work loop is unblocked
232
+ this.pendingL1Submission = this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises);
233
+
234
+ // Return the built checkpoint immediately — the work loop is now unblocked
235
+ return checkpoint;
236
+ }
237
+
238
+ /**
239
+ * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
240
+ * Runs as a fire-and-forget task stored in `pendingL1Submission` so the work loop is unblocked.
241
+ */
242
+ private async waitForAttestationsAndEnqueueSubmissionAsync(
243
+ broadcast: CheckpointProposalBroadcast,
244
+ votesPromises: Promise<unknown>[],
245
+ ): Promise<void> {
246
+ const { checkpoint } = broadcast;
247
+ const isPipelining = this.epochCache.isProposerPipeliningEnabled();
248
+
249
+ try {
250
+ // Wait for all votes actions, enqueued at the beginning, to resolve
251
+ await Promise.all(votesPromises);
252
+
253
+ // Try to collect attestations from the committee
254
+ const signedAttestations = await this.getSignedCommitteeAttestations(broadcast);
255
+
256
+ // If pipelining, wait for the previous checkpoint to land on L1 before submitting,
257
+ // so we can check it matches the proposed checkpoint we used as parent, and has valid attestations.
258
+ if (signedAttestations && (!isPipelining || (await this.waitForValidParentCheckpointOnL1()))) {
259
+ await this.enqueueCheckpointForSubmission({ checkpoint, ...signedAttestations });
260
+ }
261
+
262
+ // If we failed to collect attestations, at least check if we need to issue an invalidation
263
+ // Note that if we are not pipelining, we enqueued the invalidation at the beginning
264
+ if (!signedAttestations && isPipelining && (await this.waitForSyncedL2SlotNumber(this.slotNow))) {
265
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
266
+ if (!validationStatus.valid) {
267
+ this.log.warn(
268
+ `Checkpoint ${validationStatus.checkpoint.checkpointNumber} has invalid attestations, enqueuing invalidation in spite of attestation collection failure`,
269
+ { checkpoint: validationStatus.checkpoint, reason: validationStatus.reason },
270
+ );
271
+ await this.enqueueInvalidation(validationStatus);
272
+ }
273
+ }
274
+
275
+ // Send whatever was enqueued: votes + (propose | invalidation | nothing).
276
+ const l1Response = await this.publisher.sendRequestsAt(this.targetSlot);
277
+ const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
278
+ if (proposedAction) {
279
+ this.logCheckpointEvent('published', `Checkpoint published for slot ${this.targetSlot}`, {
280
+ slot: this.targetSlot,
281
+ checkpointNumber: this.checkpointNumber,
282
+ successfulActions: l1Response?.successfulActions,
283
+ sentActions: l1Response?.sentActions,
284
+ });
285
+ this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
286
+ const coinbase = checkpoint.header.coinbase;
287
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
288
+ } else {
289
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
290
+ slot: this.targetSlot,
291
+ checkpointNumber: this.checkpointNumber,
292
+ successfulActions: l1Response?.successfulActions,
293
+ failedActions: l1Response?.failedActions,
294
+ sentActions: l1Response?.sentActions,
295
+ expiredActions: l1Response?.expiredActions,
296
+ reason: 'propose_action_not_successful',
297
+ });
298
+ this.log.warn(`Checkpoint publish failed for slot ${this.targetSlot}`, {
299
+ slot: this.targetSlot,
300
+ checkpointNumber: this.checkpointNumber,
301
+ successfulActions: l1Response?.successfulActions,
302
+ failedActions: l1Response?.failedActions,
303
+ sentActions: l1Response?.sentActions,
304
+ expiredActions: l1Response?.expiredActions,
305
+ reason: 'propose_action_not_successful',
306
+ });
307
+ this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
308
+ if (isPipelining) {
309
+ this.metrics.recordPipelineDiscard();
310
+ }
311
+ }
312
+ } catch (err) {
313
+ if (err instanceof SequencerInterruptedError) {
314
+ return;
315
+ }
316
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
317
+ slot: this.targetSlot,
318
+ checkpointNumber: this.checkpointNumber,
319
+ reason: err instanceof Error ? err.message : String(err),
320
+ });
321
+ this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err, {
322
+ slot: this.targetSlot,
323
+ checkpointNumber: this.checkpointNumber,
324
+ reason: err instanceof Error ? err.message : String(err),
325
+ });
326
+ this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
327
+ if (isPipelining) {
328
+ this.metrics.recordPipelineDiscard();
329
+ }
128
330
  }
129
331
  }
130
332
 
131
- private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
333
+ /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */
334
+ private async enqueueCheckpointForSubmission(result: CheckpointProposalResult): Promise<void> {
335
+ const { checkpoint, attestations, attestationsSignature } = result;
336
+
337
+ this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.targetSlot);
338
+ const aztecSlotDuration = this.l1Constants.slotDuration;
339
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
340
+ const txTimeoutAt = new Date((submissionSlotStart + aztecSlotDuration) * 1000);
341
+
342
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
343
+ if (
344
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
345
+ this.config.skipPublishingCheckpointsPercent > 0
346
+ ) {
347
+ const roll = Math.max(0, randomInt(100));
348
+ if (roll < this.config.skipPublishingCheckpointsPercent) {
349
+ this.log.warn(
350
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${roll}`,
351
+ );
352
+ return;
353
+ }
354
+ }
355
+
356
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
357
+ txTimeoutAt,
358
+ });
359
+ }
360
+
361
+ /**
362
+ * Wait until the archiver syncs past the given L2 slot number.
363
+ * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
364
+ * L1 submission window and is no longer useful.
365
+ */
366
+ private async waitForSyncedL2SlotNumber(waitForSlot: SlotNumber): Promise<boolean> {
367
+ const targetSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
368
+ const targetSlotEndMs = (targetSlotStart + this.l1Constants.slotDuration) * 1000;
369
+ const syncDelayTolerance = this.l1Constants.ethereumSlotDuration * 2 * 1000;
370
+ const timeoutSeconds = Math.max(0.1, (targetSlotEndMs + syncDelayTolerance - this.dateProvider.now()) / 1000);
371
+
132
372
  try {
373
+ return await retryUntil(
374
+ async () => {
375
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
376
+ return syncedSlot !== undefined && syncedSlot >= waitForSlot;
377
+ },
378
+ `archiver sync past slot ${waitForSlot}`,
379
+ timeoutSeconds,
380
+ 0.2,
381
+ );
382
+ } catch {
383
+ this.log.warn(
384
+ `Archiver did not sync L1 past slot ${waitForSlot} before slot ${this.targetSlot} expired, discarding pipelined work`,
385
+ { checkpointNumber: this.checkpointNumber },
386
+ );
387
+ this.emitPipelinedCheckpointDiscarded('archiver-sync-timeout');
388
+ return false;
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Waits for the parent checkpoint to land on L1 before submitting a pipelined checkpoint.
394
+ * Polls until the archiver has synced L1 past the parent's slot, then verifies:
395
+ * - If we built on a proposed parent: it must have landed on L1 with matching hash and valid attestations.
396
+ * - If we built without a proposed parent: no new checkpoint must have appeared for that slot.
397
+ * If the parent has invalid attestations, enqueues an invalidation. Returns whether to proceed with the proposal.
398
+ */
399
+ protected async waitForValidParentCheckpointOnL1(): Promise<boolean> {
400
+ if (this.config.skipWaitForValidParentCheckpointOnL1) {
401
+ this.log.warn(`Skipping waitForValidParentCheckpointOnL1 due to test configuration`, {
402
+ checkpointNumber: this.checkpointNumber,
403
+ });
404
+ return true;
405
+ }
406
+
407
+ const parentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 1);
408
+
409
+ // Wait until archiver has synced L1 past the parent's slot (slotNow)
410
+ if (!(await this.waitForSyncedL2SlotNumber(this.slotNow))) {
411
+ return false;
412
+ }
413
+
414
+ const tips = await this.l2BlockSource.getL2Tips();
415
+ const checkpointedNumber = tips.checkpointed.checkpoint.number;
416
+
417
+ // We built on top of a proposed checkpoint. Verify it landed on L1 as expected.
418
+ if (this.proposedCheckpointData) {
419
+ // After syncing from L1 we see the chain tip has invalid attestations. This means the parent checkpoint was posted
420
+ // with invalid attestations, or it built on top of something with invalid attestations and didnt invalidate them.
421
+ // Either way, we thought our parent would be valid, so we have to throw away our work. But at least we'll try and
422
+ // invalidate on L1 so we clean up the chain for the next proposer. And we'll slash them, but that's handled elsewhere.
423
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
424
+ if (!validationStatus.valid) {
425
+ this.log.warn(
426
+ `Parent checkpoint ${parentCheckpointNumber} has invalid attestations, discarding pipelined work`,
427
+ { checkpointNumber: this.checkpointNumber, reason: validationStatus.reason },
428
+ );
429
+ this.emitPipelinedCheckpointDiscarded('parent-invalid-attestations');
430
+ await this.enqueueInvalidation(validationStatus);
431
+ return false;
432
+ }
433
+
434
+ // The pending chain is valid. But did the parent checkpoint land on L1 at all?
435
+ if (checkpointedNumber < parentCheckpointNumber) {
436
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} did not land on L1, discarding pipelined work`, {
437
+ checkpointNumber: this.checkpointNumber,
438
+ checkpointedNumber,
439
+ });
440
+ this.emitPipelinedCheckpointDiscarded('parent-not-on-l1');
441
+ return false;
442
+ }
443
+
444
+ // It landed. But is it the one we were expecting?
445
+ const expectedHash = this.proposedCheckpointData.header.hash().toString();
446
+ if (tips.checkpointed.checkpoint.hash !== expectedHash) {
447
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} hash mismatch on L1, discarding pipelined work`, {
448
+ checkpointNumber: this.checkpointNumber,
449
+ expectedHash,
450
+ actualHash: tips.checkpointed.checkpoint.hash,
451
+ });
452
+ this.emitPipelinedCheckpointDiscarded('parent-hash-mismatch');
453
+ return false;
454
+ }
455
+
456
+ return true;
457
+ } else {
458
+ // We didn't see a proposed checkpoint at build time, so we built on checkpointed parent from two slots ago.
459
+ // But if a new checkpoint for the previous slot appeared on L1 in the meantime, our checkpoint assumed the wrong parent,
460
+ // so we have to discard our work. This can happen if we're somehow cut off from p2p and fail to see the checkpoint
461
+ // proposal for the previous slot.
462
+ if (checkpointedNumber > parentCheckpointNumber) {
463
+ this.log.warn(
464
+ `Unexpected checkpoint ${checkpointedNumber} landed on L1 after we built on top of parent ${parentCheckpointNumber}, discarding pipelined work`,
465
+ { checkpointNumber: this.checkpointNumber, checkpointedNumber },
466
+ );
467
+ this.emitPipelinedCheckpointDiscarded('unexpected-parent-appeared');
468
+ return false;
469
+ }
470
+
471
+ return true;
472
+ }
473
+ }
474
+
475
+ /** Emits the pipelined-checkpoint-discarded event and records the metric. */
476
+ private emitPipelinedCheckpointDiscarded(reason: string): void {
477
+ this.metrics.recordPipelineParentCheckpointMismatch(reason);
478
+ this.eventEmitter.emit('pipelined-checkpoint-discarded', {
479
+ slot: this.targetSlot,
480
+ checkpointNumber: this.checkpointNumber,
481
+ reason,
482
+ });
483
+ }
484
+
485
+ /** Simulates and enqueues an invalidation request for the invalid parent checkpoint. */
486
+ private async enqueueInvalidation(validationStatus: ValidateCheckpointResult): Promise<void> {
487
+ if (this.config.skipInvalidateBlockAsProposer) {
488
+ this.log.warn(`Skipping checkpoint invalidation as proposer due to test configuration`);
489
+ return;
490
+ }
491
+ const invalidateRequest = await this.publisher.simulateInvalidateCheckpoint(validationStatus);
492
+ if (invalidateRequest) {
493
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
494
+ const txTimeoutAt = new Date((submissionSlotStart + this.l1Constants.slotDuration) * 1000);
495
+ this.publisher.enqueueInvalidateCheckpoint(invalidateRequest, { txTimeoutAt });
496
+ } else {
497
+ this.log.info(`Invalidation simulation returned undefined, checkpoint may have been removed already`, {
498
+ checkpointNumber: this.checkpointNumber,
499
+ });
500
+ }
501
+ }
502
+
503
+ @trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
504
+ return {
505
+ // nullish operator needed for tests
506
+ [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
507
+ [Attributes.SLOT_NUMBER]: this.targetSlot,
508
+ };
509
+ })
510
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
511
+ try {
512
+ const now = this.dateProvider.now();
513
+ if (this.epochCache.isProposerPipeliningEnabled() && this.proposedCheckpointData) {
514
+ // Measure against the wall-clock slot whose build window we are currently using.
515
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
516
+ // target-slot boundary a full slot away from the actual build start time.
517
+ const slotBoundaryMs = Number(getTimestampForSlot(this.slotNow, this.l1Constants)) * 1000;
518
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
519
+ }
520
+ this.checkpointMetrics.startCheckpointTiming(now);
521
+
133
522
  // Get operator configured coinbase and fee recipient for this attestor
134
523
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
135
524
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
136
525
 
137
526
  // Start the checkpoint
138
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
139
- this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
527
+ this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
528
+ this.logCheckpointEvent('slot-started', `Starting checkpoint proposal for slot ${this.targetSlot}`, {
529
+ buildSlot: this.slotNow,
530
+ submissionSlot: this.targetSlot,
531
+ slot: this.targetSlot,
532
+ checkpointNumber: this.checkpointNumber,
533
+ pipelining: this.epochCache.isProposerPipeliningEnabled(),
534
+ proposer: this.proposer?.toString(),
535
+ attestorAddress: this.attestorAddress.toString(),
536
+ publisherAddress: this.publisher.getSenderAddress().toString(),
537
+ coinbase: coinbase.toString(),
538
+ });
539
+ this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
140
540
 
141
- // Enqueues block invalidation (constant for the whole slot)
142
- if (this.invalidateBlock && !this.config.skipInvalidateBlockAsProposer) {
143
- this.publisher.enqueueInvalidateBlock(this.invalidateBlock);
541
+ // Enqueues checkpoint invalidation (constant for the whole slot)
542
+ if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
543
+ this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
144
544
  }
145
545
 
146
- // Create checkpoint builder for the slot
546
+ // Build the simulation plan for this slot. When pipelining, this overrides L1's view of
547
+ // pending/archive/fee-header to "as if the proposed parent had landed", so both the
548
+ // mana-min-fee simulation (in the globals builder) and the pre-broadcast
549
+ // validateBlockHeader see the chain tip the eventual L1 send will see.
550
+ const isPipelining = this.epochCache.isProposerPipeliningEnabled();
551
+ this.checkpointSimulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
552
+ checkpointNumber: this.checkpointNumber,
553
+ proposedCheckpointData: isPipelining ? this.proposedCheckpointData : undefined,
554
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
555
+ checkpointedCheckpointNumber: this.checkpointedCheckpointNumber,
556
+ rollup: this.publisher.rollupContract,
557
+ signatureContext: this.signatureContext,
558
+ log: this.log,
559
+ });
560
+
147
561
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
148
562
  coinbase,
149
563
  feeRecipient,
150
- this.slot,
564
+ this.targetSlot,
565
+ this.checkpointSimulationOverridesPlan,
151
566
  );
152
567
 
153
- // Collect L1 to L2 messages for the checkpoint
568
+ // Collect L1 to L2 messages for the checkpoint and compute their hash
154
569
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
570
+ const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
571
+
572
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
573
+ // Under pipelining the parent checkpoint may not be on L1 yet at build time, so the helper
574
+ // splices in the parent's checkpointOutHash from the locally-known proposed checkpoint so
575
+ // the resulting `epochOutHash` matches what validators (and L1) compute once the parent
576
+ // lands on L1.
577
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
578
+ blockSource: this.l2BlockSource,
579
+ epoch: this.targetEpoch,
580
+ checkpointNumber: this.checkpointNumber,
581
+ l1Constants: this.epochCache.getL1Constants(),
582
+ pipeliningEnabled: this.epochCache.isProposerPipeliningEnabled(),
583
+ proposedCheckpointData: this.proposedCheckpointData,
584
+ log: this.log,
585
+ });
586
+
587
+ // Anchor the modifier to the predicted parent fee header: L1 will apply it against
588
+ // that, not against the latest published checkpoint (which lags by one under pipelining).
589
+ const predictedParentEthPerFeeAssetE12 =
590
+ this.checkpointSimulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
591
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12);
155
592
 
156
593
  // Create a long-lived forked world state for the checkpoint builder
157
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
594
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
158
595
 
159
596
  // Create checkpoint builder for the entire slot
160
597
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
161
598
  this.checkpointNumber,
162
599
  checkpointGlobalVariables,
600
+ feeAssetPriceModifier,
163
601
  l1ToL2Messages,
602
+ previousCheckpointOutHashes,
164
603
  fork,
604
+ this.log.getBindings(),
165
605
  );
166
606
 
167
607
  // Options for the validator client when creating block and checkpoint proposals
@@ -170,73 +610,201 @@ export class CheckpointProposalJob {
170
610
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
171
611
  };
172
612
 
173
- // Main loop: build blocks for the checkpoint
174
- const { blocksInCheckpoint, pendingBroadcast } = await this.buildBlocksForCheckpoint(
175
- checkpointBuilder,
176
- checkpointGlobalVariables.timestamp,
177
- blockProposalOptions,
178
- );
613
+ const checkpointProposalOptions: CheckpointProposalOptions = {
614
+ publishFullTxs: !!this.config.publishTxsWithProposals,
615
+ broadcastInvalidCheckpointProposal:
616
+ this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal,
617
+ };
618
+
619
+ let blocksInCheckpoint: L2Block[] = [];
620
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
621
+ const checkpointBuildTimer = new Timer();
622
+
623
+ try {
624
+ // Main loop: build blocks for the checkpoint
625
+ const result = await this.buildBlocksForCheckpoint(
626
+ checkpointBuilder,
627
+ checkpointGlobalVariables.timestamp,
628
+ inHash,
629
+ blockProposalOptions,
630
+ );
631
+ blocksInCheckpoint = result.blocksInCheckpoint;
632
+ blockPendingBroadcast = result.blockPendingBroadcast;
633
+ } catch (err) {
634
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
635
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
636
+ // which is normal for block building (may have picked different txs)
637
+ if (this.handleHASigningError(err, 'Block proposal')) {
638
+ return undefined;
639
+ }
640
+ throw err;
641
+ }
179
642
 
180
643
  if (blocksInCheckpoint.length === 0) {
181
- this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
182
- this.eventEmitter.emit('checkpoint-empty', { slot: this.slot });
644
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
645
+ slot: this.targetSlot,
646
+ checkpointNumber: this.checkpointNumber,
647
+ reason: 'no_blocks_built',
648
+ });
649
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
650
+ slot: this.targetSlot,
651
+ checkpointNumber: this.checkpointNumber,
652
+ reason: 'no_blocks_built',
653
+ });
654
+ this.eventEmitter.emit('checkpoint-empty', { slot: this.targetSlot });
655
+ return undefined;
656
+ }
657
+
658
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
659
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
660
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
661
+ slot: this.targetSlot,
662
+ checkpointNumber: this.checkpointNumber,
663
+ blocksBuilt: blocksInCheckpoint.length,
664
+ minBlocksForCheckpoint,
665
+ reason: 'min_blocks_not_met',
666
+ });
667
+ this.log.warn(
668
+ `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
669
+ {
670
+ slot: this.targetSlot,
671
+ checkpointNumber: this.checkpointNumber,
672
+ blocksBuilt: blocksInCheckpoint.length,
673
+ minBlocksForCheckpoint,
674
+ reason: 'min_blocks_not_met',
675
+ },
676
+ );
183
677
  return undefined;
184
678
  }
185
679
 
186
680
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
187
681
  // broadcasted yet, and wait to collect the committee attestations.
188
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
682
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
189
683
  const checkpoint = await checkpointBuilder.completeCheckpoint();
190
684
 
191
- // Do not collect attestations nor publish to L1 in fisherman mode
685
+ // Final validation: per-block limits are only checked if the operator set them explicitly.
686
+ // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
687
+ try {
688
+ validateCheckpoint(checkpoint, {
689
+ rollupManaLimit: this.l1Constants.rollupManaLimit,
690
+ maxL2BlockGas: this.config.maxL2BlockGas,
691
+ maxDABlockGas: this.config.maxDABlockGas,
692
+ maxTxsPerBlock: this.config.maxTxsPerBlock,
693
+ maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
694
+ });
695
+ } catch (err) {
696
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
697
+ slot: this.targetSlot,
698
+ checkpointNumber: this.checkpointNumber,
699
+ blocksBuilt: blocksInCheckpoint.length,
700
+ reason: 'invalid_checkpoint',
701
+ checkpoint: checkpoint.header.toInspect(),
702
+ });
703
+ this.log.error(`Built an invalid checkpoint at slot ${this.slotNow} (skipping proposal)`, err, {
704
+ slot: this.targetSlot,
705
+ checkpointNumber: this.checkpointNumber,
706
+ blocksBuilt: blocksInCheckpoint.length,
707
+ reason: 'invalid_checkpoint',
708
+ checkpoint: checkpoint.header.toInspect(),
709
+ });
710
+ return undefined;
711
+ }
712
+
713
+ // Record checkpoint-level build metrics
714
+ this.checkpointMetrics.recordCheckpointBuild(
715
+ checkpointBuildTimer.ms(),
716
+ blocksInCheckpoint.length,
717
+ checkpoint.getStats().txCount,
718
+ Number(checkpoint.header.totalManaUsed.toBigInt()),
719
+ );
720
+ this.logCheckpointEvent('built', `Checkpoint built for slot ${this.targetSlot}`, {
721
+ slot: this.targetSlot,
722
+ buildSlot: this.slotNow,
723
+ checkpointNumber: this.checkpointNumber,
724
+ proposer: this.proposer?.toString(),
725
+ attestorAddress: this.attestorAddress.toString(),
726
+ publisherAddress: this.publisher.getSenderAddress().toString(),
727
+ blocksBuilt: blocksInCheckpoint.length,
728
+ txCount: checkpoint.getStats().txCount,
729
+ totalMana: Number(checkpoint.header.totalManaUsed.toBigInt()),
730
+ });
731
+
732
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
192
733
  if (this.config.fishermanMode) {
193
734
  this.log.info(
194
- `Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` +
735
+ `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
195
736
  `Skipping proposal in fisherman mode.`,
196
737
  {
197
- slot: this.slot,
738
+ slot: this.targetSlot,
198
739
  checkpoint: checkpoint.header.toInspect(),
199
740
  blocksBuilt: blocksInCheckpoint.length,
200
741
  },
201
742
  );
202
743
  this.metrics.recordCheckpointSuccess();
203
- return checkpoint;
744
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
745
+ return { checkpoint, proposal: undefined!, blockProposedAt: this.dateProvider.now() };
746
+ }
747
+
748
+ // Validate the header against L1 state before broadcasting.
749
+ // If this fails the slot is aborted before any gossip work; state drift between here
750
+ // and the eventual L1 send is caught by the bundle simulate at send time.
751
+ try {
752
+ await this.publisher.validateBlockHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
753
+ } catch (err) {
754
+ this.log.error(`Pre-broadcast header validation failed for slot ${this.targetSlot}; aborting`, err, {
755
+ slot: this.targetSlot,
756
+ checkpointNumber: this.checkpointNumber,
757
+ });
758
+ this.metrics.recordCheckpointProposalFailed('header_validation_failed');
759
+ this.eventEmitter.emit('header-validation-failed', {
760
+ slot: this.targetSlot,
761
+ checkpointNumber: this.checkpointNumber,
762
+ reason: err instanceof Error ? err.message : String(err),
763
+ });
764
+ return undefined;
204
765
  }
205
766
 
206
- // TODO(palla/mbps): Wire this to the new p2p API once available, including the pendingBroadcast.block
767
+ // Create the checkpoint proposal and broadcast it
207
768
  const proposal = await this.validatorClient.createCheckpointProposal(
208
769
  checkpoint.header,
209
770
  checkpoint.archive.root,
210
- pendingBroadcast?.txs ?? [],
771
+ this.checkpointNumber,
772
+ feeAssetPriceModifier,
773
+ blockPendingBroadcast,
211
774
  this.proposer,
212
- blockProposalOptions,
775
+ checkpointProposalOptions,
213
776
  );
777
+
778
+ // Advance our own optimistic proposed-checkpoint tip locally before gossiping. Gossipsub
779
+ // doesn't echo our own messages back, so this is how the proposer makes its own proposed
780
+ // checkpoint visible for pipelining the next slot. Built from local checkpoint data — never
781
+ // from the broadcast proposal archive, which may be deliberately corrupted under test flags.
782
+ // Fail closed: if this throws, the outer catch aborts the slot before gossiping.
783
+ await this.syncProposedCheckpointToArchiver(checkpoint, blocksInCheckpoint.length, feeAssetPriceModifier);
784
+
214
785
  const blockProposedAt = this.dateProvider.now();
215
- await this.p2pClient.broadcastProposal(proposal);
216
-
217
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
218
- const attestations = await this.waitForAttestations(proposal);
219
- const blockAttestedAt = this.dateProvider.now();
220
-
221
- this.metrics.recordBlockAttestationDelay(blockAttestedAt - blockProposedAt);
222
-
223
- // Proposer must sign over the attestations before pushing them to L1
224
- const signer = this.proposer ?? this.publisher.getSenderAddress();
225
- const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer);
226
-
227
- // Enqueue publishing the checkpoint to L1
228
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
229
- const aztecSlotDuration = this.l1Constants.slotDuration;
230
- const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
231
- const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
232
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
233
- txTimeoutAt,
234
- forcePendingBlockNumber: this.invalidateBlock?.forcePendingBlockNumber,
235
- });
786
+ if (this.config.skipBroadcastCheckpointProposal) {
787
+ // Test-only: suppress the CheckpointProposal so peers never see a proposed checkpoint for
788
+ // this slot, but still broadcast the held last block standalone so peers' archivers ingest
789
+ // it as a proposed-but-uncheckpointed tip — the exact orphan-block state that
790
+ // pruneOrphanProposedBlocks / checkSync must handle.
791
+ if (blockPendingBroadcast && !this.config.skipBroadcastProposals) {
792
+ await this.p2pClient.broadcastProposal(blockPendingBroadcast);
793
+ }
794
+ } else if (!this.config.skipBroadcastProposals) {
795
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
796
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
797
+ }
236
798
 
237
- return checkpoint;
799
+ // Return immediately after broadcast — attestation collection happens in the background
800
+ return { checkpoint, proposal, blockProposedAt };
238
801
  } catch (err) {
239
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
802
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
803
+ // swallow this error. It's already been logged by a function deeper in the stack
804
+ return undefined;
805
+ }
806
+
807
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
240
808
  return undefined;
241
809
  }
242
810
  }
@@ -244,32 +812,43 @@ export class CheckpointProposalJob {
244
812
  /**
245
813
  * Builds blocks for a checkpoint within the current slot.
246
814
  */
815
+ @trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint')
247
816
  private async buildBlocksForCheckpoint(
248
817
  checkpointBuilder: CheckpointBuilder,
249
818
  timestamp: bigint,
819
+ inHash: Fr,
250
820
  blockProposalOptions: BlockProposalOptions,
251
821
  ): Promise<{
252
- blocksInCheckpoint: L2BlockNew[];
253
- pendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined;
822
+ blocksInCheckpoint: L2Block[];
823
+ blockPendingBroadcast: BlockProposal | undefined;
254
824
  }> {
255
- const blocksInCheckpoint: L2BlockNew[] = [];
825
+ const blocksInCheckpoint: L2Block[] = [];
256
826
  const txHashesAlreadyIncluded = new Set<string>();
257
827
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
258
828
 
259
829
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
260
- let pendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined = undefined;
830
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
261
831
 
262
832
  while (true) {
263
833
  const blocksBuilt = blocksInCheckpoint.length;
264
- const indexWithinCheckpoint = blocksBuilt;
834
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
265
835
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
266
836
 
837
+ if (blocksBuilt >= this.config.maxBlocksPerCheckpoint) {
838
+ this.log.debug(`Reached max blocks per checkpoint`, {
839
+ slot: this.targetSlot,
840
+ blocksBuilt,
841
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint,
842
+ });
843
+ break;
844
+ }
845
+
267
846
  const secondsIntoSlot = this.getSecondsIntoSlot();
268
847
  const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
269
848
 
270
849
  if (!timingInfo.canStart) {
271
850
  this.log.debug(`Not enough time left in slot to start another block`, {
272
- slot: this.slot,
851
+ slot: this.targetSlot,
273
852
  blocksBuilt,
274
853
  secondsIntoSlot,
275
854
  });
@@ -290,21 +869,23 @@ export class CheckpointProposalJob {
290
869
  txHashesAlreadyIncluded,
291
870
  });
292
871
 
293
- if (!buildResult && timingInfo.isLastBlock) {
294
- // If no block was produced due to not enough txs and this was the last subslot, exit
295
- break;
296
- } else if (!buildResult && timingInfo.deadline !== undefined) {
297
- // But if there is still time for more blocks, wait until the next subslot and try again
872
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
873
+ if ('failure' in buildResult) {
874
+ // If this was the last subslot, or we're running with a single block per slot, we're done
875
+ if (timingInfo.isLastBlock || timingInfo.deadline === undefined) {
876
+ break;
877
+ }
878
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
298
879
  await this.waitUntilNextSubslot(timingInfo.deadline);
299
880
  continue;
300
- } else if (!buildResult) {
301
- // Exit if there is no possibility of building more blocks
302
- break;
303
- } else if ('error' in buildResult) {
304
- // If there was an error building the block, just exit the loop and give up the rest of the slot
881
+ }
882
+
883
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
884
+ // We don't want to risk building more blocks if something went wrong.
885
+ if ('error' in buildResult) {
305
886
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
306
- this.log.warn(`Halting block building for slot ${this.slot}`, {
307
- slot: this.slot,
887
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
888
+ slot: this.targetSlot,
308
889
  blocksBuilt,
309
890
  error: buildResult.error,
310
891
  });
@@ -313,36 +894,42 @@ export class CheckpointProposalJob {
313
894
  }
314
895
 
315
896
  const { block, usedTxs } = buildResult;
897
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
898
+ isFirstBlock: blocksBuilt === 0,
899
+ isLastBlock: timingInfo.isLastBlock,
900
+ });
901
+
316
902
  blocksInCheckpoint.push(block);
903
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
904
+
905
+ // Sign the block proposal. This will throw if HA signing fails.
906
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, {
907
+ ...blockProposalOptions,
908
+ broadcastInvalidBlockProposal:
909
+ blockProposalOptions.broadcastInvalidBlockProposal ||
910
+ block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint,
911
+ });
317
912
 
318
- // Sync the proposed block to the archiver to make it available
319
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
320
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
913
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
914
+ // so we avoid polluting our archive with a block that would fail.
915
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
916
+ // If this throws, we abort the entire checkpoint.
321
917
  await this.syncProposedBlockToArchiver(block);
322
918
 
323
- // If this is the last block, exit the loop now so we start collecting attestations
919
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
324
920
  if (timingInfo.isLastBlock) {
325
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
326
- slot: this.slot,
921
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
922
+ slot: this.targetSlot,
327
923
  blockNumber,
328
924
  blocksBuilt,
329
925
  });
330
- pendingBroadcast = { block, txs: usedTxs };
926
+
927
+ blockPendingBroadcast = proposal;
331
928
  break;
332
929
  }
333
930
 
334
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
335
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
336
- if (!this.config.fishermanMode) {
337
- // TODO(palla/mbps): Wire this to the new p2p API once available
338
- const proposal = await this.validatorClient.createBlockProposal(
339
- block.header.globalVariables.blockNumber,
340
- (await checkpointBuilder.getCheckpoint()).header,
341
- block.archive.root,
342
- usedTxs,
343
- this.proposer,
344
- blockProposalOptions,
345
- );
931
+ // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
932
+ if (proposal && !this.config.skipBroadcastProposals) {
346
933
  await this.p2pClient.broadcastProposal(proposal);
347
934
  }
348
935
 
@@ -350,145 +937,267 @@ export class CheckpointProposalJob {
350
937
  await this.waitUntilNextSubslot(timingInfo.deadline);
351
938
  }
352
939
 
353
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
354
- slot: this.slot,
940
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
941
+ slot: this.targetSlot,
355
942
  blocksBuilt: blocksInCheckpoint.length,
356
943
  });
357
944
 
358
- return {
359
- blocksInCheckpoint,
360
- pendingBroadcast,
361
- };
945
+ return { blocksInCheckpoint, blockPendingBroadcast };
946
+ }
947
+
948
+ /** Creates a block proposal for a given block via the validator client (unless in fisherman mode) */
949
+ private createBlockProposal(
950
+ block: L2Block,
951
+ inHash: Fr,
952
+ usedTxs: Tx[],
953
+ blockProposalOptions: BlockProposalOptions,
954
+ ): Promise<BlockProposal | undefined> {
955
+ if (this.config.fishermanMode) {
956
+ this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
957
+ return Promise.resolve(undefined);
958
+ }
959
+ return this.validatorClient.createBlockProposal(
960
+ block.header,
961
+ this.checkpointNumber,
962
+ block.indexWithinCheckpoint,
963
+ inHash,
964
+ block.archive.root,
965
+ usedTxs,
966
+ this.proposer,
967
+ blockProposalOptions,
968
+ );
362
969
  }
363
970
 
364
971
  /** Sleeps until it is time to produce the next block in the slot */
972
+ @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
365
973
  private async waitUntilNextSubslot(nextSubslotStart: number) {
366
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
367
- this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
974
+ this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
975
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
976
+ slot: this.targetSlot,
977
+ });
368
978
  await this.waitUntilTimeInSlot(nextSubslotStart);
369
979
  }
370
980
 
371
981
  /** Builds a single block. Called from the main block building loop. */
372
- private async buildSingleBlock(
982
+ @trackSpan('CheckpointProposalJob.buildSingleBlock')
983
+ protected async buildSingleBlock(
373
984
  checkpointBuilder: CheckpointBuilder,
374
985
  opts: {
375
986
  forceCreate?: boolean;
376
987
  blockTimestamp: bigint;
377
988
  blockNumber: BlockNumber;
378
- indexWithinCheckpoint: number;
989
+ indexWithinCheckpoint: IndexWithinCheckpoint;
379
990
  buildDeadline: Date | undefined;
380
991
  txHashesAlreadyIncluded: Set<string>;
381
992
  },
382
- ): Promise<{ block: L2BlockNew; usedTxs: Tx[] } | { error: Error } | undefined> {
993
+ ): Promise<
994
+ { block: L2Block; usedTxs: Tx[] } | { failure: 'insufficient-txs' | 'insufficient-valid-txs' } | { error: Error }
995
+ > {
383
996
  const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
384
997
  opts;
385
998
 
386
999
  this.log.verbose(
387
- `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
1000
+ `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot}`,
388
1001
  { ...checkpointBuilder.getConstantData(), ...opts },
389
1002
  );
390
1003
 
391
1004
  try {
392
1005
  // Wait until we have enough txs to build the block
393
- const minTxs = this.config.minTxsPerBlock;
394
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
1006
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
395
1007
  if (!canStartBuilding) {
1008
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1009
+ reason: 'insufficient_txs',
1010
+ blockNumber,
1011
+ slot: this.targetSlot,
1012
+ checkpointNumber: this.checkpointNumber,
1013
+ indexWithinCheckpoint,
1014
+ availableTxs,
1015
+ minTxs,
1016
+ });
396
1017
  this.log.warn(
397
- `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
398
- { blockNumber, slot: this.slot, indexWithinCheckpoint },
1018
+ `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (got ${availableTxs} txs but needs ${minTxs})`,
1019
+ {
1020
+ reason: 'insufficient_txs',
1021
+ blockNumber,
1022
+ slot: this.targetSlot,
1023
+ checkpointNumber: this.checkpointNumber,
1024
+ indexWithinCheckpoint,
1025
+ availableTxs,
1026
+ minTxs,
1027
+ },
399
1028
  );
400
- this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.slot });
1029
+ this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.targetSlot });
401
1030
  this.metrics.recordBlockProposalFailed('insufficient_txs');
402
- return undefined;
1031
+ return { failure: 'insufficient-txs' };
403
1032
  }
404
1033
 
405
1034
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
406
1035
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
407
1036
  const pendingTxs = filter(
408
- this.p2pClient.iteratePendingTxs(),
1037
+ this.p2pClient.iterateEligiblePendingTxs(),
409
1038
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
410
1039
  );
411
1040
 
412
1041
  this.log.debug(
413
- `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
414
- { slot: this.slot, blockNumber, indexWithinCheckpoint },
1042
+ `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`,
1043
+ { slot: this.targetSlot, blockNumber, indexWithinCheckpoint },
415
1044
  );
416
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
417
- const blockBuilderOptions: PublicProcessorLimits = {
1045
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
1046
+
1047
+ // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
1048
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
1049
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
1050
+ const minValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
1051
+ const blockBuilderOptions: BlockBuilderOptions = {
418
1052
  maxTransactions: this.config.maxTxsPerBlock,
419
- maxBlockSize: this.config.maxBlockSizeInBytes,
420
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
421
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
1053
+ maxBlockGas:
1054
+ this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined
1055
+ ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity)
1056
+ : undefined,
422
1057
  deadline: buildDeadline,
1058
+ isBuildingProposal: true,
1059
+ minValidTxs,
1060
+ maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
1061
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
423
1062
  };
424
1063
 
425
- // Actually build the block by executing txs
426
- const workTimer = new Timer();
427
- const { publicGas, block, publicProcessorDuration, numTxs, blockBuildingTimer, usedTxs, failedTxs } =
428
- await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
429
- const blockBuildDuration = workTimer.ms();
1064
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
1065
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
1066
+ // updated for blocks that will be discarded.
1067
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
1068
+ checkpointBuilder,
1069
+ pendingTxs,
1070
+ blockNumber,
1071
+ blockTimestamp,
1072
+ blockBuilderOptions,
1073
+ );
430
1074
 
431
1075
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
432
- await this.dropFailedTxsFromP2P(failedTxs);
1076
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
433
1077
 
434
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
435
- // too long, then we may not get to minTxsPerBlock after executing public functions.
436
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
437
- if (!forceCreate && numTxs < minValidTxs) {
1078
+ if (buildResult.status === 'insufficient-valid-txs') {
1079
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1080
+ reason: 'insufficient_valid_txs',
1081
+ slot: this.targetSlot,
1082
+ checkpointNumber: this.checkpointNumber,
1083
+ blockNumber,
1084
+ numTxs: buildResult.processedCount,
1085
+ indexWithinCheckpoint,
1086
+ minValidTxs,
1087
+ });
438
1088
  this.log.warn(
439
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
440
- { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint },
1089
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`,
1090
+ {
1091
+ reason: 'insufficient_valid_txs',
1092
+ slot: this.targetSlot,
1093
+ checkpointNumber: this.checkpointNumber,
1094
+ blockNumber,
1095
+ numTxs: buildResult.processedCount,
1096
+ indexWithinCheckpoint,
1097
+ minValidTxs,
1098
+ },
441
1099
  );
442
- this.eventEmitter.emit('block-tx-count-check-failed', {
443
- minTxs: minValidTxs,
444
- availableTxs: numTxs,
445
- slot: this.slot,
1100
+ this.eventEmitter.emit('block-build-failed', {
1101
+ reason: `Insufficient valid txs`,
1102
+ slot: this.targetSlot,
446
1103
  });
447
1104
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
448
- return undefined;
1105
+ return { failure: 'insufficient-valid-txs' };
449
1106
  }
450
1107
 
451
1108
  // Block creation succeeded, emit stats and metrics
1109
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
1110
+
452
1111
  const blockStats = {
453
1112
  eventName: 'l2-block-built',
454
1113
  duration: blockBuildDuration,
455
1114
  publicProcessDuration: publicProcessorDuration,
456
- rollupCircuitsDuration: blockBuildingTimer.ms(),
457
1115
  ...block.getStats(),
458
1116
  } satisfies L2BlockBuiltStats;
459
1117
 
460
1118
  const blockHash = await block.hash();
461
1119
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
462
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
1120
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
463
1121
 
464
1122
  this.log.info(
465
- `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`,
1123
+ `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot} with ${numTxs} txs`,
466
1124
  { blockHash, txHashes, manaPerSec, ...blockStats },
467
1125
  );
468
1126
 
469
- this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
470
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
1127
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
1128
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
1129
+ this.eventEmitter.emit('block-proposed', {
1130
+ blockNumber: block.number,
1131
+ blockHash,
1132
+ checkpointNumber: this.checkpointNumber,
1133
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1134
+ slot: this.targetSlot,
1135
+ buildSlot: this.slotNow,
1136
+ });
1137
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
471
1138
 
472
1139
  return { block, usedTxs };
473
1140
  } catch (err: any) {
474
- this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
475
- this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
1141
+ this.eventEmitter.emit('block-build-failed', {
1142
+ reason: err.message,
1143
+ slot: this.targetSlot,
1144
+ });
1145
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1146
+ reason: err instanceof Error ? err.message : String(err),
1147
+ slot: this.targetSlot,
1148
+ checkpointNumber: this.checkpointNumber,
1149
+ blockNumber,
1150
+ });
1151
+ this.log.error(`Error building block`, err, {
1152
+ reason: err instanceof Error ? err.message : String(err),
1153
+ slot: this.targetSlot,
1154
+ checkpointNumber: this.checkpointNumber,
1155
+ blockNumber,
1156
+ });
476
1157
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
477
1158
  this.metrics.recordFailedBlock();
478
1159
  return { error: err };
479
1160
  }
480
1161
  }
481
1162
 
1163
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
1164
+ private async buildSingleBlockWithCheckpointBuilder(
1165
+ checkpointBuilder: CheckpointBuilder,
1166
+ pendingTxs: AsyncIterable<Tx>,
1167
+ blockNumber: BlockNumber,
1168
+ blockTimestamp: bigint,
1169
+ blockBuilderOptions: BlockBuilderOptions,
1170
+ ) {
1171
+ try {
1172
+ const workTimer = new Timer();
1173
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
1174
+ const blockBuildDuration = workTimer.ms();
1175
+ return { ...result, blockBuildDuration, status: 'success' as const };
1176
+ } catch (err: unknown) {
1177
+ if (isErrorClass(err, InsufficientValidTxsError)) {
1178
+ return {
1179
+ failedTxs: err.failedTxs,
1180
+ processedCount: err.processedCount,
1181
+ status: 'insufficient-valid-txs' as const,
1182
+ };
1183
+ }
1184
+ throw err;
1185
+ }
1186
+ }
1187
+
482
1188
  /** Waits until minTxs are available on the pool for building a block. */
1189
+ @trackSpan('CheckpointProposalJob.waitForMinTxs')
483
1190
  private async waitForMinTxs(opts: {
484
1191
  forceCreate?: boolean;
485
1192
  blockNumber: BlockNumber;
486
- indexWithinCheckpoint: number;
1193
+ indexWithinCheckpoint: IndexWithinCheckpoint;
487
1194
  buildDeadline: Date | undefined;
488
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
489
- const minTxs = this.config.minTxsPerBlock;
1195
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
490
1196
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
491
1197
 
1198
+ // We only allow a block with 0 txs in the first block of the checkpoint
1199
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
1200
+
492
1201
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
493
1202
  const startBuildingDeadline = buildDeadline
494
1203
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -500,30 +1209,63 @@ export class CheckpointProposalJob {
500
1209
  // If we're past deadline, or we have no deadline, give up
501
1210
  const now = this.dateProvider.nowAsDate();
502
1211
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
503
- return { canStartBuilding: false, availableTxs: availableTxs };
1212
+ return { canStartBuilding: false, availableTxs, minTxs };
504
1213
  }
505
1214
 
506
1215
  // Wait a bit before checking again
507
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
1216
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
508
1217
  this.log.verbose(
509
- `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
510
- { blockNumber, slot: this.slot, indexWithinCheckpoint },
1218
+ `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`,
1219
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
511
1220
  );
512
- await sleep(TXS_POLLING_MS);
1221
+ await this.waitForTxsPollingInterval();
513
1222
  availableTxs = await this.p2pClient.getPendingTxCount();
514
1223
  }
515
1224
 
516
- return { canStartBuilding: true, availableTxs };
1225
+ return { canStartBuilding: true, availableTxs, minTxs };
1226
+ }
1227
+
1228
+ private async getSignedCommitteeAttestations(
1229
+ broadcast: CheckpointProposalBroadcast,
1230
+ ): Promise<{ attestations: CommitteeAttestationsAndSigners; attestationsSignature: Signature } | undefined> {
1231
+ const { proposal, blockProposedAt } = broadcast;
1232
+ this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.targetSlot);
1233
+ const attestations = await this.waitForAttestations(proposal);
1234
+ if (!attestations) {
1235
+ return undefined;
1236
+ }
1237
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
1238
+
1239
+ // Proposer must sign over the attestations before pushing them to L1
1240
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1241
+ try {
1242
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
1243
+ attestations,
1244
+ signer,
1245
+ this.targetSlot,
1246
+ this.checkpointNumber,
1247
+ );
1248
+ return { attestations, attestationsSignature };
1249
+ } catch (err) {
1250
+ if (this.handleHASigningError(err, 'Attestations signature')) {
1251
+ return;
1252
+ }
1253
+ this.log.error(`Error signing attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1254
+ return undefined;
1255
+ }
517
1256
  }
518
1257
 
519
1258
  /**
520
1259
  * Waits for enough attestations to be collected via p2p.
521
1260
  * This is run after all blocks for the checkpoint have been built.
522
1261
  */
523
- private async waitForAttestations(proposal: BlockProposal): Promise<CommitteeAttestationsAndSigners> {
1262
+ @trackSpan('CheckpointProposalJob.waitForAttestations')
1263
+ private async waitForAttestations(
1264
+ proposal: CheckpointProposal,
1265
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
524
1266
  if (this.config.fishermanMode) {
525
1267
  this.log.debug('Skipping attestation collection in fisherman mode');
526
- return CommitteeAttestationsAndSigners.empty();
1268
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
527
1269
  }
528
1270
 
529
1271
  const slotNumber = proposal.slotNumber;
@@ -533,23 +1275,29 @@ export class CheckpointProposalJob {
533
1275
  throw new Error('No committee when collecting attestations');
534
1276
  } else if (committee.length === 0) {
535
1277
  this.log.verbose(`Attesting committee is empty`);
536
- return CommitteeAttestationsAndSigners.empty();
1278
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
537
1279
  } else {
538
1280
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
539
1281
  }
540
1282
 
541
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
1283
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
542
1284
 
543
1285
  if (this.config.skipCollectingAttestations) {
544
1286
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
545
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
546
- return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
1287
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
1288
+ this.logCheckpointAttestations('collected', committee, attestations ?? [], numberOfRequiredAttestations, {
1289
+ reason: 'collect_own_only',
1290
+ });
1291
+ return new CommitteeAttestationsAndSigners(
1292
+ orderAttestations(attestations ?? [], committee),
1293
+ this.getSignatureContext(),
1294
+ );
547
1295
  }
548
1296
 
549
1297
  const attestationTimeAllowed = this.config.enforceTimeTable
550
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
1298
+ ? this.timetable.getCheckpointAttestationDeadline()
551
1299
  : this.l1Constants.slotDuration;
552
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
1300
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
553
1301
 
554
1302
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
555
1303
 
@@ -560,33 +1308,92 @@ export class CheckpointProposalJob {
560
1308
  proposal,
561
1309
  numberOfRequiredAttestations,
562
1310
  attestationDeadline,
1311
+ this.checkpointNumber,
563
1312
  );
564
1313
 
565
1314
  collectedAttestationsCount = attestations.length;
566
1315
 
1316
+ // Trim attestations to minimum required to save L1 calldata gas
1317
+ const localAddresses = this.validatorClient.getValidatorAddresses();
1318
+ const trimmed = trimAttestations(
1319
+ attestations,
1320
+ numberOfRequiredAttestations,
1321
+ this.attestorAddress,
1322
+ localAddresses,
1323
+ );
1324
+ if (trimmed.length < attestations.length) {
1325
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
1326
+ }
1327
+
567
1328
  // Rollup contract requires that the signatures are provided in the order of the committee
568
- const sorted = orderAttestations(attestations, committee);
1329
+ const sorted = orderAttestations(trimmed, committee);
1330
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1331
+ submittedCount: trimmed.length,
1332
+ });
569
1333
 
570
1334
  // Manipulate the attestations if we've been configured to do so
571
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
572
- const checkpoint = proposal.payload.header;
573
- return this.manipulateAttestations(checkpoint, epoch, seed, committee, sorted);
1335
+ if (
1336
+ this.config.injectFakeAttestation ||
1337
+ this.config.injectHighSValueAttestation ||
1338
+ this.config.injectUnrecoverableSignatureAttestation ||
1339
+ this.config.shuffleAttestationOrdering
1340
+ ) {
1341
+ return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
574
1342
  }
575
1343
 
576
- return new CommitteeAttestationsAndSigners(sorted);
1344
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
577
1345
  } catch (err) {
578
1346
  if (err && err instanceof AttestationTimeoutError) {
579
1347
  collectedAttestationsCount = err.collectedCount;
1348
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1349
+ collectedCount: collectedAttestationsCount,
1350
+ reason: 'timeout',
1351
+ });
1352
+ this.log.error(
1353
+ `Timeout while waiting for attestations for checkpoint proposal at slot ${proposal.slotNumber} (collected ${collectedAttestationsCount}/${numberOfRequiredAttestations})`,
1354
+ err,
1355
+ );
1356
+ } else {
1357
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1358
+ collectedCount: collectedAttestationsCount,
1359
+ reason: err instanceof Error ? err.message : String(err),
1360
+ });
1361
+ this.log.error(`Error collecting attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
580
1362
  }
581
- throw err;
1363
+ return undefined;
582
1364
  } finally {
583
1365
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
584
1366
  }
585
1367
  }
586
1368
 
1369
+ private logCheckpointAttestations(
1370
+ status: 'collected' | 'failed',
1371
+ committee: EthAddress[],
1372
+ attestations: CheckpointAttestation[] | undefined,
1373
+ requiredAttestations: number,
1374
+ opts: { collectedCount?: number; submittedCount?: number; reason?: string } = {},
1375
+ ) {
1376
+ const signedValidators =
1377
+ attestations
1378
+ ?.map(attestation => attestation.getSender()?.toString())
1379
+ .filter((address): address is `0x${string}` => address !== undefined) ?? [];
1380
+ const collectedCount = opts.collectedCount ?? new Set(signedValidators).size;
1381
+ const missingValidatorCount = status === 'failed' ? Math.max(0, requiredAttestations - collectedCount) : undefined;
1382
+ this.logCheckpointEvent(`attestations-${status}`, `Checkpoint attestations ${status} for slot ${this.targetSlot}`, {
1383
+ slot: this.targetSlot,
1384
+ checkpointNumber: this.checkpointNumber,
1385
+ committeeSize: committee.length,
1386
+ requiredAttestations,
1387
+ collectedAttestations: collectedCount,
1388
+ ...(opts.submittedCount !== undefined && { submittedAttestations: opts.submittedCount }),
1389
+ ...(missingValidatorCount !== undefined && { missingValidatorCount }),
1390
+ ...(opts.reason !== undefined && { reason: opts.reason }),
1391
+ });
1392
+ }
1393
+
587
1394
  /** Breaks the attestations before publishing based on attack configs */
588
1395
  private manipulateAttestations(
589
- checkpoint: CheckpointHeader,
1396
+ slotNumber: SlotNumber,
590
1397
  epoch: EpochNumber,
591
1398
  seed: bigint,
592
1399
  committee: EthAddress[],
@@ -594,12 +1401,15 @@ export class CheckpointProposalJob {
594
1401
  ) {
595
1402
  // Compute the proposer index in the committee, since we dont want to tweak it.
596
1403
  // Otherwise, the L1 rollup contract will reject the block outright.
597
- const { slotNumber } = checkpoint;
598
1404
  const proposerIndex = Number(
599
1405
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
600
1406
  );
601
1407
 
602
- if (this.config.injectFakeAttestation) {
1408
+ if (
1409
+ this.config.injectFakeAttestation ||
1410
+ this.config.injectHighSValueAttestation ||
1411
+ this.config.injectUnrecoverableSignatureAttestation
1412
+ ) {
603
1413
  // Find non-empty attestations that are not from the proposer
604
1414
  const nonProposerIndices: number[] = [];
605
1415
  for (let i = 0; i < attestations.length; i++) {
@@ -609,27 +1419,48 @@ export class CheckpointProposalJob {
609
1419
  }
610
1420
  if (nonProposerIndices.length > 0) {
611
1421
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
612
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
613
- unfreeze(attestations[targetIndex]).signature = Signature.random();
1422
+ if (this.config.injectHighSValueAttestation) {
1423
+ this.log.warn(
1424
+ `Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
1425
+ );
1426
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
1427
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
1428
+ this.log.warn(
1429
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
1430
+ );
1431
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
1432
+ } else {
1433
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1434
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
1435
+ }
614
1436
  }
615
- return new CommitteeAttestationsAndSigners(attestations);
1437
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
616
1438
  }
617
1439
 
618
1440
  if (this.config.shuffleAttestationOrdering) {
619
1441
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
620
1442
 
621
1443
  const shuffled = [...attestations];
622
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
623
- const valueI = shuffled[i];
624
- const valueJ = shuffled[j];
625
- shuffled[i] = valueJ;
626
- shuffled[j] = valueI;
627
-
628
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
629
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
1444
+
1445
+ // Find two non-proposer positions that both have non-empty signatures to swap.
1446
+ // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
1447
+ // signers array stays correctly aligned with L1's committee reconstruction.
1448
+ const swappable: number[] = [];
1449
+ for (let k = 0; k < shuffled.length; k++) {
1450
+ if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
1451
+ swappable.push(k);
1452
+ }
1453
+ }
1454
+ if (swappable.length >= 2) {
1455
+ const [i, j] = [swappable[0], swappable[1]];
1456
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
1457
+ }
1458
+
1459
+ const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
1460
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
630
1461
  }
631
1462
 
632
- return new CommitteeAttestationsAndSigners(attestations);
1463
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
633
1464
  }
634
1465
 
635
1466
  private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
@@ -639,57 +1470,134 @@ export class CheckpointProposalJob {
639
1470
  const failedTxData = failedTxs.map(fail => fail.tx);
640
1471
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
641
1472
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
642
- await this.p2pClient.deleteTxs(failedTxHashes);
1473
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
643
1474
  }
644
1475
 
645
1476
  /**
646
- * Placeholder for pushing block to archiver and waiting for sync.
647
- * To be implemented when archiver and world-state support proposed blocks.
1477
+ * Adds the proposed block to the archiver so it's available via P2P.
1478
+ * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1479
+ * would never receive its own block without this explicit sync.
1480
+ *
1481
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1482
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1483
+ * whenever the real proposer's block arrives from L1.
648
1484
  */
649
- private async syncProposedBlockToArchiver(block: L2BlockNew): Promise<void> {
650
- this.log.debug(`Syncing proposed block ${block.number}`, {
1485
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
1486
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1487
+ this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1488
+ blockNumber: block.number,
1489
+ slot: block.header.globalVariables.slotNumber,
1490
+ });
1491
+ return;
1492
+ }
1493
+ this.log.debug(`Syncing proposed block ${block.number} to archiver`, {
651
1494
  blockNumber: block.number,
652
1495
  slot: block.header.globalVariables.slotNumber,
653
1496
  });
654
- // TODO(palla/mbps): Implement actual sync to archiver and world-state
655
- await Promise.resolve();
1497
+ await this.blockSink.addBlock(block);
1498
+ }
1499
+
1500
+ /**
1501
+ * Adds the proposed checkpoint to the archiver so the proposer's optimistic proposed-checkpoint
1502
+ * tip advances locally. Gossip doesn't echo our own messages back, so without this the proposer
1503
+ * would never see its own proposed checkpoint and couldn't pipeline the next slot.
1504
+ *
1505
+ * Only runs under proposer pipelining (the proposed tip is a pipelining-only concept) and is
1506
+ * skipped whenever proposed blocks aren't pushed (`skipPushProposedBlocksToArchiver`, fisherman
1507
+ * mode): the archiver derives the checkpoint archive from its stored blocks, so without them the
1508
+ * push would fail. All blocks were already added (and awaited) during block building, so this
1509
+ * needs no retry — they are guaranteed present by the time we get here.
1510
+ */
1511
+ private async syncProposedCheckpointToArchiver(
1512
+ checkpoint: Checkpoint,
1513
+ blockCount: number,
1514
+ feeAssetPriceModifier: bigint,
1515
+ ): Promise<void> {
1516
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1517
+ return;
1518
+ }
1519
+ if (!this.epochCache.isProposerPipeliningEnabled()) {
1520
+ return;
1521
+ }
1522
+ const startBlock = BlockNumber(this.syncedToBlockNumber + 1);
1523
+ this.log.debug(`Syncing proposed checkpoint ${this.checkpointNumber} to archiver`, {
1524
+ checkpointNumber: this.checkpointNumber,
1525
+ slot: this.targetSlot,
1526
+ startBlock,
1527
+ blockCount,
1528
+ });
1529
+ await this.blockSink.addProposedCheckpoint({
1530
+ header: checkpoint.header,
1531
+ checkpointNumber: this.checkpointNumber,
1532
+ startBlock,
1533
+ blockCount,
1534
+ totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
1535
+ feeAssetPriceModifier,
1536
+ });
656
1537
  }
657
1538
 
658
1539
  /** Runs fee analysis and logs checkpoint outcome as fisherman */
659
1540
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
660
1541
  // Perform L1 fee analysis before clearing requests
661
1542
  // The callback is invoked asynchronously after the next block is mined
662
- const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
1543
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, analysis =>
663
1544
  this.metrics.recordFishermanFeeAnalysis(analysis),
664
1545
  );
665
1546
 
666
1547
  if (checkpoint) {
667
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1548
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
668
1549
  ...checkpoint.toCheckpointInfo(),
669
1550
  ...checkpoint.getStats(),
670
1551
  feeAnalysisId: feeAnalysis?.id,
671
1552
  });
672
- this.metrics.recordBlockProposalSuccess();
673
1553
  } else {
674
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
675
- slot: this.slot,
1554
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1555
+ slot: this.targetSlot,
676
1556
  feeAnalysisId: feeAnalysis?.id,
677
1557
  });
678
- this.metrics.recordBlockProposalFailed('block_build_failed');
1558
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
679
1559
  }
680
1560
 
681
1561
  this.publisher.clearPendingRequests();
682
1562
  }
683
1563
 
1564
+ /**
1565
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
1566
+ */
1567
+ private handleHASigningError(err: any, errorContext: string): boolean {
1568
+ if (err instanceof DutyAlreadySignedError) {
1569
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1570
+ slot: this.targetSlot,
1571
+ signedByNode: err.signedByNode,
1572
+ });
1573
+ return true;
1574
+ }
1575
+ if (err instanceof SlashingProtectionError) {
1576
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1577
+ slot: this.targetSlot,
1578
+ existingMessageHash: err.existingMessageHash,
1579
+ attemptedMessageHash: err.attemptedMessageHash,
1580
+ });
1581
+ return true;
1582
+ }
1583
+ return false;
1584
+ }
1585
+
684
1586
  /** Waits until a specific time within the current slot */
1587
+ @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
685
1588
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
686
1589
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();
687
1590
  const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
688
1591
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
689
1592
  }
690
1593
 
1594
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
1595
+ protected async waitForTxsPollingInterval(): Promise<void> {
1596
+ await sleep(TXS_POLLING_MS);
1597
+ }
1598
+
691
1599
  private getSlotStartBuildTimestamp(): number {
692
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1600
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
693
1601
  }
694
1602
 
695
1603
  private getSecondsIntoSlot(): number {