@aztec/sequencer-client 0.0.1-commit.03f7ef2 → 0.0.1-commit.08c5969dc

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 (79) hide show
  1. package/dest/client/sequencer-client.d.ts +5 -6
  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-factory.d.ts +2 -2
  14. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  15. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  16. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  17. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  18. package/dest/publisher/sequencer-publisher.d.ts +19 -19
  19. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  20. package/dest/publisher/sequencer-publisher.js +482 -71
  21. package/dest/sequencer/checkpoint_proposal_job.d.ts +40 -12
  22. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  23. package/dest/sequencer/checkpoint_proposal_job.js +610 -59
  24. package/dest/sequencer/checkpoint_voter.d.ts +3 -2
  25. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  26. package/dest/sequencer/checkpoint_voter.js +34 -10
  27. package/dest/sequencer/index.d.ts +1 -3
  28. package/dest/sequencer/index.d.ts.map +1 -1
  29. package/dest/sequencer/index.js +0 -2
  30. package/dest/sequencer/metrics.d.ts +7 -4
  31. package/dest/sequencer/metrics.d.ts.map +1 -1
  32. package/dest/sequencer/metrics.js +72 -128
  33. package/dest/sequencer/sequencer.d.ts +27 -15
  34. package/dest/sequencer/sequencer.d.ts.map +1 -1
  35. package/dest/sequencer/sequencer.js +492 -43
  36. package/dest/sequencer/timetable.d.ts +1 -4
  37. package/dest/sequencer/timetable.d.ts.map +1 -1
  38. package/dest/sequencer/timetable.js +1 -4
  39. package/dest/test/index.d.ts +2 -3
  40. package/dest/test/index.d.ts.map +1 -1
  41. package/dest/test/mock_checkpoint_builder.d.ts +23 -11
  42. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  43. package/dest/test/mock_checkpoint_builder.js +50 -9
  44. package/dest/test/utils.d.ts +13 -9
  45. package/dest/test/utils.d.ts.map +1 -1
  46. package/dest/test/utils.js +27 -17
  47. package/package.json +30 -28
  48. package/src/client/sequencer-client.ts +5 -6
  49. package/src/config.ts +14 -11
  50. package/src/global_variable_builder/global_builder.ts +13 -13
  51. package/src/index.ts +1 -9
  52. package/src/publisher/sequencer-publisher-factory.ts +1 -1
  53. package/src/publisher/sequencer-publisher-metrics.ts +17 -69
  54. package/src/publisher/sequencer-publisher.ts +121 -95
  55. package/src/sequencer/checkpoint_proposal_job.ts +263 -89
  56. package/src/sequencer/checkpoint_voter.ts +32 -7
  57. package/src/sequencer/index.ts +0 -2
  58. package/src/sequencer/metrics.ts +70 -136
  59. package/src/sequencer/sequencer.ts +133 -43
  60. package/src/sequencer/timetable.ts +6 -5
  61. package/src/test/index.ts +1 -2
  62. package/src/test/mock_checkpoint_builder.ts +91 -29
  63. package/src/test/utils.ts +56 -28
  64. package/dest/sequencer/block_builder.d.ts +0 -26
  65. package/dest/sequencer/block_builder.d.ts.map +0 -1
  66. package/dest/sequencer/block_builder.js +0 -129
  67. package/dest/sequencer/checkpoint_builder.d.ts +0 -63
  68. package/dest/sequencer/checkpoint_builder.d.ts.map +0 -1
  69. package/dest/sequencer/checkpoint_builder.js +0 -131
  70. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  71. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  72. package/dest/tx_validator/nullifier_cache.js +0 -24
  73. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  74. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  75. package/dest/tx_validator/tx_validator_factory.js +0 -53
  76. package/src/sequencer/block_builder.ts +0 -217
  77. package/src/sequencer/checkpoint_builder.ts +0 -217
  78. package/src/tx_validator/nullifier_cache.ts +0 -30
  79. 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
@@ -108,6 +128,10 @@ export class CheckpointProposalJob {
108
128
  // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
109
129
  await Promise.all(votesPromises);
110
130
 
131
+ if (checkpoint) {
132
+ this.metrics.recordBlockProposalSuccess();
133
+ }
134
+
111
135
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
112
136
  if (this.config.fishermanMode) {
113
137
  await this.handleCheckpointEndAsFisherman(checkpoint);
@@ -128,6 +152,13 @@ export class CheckpointProposalJob {
128
152
  }
129
153
  }
130
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
+ })
131
162
  private async proposeCheckpoint(): Promise<Checkpoint | undefined> {
132
163
  try {
133
164
  // Get operator configured coinbase and fee recipient for this attestor
@@ -138,9 +169,9 @@ export class CheckpointProposalJob {
138
169
  this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
139
170
  this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
140
171
 
141
- // Enqueues block invalidation (constant for the whole slot)
142
- if (this.invalidateBlock && !this.config.skipInvalidateBlockAsProposer) {
143
- 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);
144
175
  }
145
176
 
146
177
  // Create checkpoint builder for the slot
@@ -150,8 +181,15 @@ export class CheckpointProposalJob {
150
181
  this.slot,
151
182
  );
152
183
 
153
- // Collect L1 to L2 messages for the checkpoint
184
+ // Collect L1 to L2 messages for the checkpoint and compute their hash
154
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());
155
193
 
156
194
  // Create a long-lived forked world state for the checkpoint builder
157
195
  using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
@@ -161,7 +199,9 @@ export class CheckpointProposalJob {
161
199
  this.checkpointNumber,
162
200
  checkpointGlobalVariables,
163
201
  l1ToL2Messages,
202
+ previousCheckpointOutHashes,
164
203
  fork,
204
+ this.log.getBindings(),
165
205
  );
166
206
 
167
207
  // Options for the validator client when creating block and checkpoint proposals
@@ -170,12 +210,33 @@ export class CheckpointProposalJob {
170
210
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
171
211
  };
172
212
 
173
- // Main loop: build blocks for the checkpoint
174
- const { blocksInCheckpoint, pendingBroadcast } = await this.buildBlocksForCheckpoint(
175
- checkpointBuilder,
176
- checkpointGlobalVariables.timestamp,
177
- blockProposalOptions,
178
- );
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
+ }
179
240
 
180
241
  if (blocksInCheckpoint.length === 0) {
181
242
  this.log.warn(`No blocks were built for slot ${this.slot}`, { slot: this.slot });
@@ -203,26 +264,49 @@ export class CheckpointProposalJob {
203
264
  return checkpoint;
204
265
  }
205
266
 
206
- // 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
207
275
  const proposal = await this.validatorClient.createCheckpointProposal(
208
276
  checkpoint.header,
209
277
  checkpoint.archive.root,
210
- pendingBroadcast?.txs ?? [],
278
+ lastBlock,
211
279
  this.proposer,
212
- blockProposalOptions,
280
+ checkpointProposalOptions,
213
281
  );
282
+
214
283
  const blockProposedAt = this.dateProvider.now();
215
- await this.p2pClient.broadcastProposal(proposal);
284
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
216
285
 
217
286
  this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
218
287
  const attestations = await this.waitForAttestations(proposal);
219
288
  const blockAttestedAt = this.dateProvider.now();
220
289
 
221
- this.metrics.recordBlockAttestationDelay(blockAttestedAt - blockProposedAt);
290
+ this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
222
291
 
223
292
  // Proposer must sign over the attestations before pushing them to L1
224
293
  const signer = this.proposer ?? this.publisher.getSenderAddress();
225
- 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
+ }
226
310
 
227
311
  // Enqueue publishing the checkpoint to L1
228
312
  this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
@@ -231,11 +315,16 @@ export class CheckpointProposalJob {
231
315
  const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
232
316
  await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
233
317
  txTimeoutAt,
234
- forcePendingBlockNumber: this.invalidateBlock?.forcePendingBlockNumber,
318
+ forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
235
319
  });
236
320
 
237
321
  return checkpoint;
238
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
+
239
328
  this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
240
329
  return undefined;
241
330
  }
@@ -244,24 +333,29 @@ export class CheckpointProposalJob {
244
333
  /**
245
334
  * Builds blocks for a checkpoint within the current slot.
246
335
  */
336
+ @trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint')
247
337
  private async buildBlocksForCheckpoint(
248
338
  checkpointBuilder: CheckpointBuilder,
249
339
  timestamp: bigint,
340
+ inHash: Fr,
250
341
  blockProposalOptions: BlockProposalOptions,
251
342
  ): Promise<{
252
- blocksInCheckpoint: L2BlockNew[];
253
- pendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined;
343
+ blocksInCheckpoint: L2Block[];
344
+ blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
254
345
  }> {
255
- const blocksInCheckpoint: L2BlockNew[] = [];
346
+ const blocksInCheckpoint: L2Block[] = [];
256
347
  const txHashesAlreadyIncluded = new Set<string>();
257
348
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
258
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
+
259
353
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
260
- let pendingBroadcast: { block: L2BlockNew; txs: Tx[] } | undefined = undefined;
354
+ let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
261
355
 
262
356
  while (true) {
263
357
  const blocksBuilt = blocksInCheckpoint.length;
264
- const indexWithinCheckpoint = blocksBuilt;
358
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
265
359
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
266
360
 
267
361
  const secondsIntoSlot = this.getSecondsIntoSlot();
@@ -288,8 +382,10 @@ export class CheckpointProposalJob {
288
382
  blockNumber,
289
383
  indexWithinCheckpoint,
290
384
  txHashesAlreadyIncluded,
385
+ remainingBlobFields,
291
386
  });
292
387
 
388
+ // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
293
389
  if (!buildResult && timingInfo.isLastBlock) {
294
390
  // If no block was produced due to not enough txs and this was the last subslot, exit
295
391
  break;
@@ -312,13 +408,21 @@ export class CheckpointProposalJob {
312
408
  break;
313
409
  }
314
410
 
315
- const { block, usedTxs } = buildResult;
411
+ const { block, usedTxs, remainingBlobFields: newRemainingBlobFields } = buildResult;
316
412
  blocksInCheckpoint.push(block);
317
413
 
414
+ // Update remaining blob fields for the next block
415
+ remainingBlobFields = newRemainingBlobFields;
416
+
318
417
  // Sync the proposed block to the archiver to make it available
319
418
  // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
320
419
  // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
321
- 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()));
322
426
 
323
427
  // If this is the last block, exit the loop now so we start collecting attestations
324
428
  if (timingInfo.isLastBlock) {
@@ -327,17 +431,17 @@ export class CheckpointProposalJob {
327
431
  blockNumber,
328
432
  blocksBuilt,
329
433
  });
330
- pendingBroadcast = { block, txs: usedTxs };
434
+ blockPendingBroadcast = { block, txs: usedTxs };
331
435
  break;
332
436
  }
333
437
 
334
438
  // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
335
439
  // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
336
440
  if (!this.config.fishermanMode) {
337
- // TODO(palla/mbps): Wire this to the new p2p API once available
338
441
  const proposal = await this.validatorClient.createBlockProposal(
339
- block.header.globalVariables.blockNumber,
340
- (await checkpointBuilder.getCheckpoint()).header,
442
+ block.header,
443
+ block.indexWithinCheckpoint,
444
+ inHash,
341
445
  block.archive.root,
342
446
  usedTxs,
343
447
  this.proposer,
@@ -355,13 +459,11 @@ export class CheckpointProposalJob {
355
459
  blocksBuilt: blocksInCheckpoint.length,
356
460
  });
357
461
 
358
- return {
359
- blocksInCheckpoint,
360
- pendingBroadcast,
361
- };
462
+ return { blocksInCheckpoint, blockPendingBroadcast };
362
463
  }
363
464
 
364
465
  /** Sleeps until it is time to produce the next block in the slot */
466
+ @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
365
467
  private async waitUntilNextSubslot(nextSubslotStart: number) {
366
468
  this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
367
469
  this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, { slot: this.slot });
@@ -369,19 +471,28 @@ export class CheckpointProposalJob {
369
471
  }
370
472
 
371
473
  /** Builds a single block. Called from the main block building loop. */
372
- private async buildSingleBlock(
474
+ @trackSpan('CheckpointProposalJob.buildSingleBlock')
475
+ protected async buildSingleBlock(
373
476
  checkpointBuilder: CheckpointBuilder,
374
477
  opts: {
375
478
  forceCreate?: boolean;
376
479
  blockTimestamp: bigint;
377
480
  blockNumber: BlockNumber;
378
- indexWithinCheckpoint: number;
481
+ indexWithinCheckpoint: IndexWithinCheckpoint;
379
482
  buildDeadline: Date | undefined;
380
483
  txHashesAlreadyIncluded: Set<string>;
484
+ remainingBlobFields: number;
381
485
  },
382
- ): Promise<{ block: L2BlockNew; usedTxs: Tx[] } | { error: Error } | undefined> {
383
- const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
384
- 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;
385
496
 
386
497
  this.log.verbose(
387
498
  `Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`,
@@ -405,7 +516,7 @@ export class CheckpointProposalJob {
405
516
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
406
517
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
407
518
  const pendingTxs = filter(
408
- this.p2pClient.iteratePendingTxs(),
519
+ this.p2pClient.iterateEligiblePendingTxs(),
409
520
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
410
521
  );
411
522
 
@@ -414,46 +525,52 @@ export class CheckpointProposalJob {
414
525
  { slot: this.slot, blockNumber, indexWithinCheckpoint },
415
526
  );
416
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
+
417
533
  const blockBuilderOptions: PublicProcessorLimits = {
418
534
  maxTransactions: this.config.maxTxsPerBlock,
419
535
  maxBlockSize: this.config.maxBlockSizeInBytes,
420
536
  maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
421
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
537
+ maxBlobFields: maxBlobFieldsForTxs,
422
538
  deadline: buildDeadline,
423
539
  };
424
540
 
425
541
  // Actually build the block by executing txs
426
- const workTimer = new Timer();
427
- const { publicGas, block, publicProcessorDuration, numTxs, blockBuildingTimer, usedTxs, failedTxs } =
428
- await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
429
- const blockBuildDuration = workTimer.ms();
542
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(
543
+ checkpointBuilder,
544
+ pendingTxs,
545
+ blockNumber,
546
+ blockTimestamp,
547
+ blockBuilderOptions,
548
+ );
430
549
 
431
550
  // If any txs failed during execution, drop them from the mempool so we don't pick them up again
432
- await this.dropFailedTxsFromP2P(failedTxs);
551
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
433
552
 
434
553
  // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
435
554
  // too long, then we may not get to minTxsPerBlock after executing public functions.
436
555
  const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
437
- 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)) {
438
558
  this.log.warn(
439
- `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`,
440
- { 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 },
441
561
  );
442
- this.eventEmitter.emit('block-tx-count-check-failed', {
443
- minTxs: minValidTxs,
444
- availableTxs: numTxs,
445
- slot: this.slot,
446
- });
562
+ this.eventEmitter.emit('block-build-failed', { reason: `Insufficient valid txs`, slot: this.slot });
447
563
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
448
564
  return undefined;
449
565
  }
450
566
 
451
567
  // Block creation succeeded, emit stats and metrics
568
+ const { publicGas, block, publicProcessorDuration, usedTxs, usedTxBlobFields, blockBuildDuration } = buildResult;
569
+
452
570
  const blockStats = {
453
571
  eventName: 'l2-block-built',
454
572
  duration: blockBuildDuration,
455
573
  publicProcessDuration: publicProcessorDuration,
456
- rollupCircuitsDuration: blockBuildingTimer.ms(),
457
574
  ...block.getStats(),
458
575
  } satisfies L2BlockBuiltStats;
459
576
 
@@ -469,7 +586,7 @@ export class CheckpointProposalJob {
469
586
  this.eventEmitter.emit('block-proposed', { blockNumber: block.number, slot: this.slot });
470
587
  this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
471
588
 
472
- return { block, usedTxs };
589
+ return { block, usedTxs, remainingBlobFields: maxBlobFieldsForTxs - usedTxBlobFields };
473
590
  } catch (err: any) {
474
591
  this.eventEmitter.emit('block-build-failed', { reason: err.message, slot: this.slot });
475
592
  this.log.error(`Error building block`, err, { blockNumber, slot: this.slot });
@@ -479,16 +596,40 @@ export class CheckpointProposalJob {
479
596
  }
480
597
  }
481
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
+
482
620
  /** Waits until minTxs are available on the pool for building a block. */
621
+ @trackSpan('CheckpointProposalJob.waitForMinTxs')
483
622
  private async waitForMinTxs(opts: {
484
623
  forceCreate?: boolean;
485
624
  blockNumber: BlockNumber;
486
- indexWithinCheckpoint: number;
625
+ indexWithinCheckpoint: IndexWithinCheckpoint;
487
626
  buildDeadline: Date | undefined;
488
627
  }): Promise<{ canStartBuilding: boolean; availableTxs: number }> {
489
- const minTxs = this.config.minTxsPerBlock;
490
628
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
491
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
+
492
633
  // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
493
634
  const startBuildingDeadline = buildDeadline
494
635
  ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
@@ -509,7 +650,7 @@ export class CheckpointProposalJob {
509
650
  `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`,
510
651
  { blockNumber, slot: this.slot, indexWithinCheckpoint },
511
652
  );
512
- await sleep(TXS_POLLING_MS);
653
+ await this.waitForTxsPollingInterval();
513
654
  availableTxs = await this.p2pClient.getPendingTxCount();
514
655
  }
515
656
 
@@ -520,7 +661,8 @@ export class CheckpointProposalJob {
520
661
  * Waits for enough attestations to be collected via p2p.
521
662
  * This is run after all blocks for the checkpoint have been built.
522
663
  */
523
- private async waitForAttestations(proposal: BlockProposal): Promise<CommitteeAttestationsAndSigners> {
664
+ @trackSpan('CheckpointProposalJob.waitForAttestations')
665
+ private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
524
666
  if (this.config.fishermanMode) {
525
667
  this.log.debug('Skipping attestation collection in fisherman mode');
526
668
  return CommitteeAttestationsAndSigners.empty();
@@ -549,7 +691,7 @@ export class CheckpointProposalJob {
549
691
  const attestationTimeAllowed = this.config.enforceTimeTable
550
692
  ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
551
693
  : this.l1Constants.slotDuration;
552
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
694
+ const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
553
695
 
554
696
  this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
555
697
 
@@ -569,8 +711,7 @@ export class CheckpointProposalJob {
569
711
 
570
712
  // Manipulate the attestations if we've been configured to do so
571
713
  if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
572
- const checkpoint = proposal.payload.header;
573
- return this.manipulateAttestations(checkpoint, epoch, seed, committee, sorted);
714
+ return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
574
715
  }
575
716
 
576
717
  return new CommitteeAttestationsAndSigners(sorted);
@@ -586,7 +727,7 @@ export class CheckpointProposalJob {
586
727
 
587
728
  /** Breaks the attestations before publishing based on attack configs */
588
729
  private manipulateAttestations(
589
- checkpoint: CheckpointHeader,
730
+ slotNumber: SlotNumber,
590
731
  epoch: EpochNumber,
591
732
  seed: bigint,
592
733
  committee: EthAddress[],
@@ -594,7 +735,6 @@ export class CheckpointProposalJob {
594
735
  ) {
595
736
  // Compute the proposer index in the committee, since we dont want to tweak it.
596
737
  // Otherwise, the L1 rollup contract will reject the block outright.
597
- const { slotNumber } = checkpoint;
598
738
  const proposerIndex = Number(
599
739
  this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)),
600
740
  );
@@ -639,20 +779,27 @@ export class CheckpointProposalJob {
639
779
  const failedTxData = failedTxs.map(fail => fail.tx);
640
780
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
641
781
  this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
642
- await this.p2pClient.deleteTxs(failedTxHashes);
782
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
643
783
  }
644
784
 
645
785
  /**
646
- * Placeholder for pushing block to archiver and waiting for sync.
647
- * 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.
648
789
  */
649
- private async syncProposedBlockToArchiver(block: L2BlockNew): Promise<void> {
650
- 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`, {
651
799
  blockNumber: block.number,
652
800
  slot: block.header.globalVariables.slotNumber,
653
801
  });
654
- // TODO(palla/mbps): Implement actual sync to archiver and world-state
655
- await Promise.resolve();
802
+ await this.blockSink.addBlock(block);
656
803
  }
657
804
 
658
805
  /** Runs fee analysis and logs checkpoint outcome as fisherman */
@@ -669,7 +816,6 @@ export class CheckpointProposalJob {
669
816
  ...checkpoint.getStats(),
670
817
  feeAnalysisId: feeAnalysis?.id,
671
818
  });
672
- this.metrics.recordBlockProposalSuccess();
673
819
  } else {
674
820
  this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
675
821
  slot: this.slot,
@@ -681,13 +827,41 @@ export class CheckpointProposalJob {
681
827
  this.publisher.clearPendingRequests();
682
828
  }
683
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
+
684
852
  /** Waits until a specific time within the current slot */
853
+ @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
685
854
  protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
686
855
  const slotStartTimestamp = this.getSlotStartBuildTimestamp();
687
856
  const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
688
857
  await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
689
858
  }
690
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
+
691
865
  private getSlotStartBuildTimestamp(): number {
692
866
  return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
693
867
  }