@aztec/sequencer-client 0.0.1-commit.6230efd → 0.0.1-commit.6a729f7

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 +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 -1
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +6 -1
  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 +34 -12
  20. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  21. package/dest/sequencer/checkpoint_proposal_job.js +605 -55
  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 +25 -15
  32. package/dest/sequencer/sequencer.d.ts.map +1 -1
  33. package/dest/sequencer/sequencer.js +486 -42
  34. package/dest/test/index.d.ts +2 -3
  35. package/dest/test/index.d.ts.map +1 -1
  36. package/dest/test/mock_checkpoint_builder.d.ts +23 -11
  37. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  38. package/dest/test/mock_checkpoint_builder.js +50 -9
  39. package/dest/test/utils.d.ts +13 -9
  40. package/dest/test/utils.d.ts.map +1 -1
  41. package/dest/test/utils.js +26 -17
  42. package/package.json +30 -28
  43. package/src/client/sequencer-client.ts +4 -5
  44. package/src/config.ts +5 -0
  45. package/src/global_variable_builder/global_builder.ts +13 -13
  46. package/src/index.ts +1 -9
  47. package/src/publisher/sequencer-publisher-metrics.ts +17 -69
  48. package/src/publisher/sequencer-publisher.ts +118 -91
  49. package/src/sequencer/checkpoint_proposal_job.ts +253 -85
  50. package/src/sequencer/checkpoint_voter.ts +32 -7
  51. package/src/sequencer/index.ts +0 -2
  52. package/src/sequencer/metrics.ts +48 -138
  53. package/src/sequencer/sequencer.ts +125 -42
  54. package/src/test/index.ts +1 -2
  55. package/src/test/mock_checkpoint_builder.ts +91 -29
  56. package/src/test/utils.ts +55 -28
  57. package/dest/sequencer/block_builder.d.ts +0 -26
  58. package/dest/sequencer/block_builder.d.ts.map +0 -1
  59. package/dest/sequencer/block_builder.js +0 -129
  60. package/dest/sequencer/checkpoint_builder.d.ts +0 -63
  61. package/dest/sequencer/checkpoint_builder.d.ts.map +0 -1
  62. package/dest/sequencer/checkpoint_builder.js +0 -131
  63. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  64. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  65. package/dest/tx_validator/nullifier_cache.js +0 -24
  66. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  67. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  68. package/dest/tx_validator/tx_validator_factory.js +0 -53
  69. package/src/sequencer/block_builder.ts +0 -217
  70. package/src/sequencer/checkpoint_builder.ts +0 -217
  71. package/src/tx_validator/nullifier_cache.ts +0 -30
  72. 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,45 @@ 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 (err instanceof DutyAlreadySignedError) {
236
+ this.log.info(`Checkpoint proposal for slot ${this.slot} already signed by another HA node, yielding`, {
237
+ slot: this.slot,
238
+ signedByNode: err.signedByNode,
239
+ });
240
+ return undefined;
241
+ }
242
+ if (err instanceof SlashingProtectionError) {
243
+ this.log.info(`Checkpoint proposal for slot ${this.slot} blocked by slashing protection, yielding`, {
244
+ slot: this.slot,
245
+ existingMessageHash: err.existingMessageHash,
246
+ attemptedMessageHash: err.attemptedMessageHash,
247
+ });
248
+ return undefined;
249
+ }
250
+ throw err;
251
+ }
183
252
 
184
253
  if (blocksInCheckpoint.length === 0) {
185
254
  this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
@@ -207,26 +276,61 @@ export class CheckpointProposalJob {
207
276
  return checkpoint;
208
277
  }
209
278
 
210
- // TODO(palla/mbps): Wire this to the new p2p API once available, including the pendingBroadcast.block
279
+ // Include the block pending broadcast in the checkpoint proposal if any
280
+ const lastBlock = blockPendingBroadcast && {
281
+ blockHeader: blockPendingBroadcast.block.header,
282
+ indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
283
+ txs: blockPendingBroadcast.txs,
284
+ };
285
+
286
+ // Create the checkpoint proposal and broadcast it
211
287
  const proposal = await this.validatorClient.createCheckpointProposal(
212
288
  checkpoint.header,
213
289
  checkpoint.archive.root,
214
- pendingBroadcast?.txs ?? [],
290
+ lastBlock,
215
291
  this.proposer,
216
- blockProposalOptions,
292
+ checkpointProposalOptions,
217
293
  );
294
+
218
295
  const blockProposedAt = this.dateProvider.now();
219
- await this.p2pClient.broadcastProposal(proposal);
296
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
220
297
 
221
298
  this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
222
299
  const attestations = await this.waitForAttestations(proposal);
223
300
  const blockAttestedAt = this.dateProvider.now();
224
301
 
225
- this.metrics.recordBlockAttestationDelay(blockAttestedAt - blockProposedAt);
302
+ this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
226
303
 
227
304
  // Proposer must sign over the attestations before pushing them to L1
228
305
  const signer = this.proposer ?? this.publisher.getSenderAddress();
229
- const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer);
306
+ let attestationsSignature: Signature;
307
+ try {
308
+ attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
309
+ attestations,
310
+ signer,
311
+ this.slot,
312
+ this.checkpointNumber,
313
+ );
314
+ } catch (err) {
315
+ // We shouldn't really get here since we yield to another HA node
316
+ // as soon as we see these errors when creating block proposals.
317
+ if (err instanceof DutyAlreadySignedError) {
318
+ this.log.info(`Attestations signature for slot ${this.slot} already signed by another HA node, yielding`, {
319
+ slot: this.slot,
320
+ signedByNode: err.signedByNode,
321
+ });
322
+ return undefined;
323
+ }
324
+ if (err instanceof SlashingProtectionError) {
325
+ this.log.info(`Attestations signature for slot ${this.slot} blocked by slashing protection, yielding`, {
326
+ slot: this.slot,
327
+ existingMessageHash: err.existingMessageHash,
328
+ attemptedMessageHash: err.attemptedMessageHash,
329
+ });
330
+ return undefined;
331
+ }
332
+ throw err;
333
+ }
230
334
 
231
335
  // Enqueue publishing the checkpoint to L1
232
336
  this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
@@ -235,11 +339,16 @@ export class CheckpointProposalJob {
235
339
  const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
236
340
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
237
341
  txTimeoutAt,
238
- forcePendingBlockNumber: this.invalidateBlock?.forcePendingBlockNumber,
342
+ forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
239
343
  });
240
344
 
241
345
  return checkpoint;
242
346
  } catch (err) {
347
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
348
+ // swallow this error. It's already been logged by a function deeper in the stack
349
+ return undefined;
350
+ }
351
+
243
352
  this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
244
353
  return undefined;
245
354
  }
@@ -248,24 +357,29 @@ export class CheckpointProposalJob {
248
357
  /**
249
358
  * Builds blocks for a checkpoint within the current slot.
250
359
  */
360
+ @trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint')
251
361
  private async buildBlocksForCheckpoint(
252
362
  checkpointBuilder: CheckpointBuilder,
253
363
  timestamp: bigint,
364
+ inHash: Fr,
254
365
  blockProposalOptions: BlockProposalOptions,
255
366
  ): Promise<{
256
- blocksInCheckpoint: L2BlockNew[];
257
- pendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined;
367
+ blocksInCheckpoint: L2Block[];
368
+ blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
258
369
  }> {
259
- const blocksInCheckpoint: L2BlockNew[] = [];
370
+ const blocksInCheckpoint: L2Block[] = [];
260
371
  const txHashesAlreadyIncluded = new Set<string>();
261
372
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
262
373
 
374
+ // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
375
+ let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
376
+
263
377
  // 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;
378
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
265
379
 
266
380
  while (true) {
267
381
  const blocksBuilt = blocksInCheckpoint.length;
268
- const indexWithinCheckpoint = blocksBuilt;
382
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
269
383
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
270
384
 
271
385
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -292,8 +406,10 @@ export class CheckpointProposalJob {
292
406
  blockNumber,
293
407
  indexWithinCheckpoint,
294
408
  txHashesAlreadyIncluded,
409
+ remainingBlobFields,
295
410
  });
296
411
 
412
+ // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
297
413
  if (!buildResult && timingInfo.isLastBlock) {
298
414
  // If no block was produced due to not enough txs and this was the last subslot, exit
299
415
  break;
@@ -316,13 +432,21 @@ export class CheckpointProposalJob {
316
432
  break;
317
433
  }
318
434
 
319
- const { block, usedTxs } = buildResult;
435
+ const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
320
436
  blocksInCheckpoint.push(block);
321
437
 
438
+ // Update remaining blob fields for the next block
439
+ remainingBlobFields = newRemainingBlobFields;
440
+
322
441
  // Sync the proposed block to the archiver to make it available
323
442
  // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
324
443
  // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
325
- await this.syncProposedBlockToArchiver(block);
444
+ // Fire and forget - don't block the critical path, but log errors
445
+ this.syncProposedBlockToArchiver(block).catch(err => {
446
+ this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
447
+ });
448
+
449
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
326
450
 
327
451
  // If this is the last block, exit the loop now so we start collecting attestations
328
452
  if (timingInfo.isLastBlock) {
@@ -331,17 +455,17 @@ export class CheckpointProposalJob {
331
455
  blockNumber,
332
456
  blocksBuilt,
333
457
  });
334
- pendingBroadcast = { block, txs: usedTxs };
458
+ blockPendingBroadcast = { block, txs: usedTxs };
335
459
  break;
336
460
  }
337
461
 
338
462
  // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
339
463
  // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
340
464
  if (!this.config.fishermanMode) {
341
- // TODO(palla/mbps): Wire this to the new p2p API once available
342
465
  const proposal = await this.validatorClient.createBlockProposal(
343
- block.header.globalVariables.blockNumber,
344
- (await checkpointBuilder.getCheckpoint()).header,
466
+ block.header,
467
+ block.indexWithinCheckpoint,
468
+ inHash,
345
469
  block.archive.root,
346
470
  usedTxs,
347
471
  this.proposer,
@@ -359,13 +483,11 @@ export class CheckpointProposalJob {
359
483
  blocksBuilt: blocksInCheckpoint.length,
360
484
  });
361
485
 
362
- return {
363
- blocksInCheckpoint,
364
- pendingBroadcast,
365
- };
486
+ return { blocksInCheckpoint, blockPendingBroadcast };
366
487
  }
367
488
 
368
489
  /** Sleeps until it is time to produce the next block in the slot */
490
+ @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
369
491
  private async waitUntilNextSubslot(nextSubslotStart: number) {
370
492
  this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
371
493
  this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
@@ -373,19 +495,28 @@ export class CheckpointProposalJob {
373
495
  }
374
496
 
375
497
  /** Builds a single block. Called from the main block building loop. */
376
- private async buildSingleBlock(
498
+ @trackSpan('CheckpointProposalJob.buildSingleBlock')
499
+ protected async buildSingleBlock(
377
500
  checkpointBuilder: CheckpointBuilder,
378
501
  opts: {
379
502
  forceCreate?: boolean;
380
503
  blockTimestamp: bigint;
381
504
  blockNumber: BlockNumber;
382
- indexWithinCheckpoint: number;
505
+ indexWithinCheckpoint: IndexWithinCheckpoint;
383
506
  buildDeadline: Date | undefined;
384
507
  txHashesAlreadyIncluded: Set<string>;
508
+ remainingBlobFields: number;
385
509
  },
386
- ): Promise<{ block: L2BlockNew; usedTxs: Tx[] } | { error: Error } | undefined> {
387
- const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
388
- opts;
510
+ ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
511
+ const {
512
+ blockTimestamp,
513
+ forceCreate,
514
+ blockNumber,
515
+ indexWithinCheckpoint,
516
+ buildDeadline,
517
+ txHashesAlreadyIncluded,
518
+ remainingBlobFields,
519
+ } = opts;
389
520
 
390
521
  this.log.verbose(
391
522
  `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
@@ -418,46 +549,52 @@ export class CheckpointProposalJob {
418
549
  { slot: this.slot, blockNumber, indexWithinCheckpoint },
419
550
  );
420
551
  this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
552
+
553
+ // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
554
+ const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
555
+ const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
556
+
421
557
  const blockBuilderOptions: PublicProcessorLimits = {
422
558
  maxTransactions: this.config.maxTxsPerBlock,
423
559
  maxBlockSize: this.config.maxBlockSizeInBytes,
424
560
  maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
425
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
561
+ maxBlobFields: maxBlobFieldsForTxs,
426
562
  deadline: buildDeadline,
427
563
  };
428
564
 
429
565
  // 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();
566
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
567
+ checkpointBuilder,
568
+ pendingTxs,
569
+ blockNumber,
570
+ blockTimestamp,
571
+ blockBuilderOptions,
572
+ );
434
573
 
435
574
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
436
- await this.dropFailedTxsFromP2P(failedTxs);
575
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
437
576
 
438
577
  // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
439
578
  // too long, then we may not get to minTxsPerBlock after executing public functions.
440
579
  const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
441
- if (!forceCreate && numTxs < minValidTxs) {
580
+ const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
581
+ if (buildResult.status === 'no-valid-txs' || (!forceCreate && numTxs < minValidTxs)) {
442
582
  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 },
583
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
584
+ { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint, minValidTxs, buildResult: buildResult.status },
445
585
  );
446
- this.eventEmitter.emit('block-tx-count-check-failed', {
447
- minTxs: minValidTxs,
448
- availableTxs: numTxs,
449
- slot: this.slot,
450
- });
586
+ this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
451
587
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
452
588
  return undefined;
453
589
  }
454
590
 
455
591
  // Block creation succeeded, emit stats and metrics
592
+ const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
593
+
456
594
  const blockStats = {
457
595
  eventName: 'l2-block-built',
458
596
  duration: blockBuildDuration,
459
597
  publicProcessDuration: publicProcessorDuration,
460
- rollupCircuitsDuration: blockBuildingTimer.ms(),
461
598
  ...block.getStats(),
462
599
  } satisfies L2BlockBuiltStats;
463
600
 
@@ -473,7 +610,7 @@ export class CheckpointProposalJob {
473
610
  this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
474
611
  this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
475
612
 
476
- return { block, usedTxs };
613
+ return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
477
614
  } catch (err: any) {
478
615
  this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
479
616
  this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
@@ -483,16 +620,40 @@ export class CheckpointProposalJob {
483
620
  }
484
621
  }
485
622
 
623
+ /** Uses the checkpoint builder to build a block, catching specific txs */
624
+ private async buildSingleBlockWithCheckpointBuilder(
625
+ checkpointBuilder: CheckpointBuilder,
626
+ pendingTxs: AsyncIterable<Tx>,
627
+ blockNumber: BlockNumber,
628
+ blockTimestamp: bigint,
629
+ blockBuilderOptions: PublicProcessorLimits,
630
+ ) {
631
+ try {
632
+ const workTimer = new Timer();
633
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
634
+ const blockBuildDuration = workTimer.ms();
635
+ return { ...result, blockBuildDuration, status: 'success' as const };
636
+ } catch (err: unknown) {
637
+ if (isErrorClass(err, NoValidTxsError)) {
638
+ return { failedTxs: err.failedTxs, status: 'no-valid-txs' as const };
639
+ }
640
+ throw err;
641
+ }
642
+ }
643
+
486
644
  /** Waits until minTxs are available on the pool for building a block. */
645
+ @trackSpan('CheckpointProposalJob.waitForMinTxs')
487
646
  private async waitForMinTxs(opts: {
488
647
  forceCreate?: boolean;
489
648
  blockNumber: BlockNumber;
490
- indexWithinCheckpoint: number;
649
+ indexWithinCheckpoint: IndexWithinCheckpoint;
491
650
  buildDeadline: Date | undefined;
492
651
  }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
493
- const minTxs = this.config.minTxsPerBlock;
494
652
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
495
653
 
654
+ // We only allow a block with 0 txs in the first block of the checkpoint
655
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
656
+
496
657
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
497
658
  const startBuildingDeadline = buildDeadline
498
659
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -524,7 +685,8 @@ export class CheckpointProposalJob {
524
685
  * Waits for enough attestations to be collected via p2p.
525
686
  * This is run after all blocks for the checkpoint have been built.
526
687
  */
527
- private async waitForAttestations(proposal: BlockProposal): Promise<CommitteeAttestationsAndSigners> {
688
+ @trackSpan('CheckpointProposalJob.waitForAttestations')
689
+ private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
528
690
  if (this.config.fishermanMode) {
529
691
  this.log.debug('Skipping attestation collection in fisherman mode');
530
692
  return CommitteeAttestationsAndSigners.empty();
@@ -553,7 +715,7 @@ export class CheckpointProposalJob {
553
715
  const attestationTimeAllowed = this.config.enforceTimeTable
554
716
  ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
555
717
  : this.l1Constants.slotDuration;
556
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
718
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
557
719
 
558
720
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
559
721
 
@@ -573,8 +735,7 @@ export class CheckpointProposalJob {
573
735
 
574
736
  // Manipulate the attestations if we've been configured to do so
575
737
  if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
576
- const checkpoint = proposal.payload.header;
577
- return this.manipulateAttestations(checkpoint, epoch, seed, committee, sorted);
738
+ return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
578
739
  }
579
740
 
580
741
  return new CommitteeAttestationsAndSigners(sorted);
@@ -590,7 +751,7 @@ export class CheckpointProposalJob {
590
751
 
591
752
  /** Breaks the attestations before publishing based on attack configs */
592
753
  private manipulateAttestations(
593
- checkpoint: CheckpointHeader,
754
+ slotNumber: SlotNumber,
594
755
  epoch: EpochNumber,
595
756
  seed: bigint,
596
757
  committee: EthAddress[],
@@ -598,7 +759,6 @@ export class CheckpointProposalJob {
598
759
  ) {
599
760
  // Compute the proposer index in the committee, since we dont want to tweak it.
600
761
  // Otherwise, the L1 rollup contract will reject the block outright.
601
- const { slotNumber } = checkpoint;
602
762
  const proposerIndex = Number(
603
763
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
604
764
  );
@@ -647,16 +807,23 @@ export class CheckpointProposalJob {
647
807
  }
648
808
 
649
809
  /**
650
- * Placeholder for pushing block to archiver and waiting for sync.
651
- * To be implemented when archiver and world-state support proposed blocks.
810
+ * Adds the proposed block to the archiver so it's available via P2P.
811
+ * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
812
+ * would never receive its own block without this explicit sync.
652
813
  */
653
- private async syncProposedBlockToArchiver(block: L2BlockNew): Promise<void> {
654
- this.log.debug(`Syncing proposed block ${block.number}`, {
814
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
815
+ if (this.config.skipPushProposedBlocksToArchiver !== false) {
816
+ this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
817
+ blockNumber: block.number,
818
+ slot: block.header.globalVariables.slotNumber,
819
+ });
820
+ return;
821
+ }
822
+ this.log.debug(`Syncing proposed block ${block.number} to archiver`, {
655
823
  blockNumber: block.number,
656
824
  slot: block.header.globalVariables.slotNumber,
657
825
  });
658
- // TODO(palla/mbps): Implement actual sync to archiver and world-state
659
- await Promise.resolve();
826
+ await this.blockSink.addBlock(block);
660
827
  }
661
828
 
662
829
  /** Runs fee analysis and logs checkpoint outcome as fisherman */
@@ -685,6 +852,7 @@ export class CheckpointProposalJob {
685
852
  }
686
853
 
687
854
  /** Waits until a specific time within the current slot */
855
+ @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
688
856
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
689
857
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();
690
858
  const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;