@aztec/sequencer-client 0.0.1-commit.c7c42ec → 0.0.1-commit.cf93bcc56

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 (84) hide show
  1. package/dest/client/sequencer-client.d.ts +14 -10
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +15 -4
  4. package/dest/config.d.ts +3 -4
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +22 -12
  7. package/dest/global_variable_builder/global_builder.d.ts +5 -7
  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/config.d.ts +31 -17
  14. package/dest/publisher/config.d.ts.map +1 -1
  15. package/dest/publisher/config.js +101 -42
  16. package/dest/publisher/sequencer-publisher-factory.d.ts +11 -3
  17. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  18. package/dest/publisher/sequencer-publisher-factory.js +13 -2
  19. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  20. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  21. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  22. package/dest/publisher/sequencer-publisher.d.ts +32 -23
  23. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  24. package/dest/publisher/sequencer-publisher.js +522 -88
  25. package/dest/sequencer/checkpoint_proposal_job.d.ts +40 -12
  26. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  27. package/dest/sequencer/checkpoint_proposal_job.js +633 -62
  28. package/dest/sequencer/checkpoint_voter.d.ts +3 -2
  29. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  30. package/dest/sequencer/checkpoint_voter.js +34 -10
  31. package/dest/sequencer/index.d.ts +1 -3
  32. package/dest/sequencer/index.d.ts.map +1 -1
  33. package/dest/sequencer/index.js +0 -2
  34. package/dest/sequencer/metrics.d.ts +19 -7
  35. package/dest/sequencer/metrics.d.ts.map +1 -1
  36. package/dest/sequencer/metrics.js +131 -141
  37. package/dest/sequencer/sequencer.d.ts +33 -18
  38. package/dest/sequencer/sequencer.d.ts.map +1 -1
  39. package/dest/sequencer/sequencer.js +508 -66
  40. package/dest/sequencer/timetable.d.ts +1 -4
  41. package/dest/sequencer/timetable.d.ts.map +1 -1
  42. package/dest/sequencer/timetable.js +1 -4
  43. package/dest/test/index.d.ts +4 -7
  44. package/dest/test/index.d.ts.map +1 -1
  45. package/dest/test/mock_checkpoint_builder.d.ts +25 -11
  46. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  47. package/dest/test/mock_checkpoint_builder.js +52 -9
  48. package/dest/test/utils.d.ts +13 -9
  49. package/dest/test/utils.d.ts.map +1 -1
  50. package/dest/test/utils.js +27 -17
  51. package/package.json +30 -28
  52. package/src/client/sequencer-client.ts +28 -11
  53. package/src/config.ts +31 -19
  54. package/src/global_variable_builder/global_builder.ts +14 -14
  55. package/src/index.ts +1 -9
  56. package/src/publisher/config.ts +112 -43
  57. package/src/publisher/sequencer-publisher-factory.ts +23 -6
  58. package/src/publisher/sequencer-publisher-metrics.ts +17 -69
  59. package/src/publisher/sequencer-publisher.ts +180 -118
  60. package/src/sequencer/checkpoint_proposal_job.ts +299 -91
  61. package/src/sequencer/checkpoint_voter.ts +32 -7
  62. package/src/sequencer/index.ts +0 -2
  63. package/src/sequencer/metrics.ts +132 -148
  64. package/src/sequencer/sequencer.ts +152 -68
  65. package/src/sequencer/timetable.ts +6 -5
  66. package/src/test/index.ts +3 -6
  67. package/src/test/mock_checkpoint_builder.ts +102 -29
  68. package/src/test/utils.ts +58 -28
  69. package/dest/sequencer/block_builder.d.ts +0 -26
  70. package/dest/sequencer/block_builder.d.ts.map +0 -1
  71. package/dest/sequencer/block_builder.js +0 -129
  72. package/dest/sequencer/checkpoint_builder.d.ts +0 -63
  73. package/dest/sequencer/checkpoint_builder.d.ts.map +0 -1
  74. package/dest/sequencer/checkpoint_builder.js +0 -131
  75. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  76. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  77. package/dest/tx_validator/nullifier_cache.js +0 -24
  78. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  79. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  80. package/dest/tx_validator/tx_validator_factory.js +0 -53
  81. package/src/sequencer/block_builder.ts +0 -217
  82. package/src/sequencer/checkpoint_builder.ts +0 -217
  83. package/src/tx_validator/nullifier_cache.ts +0 -30
  84. 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
@@ -109,7 +129,7 @@ export class CheckpointProposalJob {
109
129
  await Promise.all(votesPromises);
110
130
 
111
131
  if (checkpoint) {
112
- this.metrics.recordBlockProposalSuccess();
132
+ this.metrics.recordCheckpointProposalSuccess();
113
133
  }
114
134
 
115
135
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
@@ -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,18 +181,30 @@ 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 previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.epoch))
190
+ .filter(c => c.checkpointNumber < this.checkpointNumber)
191
+ .map(c => c.checkpointOutHash);
192
+
193
+ // Get the fee asset price modifier from the oracle
194
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
159
195
 
160
196
  // Create a long-lived forked world state for the checkpoint builder
161
- using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
197
+ await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
162
198
 
163
199
  // Create checkpoint builder for the entire slot
164
200
  const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(
165
201
  this.checkpointNumber,
166
202
  checkpointGlobalVariables,
203
+ feeAssetPriceModifier,
167
204
  l1ToL2Messages,
205
+ previousCheckpointOutHashes,
168
206
  fork,
207
+ this.log.getBindings(),
169
208
  );
170
209
 
171
210
  // Options for the validator client when creating block and checkpoint proposals
@@ -174,12 +213,34 @@ export class CheckpointProposalJob {
174
213
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
175
214
  };
176
215
 
177
- // Main loop: build blocks for the checkpoint
178
- const { blocksInCheckpoint, pendingBroadcast } = await this.buildBlocksForCheckpoint(
179
- checkpointBuilder,
180
- checkpointGlobalVariables.timestamp,
181
- blockProposalOptions,
182
- );
216
+ const checkpointProposalOptions: CheckpointProposalOptions = {
217
+ publishFullTxs: !!this.config.publishTxsWithProposals,
218
+ broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
219
+ };
220
+
221
+ let blocksInCheckpoint: L2Block[] = [];
222
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
223
+ const checkpointBuildTimer = new Timer();
224
+
225
+ try {
226
+ // Main loop: build blocks for the checkpoint
227
+ const result = await this.buildBlocksForCheckpoint(
228
+ checkpointBuilder,
229
+ checkpointGlobalVariables.timestamp,
230
+ inHash,
231
+ blockProposalOptions,
232
+ );
233
+ blocksInCheckpoint = result.blocksInCheckpoint;
234
+ blockPendingBroadcast = result.blockPendingBroadcast;
235
+ } catch (err) {
236
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
237
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
238
+ // which is normal for block building (may have picked different txs)
239
+ if (this.handleHASigningError(err, 'Block proposal')) {
240
+ return undefined;
241
+ }
242
+ throw err;
243
+ }
183
244
 
184
245
  if (blocksInCheckpoint.length === 0) {
185
246
  this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
@@ -187,11 +248,28 @@ export class CheckpointProposalJob {
187
248
  return undefined;
188
249
  }
189
250
 
251
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
252
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
253
+ this.log.warn(
254
+ `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
255
+ { slot: this.slot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
256
+ );
257
+ return undefined;
258
+ }
259
+
190
260
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
191
261
  // broadcasted yet, and wait to collect the committee attestations.
192
262
  this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
193
263
  const checkpoint = await checkpointBuilder.completeCheckpoint();
194
264
 
265
+ // Record checkpoint-level build metrics
266
+ this.metrics.recordCheckpointBuild(
267
+ checkpointBuildTimer.ms(),
268
+ blocksInCheckpoint.length,
269
+ checkpoint.getStats().txCount,
270
+ Number(checkpoint.header.totalManaUsed.toBigInt()),
271
+ );
272
+
195
273
  // Do not collect attestations nor publish to L1 in fisherman mode
196
274
  if (this.config.fishermanMode) {
197
275
  this.log.info(
@@ -207,39 +285,83 @@ export class CheckpointProposalJob {
207
285
  return checkpoint;
208
286
  }
209
287
 
210
- // TODO(palla/mbps): Wire this to the new p2p API once available, including the pendingBroadcast.block
288
+ // Include the block pending broadcast in the checkpoint proposal if any
289
+ const lastBlock = blockPendingBroadcast && {
290
+ blockHeader: blockPendingBroadcast.block.header,
291
+ indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
292
+ txs: blockPendingBroadcast.txs,
293
+ };
294
+
295
+ // Create the checkpoint proposal and broadcast it
211
296
  const proposal = await this.validatorClient.createCheckpointProposal(
212
297
  checkpoint.header,
213
298
  checkpoint.archive.root,
214
- pendingBroadcast?.txs ?? [],
299
+ feeAssetPriceModifier,
300
+ lastBlock,
215
301
  this.proposer,
216
- blockProposalOptions,
302
+ checkpointProposalOptions,
217
303
  );
304
+
218
305
  const blockProposedAt = this.dateProvider.now();
219
- await this.p2pClient.broadcastProposal(proposal);
306
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
220
307
 
221
308
  this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
222
309
  const attestations = await this.waitForAttestations(proposal);
223
310
  const blockAttestedAt = this.dateProvider.now();
224
311
 
225
- this.metrics.recordBlockAttestationDelay(blockAttestedAt - blockProposedAt);
312
+ this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
226
313
 
227
314
  // Proposer must sign over the attestations before pushing them to L1
228
315
  const signer = this.proposer ?? this.publisher.getSenderAddress();
229
- const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer);
316
+ let attestationsSignature: Signature;
317
+ try {
318
+ attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
319
+ attestations,
320
+ signer,
321
+ this.slot,
322
+ this.checkpointNumber,
323
+ );
324
+ } catch (err) {
325
+ // We shouldn't really get here since we yield to another HA node
326
+ // as soon as we see these errors when creating block or checkpoint proposals.
327
+ if (this.handleHASigningError(err, 'Attestations signature')) {
328
+ return undefined;
329
+ }
330
+ throw err;
331
+ }
230
332
 
231
333
  // Enqueue publishing the checkpoint to L1
232
334
  this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
233
335
  const aztecSlotDuration = this.l1Constants.slotDuration;
234
336
  const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
235
337
  const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
338
+
339
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
340
+ if (
341
+ this.config.skipPublishingCheckpointsPercent !== undefined &&
342
+ this.config.skipPublishingCheckpointsPercent > 0
343
+ ) {
344
+ const result = Math.max(0, randomInt(100));
345
+ if (result < this.config.skipPublishingCheckpointsPercent) {
346
+ this.log.warn(
347
+ `Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${result}`,
348
+ );
349
+ return checkpoint;
350
+ }
351
+ }
352
+
236
353
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
237
354
  txTimeoutAt,
238
- forcePendingBlockNumber: this.invalidateBlock?.forcePendingBlockNumber,
355
+ forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
239
356
  });
240
357
 
241
358
  return checkpoint;
242
359
  } catch (err) {
360
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
361
+ // swallow this error. It's already been logged by a function deeper in the stack
362
+ return undefined;
363
+ }
364
+
243
365
  this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
244
366
  return undefined;
245
367
  }
@@ -248,24 +370,29 @@ export class CheckpointProposalJob {
248
370
  /**
249
371
  * Builds blocks for a checkpoint within the current slot.
250
372
  */
373
+ @trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint')
251
374
  private async buildBlocksForCheckpoint(
252
375
  checkpointBuilder: CheckpointBuilder,
253
376
  timestamp: bigint,
377
+ inHash: Fr,
254
378
  blockProposalOptions: BlockProposalOptions,
255
379
  ): Promise<{
256
- blocksInCheckpoint: L2BlockNew[];
257
- pendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined;
380
+ blocksInCheckpoint: L2Block[];
381
+ blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
258
382
  }> {
259
- const blocksInCheckpoint: L2BlockNew[] = [];
383
+ const blocksInCheckpoint: L2Block[] = [];
260
384
  const txHashesAlreadyIncluded = new Set<string>();
261
385
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
262
386
 
387
+ // Remaining blob fields available for blocks (checkpoint end marker already subtracted)
388
+ let remainingBlobFields = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
389
+
263
390
  // 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;
391
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
265
392
 
266
393
  while (true) {
267
394
  const blocksBuilt = blocksInCheckpoint.length;
268
- const indexWithinCheckpoint = blocksBuilt;
395
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
269
396
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
270
397
 
271
398
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -292,8 +419,10 @@ export class CheckpointProposalJob {
292
419
  blockNumber,
293
420
  indexWithinCheckpoint,
294
421
  txHashesAlreadyIncluded,
422
+ remainingBlobFields,
295
423
  });
296
424
 
425
+ // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
297
426
  if (!buildResult && timingInfo.isLastBlock) {
298
427
  // If no block was produced due to not enough txs and this was the last subslot, exit
299
428
  break;
@@ -316,13 +445,21 @@ export class CheckpointProposalJob {
316
445
  break;
317
446
  }
318
447
 
319
- const { block, usedTxs } = buildResult;
448
+ const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
320
449
  blocksInCheckpoint.push(block);
321
450
 
451
+ // Update remaining blob fields for the next block
452
+ remainingBlobFields = newRemainingBlobFields;
453
+
322
454
  // Sync the proposed block to the archiver to make it available
323
455
  // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
324
456
  // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
325
- await this.syncProposedBlockToArchiver(block);
457
+ // Fire and forget - don't block the critical path, but log errors
458
+ this.syncProposedBlockToArchiver(block).catch(err => {
459
+ this.log.error(`Failed to sync proposed block ${block.number} to archiver`, { blockNumber: block.number, err });
460
+ });
461
+
462
+ usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
326
463
 
327
464
  // If this is the last block, exit the loop now so we start collecting attestations
328
465
  if (timingInfo.isLastBlock) {
@@ -331,17 +468,17 @@ export class CheckpointProposalJob {
331
468
  blockNumber,
332
469
  blocksBuilt,
333
470
  });
334
- pendingBroadcast = { block, txs: usedTxs };
471
+ blockPendingBroadcast = { block, txs: usedTxs };
335
472
  break;
336
473
  }
337
474
 
338
475
  // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
339
476
  // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
340
477
  if (!this.config.fishermanMode) {
341
- // TODO(palla/mbps): Wire this to the new p2p API once available
342
478
  const proposal = await this.validatorClient.createBlockProposal(
343
- block.header.globalVariables.blockNumber,
344
- (await checkpointBuilder.getCheckpoint()).header,
479
+ block.header,
480
+ block.indexWithinCheckpoint,
481
+ inHash,
345
482
  block.archive.root,
346
483
  usedTxs,
347
484
  this.proposer,
@@ -359,13 +496,11 @@ export class CheckpointProposalJob {
359
496
  blocksBuilt: blocksInCheckpoint.length,
360
497
  });
361
498
 
362
- return {
363
- blocksInCheckpoint,
364
- pendingBroadcast,
365
- };
499
+ return { blocksInCheckpoint, blockPendingBroadcast };
366
500
  }
367
501
 
368
502
  /** Sleeps until it is time to produce the next block in the slot */
503
+ @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
369
504
  private async waitUntilNextSubslot(nextSubslotStart: number) {
370
505
  this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
371
506
  this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
@@ -373,19 +508,28 @@ export class CheckpointProposalJob {
373
508
  }
374
509
 
375
510
  /** Builds a single block. Called from the main block building loop. */
376
- private async buildSingleBlock(
511
+ @trackSpan('CheckpointProposalJob.buildSingleBlock')
512
+ protected async buildSingleBlock(
377
513
  checkpointBuilder: CheckpointBuilder,
378
514
  opts: {
379
515
  forceCreate?: boolean;
380
516
  blockTimestamp: bigint;
381
517
  blockNumber: BlockNumber;
382
- indexWithinCheckpoint: number;
518
+ indexWithinCheckpoint: IndexWithinCheckpoint;
383
519
  buildDeadline: Date | undefined;
384
520
  txHashesAlreadyIncluded: Set<string>;
521
+ remainingBlobFields: number;
385
522
  },
386
- ): Promise<{ block: L2BlockNew; usedTxs: Tx[] } | { error: Error } | undefined> {
387
- const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
388
- opts;
523
+ ): Promise<{ block: L2Block; usedTxs: Tx[]; remainingBlobFields: number } | { error: Error } | undefined> {
524
+ const {
525
+ blockTimestamp,
526
+ forceCreate,
527
+ blockNumber,
528
+ indexWithinCheckpoint,
529
+ buildDeadline,
530
+ txHashesAlreadyIncluded,
531
+ remainingBlobFields,
532
+ } = opts;
389
533
 
390
534
  this.log.verbose(
391
535
  `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
@@ -409,7 +553,7 @@ export class CheckpointProposalJob {
409
553
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
410
554
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
411
555
  const pendingTxs = filter(
412
- this.p2pClient.iteratePendingTxs(),
556
+ this.p2pClient.iterateEligiblePendingTxs(),
413
557
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
414
558
  );
415
559
 
@@ -418,46 +562,52 @@ export class CheckpointProposalJob {
418
562
  { slot: this.slot, blockNumber, indexWithinCheckpoint },
419
563
  );
420
564
  this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
565
+
566
+ // Calculate blob fields limit for txs (remaining capacity - this block's end overhead)
567
+ const blockEndOverhead = getNumBlockEndBlobFields(indexWithinCheckpoint === 0);
568
+ const maxBlobFieldsForTxs = remainingBlobFields - blockEndOverhead;
569
+
421
570
  const blockBuilderOptions: PublicProcessorLimits = {
422
571
  maxTransactions: this.config.maxTxsPerBlock,
423
572
  maxBlockSize: this.config.maxBlockSizeInBytes,
424
573
  maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
425
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
574
+ maxBlobFields: maxBlobFieldsForTxs,
426
575
  deadline: buildDeadline,
427
576
  };
428
577
 
429
578
  // 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();
579
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
580
+ checkpointBuilder,
581
+ pendingTxs,
582
+ blockNumber,
583
+ blockTimestamp,
584
+ blockBuilderOptions,
585
+ );
434
586
 
435
587
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
436
- await this.dropFailedTxsFromP2P(failedTxs);
588
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
437
589
 
438
590
  // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
439
591
  // too long, then we may not get to minTxsPerBlock after executing public functions.
440
592
  const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
441
- if (!forceCreate && numTxs < minValidTxs) {
593
+ const numTxs = buildResult.status === 'no-valid-txs' ? 0 : buildResult.numTxs;
594
+ if (buildResult.status === 'no-valid-txs' || (!forceCreate && numTxs < minValidTxs)) {
442
595
  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 },
596
+ `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed`,
597
+ { slot: this.slot, blockNumber, numTxs, indexWithinCheckpoint, minValidTxs, buildResult: buildResult.status },
445
598
  );
446
- this.eventEmitter.emit('block-tx-count-check-failed', {
447
- minTxs: minValidTxs,
448
- availableTxs: numTxs,
449
- slot: this.slot,
450
- });
599
+ this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
451
600
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
452
601
  return undefined;
453
602
  }
454
603
 
455
604
  // Block creation succeeded, emit stats and metrics
605
+ const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
606
+
456
607
  const blockStats = {
457
608
  eventName: 'l2-block-built',
458
609
  duration: blockBuildDuration,
459
610
  publicProcessDuration: publicProcessorDuration,
460
- rollupCircuitsDuration: blockBuildingTimer.ms(),
461
611
  ...block.getStats(),
462
612
  } satisfies L2BlockBuiltStats;
463
613
 
@@ -473,7 +623,7 @@ export class CheckpointProposalJob {
473
623
  this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
474
624
  this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
475
625
 
476
- return { block, usedTxs };
626
+ return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
477
627
  } catch (err: any) {
478
628
  this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
479
629
  this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
@@ -483,16 +633,40 @@ export class CheckpointProposalJob {
483
633
  }
484
634
  }
485
635
 
636
+ /** Uses the checkpoint builder to build a block, catching specific txs */
637
+ private async buildSingleBlockWithCheckpointBuilder(
638
+ checkpointBuilder: CheckpointBuilder,
639
+ pendingTxs: AsyncIterable<Tx>,
640
+ blockNumber: BlockNumber,
641
+ blockTimestamp: bigint,
642
+ blockBuilderOptions: PublicProcessorLimits,
643
+ ) {
644
+ try {
645
+ const workTimer = new Timer();
646
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
647
+ const blockBuildDuration = workTimer.ms();
648
+ return { ...result, blockBuildDuration, status: 'success' as const };
649
+ } catch (err: unknown) {
650
+ if (isErrorClass(err, NoValidTxsError)) {
651
+ return { failedTxs: err.failedTxs, status: 'no-valid-txs' as const };
652
+ }
653
+ throw err;
654
+ }
655
+ }
656
+
486
657
  /** Waits until minTxs are available on the pool for building a block. */
658
+ @trackSpan('CheckpointProposalJob.waitForMinTxs')
487
659
  private async waitForMinTxs(opts: {
488
660
  forceCreate?: boolean;
489
661
  blockNumber: BlockNumber;
490
- indexWithinCheckpoint: number;
662
+ indexWithinCheckpoint: IndexWithinCheckpoint;
491
663
  buildDeadline: Date | undefined;
492
664
  }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
493
- const minTxs = this.config.minTxsPerBlock;
494
665
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
495
666
 
667
+ // We only allow a block with 0 txs in the first block of the checkpoint
668
+ const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
669
+
496
670
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
497
671
  const startBuildingDeadline = buildDeadline
498
672
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -513,7 +687,7 @@ export class CheckpointProposalJob {
513
687
  `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
514
688
  { blockNumber, slot: this.slot, indexWithinCheckpoint },
515
689
  );
516
- await sleep(TXS_POLLING_MS);
690
+ await this.waitForTxsPollingInterval();
517
691
  availableTxs = await this.p2pClient.getPendingTxCount();
518
692
  }
519
693
 
@@ -524,7 +698,8 @@ export class CheckpointProposalJob {
524
698
  * Waits for enough attestations to be collected via p2p.
525
699
  * This is run after all blocks for the checkpoint have been built.
526
700
  */
527
- private async waitForAttestations(proposal: BlockProposal): Promise<CommitteeAttestationsAndSigners> {
701
+ @trackSpan('CheckpointProposalJob.waitForAttestations')
702
+ private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
528
703
  if (this.config.fishermanMode) {
529
704
  this.log.debug('Skipping attestation collection in fisherman mode');
530
705
  return CommitteeAttestationsAndSigners.empty();
@@ -553,7 +728,7 @@ export class CheckpointProposalJob {
553
728
  const attestationTimeAllowed = this.config.enforceTimeTable
554
729
  ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
555
730
  : this.l1Constants.slotDuration;
556
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
731
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
557
732
 
558
733
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
559
734
 
@@ -573,8 +748,7 @@ export class CheckpointProposalJob {
573
748
 
574
749
  // Manipulate the attestations if we've been configured to do so
575
750
  if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
576
- const checkpoint = proposal.payload.header;
577
- return this.manipulateAttestations(checkpoint, epoch, seed, committee, sorted);
751
+ return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
578
752
  }
579
753
 
580
754
  return new CommitteeAttestationsAndSigners(sorted);
@@ -590,7 +764,7 @@ export class CheckpointProposalJob {
590
764
 
591
765
  /** Breaks the attestations before publishing based on attack configs */
592
766
  private manipulateAttestations(
593
- checkpoint: CheckpointHeader,
767
+ slotNumber: SlotNumber,
594
768
  epoch: EpochNumber,
595
769
  seed: bigint,
596
770
  committee: EthAddress[],
@@ -598,7 +772,6 @@ export class CheckpointProposalJob {
598
772
  ) {
599
773
  // Compute the proposer index in the committee, since we dont want to tweak it.
600
774
  // Otherwise, the L1 rollup contract will reject the block outright.
601
- const { slotNumber } = checkpoint;
602
775
  const proposerIndex = Number(
603
776
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
604
777
  );
@@ -643,20 +816,27 @@ export class CheckpointProposalJob {
643
816
  const failedTxData = failedTxs.map(fail => fail.tx);
644
817
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
645
818
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
646
- await this.p2pClient.deleteTxs(failedTxHashes);
819
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
647
820
  }
648
821
 
649
822
  /**
650
- * Placeholder for pushing block to archiver and waiting for sync.
651
- * To be implemented when archiver and world-state support proposed blocks.
823
+ * Adds the proposed block to the archiver so it's available via P2P.
824
+ * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
825
+ * would never receive its own block without this explicit sync.
652
826
  */
653
- private async syncProposedBlockToArchiver(block: L2BlockNew): Promise<void> {
654
- this.log.debug(`Syncing proposed block ${block.number}`, {
827
+ private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
828
+ if (this.config.skipPushProposedBlocksToArchiver !== false) {
829
+ this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
830
+ blockNumber: block.number,
831
+ slot: block.header.globalVariables.slotNumber,
832
+ });
833
+ return;
834
+ }
835
+ this.log.debug(`Syncing proposed block ${block.number} to archiver`, {
655
836
  blockNumber: block.number,
656
837
  slot: block.header.globalVariables.slotNumber,
657
838
  });
658
- // TODO(palla/mbps): Implement actual sync to archiver and world-state
659
- await Promise.resolve();
839
+ await this.blockSink.addBlock(block);
660
840
  }
661
841
 
662
842
  /** Runs fee analysis and logs checkpoint outcome as fisherman */
@@ -678,19 +858,47 @@ export class CheckpointProposalJob {
678
858
  slot: this.slot,
679
859
  feeAnalysisId: feeAnalysis?.id,
680
860
  });
681
- this.metrics.recordBlockProposalFailed('block_build_failed');
861
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
682
862
  }
683
863
 
684
864
  this.publisher.clearPendingRequests();
685
865
  }
686
866
 
867
+ /**
868
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
869
+ */
870
+ private handleHASigningError(err: any, errorContext: string): boolean {
871
+ if (err instanceof DutyAlreadySignedError) {
872
+ this.log.info(`${errorContext} for slot ${this.slot} already signed by another HA node, yielding`, {
873
+ slot: this.slot,
874
+ signedByNode: err.signedByNode,
875
+ });
876
+ return true;
877
+ }
878
+ if (err instanceof SlashingProtectionError) {
879
+ this.log.info(`${errorContext} for slot ${this.slot} blocked by slashing protection, yielding`, {
880
+ slot: this.slot,
881
+ existingMessageHash: err.existingMessageHash,
882
+ attemptedMessageHash: err.attemptedMessageHash,
883
+ });
884
+ return true;
885
+ }
886
+ return false;
887
+ }
888
+
687
889
  /** Waits until a specific time within the current slot */
890
+ @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
688
891
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
689
892
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();
690
893
  const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
691
894
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
692
895
  }
693
896
 
897
+ /** Waits the polling interval for transactions. Extracted for test overriding. */
898
+ protected async waitForTxsPollingInterval(): Promise<void> {
899
+ await sleep(TXS_POLLING_MS);
900
+ }
901
+
694
902
  private getSlotStartBuildTimestamp(): number {
695
903
  return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
696
904
  }