@aztec/sequencer-client 0.0.1-commit.29c6b1a3 → 0.0.1-commit.2d9cb6034

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 (88) hide show
  1. package/dest/client/sequencer-client.d.ts +15 -7
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +60 -26
  4. package/dest/config.d.ts +26 -7
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +47 -28
  7. package/dest/global_variable_builder/global_builder.d.ts +15 -11
  8. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  9. package/dest/global_variable_builder/global_builder.js +29 -25
  10. package/dest/global_variable_builder/index.d.ts +2 -2
  11. package/dest/global_variable_builder/index.d.ts.map +1 -1
  12. package/dest/publisher/config.d.ts +47 -17
  13. package/dest/publisher/config.d.ts.map +1 -1
  14. package/dest/publisher/config.js +121 -42
  15. package/dest/publisher/index.d.ts +2 -1
  16. package/dest/publisher/index.d.ts.map +1 -1
  17. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  18. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  19. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  20. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +59 -0
  21. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  22. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  23. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  24. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  25. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  26. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  27. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  28. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  29. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -3
  30. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  31. package/dest/publisher/sequencer-publisher-factory.js +27 -2
  32. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  33. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  34. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  35. package/dest/publisher/sequencer-publisher.d.ts +76 -31
  36. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  37. package/dest/publisher/sequencer-publisher.js +434 -88
  38. package/dest/sequencer/checkpoint_proposal_job.d.ts +61 -13
  39. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  40. package/dest/sequencer/checkpoint_proposal_job.js +400 -201
  41. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  42. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  43. package/dest/sequencer/checkpoint_voter.js +2 -5
  44. package/dest/sequencer/events.d.ts +2 -1
  45. package/dest/sequencer/events.d.ts.map +1 -1
  46. package/dest/sequencer/metrics.d.ts +21 -5
  47. package/dest/sequencer/metrics.d.ts.map +1 -1
  48. package/dest/sequencer/metrics.js +122 -30
  49. package/dest/sequencer/sequencer.d.ts +42 -17
  50. package/dest/sequencer/sequencer.d.ts.map +1 -1
  51. package/dest/sequencer/sequencer.js +147 -89
  52. package/dest/sequencer/timetable.d.ts +4 -6
  53. package/dest/sequencer/timetable.d.ts.map +1 -1
  54. package/dest/sequencer/timetable.js +7 -11
  55. package/dest/sequencer/types.d.ts +2 -2
  56. package/dest/sequencer/types.d.ts.map +1 -1
  57. package/dest/test/index.d.ts +3 -5
  58. package/dest/test/index.d.ts.map +1 -1
  59. package/dest/test/mock_checkpoint_builder.d.ts +12 -12
  60. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  61. package/dest/test/mock_checkpoint_builder.js +45 -36
  62. package/dest/test/utils.d.ts +3 -3
  63. package/dest/test/utils.d.ts.map +1 -1
  64. package/dest/test/utils.js +5 -4
  65. package/package.json +27 -28
  66. package/src/client/sequencer-client.ts +76 -23
  67. package/src/config.ts +65 -38
  68. package/src/global_variable_builder/global_builder.ts +38 -27
  69. package/src/global_variable_builder/index.ts +1 -1
  70. package/src/publisher/config.ts +153 -43
  71. package/src/publisher/index.ts +3 -0
  72. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  73. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +55 -0
  74. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  75. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  76. package/src/publisher/sequencer-publisher-factory.ts +38 -6
  77. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  78. package/src/publisher/sequencer-publisher.ts +474 -111
  79. package/src/sequencer/checkpoint_proposal_job.ts +532 -224
  80. package/src/sequencer/checkpoint_voter.ts +1 -12
  81. package/src/sequencer/events.ts +1 -1
  82. package/src/sequencer/metrics.ts +138 -32
  83. package/src/sequencer/sequencer.ts +213 -106
  84. package/src/sequencer/timetable.ts +13 -12
  85. package/src/sequencer/types.ts +1 -1
  86. package/src/test/index.ts +2 -4
  87. package/src/test/mock_checkpoint_builder.ts +65 -53
  88. package/src/test/utils.ts +5 -2
@@ -1,16 +1,26 @@
1
- import { NUM_CHECKPOINT_END_MARKER_FIELDS, getNumBlockEndBlobFields } from '@aztec/blob-lib/encoding';
2
- import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
3
1
  import type { EpochCache } from '@aztec/epoch-cache';
4
- import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { type FeeHeader, RollupContract } from '@aztec/ethereum/contracts';
3
+ import {
4
+ BlockNumber,
5
+ CheckpointNumber,
6
+ EpochNumber,
7
+ IndexWithinCheckpoint,
8
+ SlotNumber,
9
+ } from '@aztec/foundation/branded-types';
5
10
  import { randomInt } from '@aztec/foundation/crypto/random';
11
+ import {
12
+ flipSignature,
13
+ generateRecoverableSignature,
14
+ generateUnrecoverableSignature,
15
+ } from '@aztec/foundation/crypto/secp256k1-signer';
6
16
  import { Fr } from '@aztec/foundation/curves/bn254';
7
17
  import { EthAddress } from '@aztec/foundation/eth-address';
8
18
  import { Signature } from '@aztec/foundation/eth-signature';
9
19
  import { filter } from '@aztec/foundation/iterator';
10
- import type { Logger } from '@aztec/foundation/log';
20
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
11
21
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
12
22
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
13
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
23
+ import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
14
24
  import type { P2P } from '@aztec/p2p';
15
25
  import type { SlasherClientInterface } from '@aztec/slasher';
16
26
  import {
@@ -21,17 +31,23 @@ import {
21
31
  type L2BlockSource,
22
32
  MaliciousCommitteeAttestationsAndSigners,
23
33
  } from '@aztec/stdlib/block';
24
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
25
- import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
34
+ import { type Checkpoint, type ProposedCheckpointData, validateCheckpoint } from '@aztec/stdlib/checkpoint';
35
+ import { computeQuorum, getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
26
36
  import { Gas } from '@aztec/stdlib/gas';
27
- import type {
28
- PublicProcessorLimits,
29
- ResolvedSequencerConfig,
30
- WorldStateSynchronizer,
37
+ import {
38
+ type BlockBuilderOptions,
39
+ InsufficientValidTxsError,
40
+ type ResolvedSequencerConfig,
41
+ type WorldStateSynchronizer,
31
42
  } from '@aztec/stdlib/interfaces/server';
32
43
  import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
33
- import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
34
- import { orderAttestations } from '@aztec/stdlib/p2p';
44
+ import type {
45
+ BlockProposal,
46
+ BlockProposalOptions,
47
+ CheckpointProposal,
48
+ CheckpointProposalOptions,
49
+ } from '@aztec/stdlib/p2p';
50
+ import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
35
51
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
36
52
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
37
53
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
@@ -52,6 +68,13 @@ import { SequencerState } from './utils.js';
52
68
  /** How much time to sleep while waiting for min transactions to accumulate for a block */
53
69
  const TXS_POLLING_MS = 500;
54
70
 
71
+ /** Result from proposeCheckpoint when a checkpoint was successfully built and attested. */
72
+ type CheckpointProposalResult = {
73
+ checkpoint: Checkpoint;
74
+ attestations: CommitteeAttestationsAndSigners;
75
+ attestationsSignature: Signature;
76
+ };
77
+
55
78
  /**
56
79
  * Handles the execution of a checkpoint proposal after the initial preparation phase.
57
80
  * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
@@ -59,9 +82,18 @@ const TXS_POLLING_MS = 500;
59
82
  * the Sequencer once the check for being the proposer for the slot has succeeded.
60
83
  */
61
84
  export class CheckpointProposalJob implements Traceable {
85
+ protected readonly log: Logger;
86
+
87
+ /** Tracks the fire-and-forget L1 submission promise so it can be awaited during shutdown. */
88
+ private pendingL1Submission: Promise<void> | undefined;
89
+
90
+ /** Fee header override computed during proposeCheckpoint, reused in enqueueCheckpointForSubmission. */
91
+ private computedForceProposedFeeHeader?: { checkpointNumber: CheckpointNumber; feeHeader: FeeHeader };
92
+
62
93
  constructor(
63
- private readonly epoch: EpochNumber,
64
- private readonly slot: SlotNumber,
94
+ private readonly slotNow: SlotNumber,
95
+ private readonly targetSlot: SlotNumber,
96
+ private readonly targetEpoch: EpochNumber,
65
97
  private readonly checkpointNumber: CheckpointNumber,
66
98
  private readonly syncedToBlockNumber: BlockNumber,
67
99
  // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
@@ -86,13 +118,27 @@ export class CheckpointProposalJob implements Traceable {
86
118
  private readonly metrics: SequencerMetrics,
87
119
  private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
88
120
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
89
- protected readonly log: Logger,
90
121
  public readonly tracer: Tracer,
91
- ) {}
122
+ bindings?: LoggerBindings,
123
+ private readonly proposedCheckpointData?: ProposedCheckpointData,
124
+ ) {
125
+ this.log = createLogger('sequencer:checkpoint-proposal', {
126
+ ...bindings,
127
+ instanceId: `slot-${this.slotNow}`,
128
+ });
129
+ }
130
+
131
+ /** Awaits the pending L1 submission if one is in progress. Call during shutdown. */
132
+ public async awaitPendingSubmission(): Promise<void> {
133
+ this.log.info('Awaiting pending L1 payload submission');
134
+ await this.pendingL1Submission;
135
+ }
92
136
 
93
137
  /**
94
138
  * Executes the checkpoint proposal job.
95
- * Returns the published checkpoint if successful, undefined otherwise.
139
+ * Builds blocks, collects attestations, enqueues requests, and schedules L1 submission as a
140
+ * background task so the work loop can return to IDLE immediately.
141
+ * Returns the built checkpoint if successful, undefined otherwise.
96
142
  */
97
143
  @trackSpan('CheckpointProposalJob.execute')
98
144
  public async execute(): Promise<Checkpoint | undefined> {
@@ -100,7 +146,7 @@ export class CheckpointProposalJob implements Traceable {
100
146
  // In fisherman mode, we simulate slashing but don't actually publish to L1
101
147
  // These are constant for the whole slot, so we only enqueue them once
102
148
  const votesPromises = new CheckpointVoter(
103
- this.slot,
149
+ this.targetSlot,
104
150
  this.publisher,
105
151
  this.attestorAddress,
106
152
  this.validatorClient,
@@ -111,14 +157,16 @@ export class CheckpointProposalJob implements Traceable {
111
157
  this.log,
112
158
  ).enqueueVotes();
113
159
 
114
- // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
115
- const checkpoint = await this.proposeCheckpoint();
160
+ // Build and propose the checkpoint. Builds blocks, broadcasts, collects attestations, and signs.
161
+ // Does NOT enqueue to L1 yet — that happens after the pipeline sleep.
162
+ const proposalResult = await this.proposeCheckpoint();
163
+ const checkpoint = proposalResult?.checkpoint;
116
164
 
117
165
  // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
118
166
  await Promise.all(votesPromises);
119
167
 
120
168
  if (checkpoint) {
121
- this.metrics.recordBlockProposalSuccess();
169
+ this.metrics.recordCheckpointProposalSuccess();
122
170
  }
123
171
 
124
172
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
@@ -127,47 +175,135 @@ export class CheckpointProposalJob implements Traceable {
127
175
  return;
128
176
  }
129
177
 
130
- // Then send everything to L1
131
- const l1Response = await this.publisher.sendRequests();
132
- const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
133
- if (proposedAction) {
134
- this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.slot });
135
- const coinbase = checkpoint?.header.coinbase;
136
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
137
- return checkpoint;
138
- } else if (checkpoint) {
139
- this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.slot });
140
- return undefined;
178
+ // Enqueue the checkpoint for L1 submission
179
+ if (proposalResult) {
180
+ try {
181
+ await this.enqueueCheckpointForSubmission(proposalResult);
182
+ } catch (err) {
183
+ this.log.error(`Failed to enqueue checkpoint for L1 submission at slot ${this.targetSlot}`, err);
184
+ // Continue to sendRequestsAt so votes are still sent
185
+ }
141
186
  }
187
+
188
+ // Compute the earliest time to submit: pipeline slot start when pipelining, now otherwise.
189
+ const submitAfter = this.epochCache.isProposerPipeliningEnabled()
190
+ ? new Date(Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) * 1000)
191
+ : new Date(this.dateProvider.now());
192
+
193
+ // TODO(https://github.com/AztecProtocol/aztec-packages/pull/21250): should discard the pending submission if a reorg occurs underneath
194
+
195
+ // Schedule L1 submission in the background so the work loop returns immediately.
196
+ // The publisher will sleep until submitAfter, then send the bundled requests.
197
+ // The promise is stored so it can be awaited during shutdown.
198
+ this.pendingL1Submission = this.publisher
199
+ .sendRequestsAt(submitAfter)
200
+ .then(async l1Response => {
201
+ const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
202
+ if (proposedAction) {
203
+ this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
204
+ const coinbase = checkpoint?.header.coinbase;
205
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
206
+ } else if (checkpoint) {
207
+ this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
208
+
209
+ if (this.epochCache.isProposerPipeliningEnabled()) {
210
+ this.metrics.recordPipelineDiscard();
211
+ }
212
+ }
213
+ })
214
+ .catch(err => {
215
+ this.log.error(`Background L1 submission failed for slot ${this.targetSlot}`, err);
216
+ if (checkpoint) {
217
+ this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
218
+
219
+ if (this.epochCache.isProposerPipeliningEnabled()) {
220
+ this.metrics.recordPipelineDiscard();
221
+ }
222
+ }
223
+ });
224
+
225
+ // Return the built checkpoint immediately — the work loop is now unblocked
226
+ return checkpoint;
227
+ }
228
+
229
+ /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */
230
+ private async enqueueCheckpointForSubmission(result: CheckpointProposalResult): Promise<void> {
231
+ const { checkpoint, attestations, attestationsSignature } = result;
232
+
233
+ this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.targetSlot);
234
+ const aztecSlotDuration = this.l1Constants.slotDuration;
235
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
236
+ const txTimeoutAt = new Date((submissionSlotStart + aztecSlotDuration) * 1000);
237
+
238
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
239
+ if (
240
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
241
+ this.config.skipPublishingCheckpointsPercent > 0
242
+ ) {
243
+ const roll = Math.max(0, randomInt(100));
244
+ if (roll < this.config.skipPublishingCheckpointsPercent) {
245
+ this.log.warn(
246
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${roll}`,
247
+ );
248
+ return;
249
+ }
250
+ }
251
+
252
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
253
+ txTimeoutAt,
254
+ forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
255
+ forceProposedFeeHeader: this.computedForceProposedFeeHeader,
256
+ });
142
257
  }
143
258
 
144
259
  @trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
145
260
  return {
146
261
  // nullish operator needed for tests
147
262
  [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
148
- [Attributes.SLOT_NUMBER]: this.slot,
263
+ [Attributes.SLOT_NUMBER]: this.targetSlot,
149
264
  };
150
265
  })
151
- private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
266
+ private async proposeCheckpoint(): Promise<CheckpointProposalResult | undefined> {
152
267
  try {
153
268
  // Get operator configured coinbase and fee recipient for this attestor
154
269
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
155
270
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
156
271
 
157
272
  // Start the checkpoint
158
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
159
- this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
273
+ this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
274
+ this.log.info(`Starting checkpoint proposal`, {
275
+ buildSlot: this.slotNow,
276
+ submissionSlot: this.targetSlot,
277
+ pipelining: this.epochCache.isProposerPipeliningEnabled(),
278
+ proposer: this.proposer?.toString(),
279
+ coinbase: coinbase.toString(),
280
+ });
281
+ this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
160
282
 
161
283
  // Enqueues checkpoint invalidation (constant for the whole slot)
162
284
  if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
163
285
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
164
286
  }
165
287
 
166
- // Create checkpoint builder for the slot
288
+ // Create checkpoint builder for the slot.
289
+ // When pipelining, force the proposed checkpoint number and fee header to our parent so the
290
+ // fee computation sees the same chain tip that L1 will see once the previous pipelined checkpoint lands.
291
+ const isPipelining = this.epochCache.isProposerPipeliningEnabled();
292
+ const parentCheckpointNumber = isPipelining ? CheckpointNumber(this.checkpointNumber - 1) : undefined;
293
+
294
+ // Compute the parent's fee header override when pipelining
295
+ if (isPipelining && this.proposedCheckpointData) {
296
+ this.computedForceProposedFeeHeader = await this.computeForceProposedFeeHeader(parentCheckpointNumber!);
297
+ }
298
+
167
299
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
168
300
  coinbase,
169
301
  feeRecipient,
170
- this.slot,
302
+ this.targetSlot,
303
+ {
304
+ forcePendingCheckpointNumber: parentCheckpointNumber,
305
+ forceProposedFeeHeader: this.computedForceProposedFeeHeader,
306
+ },
171
307
  );
172
308
 
173
309
  // Collect L1 to L2 messages for the checkpoint and compute their hash
@@ -175,21 +311,25 @@ export class CheckpointProposalJob implements Traceable {
175
311
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
176
312
 
177
313
  // Collect the out hashes of all the checkpoints before this one in the same epoch
178
- const previousCheckpoints = (await this.l2BlockSource.getCheckpointsForEpoch(this.epoch)).filter(
179
- c => c.number < this.checkpointNumber,
180
- );
181
- const previousCheckpointOutHashes = previousCheckpoints.map(c => c.getCheckpointOutHash());
314
+ const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.targetEpoch))
315
+ .filter(c => c.checkpointNumber < this.checkpointNumber)
316
+ .map(c => c.checkpointOutHash);
317
+
318
+ // Get the fee asset price modifier from the oracle
319
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
182
320
 
183
321
  // Create a long-lived forked world state for the checkpoint builder
184
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
322
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
185
323
 
186
324
  // Create checkpoint builder for the entire slot
187
325
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
188
326
  this.checkpointNumber,
189
327
  checkpointGlobalVariables,
328
+ feeAssetPriceModifier,
190
329
  l1ToL2Messages,
191
330
  previousCheckpointOutHashes,
192
331
  fork,
332
+ this.log.getBindings(),
193
333
  );
194
334
 
195
335
  // Options for the validator client when creating block and checkpoint proposals
@@ -205,6 +345,7 @@ export class CheckpointProposalJob implements Traceable {
205
345
 
206
346
  let blocksInCheckpoint: L2Block[] = [];
207
347
  let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
348
+ const checkpointBuildTimer = new Timer();
208
349
 
209
350
  try {
210
351
  // Main loop: build blocks for the checkpoint
@@ -220,48 +361,74 @@ export class CheckpointProposalJob implements Traceable {
220
361
  // These errors are expected in HA mode, so we yield and let another HA node handle the slot
221
362
  // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
222
363
  // which is normal for block building (may have picked different txs)
223
- if (err instanceof DutyAlreadySignedError) {
224
- this.log.info(`Checkpoint proposal for slot ${this.slot} already signed by another HA node, yielding`, {
225
- slot: this.slot,
226
- signedByNode: err.signedByNode,
227
- });
228
- return undefined;
229
- }
230
- if (err instanceof SlashingProtectionError) {
231
- this.log.info(`Checkpoint proposal for slot ${this.slot} blocked by slashing protection, yielding`, {
232
- slot: this.slot,
233
- existingMessageHash: err.existingMessageHash,
234
- attemptedMessageHash: err.attemptedMessageHash,
235
- });
364
+ if (this.handleHASigningError(err, 'Block proposal')) {
236
365
  return undefined;
237
366
  }
238
367
  throw err;
239
368
  }
240
369
 
241
370
  if (blocksInCheckpoint.length === 0) {
242
- this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
243
- this.eventEmitter.emit('checkpoint-empty', { slot: this.slot });
371
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, { slot: this.targetSlot });
372
+ this.eventEmitter.emit('checkpoint-empty', { slot: this.targetSlot });
373
+ return undefined;
374
+ }
375
+
376
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
377
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
378
+ this.log.warn(
379
+ `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
380
+ { slot: this.targetSlot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
381
+ );
244
382
  return undefined;
245
383
  }
246
384
 
247
385
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
248
386
  // broadcasted yet, and wait to collect the committee attestations.
249
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
387
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
250
388
  const checkpoint = await checkpointBuilder.completeCheckpoint();
251
389
 
390
+ // Final validation: per-block limits are only checked if the operator set them explicitly.
391
+ // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
392
+ try {
393
+ validateCheckpoint(checkpoint, {
394
+ rollupManaLimit: this.l1Constants.rollupManaLimit,
395
+ maxL2BlockGas: this.config.maxL2BlockGas,
396
+ maxDABlockGas: this.config.maxDABlockGas,
397
+ maxTxsPerBlock: this.config.maxTxsPerBlock,
398
+ maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
399
+ });
400
+ } catch (err) {
401
+ this.log.error(`Built an invalid checkpoint at slot ${this.slotNow} (skipping proposal)`, err, {
402
+ checkpoint: checkpoint.header.toInspect(),
403
+ });
404
+ return undefined;
405
+ }
406
+
407
+ // Record checkpoint-level build metrics
408
+ this.metrics.recordCheckpointBuild(
409
+ checkpointBuildTimer.ms(),
410
+ blocksInCheckpoint.length,
411
+ checkpoint.getStats().txCount,
412
+ Number(checkpoint.header.totalManaUsed.toBigInt()),
413
+ );
414
+
252
415
  // Do not collect attestations nor publish to L1 in fisherman mode
253
416
  if (this.config.fishermanMode) {
254
417
  this.log.info(
255
- `Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` +
418
+ `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
256
419
  `Skipping proposal in fisherman mode.`,
257
420
  {
258
- slot: this.slot,
421
+ slot: this.targetSlot,
259
422
  checkpoint: checkpoint.header.toInspect(),
260
423
  blocksBuilt: blocksInCheckpoint.length,
261
424
  },
262
425
  );
263
426
  this.metrics.recordCheckpointSuccess();
264
- return checkpoint;
427
+ return {
428
+ checkpoint,
429
+ attestations: CommitteeAttestationsAndSigners.empty(),
430
+ attestationsSignature: Signature.empty(),
431
+ };
265
432
  }
266
433
 
267
434
  // Include the block pending broadcast in the checkpoint proposal if any
@@ -275,6 +442,7 @@ export class CheckpointProposalJob implements Traceable {
275
442
  const proposal = await this.validatorClient.createCheckpointProposal(
276
443
  checkpoint.header,
277
444
  checkpoint.archive.root,
445
+ feeAssetPriceModifier,
278
446
  lastBlock,
279
447
  this.proposer,
280
448
  checkpointProposalOptions,
@@ -283,7 +451,7 @@ export class CheckpointProposalJob implements Traceable {
283
451
  const blockProposedAt = this.dateProvider.now();
284
452
  await this.p2pClient.broadcastCheckpointProposal(proposal);
285
453
 
286
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
454
+ this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.targetSlot);
287
455
  const attestations = await this.waitForAttestations(proposal);
288
456
  const blockAttestedAt = this.dateProvider.now();
289
457
 
@@ -296,48 +464,27 @@ export class CheckpointProposalJob implements Traceable {
296
464
  attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
297
465
  attestations,
298
466
  signer,
299
- this.slot,
467
+ this.targetSlot,
300
468
  this.checkpointNumber,
301
469
  );
302
470
  } catch (err) {
303
471
  // We shouldn't really get here since we yield to another HA node
304
- // as soon as we see these errors when creating block proposals.
305
- if (err instanceof DutyAlreadySignedError) {
306
- this.log.info(`Attestations signature for slot ${this.slot} already signed by another HA node, yielding`, {
307
- slot: this.slot,
308
- signedByNode: err.signedByNode,
309
- });
310
- return undefined;
311
- }
312
- if (err instanceof SlashingProtectionError) {
313
- this.log.info(`Attestations signature for slot ${this.slot} blocked by slashing protection, yielding`, {
314
- slot: this.slot,
315
- existingMessageHash: err.existingMessageHash,
316
- attemptedMessageHash: err.attemptedMessageHash,
317
- });
472
+ // as soon as we see these errors when creating block or checkpoint proposals.
473
+ if (this.handleHASigningError(err, 'Attestations signature')) {
318
474
  return undefined;
319
475
  }
320
476
  throw err;
321
477
  }
322
478
 
323
- // Enqueue publishing the checkpoint to L1
324
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
325
- const aztecSlotDuration = this.l1Constants.slotDuration;
326
- const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
327
- const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
328
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
329
- txTimeoutAt,
330
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
331
- });
332
-
333
- return checkpoint;
479
+ // Return the result for the caller to enqueue after the pipeline sleep
480
+ return { checkpoint, attestations, attestationsSignature };
334
481
  } catch (err) {
335
482
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
336
483
  // swallow this error. It's already been logged by a function deeper in the stack
337
484
  return undefined;
338
485
  }
339
486
 
340
- this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
487
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
341
488
  return undefined;
342
489
  }
343
490
  }
@@ -359,15 +506,12 @@ export class CheckpointProposalJob implements Traceable {
359
506
  const txHashesAlreadyIncluded = new Set<string>();
360
507
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
361
508
 
362
- // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
363
- let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
364
-
365
509
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
366
510
  let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
367
511
 
368
512
  while (true) {
369
513
  const blocksBuilt = blocksInCheckpoint.length;
370
- const indexWithinCheckpoint = blocksBuilt;
514
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
371
515
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
372
516
 
373
517
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -375,7 +519,7 @@ export class CheckpointProposalJob implements Traceable {
375
519
 
376
520
  if (!timingInfo.canStart) {
377
521
  this.log.debug(`Not enough time left in slot to start another block`, {
378
- slot: this.slot,
522
+ slot: this.targetSlot,
379
523
  blocksBuilt,
380
524
  secondsIntoSlot,
381
525
  });
@@ -394,9 +538,9 @@ export class CheckpointProposalJob implements Traceable {
394
538
  blockNumber,
395
539
  indexWithinCheckpoint,
396
540
  txHashesAlreadyIncluded,
397
- remainingBlobFields,
398
541
  });
399
542
 
543
+ // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
400
544
  if (!buildResult && timingInfo.isLastBlock) {
401
545
  // If no block was produced due to not enough txs and this was the last subslot, exit
402
546
  break;
@@ -410,8 +554,8 @@ export class CheckpointProposalJob implements Traceable {
410
554
  } else if ('error' in buildResult) {
411
555
  // If there was an error building the block, just exit the loop and give up the rest of the slot
412
556
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
413
- this.log.warn(`Halting block building for slot ${this.slot}`, {
414
- slot: this.slot,
557
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
558
+ slot: this.targetSlot,
415
559
  blocksBuilt,
416
560
  error: buildResult.error,
417
561
  });
@@ -419,26 +563,16 @@ export class CheckpointProposalJob implements Traceable {
419
563
  break;
420
564
  }
421
565
 
422
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
566
+ const { block, usedTxs } = buildResult;
423
567
  blocksInCheckpoint.push(block);
424
-
425
- // Update remaining blob fields for the next block
426
- remainingBlobFields = newRemainingBlobFields;
427
-
428
- // Sync the proposed block to the archiver to make it available
429
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
430
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
431
- // Fire and forget - don't block the critical path, but log errors
432
- this.syncProposedBlockToArchiver(block).catch(err => {
433
- this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
434
- });
435
-
436
568
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
437
569
 
438
- // If this is the last block, exit the loop now so we start collecting attestations
570
+ // If this is the last block, sync it to the archiver and exit the loop
571
+ // so we can build the checkpoint and start collecting attestations.
439
572
  if (timingInfo.isLastBlock) {
440
- this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
441
- slot: this.slot,
573
+ await this.syncProposedBlockToArchiver(block);
574
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
575
+ slot: this.targetSlot,
442
576
  blockNumber,
443
577
  blocksBuilt,
444
578
  });
@@ -446,80 +580,94 @@ export class CheckpointProposalJob implements Traceable {
446
580
  break;
447
581
  }
448
582
 
449
- // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
450
- // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
451
- if (!this.config.fishermanMode) {
452
- const proposal = await this.validatorClient.createBlockProposal(
453
- block.header,
454
- block.indexWithinCheckpoint,
455
- inHash,
456
- block.archive.root,
457
- usedTxs,
458
- this.proposer,
459
- blockProposalOptions,
460
- );
461
- await this.p2pClient.broadcastProposal(proposal);
462
- }
583
+ // Broadcast the block proposal (unless we're in fisherman mode) unless the block is the last one,
584
+ // in which case we'll broadcast it along with the checkpoint at the end of the loop.
585
+ // Note that we only send the block to the archiver if we manage to create the proposal, so if there's
586
+ // a HA error we don't pollute our archiver with a block that won't make it to the chain.
587
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, blockProposalOptions);
588
+
589
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal.
590
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
591
+ // If this throws, we abort the entire checkpoint.
592
+ await this.syncProposedBlockToArchiver(block);
593
+
594
+ // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
595
+ proposal && (await this.p2pClient.broadcastProposal(proposal));
463
596
 
464
597
  // Wait until the next block's start time
465
598
  await this.waitUntilNextSubslot(timingInfo.deadline);
466
599
  }
467
600
 
468
- this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
469
- slot: this.slot,
601
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
602
+ slot: this.targetSlot,
470
603
  blocksBuilt: blocksInCheckpoint.length,
471
604
  });
472
605
 
473
606
  return { blocksInCheckpoint, blockPendingBroadcast };
474
607
  }
475
608
 
609
+ /** Creates a block proposal for a given block via the validator client (unless in fisherman mode) */
610
+ private createBlockProposal(
611
+ block: L2Block,
612
+ inHash: Fr,
613
+ usedTxs: Tx[],
614
+ blockProposalOptions: BlockProposalOptions,
615
+ ): Promise<BlockProposal | undefined> {
616
+ if (this.config.fishermanMode) {
617
+ this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
618
+ return Promise.resolve(undefined);
619
+ }
620
+ return this.validatorClient.createBlockProposal(
621
+ block.header,
622
+ block.indexWithinCheckpoint,
623
+ inHash,
624
+ block.archive.root,
625
+ usedTxs,
626
+ this.proposer,
627
+ blockProposalOptions,
628
+ );
629
+ }
630
+
476
631
  /** Sleeps until it is time to produce the next block in the slot */
477
632
  @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
478
633
  private async waitUntilNextSubslot(nextSubslotStart: number) {
479
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
480
- this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
634
+ this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
635
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
636
+ slot: this.targetSlot,
637
+ });
481
638
  await this.waitUntilTimeInSlot(nextSubslotStart);
482
639
  }
483
640
 
484
641
  /** Builds a single block. Called from the main block building loop. */
485
642
  @trackSpan('CheckpointProposalJob.buildSingleBlock')
486
- private async buildSingleBlock(
643
+ protected async buildSingleBlock(
487
644
  checkpointBuilder: CheckpointBuilder,
488
645
  opts: {
489
646
  forceCreate?: boolean;
490
647
  blockTimestamp: bigint;
491
648
  blockNumber: BlockNumber;
492
- indexWithinCheckpoint: number;
649
+ indexWithinCheckpoint: IndexWithinCheckpoint;
493
650
  buildDeadline: Date | undefined;
494
651
  txHashesAlreadyIncluded: Set<string>;
495
- remainingBlobFields: number;
496
652
  },
497
- ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
498
- const {
499
- blockTimestamp,
500
- forceCreate,
501
- blockNumber,
502
- indexWithinCheckpoint,
503
- buildDeadline,
504
- txHashesAlreadyIncluded,
505
- remainingBlobFields,
506
- } = opts;
653
+ ): Promise<{ block: L2Block; usedTxs: Tx[] } | { error: Error } | undefined> {
654
+ const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
655
+ opts;
507
656
 
508
657
  this.log.verbose(
509
- `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
658
+ `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot}`,
510
659
  { ...checkpointBuilder.getConstantData(), ...opts },
511
660
  );
512
661
 
513
662
  try {
514
663
  // Wait until we have enough txs to build the block
515
- const minTxs = this.config.minTxsPerBlock;
516
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
664
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
517
665
  if (!canStartBuilding) {
518
666
  this.log.warn(
519
- `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
520
- { blockNumber, slot: this.slot, indexWithinCheckpoint },
667
+ `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (got ${availableTxs} txs but needs ${minTxs})`,
668
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
521
669
  );
522
- this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.slot });
670
+ this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.targetSlot });
523
671
  this.metrics.recordBlockProposalFailed('insufficient_txs');
524
672
  return undefined;
525
673
  }
@@ -527,104 +675,145 @@ export class CheckpointProposalJob implements Traceable {
527
675
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
528
676
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
529
677
  const pendingTxs = filter(
530
- this.p2pClient.iteratePendingTxs(),
678
+ this.p2pClient.iterateEligiblePendingTxs(),
531
679
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
532
680
  );
533
681
 
534
682
  this.log.debug(
535
- `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`,
536
- { slot: this.slot, blockNumber, indexWithinCheckpoint },
683
+ `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`,
684
+ { slot: this.targetSlot, blockNumber, indexWithinCheckpoint },
537
685
  );
538
- this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
539
-
540
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
541
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
542
- const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
686
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
543
687
 
544
- const blockBuilderOptions: PublicProcessorLimits = {
688
+ // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
689
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
690
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
691
+ const minValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
692
+ const blockBuilderOptions: BlockBuilderOptions = {
545
693
  maxTransactions: this.config.maxTxsPerBlock,
546
- maxBlockSize: this.config.maxBlockSizeInBytes,
547
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
548
- maxBlobFields: maxBlobFieldsForTxs,
694
+ maxBlockGas:
695
+ this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined
696
+ ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity)
697
+ : undefined,
549
698
  deadline: buildDeadline,
699
+ isBuildingProposal: true,
700
+ minValidTxs,
701
+ maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
702
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
550
703
  };
551
704
 
552
- // Actually build the block by executing txs
553
- const workTimer = new Timer();
554
- const {
555
- publicGas,
556
- block,
557
- publicProcessorDuration,
558
- numTxs,
559
- blockBuildingTimer,
560
- usedTxs,
561
- failedTxs,
562
- usedTxBlobFields,
563
- } = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
564
- const blockBuildDuration = workTimer.ms();
705
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
706
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
707
+ // updated for blocks that will be discarded.
708
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
709
+ checkpointBuilder,
710
+ pendingTxs,
711
+ blockNumber,
712
+ blockTimestamp,
713
+ blockBuilderOptions,
714
+ );
565
715
 
566
716
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
567
- await this.dropFailedTxsFromP2P(failedTxs);
717
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
568
718
 
569
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
570
- // too long, then we may not get to minTxsPerBlock after executing public functions.
571
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
572
- if (!forceCreate && numTxs < minValidTxs) {
719
+ if (buildResult.status === 'insufficient-valid-txs') {
573
720
  this.log.warn(
574
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
575
- { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint },
721
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`,
722
+ {
723
+ slot: this.targetSlot,
724
+ blockNumber,
725
+ numTxs: buildResult.processedCount,
726
+ indexWithinCheckpoint,
727
+ minValidTxs,
728
+ },
576
729
  );
577
- this.eventEmitter.emit('block-tx-count-check-failed', {
578
- minTxs: minValidTxs,
579
- availableTxs: numTxs,
580
- slot: this.slot,
730
+ this.eventEmitter.emit('block-build-failed', {
731
+ reason: `Insufficient valid txs`,
732
+ slot: this.targetSlot,
581
733
  });
582
734
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
583
735
  return undefined;
584
736
  }
585
737
 
586
738
  // Block creation succeeded, emit stats and metrics
739
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
740
+
587
741
  const blockStats = {
588
742
  eventName: 'l2-block-built',
589
743
  duration: blockBuildDuration,
590
744
  publicProcessDuration: publicProcessorDuration,
591
- rollupCircuitsDuration: blockBuildingTimer.ms(),
592
745
  ...block.getStats(),
593
746
  } satisfies L2BlockBuiltStats;
594
747
 
595
748
  const blockHash = await block.hash();
596
749
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
597
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
750
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
598
751
 
599
752
  this.log.info(
600
- `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`,
753
+ `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot} with ${numTxs} txs`,
601
754
  { blockHash, txHashes, manaPerSec, ...blockStats },
602
755
  );
603
756
 
604
- this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
605
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
757
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
758
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
759
+ this.eventEmitter.emit('block-proposed', {
760
+ blockNumber: block.number,
761
+ slot: this.targetSlot,
762
+ buildSlot: this.slotNow,
763
+ });
764
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
606
765
 
607
- return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
766
+ return { block, usedTxs };
608
767
  } catch (err: any) {
609
- this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
610
- this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
768
+ this.eventEmitter.emit('block-build-failed', {
769
+ reason: err.message,
770
+ slot: this.targetSlot,
771
+ });
772
+ this.log.error(`Error building block`, err, { blockNumber, slot: this.targetSlot });
611
773
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
612
774
  this.metrics.recordFailedBlock();
613
775
  return { error: err };
614
776
  }
615
777
  }
616
778
 
779
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
780
+ private async buildSingleBlockWithCheckpointBuilder(
781
+ checkpointBuilder: CheckpointBuilder,
782
+ pendingTxs: AsyncIterable<Tx>,
783
+ blockNumber: BlockNumber,
784
+ blockTimestamp: bigint,
785
+ blockBuilderOptions: BlockBuilderOptions,
786
+ ) {
787
+ try {
788
+ const workTimer = new Timer();
789
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
790
+ const blockBuildDuration = workTimer.ms();
791
+ return { ...result, blockBuildDuration, status: 'success' as const };
792
+ } catch (err: unknown) {
793
+ if (isErrorClass(err, InsufficientValidTxsError)) {
794
+ return {
795
+ failedTxs: err.failedTxs,
796
+ processedCount: err.processedCount,
797
+ status: 'insufficient-valid-txs' as const,
798
+ };
799
+ }
800
+ throw err;
801
+ }
802
+ }
803
+
617
804
  /** Waits until minTxs are available on the pool for building a block. */
618
805
  @trackSpan('CheckpointProposalJob.waitForMinTxs')
619
806
  private async waitForMinTxs(opts: {
620
807
  forceCreate?: boolean;
621
808
  blockNumber: BlockNumber;
622
- indexWithinCheckpoint: number;
809
+ indexWithinCheckpoint: IndexWithinCheckpoint;
623
810
  buildDeadline: Date | undefined;
624
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
625
- const minTxs = this.config.minTxsPerBlock;
811
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
626
812
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
627
813
 
814
+ // We only allow a block with 0 txs in the first block of the checkpoint
815
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
816
+
628
817
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
629
818
  const startBuildingDeadline = buildDeadline
630
819
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -636,20 +825,20 @@ export class CheckpointProposalJob implements Traceable {
636
825
  // If we're past deadline, or we have no deadline, give up
637
826
  const now = this.dateProvider.nowAsDate();
638
827
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
639
- return { canStartBuilding: false, availableTxs: availableTxs };
828
+ return { canStartBuilding: false, availableTxs, minTxs };
640
829
  }
641
830
 
642
831
  // Wait a bit before checking again
643
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
832
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
644
833
  this.log.verbose(
645
- `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
646
- { blockNumber, slot: this.slot, indexWithinCheckpoint },
834
+ `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`,
835
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
647
836
  );
648
- await sleep(TXS_POLLING_MS);
837
+ await this.waitForTxsPollingInterval();
649
838
  availableTxs = await this.p2pClient.getPendingTxCount();
650
839
  }
651
840
 
652
- return { canStartBuilding: true, availableTxs };
841
+ return { canStartBuilding: true, availableTxs, minTxs };
653
842
  }
654
843
 
655
844
  /**
@@ -675,7 +864,7 @@ export class CheckpointProposalJob implements Traceable {
675
864
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
676
865
  }
677
866
 
678
- const numberOfRequiredAttestations = Math.floor((committee.length * 2) / 3) + 1;
867
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
679
868
 
680
869
  if (this.config.skipCollectingAttestations) {
681
870
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
@@ -701,11 +890,28 @@ export class CheckpointProposalJob implements Traceable {
701
890
 
702
891
  collectedAttestationsCount = attestations.length;
703
892
 
893
+ // Trim attestations to minimum required to save L1 calldata gas
894
+ const localAddresses = this.validatorClient.getValidatorAddresses();
895
+ const trimmed = trimAttestations(
896
+ attestations,
897
+ numberOfRequiredAttestations,
898
+ this.attestorAddress,
899
+ localAddresses,
900
+ );
901
+ if (trimmed.length < attestations.length) {
902
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
903
+ }
904
+
704
905
  // Rollup contract requires that the signatures are provided in the order of the committee
705
- const sorted = orderAttestations(attestations, committee);
906
+ const sorted = orderAttestations(trimmed, committee);
706
907
 
707
908
  // Manipulate the attestations if we've been configured to do so
708
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
909
+ if (
910
+ this.config.injectFakeAttestation ||
911
+ this.config.injectHighSValueAttestation ||
912
+ this.config.injectUnrecoverableSignatureAttestation ||
913
+ this.config.shuffleAttestationOrdering
914
+ ) {
709
915
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
710
916
  }
711
917
 
@@ -734,7 +940,11 @@ export class CheckpointProposalJob implements Traceable {
734
940
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
735
941
  );
736
942
 
737
- if (this.config.injectFakeAttestation) {
943
+ if (
944
+ this.config.injectFakeAttestation ||
945
+ this.config.injectHighSValueAttestation ||
946
+ this.config.injectUnrecoverableSignatureAttestation
947
+ ) {
738
948
  // Find non-empty attestations that are not from the proposer
739
949
  const nonProposerIndices: number[] = [];
740
950
  for (let i = 0; i < attestations.length; i++) {
@@ -744,8 +954,20 @@ export class CheckpointProposalJob implements Traceable {
744
954
  }
745
955
  if (nonProposerIndices.length > 0) {
746
956
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
747
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
748
- unfreeze(attestations[targetIndex]).signature = Signature.random();
957
+ if (this.config.injectHighSValueAttestation) {
958
+ this.log.warn(
959
+ `Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
960
+ );
961
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
962
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
963
+ this.log.warn(
964
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
965
+ );
966
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
967
+ } else {
968
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
969
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
970
+ }
749
971
  }
750
972
  return new CommitteeAttestationsAndSigners(attestations);
751
973
  }
@@ -754,11 +976,20 @@ export class CheckpointProposalJob implements Traceable {
754
976
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
755
977
 
756
978
  const shuffled = [...attestations];
757
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
758
- const valueI = shuffled[i];
759
- const valueJ = shuffled[j];
760
- shuffled[i] = valueJ;
761
- shuffled[j] = valueI;
979
+
980
+ // Find two non-proposer positions that both have non-empty signatures to swap.
981
+ // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
982
+ // signers array stays correctly aligned with L1's committee reconstruction.
983
+ const swappable: number[] = [];
984
+ for (let k = 0; k < shuffled.length; k++) {
985
+ if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
986
+ swappable.push(k);
987
+ }
988
+ }
989
+ if (swappable.length >= 2) {
990
+ const [i, j] = [swappable[0], swappable[1]];
991
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
992
+ }
762
993
 
763
994
  const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
764
995
  return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
@@ -774,7 +1005,7 @@ export class CheckpointProposalJob implements Traceable {
774
1005
  const failedTxData = failedTxs.map(fail => fail.tx);
775
1006
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
776
1007
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
777
- await this.p2pClient.deleteTxs(failedTxHashes);
1008
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
778
1009
  }
779
1010
 
780
1011
  /**
@@ -783,7 +1014,7 @@ export class CheckpointProposalJob implements Traceable {
783
1014
  * would never receive its own block without this explicit sync.
784
1015
  */
785
1016
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
786
- if (this.config.skipPushProposedBlocksToArchiver !== false) {
1017
+ if (this.config.skipPushProposedBlocksToArchiver) {
787
1018
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
788
1019
  blockNumber: block.number,
789
1020
  slot: block.header.globalVariables.slotNumber,
@@ -801,27 +1032,99 @@ export class CheckpointProposalJob implements Traceable {
801
1032
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
802
1033
  // Perform L1 fee analysis before clearing requests
803
1034
  // The callback is invoked asynchronously after the next block is mined
804
- const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, analysis =>
1035
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, analysis =>
805
1036
  this.metrics.recordFishermanFeeAnalysis(analysis),
806
1037
  );
807
1038
 
808
1039
  if (checkpoint) {
809
- this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1040
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
810
1041
  ...checkpoint.toCheckpointInfo(),
811
1042
  ...checkpoint.getStats(),
812
1043
  feeAnalysisId: feeAnalysis?.id,
813
1044
  });
814
1045
  } else {
815
- this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
816
- slot: this.slot,
1046
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1047
+ slot: this.targetSlot,
817
1048
  feeAnalysisId: feeAnalysis?.id,
818
1049
  });
819
- this.metrics.recordBlockProposalFailed('block_build_failed');
1050
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
820
1051
  }
821
1052
 
822
1053
  this.publisher.clearPendingRequests();
823
1054
  }
824
1055
 
1056
+ /**
1057
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
1058
+ */
1059
+ private handleHASigningError(err: any, errorContext: string): boolean {
1060
+ if (err instanceof DutyAlreadySignedError) {
1061
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1062
+ slot: this.targetSlot,
1063
+ signedByNode: err.signedByNode,
1064
+ });
1065
+ return true;
1066
+ }
1067
+ if (err instanceof SlashingProtectionError) {
1068
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1069
+ slot: this.targetSlot,
1070
+ existingMessageHash: err.existingMessageHash,
1071
+ attemptedMessageHash: err.attemptedMessageHash,
1072
+ });
1073
+ return true;
1074
+ }
1075
+ return false;
1076
+ }
1077
+
1078
+ /**
1079
+ * In times of congestion we need to simulate using the correct fee header override for the previous block
1080
+ * We calculate the correct fee header values.
1081
+ *
1082
+ * If we are in block 1, or the checkpoint we are querying does not exist, we return undefined. However
1083
+ * If we are pipelining - where this function is called, the grandparentCheckpointNumber should always exist
1084
+ * @param parentCheckpointNumber
1085
+ * @returns
1086
+ */
1087
+ protected async computeForceProposedFeeHeader(parentCheckpointNumber: CheckpointNumber): Promise<
1088
+ | {
1089
+ checkpointNumber: CheckpointNumber;
1090
+ feeHeader: FeeHeader;
1091
+ }
1092
+ | undefined
1093
+ > {
1094
+ if (!this.proposedCheckpointData) {
1095
+ return undefined;
1096
+ }
1097
+
1098
+ const rollup = this.publisher.rollupContract;
1099
+ const grandparentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 2);
1100
+ try {
1101
+ const [grandparentCheckpoint, manaTarget] = await Promise.all([
1102
+ rollup.getCheckpoint(grandparentCheckpointNumber),
1103
+ rollup.getManaTarget(),
1104
+ ]);
1105
+
1106
+ if (!grandparentCheckpoint || !grandparentCheckpoint.feeHeader) {
1107
+ this.log.error(
1108
+ `Grandparent checkpoint or its feeHeader is undefined for checkpointNumber=${grandparentCheckpointNumber.toString()}`,
1109
+ );
1110
+ return undefined;
1111
+ } else {
1112
+ const parentFeeHeader = RollupContract.computeChildFeeHeader(
1113
+ grandparentCheckpoint.feeHeader,
1114
+ this.proposedCheckpointData.totalManaUsed,
1115
+ this.proposedCheckpointData.feeAssetPriceModifier,
1116
+ manaTarget,
1117
+ );
1118
+ return { checkpointNumber: parentCheckpointNumber, feeHeader: parentFeeHeader };
1119
+ }
1120
+ } catch (err) {
1121
+ this.log.error(
1122
+ `Failed to fetch grandparent checkpoint or mana target for checkpointNumber=${grandparentCheckpointNumber.toString()}: ${err}`,
1123
+ );
1124
+ return undefined;
1125
+ }
1126
+ }
1127
+
825
1128
  /** Waits until a specific time within the current slot */
826
1129
  @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
827
1130
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
@@ -830,8 +1133,13 @@ export class CheckpointProposalJob implements Traceable {
830
1133
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
831
1134
  }
832
1135
 
1136
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
1137
+ protected async waitForTxsPollingInterval(): Promise<void> {
1138
+ await sleep(TXS_POLLING_MS);
1139
+ }
1140
+
833
1141
  private getSlotStartBuildTimestamp(): number {
834
- return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1142
+ return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
835
1143
  }
836
1144
 
837
1145
  private getSecondsIntoSlot(): number {