@aztec/sequencer-client 0.0.1-commit.3469e52 → 0.0.1-commit.381b1a9

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 (59) hide show
  1. package/dest/client/sequencer-client.d.ts +23 -7
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +99 -16
  4. package/dest/config.d.ts +24 -6
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +40 -30
  7. package/dest/global_variable_builder/global_builder.d.ts +2 -4
  8. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  9. package/dest/global_variable_builder/global_builder.js +2 -2
  10. package/dest/publisher/config.d.ts +31 -17
  11. package/dest/publisher/config.d.ts.map +1 -1
  12. package/dest/publisher/config.js +101 -42
  13. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -3
  14. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  15. package/dest/publisher/sequencer-publisher-factory.js +13 -2
  16. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  17. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  18. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  19. package/dest/publisher/sequencer-publisher.d.ts +16 -8
  20. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  21. package/dest/publisher/sequencer-publisher.js +80 -39
  22. package/dest/sequencer/checkpoint_proposal_job.d.ts +31 -10
  23. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  24. package/dest/sequencer/checkpoint_proposal_job.js +172 -96
  25. package/dest/sequencer/metrics.d.ts +17 -5
  26. package/dest/sequencer/metrics.d.ts.map +1 -1
  27. package/dest/sequencer/metrics.js +111 -30
  28. package/dest/sequencer/sequencer.d.ts +26 -13
  29. package/dest/sequencer/sequencer.d.ts.map +1 -1
  30. package/dest/sequencer/sequencer.js +42 -41
  31. package/dest/sequencer/timetable.d.ts +4 -6
  32. package/dest/sequencer/timetable.d.ts.map +1 -1
  33. package/dest/sequencer/timetable.js +7 -11
  34. package/dest/sequencer/types.d.ts +2 -2
  35. package/dest/sequencer/types.d.ts.map +1 -1
  36. package/dest/test/index.d.ts +3 -5
  37. package/dest/test/index.d.ts.map +1 -1
  38. package/dest/test/mock_checkpoint_builder.d.ts +22 -15
  39. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  40. package/dest/test/mock_checkpoint_builder.js +65 -40
  41. package/dest/test/utils.d.ts +8 -8
  42. package/dest/test/utils.d.ts.map +1 -1
  43. package/dest/test/utils.js +10 -9
  44. package/package.json +28 -28
  45. package/src/client/sequencer-client.ts +135 -18
  46. package/src/config.ts +55 -41
  47. package/src/global_variable_builder/global_builder.ts +3 -3
  48. package/src/publisher/config.ts +112 -43
  49. package/src/publisher/sequencer-publisher-factory.ts +23 -6
  50. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  51. package/src/publisher/sequencer-publisher.ts +96 -45
  52. package/src/sequencer/checkpoint_proposal_job.ts +252 -132
  53. package/src/sequencer/metrics.ts +124 -32
  54. package/src/sequencer/sequencer.ts +53 -47
  55. package/src/sequencer/timetable.ts +13 -12
  56. package/src/sequencer/types.ts +1 -1
  57. package/src/test/index.ts +2 -4
  58. package/src/test/mock_checkpoint_builder.ts +94 -64
  59. package/src/test/utils.ts +22 -13
@@ -1,37 +1,47 @@
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 {
3
+ BlockNumber,
4
+ CheckpointNumber,
5
+ EpochNumber,
6
+ IndexWithinCheckpoint,
7
+ SlotNumber,
8
+ } from '@aztec/foundation/branded-types';
5
9
  import { randomInt } from '@aztec/foundation/crypto/random';
10
+ import {
11
+ flipSignature,
12
+ generateRecoverableSignature,
13
+ generateUnrecoverableSignature,
14
+ } from '@aztec/foundation/crypto/secp256k1-signer';
6
15
  import { Fr } from '@aztec/foundation/curves/bn254';
7
16
  import { EthAddress } from '@aztec/foundation/eth-address';
8
17
  import { Signature } from '@aztec/foundation/eth-signature';
9
18
  import { filter } from '@aztec/foundation/iterator';
10
- import type { Logger } from '@aztec/foundation/log';
19
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
11
20
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
12
21
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
13
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
22
+ import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
14
23
  import type { P2P } from '@aztec/p2p';
15
24
  import type { SlasherClientInterface } from '@aztec/slasher';
16
25
  import {
17
26
  CommitteeAttestation,
18
27
  CommitteeAttestationsAndSigners,
19
- L2BlockNew,
28
+ L2Block,
20
29
  type L2BlockSink,
21
30
  type L2BlockSource,
22
31
  MaliciousCommitteeAttestationsAndSigners,
23
32
  } from '@aztec/stdlib/block';
24
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
33
+ import { type Checkpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
25
34
  import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
26
35
  import { Gas } from '@aztec/stdlib/gas';
27
- import type {
28
- PublicProcessorLimits,
29
- ResolvedSequencerConfig,
30
- WorldStateSynchronizer,
36
+ import {
37
+ InsufficientValidTxsError,
38
+ type PublicProcessorLimits,
39
+ type ResolvedSequencerConfig,
40
+ type WorldStateSynchronizer,
31
41
  } from '@aztec/stdlib/interfaces/server';
32
42
  import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
33
43
  import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
34
- import { orderAttestations } from '@aztec/stdlib/p2p';
44
+ import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
35
45
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
36
46
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
37
47
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
@@ -59,6 +69,8 @@ const TXS_POLLING_MS = 500;
59
69
  * the Sequencer once the check for being the proposer for the slot has succeeded.
60
70
  */
61
71
  export class CheckpointProposalJob implements Traceable {
72
+ protected readonly log: Logger;
73
+
62
74
  constructor(
63
75
  private readonly epoch: EpochNumber,
64
76
  private readonly slot: SlotNumber,
@@ -86,9 +98,11 @@ export class CheckpointProposalJob implements Traceable {
86
98
  private readonly metrics: SequencerMetrics,
87
99
  private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
88
100
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
89
- protected readonly log: Logger,
90
101
  public readonly tracer: Tracer,
91
- ) {}
102
+ bindings?: LoggerBindings,
103
+ ) {
104
+ this.log = createLogger('sequencer:checkpoint-proposal', { ...bindings, instanceId: `slot-${slot}` });
105
+ }
92
106
 
93
107
  /**
94
108
  * Executes the checkpoint proposal job.
@@ -118,7 +132,7 @@ export class CheckpointProposalJob implements Traceable {
118
132
  await Promise.all(votesPromises);
119
133
 
120
134
  if (checkpoint) {
121
- this.metrics.recordBlockProposalSuccess();
135
+ this.metrics.recordCheckpointProposalSuccess();
122
136
  }
123
137
 
124
138
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
@@ -175,21 +189,25 @@ export class CheckpointProposalJob implements Traceable {
175
189
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
176
190
 
177
191
  // 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());
192
+ const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.epoch))
193
+ .filter(c => c.checkpointNumber < this.checkpointNumber)
194
+ .map(c => c.checkpointOutHash);
195
+
196
+ // Get the fee asset price modifier from the oracle
197
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
182
198
 
183
199
  // Create a long-lived forked world state for the checkpoint builder
184
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
200
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
185
201
 
186
202
  // Create checkpoint builder for the entire slot
187
203
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
188
204
  this.checkpointNumber,
189
205
  checkpointGlobalVariables,
206
+ feeAssetPriceModifier,
190
207
  l1ToL2Messages,
191
208
  previousCheckpointOutHashes,
192
209
  fork,
210
+ this.log.getBindings(),
193
211
  );
194
212
 
195
213
  // Options for the validator client when creating block and checkpoint proposals
@@ -203,8 +221,9 @@ export class CheckpointProposalJob implements Traceable {
203
221
  broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
204
222
  };
205
223
 
206
- let blocksInCheckpoint: L2BlockNew[] = [];
207
- let blockPendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined = undefined;
224
+ let blocksInCheckpoint: L2Block[] = [];
225
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
226
+ const checkpointBuildTimer = new Timer();
208
227
 
209
228
  try {
210
229
  // Main loop: build blocks for the checkpoint
@@ -220,19 +239,7 @@ export class CheckpointProposalJob implements Traceable {
220
239
  // These errors are expected in HA mode, so we yield and let another HA node handle the slot
221
240
  // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
222
241
  // 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
- });
242
+ if (this.handleHASigningError(err, 'Block proposal')) {
236
243
  return undefined;
237
244
  }
238
245
  throw err;
@@ -244,11 +251,44 @@ export class CheckpointProposalJob implements Traceable {
244
251
  return undefined;
245
252
  }
246
253
 
254
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
255
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
256
+ this.log.warn(
257
+ `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
258
+ { slot: this.slot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
259
+ );
260
+ return undefined;
261
+ }
262
+
247
263
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
248
264
  // broadcasted yet, and wait to collect the committee attestations.
249
265
  this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
250
266
  const checkpoint = await checkpointBuilder.completeCheckpoint();
251
267
 
268
+ // Final validation round for the checkpoint before we propose it, just for safety
269
+ try {
270
+ validateCheckpoint(checkpoint, {
271
+ rollupManaLimit: this.l1Constants.rollupManaLimit,
272
+ maxL2BlockGas: this.config.maxL2BlockGas,
273
+ maxDABlockGas: this.config.maxDABlockGas,
274
+ maxTxsPerBlock: this.config.maxTxsPerBlock,
275
+ maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
276
+ });
277
+ } catch (err) {
278
+ this.log.error(`Built an invalid checkpoint at slot ${this.slot} (skipping proposal)`, err, {
279
+ checkpoint: checkpoint.header.toInspect(),
280
+ });
281
+ return undefined;
282
+ }
283
+
284
+ // Record checkpoint-level build metrics
285
+ this.metrics.recordCheckpointBuild(
286
+ checkpointBuildTimer.ms(),
287
+ blocksInCheckpoint.length,
288
+ checkpoint.getStats().txCount,
289
+ Number(checkpoint.header.totalManaUsed.toBigInt()),
290
+ );
291
+
252
292
  // Do not collect attestations nor publish to L1 in fisherman mode
253
293
  if (this.config.fishermanMode) {
254
294
  this.log.info(
@@ -275,6 +315,7 @@ export class CheckpointProposalJob implements Traceable {
275
315
  const proposal = await this.validatorClient.createCheckpointProposal(
276
316
  checkpoint.header,
277
317
  checkpoint.archive.root,
318
+ feeAssetPriceModifier,
278
319
  lastBlock,
279
320
  this.proposer,
280
321
  checkpointProposalOptions,
@@ -301,20 +342,8 @@ export class CheckpointProposalJob implements Traceable {
301
342
  );
302
343
  } catch (err) {
303
344
  // 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
- });
345
+ // as soon as we see these errors when creating block or checkpoint proposals.
346
+ if (this.handleHASigningError(err, 'Attestations signature')) {
318
347
  return undefined;
319
348
  }
320
349
  throw err;
@@ -325,6 +354,21 @@ export class CheckpointProposalJob implements Traceable {
325
354
  const aztecSlotDuration = this.l1Constants.slotDuration;
326
355
  const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
327
356
  const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
357
+
358
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
359
+ if (
360
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
361
+ this.config.skipPublishingCheckpointsPercent > 0
362
+ ) {
363
+ const result = Math.max(0, randomInt(100));
364
+ if (result < this.config.skipPublishingCheckpointsPercent) {
365
+ this.log.warn(
366
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${result}`,
367
+ );
368
+ return checkpoint;
369
+ }
370
+ }
371
+
328
372
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
329
373
  txTimeoutAt,
330
374
  forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
@@ -352,22 +396,19 @@ export class CheckpointProposalJob implements Traceable {
352
396
  inHash: Fr,
353
397
  blockProposalOptions: BlockProposalOptions,
354
398
  ): Promise<{
355
- blocksInCheckpoint: L2BlockNew[];
356
- blockPendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined;
399
+ blocksInCheckpoint: L2Block[];
400
+ blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
357
401
  }> {
358
- const blocksInCheckpoint: L2BlockNew[] = [];
402
+ const blocksInCheckpoint: L2Block[] = [];
359
403
  const txHashesAlreadyIncluded = new Set<string>();
360
404
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
361
405
 
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
406
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
366
- let blockPendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined = undefined;
407
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
367
408
 
368
409
  while (true) {
369
410
  const blocksBuilt = blocksInCheckpoint.length;
370
- const indexWithinCheckpoint = blocksBuilt;
411
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
371
412
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
372
413
 
373
414
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -394,9 +435,9 @@ export class CheckpointProposalJob implements Traceable {
394
435
  blockNumber,
395
436
  indexWithinCheckpoint,
396
437
  txHashesAlreadyIncluded,
397
- remainingBlobFields,
398
438
  });
399
439
 
440
+ // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
400
441
  if (!buildResult && timingInfo.isLastBlock) {
401
442
  // If no block was produced due to not enough txs and this was the last subslot, exit
402
443
  break;
@@ -419,16 +460,18 @@ export class CheckpointProposalJob implements Traceable {
419
460
  break;
420
461
  }
421
462
 
422
- const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
463
+ const { block, usedTxs } = buildResult;
423
464
  blocksInCheckpoint.push(block);
424
465
 
425
- // Update remaining blob fields for the next block
426
- remainingBlobFields = newRemainingBlobFields;
427
-
428
466
  // Sync the proposed block to the archiver to make it available
429
467
  // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
430
468
  // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
431
- await this.syncProposedBlockToArchiver(block);
469
+ // Fire and forget - don't block the critical path, but log errors
470
+ this.syncProposedBlockToArchiver(block).catch(err => {
471
+ this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
472
+ });
473
+
474
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
432
475
 
433
476
  // If this is the last block, exit the loop now so we start collecting attestations
434
477
  if (timingInfo.isLastBlock) {
@@ -478,27 +521,19 @@ export class CheckpointProposalJob implements Traceable {
478
521
 
479
522
  /** Builds a single block. Called from the main block building loop. */
480
523
  @trackSpan('CheckpointProposalJob.buildSingleBlock')
481
- private async buildSingleBlock(
524
+ protected async buildSingleBlock(
482
525
  checkpointBuilder: CheckpointBuilder,
483
526
  opts: {
484
527
  forceCreate?: boolean;
485
528
  blockTimestamp: bigint;
486
529
  blockNumber: BlockNumber;
487
- indexWithinCheckpoint: number;
530
+ indexWithinCheckpoint: IndexWithinCheckpoint;
488
531
  buildDeadline: Date | undefined;
489
532
  txHashesAlreadyIncluded: Set<string>;
490
- remainingBlobFields: number;
491
533
  },
492
- ): Promise<{ block: L2BlockNew; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
493
- const {
494
- blockTimestamp,
495
- forceCreate,
496
- blockNumber,
497
- indexWithinCheckpoint,
498
- buildDeadline,
499
- txHashesAlreadyIncluded,
500
- remainingBlobFields,
501
- } = opts;
534
+ ): Promise<{ block: L2Block; usedTxs: Tx[] } | { error: Error } | undefined> {
535
+ const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
536
+ opts;
502
537
 
503
538
  this.log.verbose(
504
539
  `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
@@ -507,8 +542,7 @@ export class CheckpointProposalJob implements Traceable {
507
542
 
508
543
  try {
509
544
  // Wait until we have enough txs to build the block
510
- const minTxs = this.config.minTxsPerBlock;
511
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
545
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
512
546
  if (!canStartBuilding) {
513
547
  this.log.warn(
514
548
  `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
@@ -522,7 +556,7 @@ export class CheckpointProposalJob implements Traceable {
522
556
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
523
557
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
524
558
  const pendingTxs = filter(
525
- this.p2pClient.iteratePendingTxs(),
559
+ this.p2pClient.iterateEligiblePendingTxs(),
526
560
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
527
561
  );
528
562
 
@@ -532,64 +566,64 @@ export class CheckpointProposalJob implements Traceable {
532
566
  );
533
567
  this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
534
568
 
535
- // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
536
- const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
537
- const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
538
-
539
- const blockBuilderOptions: PublicProcessorLimits = {
569
+ // Per-block limits derived at startup by computeBlockLimits(), further capped
570
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
571
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
572
+ const minValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
573
+ const blockBuilderOptions: PublicProcessorLimits & { minValidTxs?: number } = {
540
574
  maxTransactions: this.config.maxTxsPerBlock,
541
- maxBlockSize: this.config.maxBlockSizeInBytes,
542
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
543
- maxBlobFields: maxBlobFieldsForTxs,
575
+ maxBlockGas:
576
+ this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined
577
+ ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity)
578
+ : undefined,
544
579
  deadline: buildDeadline,
580
+ isBuildingProposal: true,
581
+ minValidTxs,
545
582
  };
546
583
 
547
- // Actually build the block by executing txs
548
- const workTimer = new Timer();
549
- const {
550
- publicGas,
551
- block,
552
- publicProcessorDuration,
553
- numTxs,
554
- blockBuildingTimer,
555
- usedTxs,
556
- failedTxs,
557
- usedTxBlobFields,
558
- } = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
559
- const blockBuildDuration = workTimer.ms();
584
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
585
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
586
+ // updated for blocks that will be discarded.
587
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
588
+ checkpointBuilder,
589
+ pendingTxs,
590
+ blockNumber,
591
+ blockTimestamp,
592
+ blockBuilderOptions,
593
+ );
560
594
 
561
595
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
562
- await this.dropFailedTxsFromP2P(failedTxs);
596
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
563
597
 
564
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
565
- // too long, then we may not get to minTxsPerBlock after executing public functions.
566
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
567
- if (!forceCreate && numTxs < minValidTxs) {
598
+ if (buildResult.status === 'insufficient-valid-txs') {
568
599
  this.log.warn(
569
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
570
- { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint },
600
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
601
+ {
602
+ slot: this.slot,
603
+ blockNumber,
604
+ numTxs: buildResult.processedCount,
605
+ indexWithinCheckpoint,
606
+ minValidTxs,
607
+ },
571
608
  );
572
- this.eventEmitter.emit('block-tx-count-check-failed', {
573
- minTxs: minValidTxs,
574
- availableTxs: numTxs,
575
- slot: this.slot,
576
- });
609
+ this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
577
610
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
578
611
  return undefined;
579
612
  }
580
613
 
581
614
  // Block creation succeeded, emit stats and metrics
615
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
616
+
582
617
  const blockStats = {
583
618
  eventName: 'l2-block-built',
584
619
  duration: blockBuildDuration,
585
620
  publicProcessDuration: publicProcessorDuration,
586
- rollupCircuitsDuration: blockBuildingTimer.ms(),
587
621
  ...block.getStats(),
588
622
  } satisfies L2BlockBuiltStats;
589
623
 
590
624
  const blockHash = await block.hash();
591
625
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
592
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
626
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
593
627
 
594
628
  this.log.info(
595
629
  `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`,
@@ -597,9 +631,9 @@ export class CheckpointProposalJob implements Traceable {
597
631
  );
598
632
 
599
633
  this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
600
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
634
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
601
635
 
602
- return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
636
+ return { block, usedTxs };
603
637
  } catch (err: any) {
604
638
  this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
605
639
  this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
@@ -609,17 +643,44 @@ export class CheckpointProposalJob implements Traceable {
609
643
  }
610
644
  }
611
645
 
646
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
647
+ private async buildSingleBlockWithCheckpointBuilder(
648
+ checkpointBuilder: CheckpointBuilder,
649
+ pendingTxs: AsyncIterable<Tx>,
650
+ blockNumber: BlockNumber,
651
+ blockTimestamp: bigint,
652
+ blockBuilderOptions: PublicProcessorLimits & { minValidTxs?: number },
653
+ ) {
654
+ try {
655
+ const workTimer = new Timer();
656
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
657
+ const blockBuildDuration = workTimer.ms();
658
+ return { ...result, blockBuildDuration, status: 'success' as const };
659
+ } catch (err: unknown) {
660
+ if (isErrorClass(err, InsufficientValidTxsError)) {
661
+ return {
662
+ failedTxs: err.failedTxs,
663
+ processedCount: err.processedCount,
664
+ status: 'insufficient-valid-txs' as const,
665
+ };
666
+ }
667
+ throw err;
668
+ }
669
+ }
670
+
612
671
  /** Waits until minTxs are available on the pool for building a block. */
613
672
  @trackSpan('CheckpointProposalJob.waitForMinTxs')
614
673
  private async waitForMinTxs(opts: {
615
674
  forceCreate?: boolean;
616
675
  blockNumber: BlockNumber;
617
- indexWithinCheckpoint: number;
676
+ indexWithinCheckpoint: IndexWithinCheckpoint;
618
677
  buildDeadline: Date | undefined;
619
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
620
- const minTxs = this.config.minTxsPerBlock;
678
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
621
679
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
622
680
 
681
+ // We only allow a block with 0 txs in the first block of the checkpoint
682
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
683
+
623
684
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
624
685
  const startBuildingDeadline = buildDeadline
625
686
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -631,7 +692,7 @@ export class CheckpointProposalJob implements Traceable {
631
692
  // If we're past deadline, or we have no deadline, give up
632
693
  const now = this.dateProvider.nowAsDate();
633
694
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
634
- return { canStartBuilding: false, availableTxs: availableTxs };
695
+ return { canStartBuilding: false, availableTxs, minTxs };
635
696
  }
636
697
 
637
698
  // Wait a bit before checking again
@@ -640,11 +701,11 @@ export class CheckpointProposalJob implements Traceable {
640
701
  `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
641
702
  { blockNumber, slot: this.slot, indexWithinCheckpoint },
642
703
  );
643
- await sleep(TXS_POLLING_MS);
704
+ await this.waitForTxsPollingInterval();
644
705
  availableTxs = await this.p2pClient.getPendingTxCount();
645
706
  }
646
707
 
647
- return { canStartBuilding: true, availableTxs };
708
+ return { canStartBuilding: true, availableTxs, minTxs };
648
709
  }
649
710
 
650
711
  /**
@@ -681,7 +742,7 @@ export class CheckpointProposalJob implements Traceable {
681
742
  const attestationTimeAllowed = this.config.enforceTimeTable
682
743
  ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
683
744
  : this.l1Constants.slotDuration;
684
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
745
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
685
746
 
686
747
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
687
748
 
@@ -696,11 +757,28 @@ export class CheckpointProposalJob implements Traceable {
696
757
 
697
758
  collectedAttestationsCount = attestations.length;
698
759
 
760
+ // Trim attestations to minimum required to save L1 calldata gas
761
+ const localAddresses = this.validatorClient.getValidatorAddresses();
762
+ const trimmed = trimAttestations(
763
+ attestations,
764
+ numberOfRequiredAttestations,
765
+ this.attestorAddress,
766
+ localAddresses,
767
+ );
768
+ if (trimmed.length < attestations.length) {
769
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
770
+ }
771
+
699
772
  // Rollup contract requires that the signatures are provided in the order of the committee
700
- const sorted = orderAttestations(attestations, committee);
773
+ const sorted = orderAttestations(trimmed, committee);
701
774
 
702
775
  // Manipulate the attestations if we've been configured to do so
703
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
776
+ if (
777
+ this.config.injectFakeAttestation ||
778
+ this.config.injectHighSValueAttestation ||
779
+ this.config.injectUnrecoverableSignatureAttestation ||
780
+ this.config.shuffleAttestationOrdering
781
+ ) {
704
782
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
705
783
  }
706
784
 
@@ -729,7 +807,11 @@ export class CheckpointProposalJob implements Traceable {
729
807
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
730
808
  );
731
809
 
732
- if (this.config.injectFakeAttestation) {
810
+ if (
811
+ this.config.injectFakeAttestation ||
812
+ this.config.injectHighSValueAttestation ||
813
+ this.config.injectUnrecoverableSignatureAttestation
814
+ ) {
733
815
  // Find non-empty attestations that are not from the proposer
734
816
  const nonProposerIndices: number[] = [];
735
817
  for (let i = 0; i < attestations.length; i++) {
@@ -739,8 +821,20 @@ export class CheckpointProposalJob implements Traceable {
739
821
  }
740
822
  if (nonProposerIndices.length > 0) {
741
823
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
742
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
743
- unfreeze(attestations[targetIndex]).signature = Signature.random();
824
+ if (this.config.injectHighSValueAttestation) {
825
+ this.log.warn(
826
+ `Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
827
+ );
828
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
829
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
830
+ this.log.warn(
831
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
832
+ );
833
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
834
+ } else {
835
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
836
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
837
+ }
744
838
  }
745
839
  return new CommitteeAttestationsAndSigners(attestations);
746
840
  }
@@ -769,7 +863,7 @@ export class CheckpointProposalJob implements Traceable {
769
863
  const failedTxData = failedTxs.map(fail => fail.tx);
770
864
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
771
865
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
772
- await this.p2pClient.deleteTxs(failedTxHashes);
866
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
773
867
  }
774
868
 
775
869
  /**
@@ -777,8 +871,7 @@ export class CheckpointProposalJob implements Traceable {
777
871
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
778
872
  * would never receive its own block without this explicit sync.
779
873
  */
780
- private async syncProposedBlockToArchiver(block: L2BlockNew): Promise<void> {
781
- // TODO(palla/mbps): Change default to false once block sync is stable.
874
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
782
875
  if (this.config.skipPushProposedBlocksToArchiver !== false) {
783
876
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
784
877
  blockNumber: block.number,
@@ -812,12 +905,34 @@ export class CheckpointProposalJob implements Traceable {
812
905
  slot: this.slot,
813
906
  feeAnalysisId: feeAnalysis?.id,
814
907
  });
815
- this.metrics.recordBlockProposalFailed('block_build_failed');
908
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
816
909
  }
817
910
 
818
911
  this.publisher.clearPendingRequests();
819
912
  }
820
913
 
914
+ /**
915
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
916
+ */
917
+ private handleHASigningError(err: any, errorContext: string): boolean {
918
+ if (err instanceof DutyAlreadySignedError) {
919
+ this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
920
+ slot: this.slot,
921
+ signedByNode: err.signedByNode,
922
+ });
923
+ return true;
924
+ }
925
+ if (err instanceof SlashingProtectionError) {
926
+ this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
927
+ slot: this.slot,
928
+ existingMessageHash: err.existingMessageHash,
929
+ attemptedMessageHash: err.attemptedMessageHash,
930
+ });
931
+ return true;
932
+ }
933
+ return false;
934
+ }
935
+
821
936
  /** Waits until a specific time within the current slot */
822
937
  @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
823
938
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
@@ -826,6 +941,11 @@ export class CheckpointProposalJob implements Traceable {
826
941
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
827
942
  }
828
943
 
944
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
945
+ protected async waitForTxsPollingInterval(): Promise<void> {
946
+ await sleep(TXS_POLLING_MS);
947
+ }
948
+
829
949
  private getSlotStartBuildTimestamp(): number {
830
950
  return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
831
951
  }