@aztec/sequencer-client 0.0.1-commit.96bb3f7 → 0.0.1-commit.993d52e

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 (72) hide show
  1. package/dest/client/sequencer-client.d.ts +12 -7
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +15 -4
  4. package/dest/config.d.ts +3 -4
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +28 -20
  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/index.d.ts +2 -2
  11. package/dest/index.d.ts.map +1 -1
  12. package/dest/index.js +1 -1
  13. package/dest/publisher/config.d.ts +31 -17
  14. package/dest/publisher/config.d.ts.map +1 -1
  15. package/dest/publisher/config.js +101 -42
  16. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -3
  17. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  18. package/dest/publisher/sequencer-publisher-factory.js +13 -2
  19. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  20. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  21. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  22. package/dest/publisher/sequencer-publisher.d.ts +16 -8
  23. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  24. package/dest/publisher/sequencer-publisher.js +80 -39
  25. package/dest/sequencer/checkpoint_proposal_job.d.ts +34 -9
  26. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  27. package/dest/sequencer/checkpoint_proposal_job.js +184 -46
  28. package/dest/sequencer/checkpoint_voter.d.ts +3 -2
  29. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  30. package/dest/sequencer/checkpoint_voter.js +34 -10
  31. package/dest/sequencer/index.d.ts +1 -2
  32. package/dest/sequencer/index.d.ts.map +1 -1
  33. package/dest/sequencer/index.js +0 -1
  34. package/dest/sequencer/metrics.d.ts +17 -5
  35. package/dest/sequencer/metrics.d.ts.map +1 -1
  36. package/dest/sequencer/metrics.js +111 -30
  37. package/dest/sequencer/sequencer.d.ts +33 -13
  38. package/dest/sequencer/sequencer.d.ts.map +1 -1
  39. package/dest/sequencer/sequencer.js +95 -36
  40. package/dest/sequencer/timetable.d.ts +1 -4
  41. package/dest/sequencer/timetable.d.ts.map +1 -1
  42. package/dest/sequencer/timetable.js +1 -4
  43. package/dest/test/index.d.ts +3 -5
  44. package/dest/test/index.d.ts.map +1 -1
  45. package/dest/test/mock_checkpoint_builder.d.ts +19 -13
  46. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  47. package/dest/test/mock_checkpoint_builder.js +31 -11
  48. package/dest/test/utils.d.ts +8 -8
  49. package/dest/test/utils.d.ts.map +1 -1
  50. package/dest/test/utils.js +12 -11
  51. package/package.json +30 -28
  52. package/src/client/sequencer-client.ts +25 -7
  53. package/src/config.ts +39 -28
  54. package/src/global_variable_builder/global_builder.ts +3 -3
  55. package/src/index.ts +1 -6
  56. package/src/publisher/config.ts +112 -43
  57. package/src/publisher/sequencer-publisher-factory.ts +23 -6
  58. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  59. package/src/publisher/sequencer-publisher.ts +96 -45
  60. package/src/sequencer/checkpoint_proposal_job.ts +273 -63
  61. package/src/sequencer/checkpoint_voter.ts +32 -7
  62. package/src/sequencer/index.ts +0 -1
  63. package/src/sequencer/metrics.ts +124 -32
  64. package/src/sequencer/sequencer.ts +118 -38
  65. package/src/sequencer/timetable.ts +6 -5
  66. package/src/test/index.ts +2 -4
  67. package/src/test/mock_checkpoint_builder.ts +75 -34
  68. package/src/test/utils.ts +24 -14
  69. package/dest/sequencer/block_builder.d.ts +0 -26
  70. package/dest/sequencer/block_builder.d.ts.map +0 -1
  71. package/dest/sequencer/block_builder.js +0 -129
  72. package/src/sequencer/block_builder.ts +0 -216
@@ -1,40 +1,55 @@
1
+ import { NUM_CHECKPOINT_END_MARKER_FIELDS, getNumBlockEndBlobFields } from '@aztec/blob-lib/encoding';
1
2
  import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
2
3
  import type { EpochCache } from '@aztec/epoch-cache';
3
- import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
+ import {
5
+ BlockNumber,
6
+ CheckpointNumber,
7
+ EpochNumber,
8
+ IndexWithinCheckpoint,
9
+ SlotNumber,
10
+ } from '@aztec/foundation/branded-types';
4
11
  import { randomInt } from '@aztec/foundation/crypto/random';
12
+ import {
13
+ flipSignature,
14
+ generateRecoverableSignature,
15
+ generateUnrecoverableSignature,
16
+ } from '@aztec/foundation/crypto/secp256k1-signer';
5
17
  import { Fr } from '@aztec/foundation/curves/bn254';
6
18
  import { EthAddress } from '@aztec/foundation/eth-address';
7
19
  import { Signature } from '@aztec/foundation/eth-signature';
8
20
  import { filter } from '@aztec/foundation/iterator';
9
- import type { Logger } from '@aztec/foundation/log';
21
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
10
22
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
11
23
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
12
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
24
+ import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
13
25
  import type { P2P } from '@aztec/p2p';
14
26
  import type { SlasherClientInterface } from '@aztec/slasher';
15
27
  import {
16
28
  CommitteeAttestation,
17
29
  CommitteeAttestationsAndSigners,
18
- L2BlockNew,
30
+ L2Block,
19
31
  type L2BlockSink,
32
+ type L2BlockSource,
20
33
  MaliciousCommitteeAttestationsAndSigners,
21
34
  } from '@aztec/stdlib/block';
22
35
  import type { Checkpoint } from '@aztec/stdlib/checkpoint';
23
36
  import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
24
37
  import { Gas } from '@aztec/stdlib/gas';
25
- import type {
26
- PublicProcessorLimits,
27
- ResolvedSequencerConfig,
28
- WorldStateSynchronizer,
38
+ import {
39
+ NoValidTxsError,
40
+ type PublicProcessorLimits,
41
+ type ResolvedSequencerConfig,
42
+ type WorldStateSynchronizer,
29
43
  } from '@aztec/stdlib/interfaces/server';
30
44
  import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
31
45
  import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
32
- import { orderAttestations } from '@aztec/stdlib/p2p';
46
+ import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
33
47
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
34
48
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
35
49
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
36
50
  import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
37
51
  import { CheckpointBuilder, type FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec/validator-client';
52
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
38
53
 
39
54
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
40
55
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
@@ -56,7 +71,10 @@ const TXS_POLLING_MS = 500;
56
71
  * the Sequencer once the check for being the proposer for the slot has succeeded.
57
72
  */
58
73
  export class CheckpointProposalJob implements Traceable {
74
+ protected readonly log: Logger;
75
+
59
76
  constructor(
77
+ private readonly epoch: EpochNumber,
60
78
  private readonly slot: SlotNumber,
61
79
  private readonly checkpointNumber: CheckpointNumber,
62
80
  private readonly syncedToBlockNumber: BlockNumber,
@@ -70,6 +88,7 @@ export class CheckpointProposalJob implements Traceable {
70
88
  private readonly p2pClient: P2P,
71
89
  private readonly worldState: WorldStateSynchronizer,
72
90
  private readonly l1ToL2MessageSource: L1ToL2MessageSource,
91
+ private readonly l2BlockSource: L2BlockSource,
73
92
  private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
74
93
  private readonly blockSink: L2BlockSink,
75
94
  private readonly l1Constants: SequencerRollupConstants,
@@ -81,9 +100,11 @@ export class CheckpointProposalJob implements Traceable {
81
100
  private readonly metrics: SequencerMetrics,
82
101
  private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
83
102
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
84
- protected readonly log: Logger,
85
103
  public readonly tracer: Tracer,
86
- ) {}
104
+ bindings?: LoggerBindings,
105
+ ) {
106
+ this.log = createLogger('sequencer:checkpoint-proposal', { ...bindings, instanceId: `slot-${slot}` });
107
+ }
87
108
 
88
109
  /**
89
110
  * Executes the checkpoint proposal job.
@@ -113,7 +134,7 @@ export class CheckpointProposalJob implements Traceable {
113
134
  await Promise.all(votesPromises);
114
135
 
115
136
  if (checkpoint) {
116
- this.metrics.recordBlockProposalSuccess();
137
+ this.metrics.recordCheckpointProposalSuccess();
117
138
  }
118
139
 
119
140
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
@@ -169,15 +190,26 @@ export class CheckpointProposalJob implements Traceable {
169
190
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
170
191
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
171
192
 
193
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
194
+ const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.epoch))
195
+ .filter(c => c.checkpointNumber < this.checkpointNumber)
196
+ .map(c => c.checkpointOutHash);
197
+
198
+ // Get the fee asset price modifier from the oracle
199
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
200
+
172
201
  // Create a long-lived forked world state for the checkpoint builder
173
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
202
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
174
203
 
175
204
  // Create checkpoint builder for the entire slot
176
205
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
177
206
  this.checkpointNumber,
178
207
  checkpointGlobalVariables,
208
+ feeAssetPriceModifier,
179
209
  l1ToL2Messages,
210
+ previousCheckpointOutHashes,
180
211
  fork,
212
+ this.log.getBindings(),
181
213
  );
182
214
 
183
215
  // Options for the validator client when creating block and checkpoint proposals
@@ -191,13 +223,29 @@ export class CheckpointProposalJob implements Traceable {
191
223
  broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
192
224
  };
193
225
 
194
- // Main loop: build blocks for the checkpoint
195
- const { blocksInCheckpoint, blockPendingBroadcast } = await this.buildBlocksForCheckpoint(
196
- checkpointBuilder,
197
- checkpointGlobalVariables.timestamp,
198
- inHash,
199
- blockProposalOptions,
200
- );
226
+ let blocksInCheckpoint: L2Block[] = [];
227
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
228
+ const checkpointBuildTimer = new Timer();
229
+
230
+ try {
231
+ // Main loop: build blocks for the checkpoint
232
+ const result = await this.buildBlocksForCheckpoint(
233
+ checkpointBuilder,
234
+ checkpointGlobalVariables.timestamp,
235
+ inHash,
236
+ blockProposalOptions,
237
+ );
238
+ blocksInCheckpoint = result.blocksInCheckpoint;
239
+ blockPendingBroadcast = result.blockPendingBroadcast;
240
+ } catch (err) {
241
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
242
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
243
+ // which is normal for block building (may have picked different txs)
244
+ if (this.handleHASigningError(err, 'Block proposal')) {
245
+ return undefined;
246
+ }
247
+ throw err;
248
+ }
201
249
 
202
250
  if (blocksInCheckpoint.length === 0) {
203
251
  this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
@@ -205,11 +253,28 @@ export class CheckpointProposalJob implements Traceable {
205
253
  return undefined;
206
254
  }
207
255
 
256
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
257
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
258
+ this.log.warn(
259
+ `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
260
+ { slot: this.slot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
261
+ );
262
+ return undefined;
263
+ }
264
+
208
265
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
209
266
  // broadcasted yet, and wait to collect the committee attestations.
210
267
  this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
211
268
  const checkpoint = await checkpointBuilder.completeCheckpoint();
212
269
 
270
+ // Record checkpoint-level build metrics
271
+ this.metrics.recordCheckpointBuild(
272
+ checkpointBuildTimer.ms(),
273
+ blocksInCheckpoint.length,
274
+ checkpoint.getStats().txCount,
275
+ Number(checkpoint.header.totalManaUsed.toBigInt()),
276
+ );
277
+
213
278
  // Do not collect attestations nor publish to L1 in fisherman mode
214
279
  if (this.config.fishermanMode) {
215
280
  this.log.info(
@@ -236,6 +301,7 @@ export class CheckpointProposalJob implements Traceable {
236
301
  const proposal = await this.validatorClient.createCheckpointProposal(
237
302
  checkpoint.header,
238
303
  checkpoint.archive.root,
304
+ feeAssetPriceModifier,
239
305
  lastBlock,
240
306
  this.proposer,
241
307
  checkpointProposalOptions,
@@ -252,13 +318,43 @@ export class CheckpointProposalJob implements Traceable {
252
318
 
253
319
  // Proposer must sign over the attestations before pushing them to L1
254
320
  const signer = this.proposer ?? this.publisher.getSenderAddress();
255
- const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer);
321
+ let attestationsSignature: Signature;
322
+ try {
323
+ attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
324
+ attestations,
325
+ signer,
326
+ this.slot,
327
+ this.checkpointNumber,
328
+ );
329
+ } catch (err) {
330
+ // We shouldn't really get here since we yield to another HA node
331
+ // as soon as we see these errors when creating block or checkpoint proposals.
332
+ if (this.handleHASigningError(err, 'Attestations signature')) {
333
+ return undefined;
334
+ }
335
+ throw err;
336
+ }
256
337
 
257
338
  // Enqueue publishing the checkpoint to L1
258
339
  this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
259
340
  const aztecSlotDuration = this.l1Constants.slotDuration;
260
341
  const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
261
342
  const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
343
+
344
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
345
+ if (
346
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
347
+ this.config.skipPublishingCheckpointsPercent > 0
348
+ ) {
349
+ const result = Math.max(0, randomInt(100));
350
+ if (result < this.config.skipPublishingCheckpointsPercent) {
351
+ this.log.warn(
352
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${result}`,
353
+ );
354
+ return checkpoint;
355
+ }
356
+ }
357
+
262
358
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
263
359
  txTimeoutAt,
264
360
  forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
@@ -266,6 +362,11 @@ export class CheckpointProposalJob implements Traceable {
266
362
 
267
363
  return checkpoint;
268
364
  } catch (err) {
365
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
366
+ // swallow this error. It's already been logged by a function deeper in the stack
367
+ return undefined;
368
+ }
369
+
269
370
  this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
270
371
  return undefined;
271
372
  }
@@ -281,19 +382,22 @@ export class CheckpointProposalJob implements Traceable {
281
382
  inHash: Fr,
282
383
  blockProposalOptions: BlockProposalOptions,
283
384
  ): Promise<{
284
- blocksInCheckpoint: L2BlockNew[];
285
- blockPendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined;
385
+ blocksInCheckpoint: L2Block[];
386
+ blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
286
387
  }> {
287
- const blocksInCheckpoint: L2BlockNew[] = [];
388
+ const blocksInCheckpoint: L2Block[] = [];
288
389
  const txHashesAlreadyIncluded = new Set<string>();
289
390
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
290
391
 
392
+ // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
393
+ let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
394
+
291
395
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
292
- let blockPendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined = undefined;
396
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
293
397
 
294
398
  while (true) {
295
399
  const blocksBuilt = blocksInCheckpoint.length;
296
- const indexWithinCheckpoint = blocksBuilt;
400
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
297
401
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
298
402
 
299
403
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -320,8 +424,10 @@ export class CheckpointProposalJob implements Traceable {
320
424
  blockNumber,
321
425
  indexWithinCheckpoint,
322
426
  txHashesAlreadyIncluded,
427
+ remainingBlobFields,
323
428
  });
324
429
 
430
+ // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
325
431
  if (!buildResult && timingInfo.isLastBlock) {
326
432
  // If no block was produced due to not enough txs and this was the last subslot, exit
327
433
  break;
@@ -344,13 +450,21 @@ export class CheckpointProposalJob implements Traceable {
344
450
  break;
345
451
  }
346
452
 
347
- const { block, usedTxs } = buildResult;
453
+ const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
348
454
  blocksInCheckpoint.push(block);
349
455
 
456
+ // Update remaining blob fields for the next block
457
+ remainingBlobFields = newRemainingBlobFields;
458
+
350
459
  // Sync the proposed block to the archiver to make it available
351
460
  // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
352
461
  // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
353
- await this.syncProposedBlockToArchiver(block);
462
+ // Fire and forget - don't block the critical path, but log errors
463
+ this.syncProposedBlockToArchiver(block).catch(err => {
464
+ this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
465
+ });
466
+
467
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
354
468
 
355
469
  // If this is the last block, exit the loop now so we start collecting attestations
356
470
  if (timingInfo.isLastBlock) {
@@ -400,19 +514,27 @@ export class CheckpointProposalJob implements Traceable {
400
514
 
401
515
  /** Builds a single block. Called from the main block building loop. */
402
516
  @trackSpan('CheckpointProposalJob.buildSingleBlock')
403
- private async buildSingleBlock(
517
+ protected async buildSingleBlock(
404
518
  checkpointBuilder: CheckpointBuilder,
405
519
  opts: {
406
520
  forceCreate?: boolean;
407
521
  blockTimestamp: bigint;
408
522
  blockNumber: BlockNumber;
409
- indexWithinCheckpoint: number;
523
+ indexWithinCheckpoint: IndexWithinCheckpoint;
410
524
  buildDeadline: Date | undefined;
411
525
  txHashesAlreadyIncluded: Set<string>;
526
+ remainingBlobFields: number;
412
527
  },
413
- ): Promise<{ block: L2BlockNew; usedTxs: Tx[] } | { error: Error } | undefined> {
414
- const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
415
- opts;
528
+ ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
529
+ const {
530
+ blockTimestamp,
531
+ forceCreate,
532
+ blockNumber,
533
+ indexWithinCheckpoint,
534
+ buildDeadline,
535
+ txHashesAlreadyIncluded,
536
+ remainingBlobFields,
537
+ } = opts;
416
538
 
417
539
  this.log.verbose(
418
540
  `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
@@ -436,7 +558,7 @@ export class CheckpointProposalJob implements Traceable {
436
558
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
437
559
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
438
560
  const pendingTxs = filter(
439
- this.p2pClient.iteratePendingTxs(),
561
+ this.p2pClient.iterateEligiblePendingTxs(),
440
562
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
441
563
  );
442
564
 
@@ -445,46 +567,52 @@ export class CheckpointProposalJob implements Traceable {
445
567
  { slot: this.slot, blockNumber, indexWithinCheckpoint },
446
568
  );
447
569
  this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
570
+
571
+ // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
572
+ const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
573
+ const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
574
+
448
575
  const blockBuilderOptions: PublicProcessorLimits = {
449
576
  maxTransactions: this.config.maxTxsPerBlock,
450
577
  maxBlockSize: this.config.maxBlockSizeInBytes,
451
578
  maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
452
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
579
+ maxBlobFields: maxBlobFieldsForTxs,
453
580
  deadline: buildDeadline,
454
581
  };
455
582
 
456
583
  // Actually build the block by executing txs
457
- const workTimer = new Timer();
458
- const { publicGas, block, publicProcessorDuration, numTxs, blockBuildingTimer, usedTxs, failedTxs } =
459
- await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
460
- const blockBuildDuration = workTimer.ms();
584
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
585
+ checkpointBuilder,
586
+ pendingTxs,
587
+ blockNumber,
588
+ blockTimestamp,
589
+ blockBuilderOptions,
590
+ );
461
591
 
462
592
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
463
- await this.dropFailedTxsFromP2P(failedTxs);
593
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
464
594
 
465
595
  // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
466
596
  // too long, then we may not get to minTxsPerBlock after executing public functions.
467
597
  const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
468
- if (!forceCreate && numTxs < minValidTxs) {
598
+ const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
599
+ if (buildResult.status === 'no-valid-txs' || (!forceCreate && numTxs < minValidTxs)) {
469
600
  this.log.warn(
470
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
471
- { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint },
601
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
602
+ { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint, minValidTxs, buildResult: buildResult.status },
472
603
  );
473
- this.eventEmitter.emit('block-tx-count-check-failed', {
474
- minTxs: minValidTxs,
475
- availableTxs: numTxs,
476
- slot: this.slot,
477
- });
604
+ this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
478
605
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
479
606
  return undefined;
480
607
  }
481
608
 
482
609
  // Block creation succeeded, emit stats and metrics
610
+ const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
611
+
483
612
  const blockStats = {
484
613
  eventName: 'l2-block-built',
485
614
  duration: blockBuildDuration,
486
615
  publicProcessDuration: publicProcessorDuration,
487
- rollupCircuitsDuration: blockBuildingTimer.ms(),
488
616
  ...block.getStats(),
489
617
  } satisfies L2BlockBuiltStats;
490
618
 
@@ -500,7 +628,7 @@ export class CheckpointProposalJob implements Traceable {
500
628
  this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
501
629
  this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
502
630
 
503
- return { block, usedTxs };
631
+ return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
504
632
  } catch (err: any) {
505
633
  this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
506
634
  this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
@@ -510,17 +638,40 @@ export class CheckpointProposalJob implements Traceable {
510
638
  }
511
639
  }
512
640
 
641
+ /** Uses the checkpoint builder to build a block, catching specific txs */
642
+ private async buildSingleBlockWithCheckpointBuilder(
643
+ checkpointBuilder: CheckpointBuilder,
644
+ pendingTxs: AsyncIterable<Tx>,
645
+ blockNumber: BlockNumber,
646
+ blockTimestamp: bigint,
647
+ blockBuilderOptions: PublicProcessorLimits,
648
+ ) {
649
+ try {
650
+ const workTimer = new Timer();
651
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
652
+ const blockBuildDuration = workTimer.ms();
653
+ return { ...result, blockBuildDuration, status: 'success' as const };
654
+ } catch (err: unknown) {
655
+ if (isErrorClass(err, NoValidTxsError)) {
656
+ return { failedTxs: err.failedTxs, status: 'no-valid-txs' as const };
657
+ }
658
+ throw err;
659
+ }
660
+ }
661
+
513
662
  /** Waits until minTxs are available on the pool for building a block. */
514
663
  @trackSpan('CheckpointProposalJob.waitForMinTxs')
515
664
  private async waitForMinTxs(opts: {
516
665
  forceCreate?: boolean;
517
666
  blockNumber: BlockNumber;
518
- indexWithinCheckpoint: number;
667
+ indexWithinCheckpoint: IndexWithinCheckpoint;
519
668
  buildDeadline: Date | undefined;
520
669
  }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
521
- const minTxs = this.config.minTxsPerBlock;
522
670
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
523
671
 
672
+ // We only allow a block with 0 txs in the first block of the checkpoint
673
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
674
+
524
675
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
525
676
  const startBuildingDeadline = buildDeadline
526
677
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -541,7 +692,7 @@ export class CheckpointProposalJob implements Traceable {
541
692
  `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
542
693
  { blockNumber, slot: this.slot, indexWithinCheckpoint },
543
694
  );
544
- await sleep(TXS_POLLING_MS);
695
+ await this.waitForTxsPollingInterval();
545
696
  availableTxs = await this.p2pClient.getPendingTxCount();
546
697
  }
547
698
 
@@ -582,7 +733,7 @@ export class CheckpointProposalJob implements Traceable {
582
733
  const attestationTimeAllowed = this.config.enforceTimeTable
583
734
  ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
584
735
  : this.l1Constants.slotDuration;
585
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
736
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
586
737
 
587
738
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
588
739
 
@@ -597,11 +748,28 @@ export class CheckpointProposalJob implements Traceable {
597
748
 
598
749
  collectedAttestationsCount = attestations.length;
599
750
 
751
+ // Trim attestations to minimum required to save L1 calldata gas
752
+ const localAddresses = this.validatorClient.getValidatorAddresses();
753
+ const trimmed = trimAttestations(
754
+ attestations,
755
+ numberOfRequiredAttestations,
756
+ this.attestorAddress,
757
+ localAddresses,
758
+ );
759
+ if (trimmed.length < attestations.length) {
760
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
761
+ }
762
+
600
763
  // Rollup contract requires that the signatures are provided in the order of the committee
601
- const sorted = orderAttestations(attestations, committee);
764
+ const sorted = orderAttestations(trimmed, committee);
602
765
 
603
766
  // Manipulate the attestations if we've been configured to do so
604
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
767
+ if (
768
+ this.config.injectFakeAttestation ||
769
+ this.config.injectHighSValueAttestation ||
770
+ this.config.injectUnrecoverableSignatureAttestation ||
771
+ this.config.shuffleAttestationOrdering
772
+ ) {
605
773
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
606
774
  }
607
775
 
@@ -630,7 +798,11 @@ export class CheckpointProposalJob implements Traceable {
630
798
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
631
799
  );
632
800
 
633
- if (this.config.injectFakeAttestation) {
801
+ if (
802
+ this.config.injectFakeAttestation ||
803
+ this.config.injectHighSValueAttestation ||
804
+ this.config.injectUnrecoverableSignatureAttestation
805
+ ) {
634
806
  // Find non-empty attestations that are not from the proposer
635
807
  const nonProposerIndices: number[] = [];
636
808
  for (let i = 0; i < attestations.length; i++) {
@@ -640,8 +812,20 @@ export class CheckpointProposalJob implements Traceable {
640
812
  }
641
813
  if (nonProposerIndices.length > 0) {
642
814
  const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
643
- this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
644
- unfreeze(attestations[targetIndex]).signature = Signature.random();
815
+ if (this.config.injectHighSValueAttestation) {
816
+ this.log.warn(
817
+ `Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
818
+ );
819
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
820
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
821
+ this.log.warn(
822
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
823
+ );
824
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
825
+ } else {
826
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
827
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
828
+ }
645
829
  }
646
830
  return new CommitteeAttestationsAndSigners(attestations);
647
831
  }
@@ -670,7 +854,7 @@ export class CheckpointProposalJob implements Traceable {
670
854
  const failedTxData = failedTxs.map(fail => fail.tx);
671
855
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
672
856
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
673
- await this.p2pClient.deleteTxs(failedTxHashes);
857
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
674
858
  }
675
859
 
676
860
  /**
@@ -678,8 +862,7 @@ export class CheckpointProposalJob implements Traceable {
678
862
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
679
863
  * would never receive its own block without this explicit sync.
680
864
  */
681
- private async syncProposedBlockToArchiver(block: L2BlockNew): Promise<void> {
682
- // TODO(palla/mbps): Change default to false once block sync is stable.
865
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
683
866
  if (this.config.skipPushProposedBlocksToArchiver !== false) {
684
867
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
685
868
  blockNumber: block.number,
@@ -713,12 +896,34 @@ export class CheckpointProposalJob implements Traceable {
713
896
  slot: this.slot,
714
897
  feeAnalysisId: feeAnalysis?.id,
715
898
  });
716
- this.metrics.recordBlockProposalFailed('block_build_failed');
899
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
717
900
  }
718
901
 
719
902
  this.publisher.clearPendingRequests();
720
903
  }
721
904
 
905
+ /**
906
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
907
+ */
908
+ private handleHASigningError(err: any, errorContext: string): boolean {
909
+ if (err instanceof DutyAlreadySignedError) {
910
+ this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
911
+ slot: this.slot,
912
+ signedByNode: err.signedByNode,
913
+ });
914
+ return true;
915
+ }
916
+ if (err instanceof SlashingProtectionError) {
917
+ this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
918
+ slot: this.slot,
919
+ existingMessageHash: err.existingMessageHash,
920
+ attemptedMessageHash: err.attemptedMessageHash,
921
+ });
922
+ return true;
923
+ }
924
+ return false;
925
+ }
926
+
722
927
  /** Waits until a specific time within the current slot */
723
928
  @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
724
929
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
@@ -727,6 +932,11 @@ export class CheckpointProposalJob implements Traceable {
727
932
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
728
933
  }
729
934
 
935
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
936
+ protected async waitForTxsPollingInterval(): Promise<void> {
937
+ await sleep(TXS_POLLING_MS);
938
+ }
939
+
730
940
  private getSlotStartBuildTimestamp(): number {
731
941
  return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
732
942
  }