@aztec/sequencer-client 0.0.1-commit.1142ef1 → 0.0.1-commit.125b3452

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 (94) hide show
  1. package/dest/client/sequencer-client.d.ts +24 -7
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +101 -16
  4. package/dest/config.d.ts +25 -6
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +49 -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 +7 -6
  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 +35 -17
  14. package/dest/publisher/config.d.ts.map +1 -1
  15. package/dest/publisher/config.js +106 -42
  16. package/dest/publisher/index.d.ts +2 -1
  17. package/dest/publisher/index.d.ts.map +1 -1
  18. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  19. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  20. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  21. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +59 -0
  22. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  23. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  24. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  25. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  26. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  27. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  28. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  29. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  30. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -3
  31. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  32. package/dest/publisher/sequencer-publisher-factory.js +27 -2
  33. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  34. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  35. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  36. package/dest/publisher/sequencer-publisher.d.ts +26 -8
  37. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  38. package/dest/publisher/sequencer-publisher.js +349 -49
  39. package/dest/sequencer/checkpoint_proposal_job.d.ts +33 -10
  40. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  41. package/dest/sequencer/checkpoint_proposal_job.js +217 -66
  42. package/dest/sequencer/checkpoint_voter.d.ts +3 -2
  43. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  44. package/dest/sequencer/checkpoint_voter.js +34 -10
  45. package/dest/sequencer/index.d.ts +1 -2
  46. package/dest/sequencer/index.d.ts.map +1 -1
  47. package/dest/sequencer/index.js +0 -1
  48. package/dest/sequencer/metrics.d.ts +17 -5
  49. package/dest/sequencer/metrics.d.ts.map +1 -1
  50. package/dest/sequencer/metrics.js +111 -30
  51. package/dest/sequencer/sequencer.d.ts +42 -19
  52. package/dest/sequencer/sequencer.d.ts.map +1 -1
  53. package/dest/sequencer/sequencer.js +107 -50
  54. package/dest/sequencer/timetable.d.ts +4 -6
  55. package/dest/sequencer/timetable.d.ts.map +1 -1
  56. package/dest/sequencer/timetable.js +7 -11
  57. package/dest/sequencer/types.d.ts +2 -2
  58. package/dest/sequencer/types.d.ts.map +1 -1
  59. package/dest/test/index.d.ts +3 -5
  60. package/dest/test/index.d.ts.map +1 -1
  61. package/dest/test/mock_checkpoint_builder.d.ts +27 -19
  62. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  63. package/dest/test/mock_checkpoint_builder.js +67 -38
  64. package/dest/test/utils.d.ts +8 -8
  65. package/dest/test/utils.d.ts.map +1 -1
  66. package/dest/test/utils.js +12 -11
  67. package/package.json +29 -28
  68. package/src/client/sequencer-client.ts +135 -18
  69. package/src/config.ts +65 -41
  70. package/src/global_variable_builder/global_builder.ts +6 -5
  71. package/src/index.ts +1 -6
  72. package/src/publisher/config.ts +121 -43
  73. package/src/publisher/index.ts +3 -0
  74. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  75. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +55 -0
  76. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  77. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  78. package/src/publisher/sequencer-publisher-factory.ts +38 -6
  79. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  80. package/src/publisher/sequencer-publisher.ts +344 -61
  81. package/src/sequencer/checkpoint_proposal_job.ts +306 -81
  82. package/src/sequencer/checkpoint_voter.ts +32 -7
  83. package/src/sequencer/index.ts +0 -1
  84. package/src/sequencer/metrics.ts +124 -32
  85. package/src/sequencer/sequencer.ts +131 -53
  86. package/src/sequencer/timetable.ts +13 -12
  87. package/src/sequencer/types.ts +1 -1
  88. package/src/test/index.ts +2 -4
  89. package/src/test/mock_checkpoint_builder.ts +122 -78
  90. package/src/test/utils.ts +24 -14
  91. package/dest/sequencer/block_builder.d.ts +0 -26
  92. package/dest/sequencer/block_builder.d.ts.map +0 -1
  93. package/dest/sequencer/block_builder.js +0 -129
  94. package/src/sequencer/block_builder.ts +0 -216
@@ -1,40 +1,53 @@
1
- import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
2
1
  import type { EpochCache } from '@aztec/epoch-cache';
3
- import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import {
3
+ BlockNumber,
4
+ CheckpointNumber,
5
+ EpochNumber,
6
+ IndexWithinCheckpoint,
7
+ SlotNumber,
8
+ } from '@aztec/foundation/branded-types';
4
9
  import { randomInt } from '@aztec/foundation/crypto/random';
10
+ import {
11
+ flipSignature,
12
+ generateRecoverableSignature,
13
+ generateUnrecoverableSignature,
14
+ } from '@aztec/foundation/crypto/secp256k1-signer';
5
15
  import { Fr } from '@aztec/foundation/curves/bn254';
6
16
  import { EthAddress } from '@aztec/foundation/eth-address';
7
17
  import { Signature } from '@aztec/foundation/eth-signature';
8
18
  import { filter } from '@aztec/foundation/iterator';
9
- import type { Logger } from '@aztec/foundation/log';
19
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
10
20
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
11
21
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
12
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
22
+ import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
13
23
  import type { P2P } from '@aztec/p2p';
14
24
  import type { SlasherClientInterface } from '@aztec/slasher';
15
25
  import {
16
26
  CommitteeAttestation,
17
27
  CommitteeAttestationsAndSigners,
18
- L2BlockNew,
28
+ L2Block,
19
29
  type L2BlockSink,
30
+ type L2BlockSource,
20
31
  MaliciousCommitteeAttestationsAndSigners,
21
32
  } from '@aztec/stdlib/block';
22
- import type { Checkpoint } from '@aztec/stdlib/checkpoint';
33
+ import { type Checkpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
23
34
  import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
24
35
  import { Gas } from '@aztec/stdlib/gas';
25
- import type {
26
- PublicProcessorLimits,
27
- ResolvedSequencerConfig,
28
- WorldStateSynchronizer,
36
+ import {
37
+ InsufficientValidTxsError,
38
+ type PublicProcessorLimits,
39
+ type ResolvedSequencerConfig,
40
+ type WorldStateSynchronizer,
29
41
  } from '@aztec/stdlib/interfaces/server';
30
42
  import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
31
43
  import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
32
- import { orderAttestations } from '@aztec/stdlib/p2p';
44
+ import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
33
45
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
34
46
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
35
47
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
36
48
  import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
37
49
  import { CheckpointBuilder, type FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec/validator-client';
50
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
38
51
 
39
52
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
40
53
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
@@ -56,7 +69,10 @@ const TXS_POLLING_MS = 500;
56
69
  * the Sequencer once the check for being the proposer for the slot has succeeded.
57
70
  */
58
71
  export class CheckpointProposalJob implements Traceable {
72
+ protected readonly log: Logger;
73
+
59
74
  constructor(
75
+ private readonly epoch: EpochNumber,
60
76
  private readonly slot: SlotNumber,
61
77
  private readonly checkpointNumber: CheckpointNumber,
62
78
  private readonly syncedToBlockNumber: BlockNumber,
@@ -70,6 +86,7 @@ export class CheckpointProposalJob implements Traceable {
70
86
  private readonly p2pClient: P2P,
71
87
  private readonly worldState: WorldStateSynchronizer,
72
88
  private readonly l1ToL2MessageSource: L1ToL2MessageSource,
89
+ private readonly l2BlockSource: L2BlockSource,
73
90
  private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
74
91
  private readonly blockSink: L2BlockSink,
75
92
  private readonly l1Constants: SequencerRollupConstants,
@@ -81,9 +98,11 @@ export class CheckpointProposalJob implements Traceable {
81
98
  private readonly metrics: SequencerMetrics,
82
99
  private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
83
100
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
84
- protected readonly log: Logger,
85
101
  public readonly tracer: Tracer,
86
- ) {}
102
+ bindings?: LoggerBindings,
103
+ ) {
104
+ this.log = createLogger('sequencer:checkpoint-proposal', { ...bindings, instanceId: `slot-${slot}` });
105
+ }
87
106
 
88
107
  /**
89
108
  * Executes the checkpoint proposal job.
@@ -113,7 +132,7 @@ export class CheckpointProposalJob implements Traceable {
113
132
  await Promise.all(votesPromises);
114
133
 
115
134
  if (checkpoint) {
116
- this.metrics.recordBlockProposalSuccess();
135
+ this.metrics.recordCheckpointProposalSuccess();
117
136
  }
118
137
 
119
138
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
@@ -169,15 +188,26 @@ export class CheckpointProposalJob implements Traceable {
169
188
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
170
189
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
171
190
 
191
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
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();
198
+
172
199
  // Create a long-lived forked world state for the checkpoint builder
173
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
200
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
174
201
 
175
202
  // Create checkpoint builder for the entire slot
176
203
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
177
204
  this.checkpointNumber,
178
205
  checkpointGlobalVariables,
206
+ feeAssetPriceModifier,
179
207
  l1ToL2Messages,
208
+ previousCheckpointOutHashes,
180
209
  fork,
210
+ this.log.getBindings(),
181
211
  );
182
212
 
183
213
  // Options for the validator client when creating block and checkpoint proposals
@@ -191,13 +221,29 @@ export class CheckpointProposalJob implements Traceable {
191
221
  broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
192
222
  };
193
223
 
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
- );
224
+ let blocksInCheckpoint: L2Block[] = [];
225
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
226
+ const checkpointBuildTimer = new Timer();
227
+
228
+ try {
229
+ // Main loop: build blocks for the checkpoint
230
+ const result = await this.buildBlocksForCheckpoint(
231
+ checkpointBuilder,
232
+ checkpointGlobalVariables.timestamp,
233
+ inHash,
234
+ blockProposalOptions,
235
+ );
236
+ blocksInCheckpoint = result.blocksInCheckpoint;
237
+ blockPendingBroadcast = result.blockPendingBroadcast;
238
+ } catch (err) {
239
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
240
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
241
+ // which is normal for block building (may have picked different txs)
242
+ if (this.handleHASigningError(err, 'Block proposal')) {
243
+ return undefined;
244
+ }
245
+ throw err;
246
+ }
201
247
 
202
248
  if (blocksInCheckpoint.length === 0) {
203
249
  this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
@@ -205,11 +251,44 @@ export class CheckpointProposalJob implements Traceable {
205
251
  return undefined;
206
252
  }
207
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
+
208
263
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
209
264
  // broadcasted yet, and wait to collect the committee attestations.
210
265
  this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
211
266
  const checkpoint = await checkpointBuilder.completeCheckpoint();
212
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
+
213
292
  // Do not collect attestations nor publish to L1 in fisherman mode
214
293
  if (this.config.fishermanMode) {
215
294
  this.log.info(
@@ -236,6 +315,7 @@ export class CheckpointProposalJob implements Traceable {
236
315
  const proposal = await this.validatorClient.createCheckpointProposal(
237
316
  checkpoint.header,
238
317
  checkpoint.archive.root,
318
+ feeAssetPriceModifier,
239
319
  lastBlock,
240
320
  this.proposer,
241
321
  checkpointProposalOptions,
@@ -252,13 +332,43 @@ export class CheckpointProposalJob implements Traceable {
252
332
 
253
333
  // Proposer must sign over the attestations before pushing them to L1
254
334
  const signer = this.proposer ?? this.publisher.getSenderAddress();
255
- const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer);
335
+ let attestationsSignature: Signature;
336
+ try {
337
+ attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
338
+ attestations,
339
+ signer,
340
+ this.slot,
341
+ this.checkpointNumber,
342
+ );
343
+ } catch (err) {
344
+ // We shouldn't really get here since we yield to another HA node
345
+ // as soon as we see these errors when creating block or checkpoint proposals.
346
+ if (this.handleHASigningError(err, 'Attestations signature')) {
347
+ return undefined;
348
+ }
349
+ throw err;
350
+ }
256
351
 
257
352
  // Enqueue publishing the checkpoint to L1
258
353
  this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
259
354
  const aztecSlotDuration = this.l1Constants.slotDuration;
260
355
  const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
261
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
+
262
372
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
263
373
  txTimeoutAt,
264
374
  forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
@@ -266,6 +376,11 @@ export class CheckpointProposalJob implements Traceable {
266
376
 
267
377
  return checkpoint;
268
378
  } catch (err) {
379
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
380
+ // swallow this error. It's already been logged by a function deeper in the stack
381
+ return undefined;
382
+ }
383
+
269
384
  this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
270
385
  return undefined;
271
386
  }
@@ -281,19 +396,19 @@ export class CheckpointProposalJob implements Traceable {
281
396
  inHash: Fr,
282
397
  blockProposalOptions: BlockProposalOptions,
283
398
  ): Promise<{
284
- blocksInCheckpoint: L2BlockNew[];
285
- blockPendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined;
399
+ blocksInCheckpoint: L2Block[];
400
+ blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
286
401
  }> {
287
- const blocksInCheckpoint: L2BlockNew[] = [];
402
+ const blocksInCheckpoint: L2Block[] = [];
288
403
  const txHashesAlreadyIncluded = new Set<string>();
289
404
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
290
405
 
291
406
  // 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;
407
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
293
408
 
294
409
  while (true) {
295
410
  const blocksBuilt = blocksInCheckpoint.length;
296
- const indexWithinCheckpoint = blocksBuilt;
411
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
297
412
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
298
413
 
299
414
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -322,6 +437,7 @@ export class CheckpointProposalJob implements Traceable {
322
437
  txHashesAlreadyIncluded,
323
438
  });
324
439
 
440
+ // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
325
441
  if (!buildResult && timingInfo.isLastBlock) {
326
442
  // If no block was produced due to not enough txs and this was the last subslot, exit
327
443
  break;
@@ -348,10 +464,12 @@ export class CheckpointProposalJob implements Traceable {
348
464
  blocksInCheckpoint.push(block);
349
465
 
350
466
  // Sync the proposed block to the archiver to make it available
351
- // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
352
- // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
467
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building
468
+ // If this throws, we abort the entire checkpoint
353
469
  await this.syncProposedBlockToArchiver(block);
354
470
 
471
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
472
+
355
473
  // If this is the last block, exit the loop now so we start collecting attestations
356
474
  if (timingInfo.isLastBlock) {
357
475
  this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
@@ -400,17 +518,17 @@ export class CheckpointProposalJob implements Traceable {
400
518
 
401
519
  /** Builds a single block. Called from the main block building loop. */
402
520
  @trackSpan('CheckpointProposalJob.buildSingleBlock')
403
- private async buildSingleBlock(
521
+ protected async buildSingleBlock(
404
522
  checkpointBuilder: CheckpointBuilder,
405
523
  opts: {
406
524
  forceCreate?: boolean;
407
525
  blockTimestamp: bigint;
408
526
  blockNumber: BlockNumber;
409
- indexWithinCheckpoint: number;
527
+ indexWithinCheckpoint: IndexWithinCheckpoint;
410
528
  buildDeadline: Date | undefined;
411
529
  txHashesAlreadyIncluded: Set<string>;
412
530
  },
413
- ): Promise<{ block: L2BlockNew; usedTxs: Tx[] } | { error: Error } | undefined> {
531
+ ): Promise<{ block: L2Block; usedTxs: Tx[] } | { error: Error } | undefined> {
414
532
  const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
415
533
  opts;
416
534
 
@@ -421,8 +539,7 @@ export class CheckpointProposalJob implements Traceable {
421
539
 
422
540
  try {
423
541
  // Wait until we have enough txs to build the block
424
- const minTxs = this.config.minTxsPerBlock;
425
- const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
542
+ const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
426
543
  if (!canStartBuilding) {
427
544
  this.log.warn(
428
545
  `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`,
@@ -436,7 +553,7 @@ export class CheckpointProposalJob implements Traceable {
436
553
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
437
554
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
438
555
  const pendingTxs = filter(
439
- this.p2pClient.iteratePendingTxs(),
556
+ this.p2pClient.iterateEligiblePendingTxs(),
440
557
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
441
558
  );
442
559
 
@@ -445,52 +562,65 @@ export class CheckpointProposalJob implements Traceable {
445
562
  { slot: this.slot, blockNumber, indexWithinCheckpoint },
446
563
  );
447
564
  this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
448
- const blockBuilderOptions: PublicProcessorLimits = {
565
+
566
+ // Per-block limits derived at startup by computeBlockLimits(), further capped
567
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
568
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
569
+ const minValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
570
+ const blockBuilderOptions: PublicProcessorLimits & { minValidTxs?: number } = {
449
571
  maxTransactions: this.config.maxTxsPerBlock,
450
- maxBlockSize: this.config.maxBlockSizeInBytes,
451
- maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
452
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
572
+ maxBlockGas:
573
+ this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined
574
+ ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity)
575
+ : undefined,
453
576
  deadline: buildDeadline,
577
+ isBuildingProposal: true,
578
+ minValidTxs,
454
579
  };
455
580
 
456
- // 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();
581
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
582
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
583
+ // updated for blocks that will be discarded.
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
- // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
466
- // too long, then we may not get to minTxsPerBlock after executing public functions.
467
- const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
468
- if (!forceCreate && numTxs < minValidTxs) {
595
+ if (buildResult.status === 'insufficient-valid-txs') {
469
596
  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 },
597
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
598
+ {
599
+ slot: this.slot,
600
+ blockNumber,
601
+ numTxs: buildResult.processedCount,
602
+ indexWithinCheckpoint,
603
+ minValidTxs,
604
+ },
472
605
  );
473
- this.eventEmitter.emit('block-tx-count-check-failed', {
474
- minTxs: minValidTxs,
475
- availableTxs: numTxs,
476
- slot: this.slot,
477
- });
606
+ this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
478
607
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
479
608
  return undefined;
480
609
  }
481
610
 
482
611
  // Block creation succeeded, emit stats and metrics
612
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
613
+
483
614
  const blockStats = {
484
615
  eventName: 'l2-block-built',
485
616
  duration: blockBuildDuration,
486
617
  publicProcessDuration: publicProcessorDuration,
487
- rollupCircuitsDuration: blockBuildingTimer.ms(),
488
618
  ...block.getStats(),
489
619
  } satisfies L2BlockBuiltStats;
490
620
 
491
621
  const blockHash = await block.hash();
492
622
  const txHashes = block.body.txEffects.map(tx => tx.txHash);
493
- const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
623
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
494
624
 
495
625
  this.log.info(
496
626
  `Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`,
@@ -498,7 +628,7 @@ export class CheckpointProposalJob implements Traceable {
498
628
  );
499
629
 
500
630
  this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
501
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
631
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
502
632
 
503
633
  return { block, usedTxs };
504
634
  } catch (err: any) {
@@ -510,17 +640,44 @@ export class CheckpointProposalJob implements Traceable {
510
640
  }
511
641
  }
512
642
 
643
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */
644
+ private async buildSingleBlockWithCheckpointBuilder(
645
+ checkpointBuilder: CheckpointBuilder,
646
+ pendingTxs: AsyncIterable<Tx>,
647
+ blockNumber: BlockNumber,
648
+ blockTimestamp: bigint,
649
+ blockBuilderOptions: PublicProcessorLimits & { minValidTxs?: number },
650
+ ) {
651
+ try {
652
+ const workTimer = new Timer();
653
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
654
+ const blockBuildDuration = workTimer.ms();
655
+ return { ...result, blockBuildDuration, status: 'success' as const };
656
+ } catch (err: unknown) {
657
+ if (isErrorClass(err, InsufficientValidTxsError)) {
658
+ return {
659
+ failedTxs: err.failedTxs,
660
+ processedCount: err.processedCount,
661
+ status: 'insufficient-valid-txs' as const,
662
+ };
663
+ }
664
+ throw err;
665
+ }
666
+ }
667
+
513
668
  /** Waits until minTxs are available on the pool for building a block. */
514
669
  @trackSpan('CheckpointProposalJob.waitForMinTxs')
515
670
  private async waitForMinTxs(opts: {
516
671
  forceCreate?: boolean;
517
672
  blockNumber: BlockNumber;
518
- indexWithinCheckpoint: number;
673
+ indexWithinCheckpoint: IndexWithinCheckpoint;
519
674
  buildDeadline: Date | undefined;
520
- }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
521
- const minTxs = this.config.minTxsPerBlock;
675
+ }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
522
676
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
523
677
 
678
+ // We only allow a block with 0 txs in the first block of the checkpoint
679
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
680
+
524
681
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
525
682
  const startBuildingDeadline = buildDeadline
526
683
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -532,7 +689,7 @@ export class CheckpointProposalJob implements Traceable {
532
689
  // If we're past deadline, or we have no deadline, give up
533
690
  const now = this.dateProvider.nowAsDate();
534
691
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
535
- return { canStartBuilding: false, availableTxs: availableTxs };
692
+ return { canStartBuilding: false, availableTxs, minTxs };
536
693
  }
537
694
 
538
695
  // Wait a bit before checking again
@@ -541,11 +698,11 @@ export class CheckpointProposalJob implements Traceable {
541
698
  `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
542
699
  { blockNumber, slot: this.slot, indexWithinCheckpoint },
543
700
  );
544
- await sleep(TXS_POLLING_MS);
701
+ await this.waitForTxsPollingInterval();
545
702
  availableTxs = await this.p2pClient.getPendingTxCount();
546
703
  }
547
704
 
548
- return { canStartBuilding: true, availableTxs };
705
+ return { canStartBuilding: true, availableTxs, minTxs };
549
706
  }
550
707
 
551
708
  /**
@@ -582,7 +739,7 @@ export class CheckpointProposalJob implements Traceable {
582
739
  const attestationTimeAllowed = this.config.enforceTimeTable
583
740
  ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
584
741
  : this.l1Constants.slotDuration;
585
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
742
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
586
743
 
587
744
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
588
745
 
@@ -597,11 +754,28 @@ export class CheckpointProposalJob implements Traceable {
597
754
 
598
755
  collectedAttestationsCount = attestations.length;
599
756
 
757
+ // Trim attestations to minimum required to save L1 calldata gas
758
+ const localAddresses = this.validatorClient.getValidatorAddresses();
759
+ const trimmed = trimAttestations(
760
+ attestations,
761
+ numberOfRequiredAttestations,
762
+ this.attestorAddress,
763
+ localAddresses,
764
+ );
765
+ if (trimmed.length < attestations.length) {
766
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
767
+ }
768
+
600
769
  // Rollup contract requires that the signatures are provided in the order of the committee
601
- const sorted = orderAttestations(attestations, committee);
770
+ const sorted = orderAttestations(trimmed, committee);
602
771
 
603
772
  // Manipulate the attestations if we've been configured to do so
604
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
773
+ if (
774
+ this.config.injectFakeAttestation ||
775
+ this.config.injectHighSValueAttestation ||
776
+ this.config.injectUnrecoverableSignatureAttestation ||
777
+ this.config.shuffleAttestationOrdering
778
+ ) {
605
779
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
606
780
  }
607
781
 
@@ -630,7 +804,11 @@ export class CheckpointProposalJob implements Traceable {
630
804
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
631
805
  );
632
806
 
633
- if (this.config.injectFakeAttestation) {
807
+ if (
808
+ this.config.injectFakeAttestation ||
809
+ this.config.injectHighSValueAttestation ||
810
+ this.config.injectUnrecoverableSignatureAttestation
811
+ ) {
634
812
  // Find non-empty attestations that are not from the proposer
635
813
  const nonProposerIndices: number[] = [];
636
814
  for (let i = 0; i < attestations.length; i++) {
@@ -640,8 +818,20 @@ export class CheckpointProposalJob implements Traceable {
640
818
  }
641
819
  if (nonProposerIndices.length > 0) {
642
820
  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();
821
+ if (this.config.injectHighSValueAttestation) {
822
+ this.log.warn(
823
+ `Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
824
+ );
825
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
826
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
827
+ this.log.warn(
828
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
829
+ );
830
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
831
+ } else {
832
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
833
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
834
+ }
645
835
  }
646
836
  return new CommitteeAttestationsAndSigners(attestations);
647
837
  }
@@ -650,11 +840,20 @@ export class CheckpointProposalJob implements Traceable {
650
840
  this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
651
841
 
652
842
  const shuffled = [...attestations];
653
- const [i, j] = [(proposerIndex + 1) % shuffled.length, (proposerIndex + 2) % shuffled.length];
654
- const valueI = shuffled[i];
655
- const valueJ = shuffled[j];
656
- shuffled[i] = valueJ;
657
- shuffled[j] = valueI;
843
+
844
+ // Find two non-proposer positions that both have non-empty signatures to swap.
845
+ // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
846
+ // signers array stays correctly aligned with L1's committee reconstruction.
847
+ const swappable: number[] = [];
848
+ for (let k = 0; k < shuffled.length; k++) {
849
+ if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
850
+ swappable.push(k);
851
+ }
852
+ }
853
+ if (swappable.length >= 2) {
854
+ const [i, j] = [swappable[0], swappable[1]];
855
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
856
+ }
658
857
 
659
858
  const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
660
859
  return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
@@ -670,7 +869,7 @@ export class CheckpointProposalJob implements Traceable {
670
869
  const failedTxData = failedTxs.map(fail => fail.tx);
671
870
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
672
871
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
673
- await this.p2pClient.deleteTxs(failedTxHashes);
872
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
674
873
  }
675
874
 
676
875
  /**
@@ -678,8 +877,7 @@ export class CheckpointProposalJob implements Traceable {
678
877
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
679
878
  * would never receive its own block without this explicit sync.
680
879
  */
681
- private async syncProposedBlockToArchiver(block: L2BlockNew): Promise<void> {
682
- // TODO(palla/mbps): Change default to false once block sync is stable.
880
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
683
881
  if (this.config.skipPushProposedBlocksToArchiver !== false) {
684
882
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
685
883
  blockNumber: block.number,
@@ -713,12 +911,34 @@ export class CheckpointProposalJob implements Traceable {
713
911
  slot: this.slot,
714
912
  feeAnalysisId: feeAnalysis?.id,
715
913
  });
716
- this.metrics.recordBlockProposalFailed('block_build_failed');
914
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
717
915
  }
718
916
 
719
917
  this.publisher.clearPendingRequests();
720
918
  }
721
919
 
920
+ /**
921
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
922
+ */
923
+ private handleHASigningError(err: any, errorContext: string): boolean {
924
+ if (err instanceof DutyAlreadySignedError) {
925
+ this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
926
+ slot: this.slot,
927
+ signedByNode: err.signedByNode,
928
+ });
929
+ return true;
930
+ }
931
+ if (err instanceof SlashingProtectionError) {
932
+ this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
933
+ slot: this.slot,
934
+ existingMessageHash: err.existingMessageHash,
935
+ attemptedMessageHash: err.attemptedMessageHash,
936
+ });
937
+ return true;
938
+ }
939
+ return false;
940
+ }
941
+
722
942
  /** Waits until a specific time within the current slot */
723
943
  @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
724
944
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
@@ -727,6 +947,11 @@ export class CheckpointProposalJob implements Traceable {
727
947
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
728
948
  }
729
949
 
950
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
951
+ protected async waitForTxsPollingInterval(): Promise<void> {
952
+ await sleep(TXS_POLLING_MS);
953
+ }
954
+
730
955
  private getSlotStartBuildTimestamp(): number {
731
956
  return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
732
957
  }