@aztec/sequencer-client 0.0.1-commit.6230efd → 0.0.1-commit.64b6bbb

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 (76) hide show
  1. package/dest/client/sequencer-client.d.ts +4 -5
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +1 -1
  4. package/dest/config.d.ts +1 -2
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +10 -9
  7. package/dest/global_variable_builder/global_builder.d.ts +4 -4
  8. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  9. package/dest/global_variable_builder/global_builder.js +13 -13
  10. package/dest/index.d.ts +2 -3
  11. package/dest/index.d.ts.map +1 -1
  12. package/dest/index.js +1 -2
  13. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  14. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  15. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  16. package/dest/publisher/sequencer-publisher.d.ts +17 -17
  17. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  18. package/dest/publisher/sequencer-publisher.js +481 -67
  19. package/dest/sequencer/checkpoint_proposal_job.d.ts +40 -12
  20. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  21. package/dest/sequencer/checkpoint_proposal_job.js +606 -57
  22. package/dest/sequencer/checkpoint_voter.d.ts +3 -2
  23. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  24. package/dest/sequencer/checkpoint_voter.js +34 -10
  25. package/dest/sequencer/index.d.ts +1 -3
  26. package/dest/sequencer/index.d.ts.map +1 -1
  27. package/dest/sequencer/index.js +0 -2
  28. package/dest/sequencer/metrics.d.ts +4 -4
  29. package/dest/sequencer/metrics.d.ts.map +1 -1
  30. package/dest/sequencer/metrics.js +48 -129
  31. package/dest/sequencer/sequencer.d.ts +27 -15
  32. package/dest/sequencer/sequencer.d.ts.map +1 -1
  33. package/dest/sequencer/sequencer.js +492 -43
  34. package/dest/sequencer/timetable.d.ts +1 -4
  35. package/dest/sequencer/timetable.d.ts.map +1 -1
  36. package/dest/sequencer/timetable.js +1 -4
  37. package/dest/test/index.d.ts +2 -3
  38. package/dest/test/index.d.ts.map +1 -1
  39. package/dest/test/mock_checkpoint_builder.d.ts +23 -11
  40. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  41. package/dest/test/mock_checkpoint_builder.js +50 -9
  42. package/dest/test/utils.d.ts +13 -9
  43. package/dest/test/utils.d.ts.map +1 -1
  44. package/dest/test/utils.js +26 -17
  45. package/package.json +30 -28
  46. package/src/client/sequencer-client.ts +4 -5
  47. package/src/config.ts +14 -11
  48. package/src/global_variable_builder/global_builder.ts +13 -13
  49. package/src/index.ts +1 -9
  50. package/src/publisher/sequencer-publisher-metrics.ts +17 -69
  51. package/src/publisher/sequencer-publisher.ts +118 -91
  52. package/src/sequencer/checkpoint_proposal_job.ts +258 -87
  53. package/src/sequencer/checkpoint_voter.ts +32 -7
  54. package/src/sequencer/index.ts +0 -2
  55. package/src/sequencer/metrics.ts +48 -138
  56. package/src/sequencer/sequencer.ts +133 -43
  57. package/src/sequencer/timetable.ts +6 -5
  58. package/src/test/index.ts +1 -2
  59. package/src/test/mock_checkpoint_builder.ts +91 -29
  60. package/src/test/utils.ts +55 -28
  61. package/dest/sequencer/block_builder.d.ts +0 -26
  62. package/dest/sequencer/block_builder.d.ts.map +0 -1
  63. package/dest/sequencer/block_builder.js +0 -129
  64. package/dest/sequencer/checkpoint_builder.d.ts +0 -63
  65. package/dest/sequencer/checkpoint_builder.d.ts.map +0 -1
  66. package/dest/sequencer/checkpoint_builder.js +0 -131
  67. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  68. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  69. package/dest/tx_validator/nullifier_cache.js +0 -24
  70. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  71. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  72. package/dest/tx_validator/tx_validator_factory.js +0 -53
  73. package/src/sequencer/block_builder.ts +0 -217
  74. package/src/sequencer/checkpoint_builder.ts +0 -217
  75. package/src/tx_validator/nullifier_cache.ts +0 -30
  76. package/src/tx_validator/tx_validator_factory.ts +0 -133
@@ -1,42 +1,53 @@
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 { Fr } from '@aztec/foundation/curves/bn254';
5
13
  import { EthAddress } from '@aztec/foundation/eth-address';
6
14
  import { Signature } from '@aztec/foundation/eth-signature';
7
15
  import { filter } from '@aztec/foundation/iterator';
8
- import type { Logger } from '@aztec/foundation/log';
16
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
9
17
  import { sleep, sleepUntil } from '@aztec/foundation/sleep';
10
18
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
11
- import { type TypedEventEmitter, unfreeze } from '@aztec/foundation/types';
19
+ import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
12
20
  import type { P2P } from '@aztec/p2p';
13
21
  import type { SlasherClientInterface } from '@aztec/slasher';
14
22
  import {
15
23
  CommitteeAttestation,
16
24
  CommitteeAttestationsAndSigners,
17
- L2BlockNew,
25
+ L2Block,
26
+ type L2BlockSink,
27
+ type L2BlockSource,
18
28
  MaliciousCommitteeAttestationsAndSigners,
19
29
  } from '@aztec/stdlib/block';
20
30
  import type { Checkpoint } from '@aztec/stdlib/checkpoint';
21
31
  import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
22
32
  import { Gas } from '@aztec/stdlib/gas';
23
- import type {
24
- PublicProcessorLimits,
25
- ResolvedSequencerConfig,
26
- WorldStateSynchronizer,
33
+ import {
34
+ NoValidTxsError,
35
+ type PublicProcessorLimits,
36
+ type ResolvedSequencerConfig,
37
+ type WorldStateSynchronizer,
27
38
  } from '@aztec/stdlib/interfaces/server';
28
- import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
29
- import type { BlockProposal, BlockProposalOptions } from '@aztec/stdlib/p2p';
39
+ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
40
+ import type { BlockProposalOptions, CheckpointProposal, CheckpointProposalOptions } from '@aztec/stdlib/p2p';
30
41
  import { orderAttestations } from '@aztec/stdlib/p2p';
31
- import { CheckpointHeader } from '@aztec/stdlib/rollup';
32
42
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
33
43
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
34
44
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
35
- import type { ValidatorClient } from '@aztec/validator-client';
45
+ import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
46
+ import { CheckpointBuilder, type FullNodeCheckpointsBuilder, type ValidatorClient } from '@aztec/validator-client';
47
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
36
48
 
37
49
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
38
- import type { InvalidateBlockRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
39
- import { CheckpointBuilder, type FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
50
+ import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
40
51
  import { CheckpointVoter } from './checkpoint_voter.js';
41
52
  import { SequencerInterruptedError } from './errors.js';
42
53
  import type { SequencerEvents } from './events.js';
@@ -54,8 +65,11 @@ const TXS_POLLING_MS = 500;
54
65
  * as well as enqueueing votes for slashing and governance proposals. This class is created from
55
66
  * the Sequencer once the check for being the proposer for the slot has succeeded.
56
67
  */
57
- export class CheckpointProposalJob {
68
+ export class CheckpointProposalJob implements Traceable {
69
+ protected readonly log: Logger;
70
+
58
71
  constructor(
72
+ private readonly epoch: EpochNumber,
59
73
  private readonly slot: SlotNumber,
60
74
  private readonly checkpointNumber: CheckpointNumber,
61
75
  private readonly syncedToBlockNumber: BlockNumber,
@@ -63,13 +77,15 @@ export class CheckpointProposalJob {
63
77
  private readonly proposer: EthAddress | undefined,
64
78
  private readonly publisher: SequencerPublisher,
65
79
  private readonly attestorAddress: EthAddress,
66
- private readonly invalidateBlock: InvalidateBlockRequest | undefined,
80
+ private readonly invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
67
81
  private readonly validatorClient: ValidatorClient,
68
82
  private readonly globalsBuilder: GlobalVariableBuilder,
69
83
  private readonly p2pClient: P2P,
70
84
  private readonly worldState: WorldStateSynchronizer,
71
85
  private readonly l1ToL2MessageSource: L1ToL2MessageSource,
86
+ private readonly l2BlockSource: L2BlockSource,
72
87
  private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
88
+ private readonly blockSink: L2BlockSink,
73
89
  private readonly l1Constants: SequencerRollupConstants,
74
90
  protected config: ResolvedSequencerConfig,
75
91
  protected timetable: SequencerTimetable,
@@ -79,13 +95,17 @@ export class CheckpointProposalJob {
79
95
  private readonly metrics: SequencerMetrics,
80
96
  private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
81
97
  private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
82
- protected readonly log: Logger,
83
- ) {}
98
+ public readonly tracer: Tracer,
99
+ bindings?: LoggerBindings,
100
+ ) {
101
+ this.log = createLogger('sequencer:checkpoint-proposal', { ...bindings, instanceId: `slot-${slot}` });
102
+ }
84
103
 
85
104
  /**
86
105
  * Executes the checkpoint proposal job.
87
106
  * Returns the published checkpoint if successful, undefined otherwise.
88
107
  */
108
+ @trackSpan('CheckpointProposalJob.execute')
89
109
  public async execute(): Promise<Checkpoint | undefined> {
90
110
  // Enqueue governance and slashing votes (returns promises that will be awaited later)
91
111
  // In fisherman mode, we simulate slashing but don't actually publish to L1
@@ -132,6 +152,13 @@ export class CheckpointProposalJob {
132
152
  }
133
153
  }
134
154
 
155
+ @trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
156
+ return {
157
+ // nullish operator needed for tests
158
+ [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
159
+ [Attributes.SLOT_NUMBER]: this.slot,
160
+ };
161
+ })
135
162
  private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
136
163
  try {
137
164
  // Get operator configured coinbase and fee recipient for this attestor
@@ -142,9 +169,9 @@ export class CheckpointProposalJob {
142
169
  this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
143
170
  this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
144
171
 
145
- // Enqueues block invalidation (constant for the whole slot)
146
- if (this.invalidateBlock && !this.config.skipInvalidateBlockAsProposer) {
147
- this.publisher.enqueueInvalidateBlock(this.invalidateBlock);
172
+ // Enqueues checkpoint invalidation (constant for the whole slot)
173
+ if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
174
+ this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
148
175
  }
149
176
 
150
177
  // Create checkpoint builder for the slot
@@ -154,8 +181,15 @@ export class CheckpointProposalJob {
154
181
  this.slot,
155
182
  );
156
183
 
157
- // Collect L1 to L2 messages for the checkpoint
184
+ // Collect L1 to L2 messages for the checkpoint and compute their hash
158
185
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
186
+ const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
187
+
188
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
189
+ const previousCheckpoints = (await this.l2BlockSource.getCheckpointsForEpoch(this.epoch)).filter(
190
+ c => c.number < this.checkpointNumber,
191
+ );
192
+ const previousCheckpointOutHashes = previousCheckpoints.map(c => c.getCheckpointOutHash());
159
193
 
160
194
  // Create a long-lived forked world state for the checkpoint builder
161
195
  using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
@@ -165,7 +199,9 @@ export class CheckpointProposalJob {
165
199
  this.checkpointNumber,
166
200
  checkpointGlobalVariables,
167
201
  l1ToL2Messages,
202
+ previousCheckpointOutHashes,
168
203
  fork,
204
+ this.log.getBindings(),
169
205
  );
170
206
 
171
207
  // Options for the validator client when creating block and checkpoint proposals
@@ -174,12 +210,33 @@ export class CheckpointProposalJob {
174
210
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
175
211
  };
176
212
 
177
- // Main loop: build blocks for the checkpoint
178
- const { blocksInCheckpoint, pendingBroadcast } = await this.buildBlocksForCheckpoint(
179
- checkpointBuilder,
180
- checkpointGlobalVariables.timestamp,
181
- blockProposalOptions,
182
- );
213
+ const checkpointProposalOptions: CheckpointProposalOptions = {
214
+ publishFullTxs: !!this.config.publishTxsWithProposals,
215
+ broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
216
+ };
217
+
218
+ let blocksInCheckpoint: L2Block[] = [];
219
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
220
+
221
+ try {
222
+ // Main loop: build blocks for the checkpoint
223
+ const result = await this.buildBlocksForCheckpoint(
224
+ checkpointBuilder,
225
+ checkpointGlobalVariables.timestamp,
226
+ inHash,
227
+ blockProposalOptions,
228
+ );
229
+ blocksInCheckpoint = result.blocksInCheckpoint;
230
+ blockPendingBroadcast = result.blockPendingBroadcast;
231
+ } catch (err) {
232
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
233
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
234
+ // which is normal for block building (may have picked different txs)
235
+ if (this.handleHASigningError(err, 'Block proposal')) {
236
+ return undefined;
237
+ }
238
+ throw err;
239
+ }
183
240
 
184
241
  if (blocksInCheckpoint.length === 0) {
185
242
  this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
@@ -207,26 +264,49 @@ export class CheckpointProposalJob {
207
264
  return checkpoint;
208
265
  }
209
266
 
210
- // TODO(palla/mbps): Wire this to the new p2p API once available, including the pendingBroadcast.block
267
+ // Include the block pending broadcast in the checkpoint proposal if any
268
+ const lastBlock = blockPendingBroadcast && {
269
+ blockHeader: blockPendingBroadcast.block.header,
270
+ indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
271
+ txs: blockPendingBroadcast.txs,
272
+ };
273
+
274
+ // Create the checkpoint proposal and broadcast it
211
275
  const proposal = await this.validatorClient.createCheckpointProposal(
212
276
  checkpoint.header,
213
277
  checkpoint.archive.root,
214
- pendingBroadcast?.txs ?? [],
278
+ lastBlock,
215
279
  this.proposer,
216
- blockProposalOptions,
280
+ checkpointProposalOptions,
217
281
  );
282
+
218
283
  const blockProposedAt = this.dateProvider.now();
219
- await this.p2pClient.broadcastProposal(proposal);
284
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
220
285
 
221
286
  this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
222
287
  const attestations = await this.waitForAttestations(proposal);
223
288
  const blockAttestedAt = this.dateProvider.now();
224
289
 
225
- this.metrics.recordBlockAttestationDelay(blockAttestedAt - blockProposedAt);
290
+ this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
226
291
 
227
292
  // Proposer must sign over the attestations before pushing them to L1
228
293
  const signer = this.proposer ?? this.publisher.getSenderAddress();
229
- const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer);
294
+ let attestationsSignature: Signature;
295
+ try {
296
+ attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
297
+ attestations,
298
+ signer,
299
+ this.slot,
300
+ this.checkpointNumber,
301
+ );
302
+ } catch (err) {
303
+ // We shouldn't really get here since we yield to another HA node
304
+ // as soon as we see these errors when creating block or checkpoint proposals.
305
+ if (this.handleHASigningError(err, 'Attestations signature')) {
306
+ return undefined;
307
+ }
308
+ throw err;
309
+ }
230
310
 
231
311
  // Enqueue publishing the checkpoint to L1
232
312
  this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
@@ -235,11 +315,16 @@ export class CheckpointProposalJob {
235
315
  const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
236
316
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
237
317
  txTimeoutAt,
238
- forcePendingBlockNumber: this.invalidateBlock?.forcePendingBlockNumber,
318
+ forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
239
319
  });
240
320
 
241
321
  return checkpoint;
242
322
  } catch (err) {
323
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
324
+ // swallow this error. It's already been logged by a function deeper in the stack
325
+ return undefined;
326
+ }
327
+
243
328
  this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
244
329
  return undefined;
245
330
  }
@@ -248,24 +333,29 @@ export class CheckpointProposalJob {
248
333
  /**
249
334
  * Builds blocks for a checkpoint within the current slot.
250
335
  */
336
+ @trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint')
251
337
  private async buildBlocksForCheckpoint(
252
338
  checkpointBuilder: CheckpointBuilder,
253
339
  timestamp: bigint,
340
+ inHash: Fr,
254
341
  blockProposalOptions: BlockProposalOptions,
255
342
  ): Promise<{
256
- blocksInCheckpoint: L2BlockNew[];
257
- pendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined;
343
+ blocksInCheckpoint: L2Block[];
344
+ blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
258
345
  }> {
259
- const blocksInCheckpoint: L2BlockNew[] = [];
346
+ const blocksInCheckpoint: L2Block[] = [];
260
347
  const txHashesAlreadyIncluded = new Set<string>();
261
348
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
262
349
 
350
+ // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
351
+ let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
352
+
263
353
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
264
- let pendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined = undefined;
354
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
265
355
 
266
356
  while (true) {
267
357
  const blocksBuilt = blocksInCheckpoint.length;
268
- const indexWithinCheckpoint = blocksBuilt;
358
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
269
359
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
270
360
 
271
361
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -292,8 +382,10 @@ export class CheckpointProposalJob {
292
382
  blockNumber,
293
383
  indexWithinCheckpoint,
294
384
  txHashesAlreadyIncluded,
385
+ remainingBlobFields,
295
386
  });
296
387
 
388
+ // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
297
389
  if (!buildResult && timingInfo.isLastBlock) {
298
390
  // If no block was produced due to not enough txs and this was the last subslot, exit
299
391
  break;
@@ -316,13 +408,21 @@ export class CheckpointProposalJob {
316
408
  break;
317
409
  }
318
410
 
319
- const { block, usedTxs } = buildResult;
411
+ const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
320
412
  blocksInCheckpoint.push(block);
321
413
 
414
+ // Update remaining blob fields for the next block
415
+ remainingBlobFields = newRemainingBlobFields;
416
+
322
417
  // Sync the proposed block to the archiver to make it available
323
418
  // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
324
419
  // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
325
- await this.syncProposedBlockToArchiver(block);
420
+ // Fire and forget - don't block the critical path, but log errors
421
+ this.syncProposedBlockToArchiver(block).catch(err => {
422
+ this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
423
+ });
424
+
425
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
326
426
 
327
427
  // If this is the last block, exit the loop now so we start collecting attestations
328
428
  if (timingInfo.isLastBlock) {
@@ -331,17 +431,17 @@ export class CheckpointProposalJob {
331
431
  blockNumber,
332
432
  blocksBuilt,
333
433
  });
334
- pendingBroadcast = { block, txs: usedTxs };
434
+ blockPendingBroadcast = { block, txs: usedTxs };
335
435
  break;
336
436
  }
337
437
 
338
438
  // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
339
439
  // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
340
440
  if (!this.config.fishermanMode) {
341
- // TODO(palla/mbps): Wire this to the new p2p API once available
342
441
  const proposal = await this.validatorClient.createBlockProposal(
343
- block.header.globalVariables.blockNumber,
344
- (await checkpointBuilder.getCheckpoint()).header,
442
+ block.header,
443
+ block.indexWithinCheckpoint,
444
+ inHash,
345
445
  block.archive.root,
346
446
  usedTxs,
347
447
  this.proposer,
@@ -359,13 +459,11 @@ export class CheckpointProposalJob {
359
459
  blocksBuilt: blocksInCheckpoint.length,
360
460
  });
361
461
 
362
- return {
363
- blocksInCheckpoint,
364
- pendingBroadcast,
365
- };
462
+ return { blocksInCheckpoint, blockPendingBroadcast };
366
463
  }
367
464
 
368
465
  /** Sleeps until it is time to produce the next block in the slot */
466
+ @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
369
467
  private async waitUntilNextSubslot(nextSubslotStart: number) {
370
468
  this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
371
469
  this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
@@ -373,19 +471,28 @@ export class CheckpointProposalJob {
373
471
  }
374
472
 
375
473
  /** Builds a single block. Called from the main block building loop. */
376
- private async buildSingleBlock(
474
+ @trackSpan('CheckpointProposalJob.buildSingleBlock')
475
+ protected async buildSingleBlock(
377
476
  checkpointBuilder: CheckpointBuilder,
378
477
  opts: {
379
478
  forceCreate?: boolean;
380
479
  blockTimestamp: bigint;
381
480
  blockNumber: BlockNumber;
382
- indexWithinCheckpoint: number;
481
+ indexWithinCheckpoint: IndexWithinCheckpoint;
383
482
  buildDeadline: Date | undefined;
384
483
  txHashesAlreadyIncluded: Set<string>;
484
+ remainingBlobFields: number;
385
485
  },
386
- ): Promise<{ block: L2BlockNew; usedTxs: Tx[] } | { error: Error } | undefined> {
387
- const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
388
- opts;
486
+ ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
487
+ const {
488
+ blockTimestamp,
489
+ forceCreate,
490
+ blockNumber,
491
+ indexWithinCheckpoint,
492
+ buildDeadline,
493
+ txHashesAlreadyIncluded,
494
+ remainingBlobFields,
495
+ } = opts;
389
496
 
390
497
  this.log.verbose(
391
498
  `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
@@ -418,46 +525,52 @@ export class CheckpointProposalJob {
418
525
  { slot: this.slot, blockNumber, indexWithinCheckpoint },
419
526
  );
420
527
  this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
528
+
529
+ // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
530
+ const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
531
+ const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
532
+
421
533
  const blockBuilderOptions: PublicProcessorLimits = {
422
534
  maxTransactions: this.config.maxTxsPerBlock,
423
535
  maxBlockSize: this.config.maxBlockSizeInBytes,
424
536
  maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
425
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
537
+ maxBlobFields: maxBlobFieldsForTxs,
426
538
  deadline: buildDeadline,
427
539
  };
428
540
 
429
541
  // Actually build the block by executing txs
430
- const workTimer = new Timer();
431
- const { publicGas, block, publicProcessorDuration, numTxs, blockBuildingTimer, usedTxs, failedTxs } =
432
- await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
433
- const blockBuildDuration = workTimer.ms();
542
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
543
+ checkpointBuilder,
544
+ pendingTxs,
545
+ blockNumber,
546
+ blockTimestamp,
547
+ blockBuilderOptions,
548
+ );
434
549
 
435
550
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
436
- await this.dropFailedTxsFromP2P(failedTxs);
551
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
437
552
 
438
553
  // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
439
554
  // too long, then we may not get to minTxsPerBlock after executing public functions.
440
555
  const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
441
- if (!forceCreate && numTxs < minValidTxs) {
556
+ const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
557
+ if (buildResult.status === 'no-valid-txs' || (!forceCreate && numTxs < minValidTxs)) {
442
558
  this.log.warn(
443
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
444
- { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint },
559
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
560
+ { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint, minValidTxs, buildResult: buildResult.status },
445
561
  );
446
- this.eventEmitter.emit('block-tx-count-check-failed', {
447
- minTxs: minValidTxs,
448
- availableTxs: numTxs,
449
- slot: this.slot,
450
- });
562
+ this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
451
563
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
452
564
  return undefined;
453
565
  }
454
566
 
455
567
  // Block creation succeeded, emit stats and metrics
568
+ const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
569
+
456
570
  const blockStats = {
457
571
  eventName: 'l2-block-built',
458
572
  duration: blockBuildDuration,
459
573
  publicProcessDuration: publicProcessorDuration,
460
- rollupCircuitsDuration: blockBuildingTimer.ms(),
461
574
  ...block.getStats(),
462
575
  } satisfies L2BlockBuiltStats;
463
576
 
@@ -473,7 +586,7 @@ export class CheckpointProposalJob {
473
586
  this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
474
587
  this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
475
588
 
476
- return { block, usedTxs };
589
+ return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
477
590
  } catch (err: any) {
478
591
  this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
479
592
  this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
@@ -483,16 +596,40 @@ export class CheckpointProposalJob {
483
596
  }
484
597
  }
485
598
 
599
+ /** Uses the checkpoint builder to build a block, catching specific txs */
600
+ private async buildSingleBlockWithCheckpointBuilder(
601
+ checkpointBuilder: CheckpointBuilder,
602
+ pendingTxs: AsyncIterable<Tx>,
603
+ blockNumber: BlockNumber,
604
+ blockTimestamp: bigint,
605
+ blockBuilderOptions: PublicProcessorLimits,
606
+ ) {
607
+ try {
608
+ const workTimer = new Timer();
609
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
610
+ const blockBuildDuration = workTimer.ms();
611
+ return { ...result, blockBuildDuration, status: 'success' as const };
612
+ } catch (err: unknown) {
613
+ if (isErrorClass(err, NoValidTxsError)) {
614
+ return { failedTxs: err.failedTxs, status: 'no-valid-txs' as const };
615
+ }
616
+ throw err;
617
+ }
618
+ }
619
+
486
620
  /** Waits until minTxs are available on the pool for building a block. */
621
+ @trackSpan('CheckpointProposalJob.waitForMinTxs')
487
622
  private async waitForMinTxs(opts: {
488
623
  forceCreate?: boolean;
489
624
  blockNumber: BlockNumber;
490
- indexWithinCheckpoint: number;
625
+ indexWithinCheckpoint: IndexWithinCheckpoint;
491
626
  buildDeadline: Date | undefined;
492
627
  }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
493
- const minTxs = this.config.minTxsPerBlock;
494
628
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
495
629
 
630
+ // We only allow a block with 0 txs in the first block of the checkpoint
631
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
632
+
496
633
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
497
634
  const startBuildingDeadline = buildDeadline
498
635
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -513,7 +650,7 @@ export class CheckpointProposalJob {
513
650
  `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
514
651
  { blockNumber, slot: this.slot, indexWithinCheckpoint },
515
652
  );
516
- await sleep(TXS_POLLING_MS);
653
+ await this.waitForTxsPollingInterval();
517
654
  availableTxs = await this.p2pClient.getPendingTxCount();
518
655
  }
519
656
 
@@ -524,7 +661,8 @@ export class CheckpointProposalJob {
524
661
  * Waits for enough attestations to be collected via p2p.
525
662
  * This is run after all blocks for the checkpoint have been built.
526
663
  */
527
- private async waitForAttestations(proposal: BlockProposal): Promise<CommitteeAttestationsAndSigners> {
664
+ @trackSpan('CheckpointProposalJob.waitForAttestations')
665
+ private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
528
666
  if (this.config.fishermanMode) {
529
667
  this.log.debug('Skipping attestation collection in fisherman mode');
530
668
  return CommitteeAttestationsAndSigners.empty();
@@ -553,7 +691,7 @@ export class CheckpointProposalJob {
553
691
  const attestationTimeAllowed = this.config.enforceTimeTable
554
692
  ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
555
693
  : this.l1Constants.slotDuration;
556
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
694
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
557
695
 
558
696
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
559
697
 
@@ -573,8 +711,7 @@ export class CheckpointProposalJob {
573
711
 
574
712
  // Manipulate the attestations if we've been configured to do so
575
713
  if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
576
- const checkpoint = proposal.payload.header;
577
- return this.manipulateAttestations(checkpoint, epoch, seed, committee, sorted);
714
+ return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
578
715
  }
579
716
 
580
717
  return new CommitteeAttestationsAndSigners(sorted);
@@ -590,7 +727,7 @@ export class CheckpointProposalJob {
590
727
 
591
728
  /** Breaks the attestations before publishing based on attack configs */
592
729
  private manipulateAttestations(
593
- checkpoint: CheckpointHeader,
730
+ slotNumber: SlotNumber,
594
731
  epoch: EpochNumber,
595
732
  seed: bigint,
596
733
  committee: EthAddress[],
@@ -598,7 +735,6 @@ export class CheckpointProposalJob {
598
735
  ) {
599
736
  // Compute the proposer index in the committee, since we dont want to tweak it.
600
737
  // Otherwise, the L1 rollup contract will reject the block outright.
601
- const { slotNumber } = checkpoint;
602
738
  const proposerIndex = Number(
603
739
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
604
740
  );
@@ -643,20 +779,27 @@ export class CheckpointProposalJob {
643
779
  const failedTxData = failedTxs.map(fail => fail.tx);
644
780
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
645
781
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
646
- await this.p2pClient.deleteTxs(failedTxHashes);
782
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
647
783
  }
648
784
 
649
785
  /**
650
- * Placeholder for pushing block to archiver and waiting for sync.
651
- * To be implemented when archiver and world-state support proposed blocks.
786
+ * Adds the proposed block to the archiver so it's available via P2P.
787
+ * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
788
+ * would never receive its own block without this explicit sync.
652
789
  */
653
- private async syncProposedBlockToArchiver(block: L2BlockNew): Promise<void> {
654
- this.log.debug(`Syncing proposed block ${block.number}`, {
790
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
791
+ if (this.config.skipPushProposedBlocksToArchiver !== false) {
792
+ this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
793
+ blockNumber: block.number,
794
+ slot: block.header.globalVariables.slotNumber,
795
+ });
796
+ return;
797
+ }
798
+ this.log.debug(`Syncing proposed block ${block.number} to archiver`, {
655
799
  blockNumber: block.number,
656
800
  slot: block.header.globalVariables.slotNumber,
657
801
  });
658
- // TODO(palla/mbps): Implement actual sync to archiver and world-state
659
- await Promise.resolve();
802
+ await this.blockSink.addBlock(block);
660
803
  }
661
804
 
662
805
  /** Runs fee analysis and logs checkpoint outcome as fisherman */
@@ -684,13 +827,41 @@ export class CheckpointProposalJob {
684
827
  this.publisher.clearPendingRequests();
685
828
  }
686
829
 
830
+ /**
831
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
832
+ */
833
+ private handleHASigningError(err: any, errorContext: string): boolean {
834
+ if (err instanceof DutyAlreadySignedError) {
835
+ this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
836
+ slot: this.slot,
837
+ signedByNode: err.signedByNode,
838
+ });
839
+ return true;
840
+ }
841
+ if (err instanceof SlashingProtectionError) {
842
+ this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
843
+ slot: this.slot,
844
+ existingMessageHash: err.existingMessageHash,
845
+ attemptedMessageHash: err.attemptedMessageHash,
846
+ });
847
+ return true;
848
+ }
849
+ return false;
850
+ }
851
+
687
852
  /** Waits until a specific time within the current slot */
853
+ @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
688
854
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
689
855
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();
690
856
  const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
691
857
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
692
858
  }
693
859
 
860
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
861
+ protected async waitForTxsPollingInterval(): Promise<void> {
862
+ await sleep(TXS_POLLING_MS);
863
+ }
864
+
694
865
  private getSlotStartBuildTimestamp(): number {
695
866
  return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
696
867
  }