@aztec/validator-client 4.0.0-nightly.20260111 → 4.0.0-nightly.20260113

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 (42) hide show
  1. package/README.md +256 -0
  2. package/dest/block_proposal_handler.d.ts +20 -10
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +333 -72
  5. package/dest/checkpoint_builder.d.ts +70 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +155 -0
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +10 -0
  11. package/dest/duties/validation_service.d.ts +26 -10
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +51 -21
  14. package/dest/factory.d.ts +10 -7
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +2 -2
  17. package/dest/index.d.ts +3 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +2 -0
  20. package/dest/tx_validator/index.d.ts +3 -0
  21. package/dest/tx_validator/index.d.ts.map +1 -0
  22. package/dest/tx_validator/index.js +2 -0
  23. package/dest/tx_validator/nullifier_cache.d.ts +14 -0
  24. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
  25. package/dest/tx_validator/nullifier_cache.js +24 -0
  26. package/dest/tx_validator/tx_validator_factory.d.ts +18 -0
  27. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  28. package/dest/tx_validator/tx_validator_factory.js +53 -0
  29. package/dest/validator.d.ts +39 -15
  30. package/dest/validator.d.ts.map +1 -1
  31. package/dest/validator.js +297 -449
  32. package/package.json +16 -12
  33. package/src/block_proposal_handler.ts +249 -39
  34. package/src/checkpoint_builder.ts +267 -0
  35. package/src/config.ts +10 -0
  36. package/src/duties/validation_service.ts +79 -25
  37. package/src/factory.ts +13 -8
  38. package/src/index.ts +2 -0
  39. package/src/tx_validator/index.ts +2 -0
  40. package/src/tx_validator/nullifier_cache.ts +30 -0
  41. package/src/tx_validator/tx_validator_factory.ts +133 -0
  42. package/src/validator.ts +400 -94
package/src/validator.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
- import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
+ import { type Blob, getBlobsPerL1Block } from '@aztec/blob-lib';
3
3
  import type { EpochCache } from '@aztec/epoch-cache';
4
- import { BlockNumber, EpochNumber } from '@aztec/foundation/branded-types';
4
+ import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
5
5
  import { Fr } from '@aztec/foundation/curves/bn254';
6
+ import { TimeoutError } from '@aztec/foundation/error';
6
7
  import type { EthAddress } from '@aztec/foundation/eth-address';
7
8
  import type { Signature } from '@aztec/foundation/eth-signature';
8
- import { type Logger, createLogger } from '@aztec/foundation/log';
9
+ import { type LogData, type Logger, createLogger } from '@aztec/foundation/log';
10
+ import { retryUntil } from '@aztec/foundation/retry';
9
11
  import { RunningPromise } from '@aztec/foundation/running-promise';
10
12
  import { sleep } from '@aztec/foundation/sleep';
11
13
  import { DateProvider } from '@aztec/foundation/timer';
@@ -14,19 +16,32 @@ import type { P2P, PeerId, TxProvider } from '@aztec/p2p';
14
16
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
15
17
  import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
16
18
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
17
- import type { CommitteeAttestationsAndSigners, L2BlockSource } from '@aztec/stdlib/block';
18
- import type { IFullNodeBlockBuilder, Validator, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
19
+ import type { CommitteeAttestationsAndSigners, L2BlockNew, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
20
+ import type {
21
+ CreateCheckpointProposalLastBlockData,
22
+ Validator,
23
+ ValidatorClientFullConfig,
24
+ WorldStateSynchronizer,
25
+ } from '@aztec/stdlib/interfaces/server';
19
26
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
20
- import type { BlockAttestation, BlockProposal, BlockProposalOptions } from '@aztec/stdlib/p2p';
27
+ import type {
28
+ BlockProposal,
29
+ BlockProposalOptions,
30
+ CheckpointAttestation,
31
+ CheckpointProposalCore,
32
+ CheckpointProposalOptions,
33
+ } from '@aztec/stdlib/p2p';
34
+ import { CheckpointProposal } from '@aztec/stdlib/p2p';
21
35
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
22
- import type { Tx } from '@aztec/stdlib/tx';
36
+ import type { BlockHeader, CheckpointGlobalVariables, Tx } from '@aztec/stdlib/tx';
23
37
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
24
- import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
38
+ import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
25
39
 
26
40
  import { EventEmitter } from 'events';
27
41
  import type { TypedDataDefinition } from 'viem';
28
42
 
29
43
  import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
44
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
30
45
  import { ValidationService } from './duties/validation_service.js';
31
46
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
32
47
  import { ValidatorMetrics } from './metrics.js';
@@ -61,11 +76,20 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
61
76
 
62
77
  private proposersOfInvalidBlocks: Set<string> = new Set();
63
78
 
79
+ // TODO(palla/mbps): Remove this once checkpoint validation is stable and we can validate all blocks properly.
80
+ // Tracks slots for which we have successfully validated a block proposal, so we can attest to checkpoint proposals for those slots.
81
+ // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
82
+ private validatedBlockSlots: Set<SlotNumber> = new Set();
83
+
64
84
  protected constructor(
65
85
  private keyStore: NodeKeystoreAdapter,
66
86
  private epochCache: EpochCache,
67
87
  private p2pClient: P2P,
68
88
  private blockProposalHandler: BlockProposalHandler,
89
+ private blockSource: L2BlockSource,
90
+ private checkpointsBuilder: FullNodeCheckpointsBuilder,
91
+ private worldState: WorldStateSynchronizer,
92
+ private l1ToL2MessageSource: L1ToL2MessageSource,
69
93
  private config: ValidatorClientFullConfig,
70
94
  private blobClient: BlobClientInterface,
71
95
  private dateProvider: DateProvider = new DateProvider(),
@@ -143,10 +167,11 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
143
167
 
144
168
  static new(
145
169
  config: ValidatorClientFullConfig,
146
- blockBuilder: IFullNodeBlockBuilder,
170
+ checkpointsBuilder: FullNodeCheckpointsBuilder,
171
+ worldState: WorldStateSynchronizer,
147
172
  epochCache: EpochCache,
148
173
  p2pClient: P2P,
149
- blockSource: L2BlockSource,
174
+ blockSource: L2BlockSource & L2BlockSink,
150
175
  l1ToL2MessageSource: L1ToL2MessageSource,
151
176
  txProvider: TxProvider,
152
177
  keyStoreManager: KeystoreManager,
@@ -159,7 +184,8 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
159
184
  txsPermitted: !config.disableTransactions,
160
185
  });
161
186
  const blockProposalHandler = new BlockProposalHandler(
162
- blockBuilder,
187
+ checkpointsBuilder,
188
+ worldState,
163
189
  blockSource,
164
190
  l1ToL2MessageSource,
165
191
  txProvider,
@@ -175,6 +201,10 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
175
201
  epochCache,
176
202
  p2pClient,
177
203
  blockProposalHandler,
204
+ blockSource,
205
+ checkpointsBuilder,
206
+ worldState,
207
+ l1ToL2MessageSource,
178
208
  config,
179
209
  blobClient,
180
210
  dateProvider,
@@ -194,16 +224,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
194
224
  return this.blockProposalHandler;
195
225
  }
196
226
 
197
- // Proxy method for backwards compatibility with tests
198
- public reExecuteTransactions(
199
- proposal: BlockProposal,
200
- blockNumber: BlockNumber,
201
- txs: any[],
202
- l1ToL2Messages: Fr[],
203
- ): Promise<any> {
204
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
205
- }
206
-
207
227
  public signWithAddress(addr: EthAddress, msg: TypedDataDefinition) {
208
228
  return this.keyStore.signTypedDataWithAddress(addr, msg);
209
229
  }
@@ -253,9 +273,19 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
253
273
  this.hasRegisteredHandlers = true;
254
274
  this.log.debug(`Registering validator handlers for p2p client`);
255
275
 
256
- const handler = (block: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> =>
257
- this.attestToProposal(block, proposalSender);
258
- this.p2pClient.registerBlockProposalHandler(handler);
276
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
277
+ const blockHandler = (block: BlockProposal, proposalSender: PeerId): Promise<boolean> =>
278
+ this.validateBlockProposal(block, proposalSender);
279
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
280
+
281
+ // Checkpoint proposal handler - validates and creates attestations
282
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
283
+ // and processed separately via the block handler above.
284
+ const checkpointHandler = (
285
+ checkpoint: CheckpointProposalCore,
286
+ proposalSender: PeerId,
287
+ ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
288
+ this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
259
289
 
260
290
  const myAddresses = this.getValidatorAddresses();
261
291
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
@@ -264,33 +294,33 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
264
294
  }
265
295
  }
266
296
 
267
- @trackSpan('validator.attestToProposal', (proposal, proposalSender) => ({
268
- [Attributes.BLOCK_HASH]: proposal.payload.header.hash.toString(),
269
- [Attributes.PEER_ID]: proposalSender.toString(),
270
- }))
271
- async attestToProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> {
297
+ /**
298
+ * Validate a block proposal from a peer.
299
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
300
+ * @returns true if the proposal is valid, false otherwise
301
+ */
302
+ async validateBlockProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<boolean> {
272
303
  const slotNumber = proposal.slotNumber;
273
304
  const proposer = proposal.getSender();
274
305
 
275
306
  // Reject proposals with invalid signatures
276
307
  if (!proposer) {
277
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
278
- return undefined;
308
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
309
+ return false;
279
310
  }
280
311
 
281
- // Check that I have any address in current committee before attesting
312
+ // Check if we're in the committee (for metrics purposes)
282
313
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
283
314
  const partOfCommittee = inCommittee.length > 0;
284
315
 
285
316
  const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
286
- this.log.info(`Received proposal for slot ${slotNumber}`, {
317
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
287
318
  ...proposalInfo,
288
319
  txHashes: proposal.txHashes.map(t => t.toString()),
289
320
  fishermanMode: this.config.fishermanMode || false,
290
321
  });
291
322
 
292
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
293
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
323
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
294
324
  // In fisherman mode, we always reexecute to validate proposals.
295
325
  const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
296
326
  this.config;
@@ -308,7 +338,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
308
338
  );
309
339
 
310
340
  if (!validationResult.isValid) {
311
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
341
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
312
342
 
313
343
  const reason = validationResult.reason || 'unknown';
314
344
  // Classify failure reason: bad proposal vs node issue
@@ -323,7 +353,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
323
353
  if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
324
354
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
325
355
  } else {
326
- // Node issues so we can't attest
356
+ // Node issues so we can't validate
327
357
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
328
358
  }
329
359
 
@@ -336,9 +366,81 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
336
366
  this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
337
367
  this.slashInvalidBlock(proposal);
338
368
  }
369
+ return false;
370
+ }
371
+
372
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
373
+ ...proposalInfo,
374
+ inCommittee: partOfCommittee,
375
+ fishermanMode: this.config.fishermanMode || false,
376
+ });
377
+
378
+ // TODO(palla/mbps): Remove this once checkpoint validation is stable.
379
+ // Track that we successfully validated a block for this slot, so we can attest to checkpoint proposals for it.
380
+ this.validatedBlockSlots.add(slotNumber);
381
+
382
+ return true;
383
+ }
384
+
385
+ /**
386
+ * Validate and attest to a checkpoint proposal from a peer.
387
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
388
+ * the lastBlock is extracted and processed separately via the block handler.
389
+ * @returns Checkpoint attestations if valid, undefined otherwise
390
+ */
391
+ async attestToCheckpointProposal(
392
+ proposal: CheckpointProposalCore,
393
+ _proposalSender: PeerId,
394
+ ): Promise<CheckpointAttestation[] | undefined> {
395
+ const slotNumber = proposal.slotNumber;
396
+ const proposer = proposal.getSender();
397
+
398
+ // Reject proposals with invalid signatures
399
+ if (!proposer) {
400
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
401
+ return undefined;
402
+ }
403
+
404
+ // Check that I have any address in current committee before attesting
405
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
406
+ const partOfCommittee = inCommittee.length > 0;
407
+
408
+ const proposalInfo = {
409
+ slotNumber,
410
+ archive: proposal.archive.toString(),
411
+ proposer: proposer.toString(),
412
+ txCount: proposal.txHashes.length,
413
+ };
414
+ this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
415
+ ...proposalInfo,
416
+ txHashes: proposal.txHashes.map(t => t.toString()),
417
+ fishermanMode: this.config.fishermanMode || false,
418
+ });
419
+
420
+ // TODO(palla/mbps): Remove this once checkpoint validation is stable.
421
+ // Check that we have successfully validated a block for this slot before attesting to the checkpoint.
422
+ if (!this.validatedBlockSlots.has(slotNumber)) {
423
+ this.log.warn(`No validated block found for slot ${slotNumber}, refusing to attest to checkpoint`, proposalInfo);
339
424
  return undefined;
340
425
  }
341
426
 
427
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
428
+ // TODO(palla/mbps): Change default to false once checkpoint validation is stable.
429
+ if (this.config.skipCheckpointProposalValidation !== false) {
430
+ this.log.verbose(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
431
+ } else {
432
+ const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
433
+ if (!validationResult.isValid) {
434
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
435
+ return undefined;
436
+ }
437
+ }
438
+
439
+ // Upload blobs to filestore if we can (fire and forget)
440
+ if (this.blobClient.canUpload()) {
441
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
442
+ }
443
+
342
444
  // Check that I have any address in current committee before attesting
343
445
  // In fisherman mode, we still create attestations for validation even if not in committee
344
446
  if (!partOfCommittee && !this.config.fishermanMode) {
@@ -347,7 +449,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
347
449
  }
348
450
 
349
451
  // Provided all of the above checks pass, we can attest to the proposal
350
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} proposal for slot ${slotNumber}`, {
452
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
351
453
  ...proposalInfo,
352
454
  inCommittee: partOfCommittee,
353
455
  fishermanMode: this.config.fishermanMode || false,
@@ -355,21 +457,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
355
457
 
356
458
  this.metrics.incSuccessfulAttestations(inCommittee.length);
357
459
 
358
- // Upload blobs to filestore after successful re-execution (fire-and-forget)
359
- if (validationResult.reexecutionResult?.block && this.blobClient.canUpload()) {
360
- void Promise.resolve().then(async () => {
361
- try {
362
- const blobFields = validationResult.reexecutionResult!.block.getCheckpointBlobFields();
363
- const blobs = getBlobsPerL1Block(blobFields);
364
- await this.blobClient.sendBlobsToFilestore(blobs);
365
- this.log.debug(`Uploaded ${blobs.length} blobs to filestore from re-execution`, proposalInfo);
366
- } catch (err) {
367
- this.log.warn(`Failed to upload blobs from re-execution`, err);
368
- }
369
- });
370
- }
371
-
372
- // If the above function does not throw an error, then we can attest to the proposal
373
460
  // Determine which validators should attest
374
461
  let attestors: EthAddress[];
375
462
  if (partOfCommittee) {
@@ -388,13 +475,222 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
388
475
 
389
476
  if (this.config.fishermanMode) {
390
477
  // bail out early and don't save attestations to the pool in fisherman mode
391
- this.log.info(`Creating attestations for proposal for slot ${slotNumber}`, {
478
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
392
479
  ...proposalInfo,
393
480
  attestors: attestors.map(a => a.toString()),
394
481
  });
395
482
  return undefined;
396
483
  }
397
- return this.createBlockAttestationsFromProposal(proposal, attestors);
484
+
485
+ return this.createCheckpointAttestationsFromProposal(proposal, attestors);
486
+ }
487
+
488
+ private async createCheckpointAttestationsFromProposal(
489
+ proposal: CheckpointProposalCore,
490
+ attestors: EthAddress[] = [],
491
+ ): Promise<CheckpointAttestation[]> {
492
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
493
+ await this.p2pClient.addCheckpointAttestations(attestations);
494
+ return attestations;
495
+ }
496
+
497
+ /**
498
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
499
+ * @returns Validation result with isValid flag and reason if invalid.
500
+ */
501
+ private async validateCheckpointProposal(
502
+ proposal: CheckpointProposalCore,
503
+ proposalInfo: LogData,
504
+ ): Promise<{ isValid: true } | { isValid: false; reason: string }> {
505
+ const slot = proposal.slotNumber;
506
+ const timeoutSeconds = 10;
507
+
508
+ // Wait for last block to sync by archive
509
+ let lastBlockHeader: BlockHeader | undefined;
510
+ try {
511
+ lastBlockHeader = await retryUntil(
512
+ async () => {
513
+ await this.blockSource.syncImmediate();
514
+ return this.blockSource.getBlockHeaderByArchive(proposal.archive);
515
+ },
516
+ `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
517
+ timeoutSeconds,
518
+ 0.5,
519
+ );
520
+ } catch (err) {
521
+ if (err instanceof TimeoutError) {
522
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
523
+ return { isValid: false, reason: 'last_block_not_found' };
524
+ }
525
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
526
+ return { isValid: false, reason: 'block_fetch_error' };
527
+ }
528
+
529
+ if (!lastBlockHeader) {
530
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
531
+ return { isValid: false, reason: 'last_block_not_found' };
532
+ }
533
+
534
+ // Get the last full block to determine checkpoint number
535
+ const lastBlock = await this.blockSource.getL2BlockNew(lastBlockHeader.getBlockNumber());
536
+ if (!lastBlock) {
537
+ this.log.warn(`Last block ${lastBlockHeader.getBlockNumber()} not found`, proposalInfo);
538
+ return { isValid: false, reason: 'last_block_not_found' };
539
+ }
540
+ const checkpointNumber = lastBlock.checkpointNumber;
541
+
542
+ // Get all full blocks for the slot and checkpoint
543
+ const blocks = await this.getBlocksForSlot(slot, lastBlockHeader, checkpointNumber);
544
+ if (blocks.length === 0) {
545
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
546
+ return { isValid: false, reason: 'no_blocks_for_slot' };
547
+ }
548
+
549
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
550
+ ...proposalInfo,
551
+ blockNumbers: blocks.map(b => b.number),
552
+ });
553
+
554
+ // Get checkpoint constants from first block
555
+ const firstBlock = blocks[0];
556
+ const constants = this.extractCheckpointConstants(firstBlock);
557
+
558
+ // Get L1-to-L2 messages for this checkpoint
559
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
560
+
561
+ // Fork world state at the block before the first block
562
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
563
+ const fork = await this.worldState.fork(parentBlockNumber);
564
+
565
+ try {
566
+ // Create checkpoint builder with all existing blocks
567
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
568
+ checkpointNumber,
569
+ constants,
570
+ l1ToL2Messages,
571
+ fork,
572
+ blocks,
573
+ );
574
+
575
+ // Complete the checkpoint to get computed values
576
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
577
+
578
+ // Compare checkpoint header with proposal
579
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
580
+ this.log.warn(`Checkpoint header mismatch`, {
581
+ ...proposalInfo,
582
+ computed: computedCheckpoint.header.toInspect(),
583
+ proposal: proposal.checkpointHeader.toInspect(),
584
+ });
585
+ return { isValid: false, reason: 'checkpoint_header_mismatch' };
586
+ }
587
+
588
+ // Compare archive root with proposal
589
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
590
+ this.log.warn(`Archive root mismatch`, {
591
+ ...proposalInfo,
592
+ computed: computedCheckpoint.archive.root.toString(),
593
+ proposal: proposal.archive.toString(),
594
+ });
595
+ return { isValid: false, reason: 'archive_mismatch' };
596
+ }
597
+
598
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
599
+ return { isValid: true };
600
+ } finally {
601
+ await fork.close();
602
+ }
603
+ }
604
+
605
+ /**
606
+ * Get all full blocks for a given slot and checkpoint by walking backwards from the last block.
607
+ * Returns blocks in ascending order (earliest to latest).
608
+ * TODO(palla/mbps): Add getL2BlocksForSlot() to L2BlockSource interface for efficiency.
609
+ */
610
+ private async getBlocksForSlot(
611
+ slot: SlotNumber,
612
+ lastBlockHeader: BlockHeader,
613
+ checkpointNumber: CheckpointNumber,
614
+ ): Promise<L2BlockNew[]> {
615
+ const blocks: L2BlockNew[] = [];
616
+ let currentHeader = lastBlockHeader;
617
+ const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
618
+
619
+ while (currentHeader.getSlot() === slot) {
620
+ const block = await this.blockSource.getL2BlockNew(currentHeader.getBlockNumber());
621
+ if (!block) {
622
+ this.log.warn(`Block ${currentHeader.getBlockNumber()} not found while getting blocks for slot ${slot}`);
623
+ break;
624
+ }
625
+ if (block.checkpointNumber !== checkpointNumber) {
626
+ break;
627
+ }
628
+ blocks.unshift(block);
629
+
630
+ const prevArchive = currentHeader.lastArchive.root;
631
+ if (prevArchive.equals(genesisArchiveRoot)) {
632
+ break;
633
+ }
634
+
635
+ const prevHeader = await this.blockSource.getBlockHeaderByArchive(prevArchive);
636
+ if (!prevHeader || prevHeader.getSlot() !== slot) {
637
+ break;
638
+ }
639
+ currentHeader = prevHeader;
640
+ }
641
+
642
+ return blocks;
643
+ }
644
+
645
+ /**
646
+ * Extract checkpoint global variables from a block.
647
+ */
648
+ private extractCheckpointConstants(block: L2BlockNew): CheckpointGlobalVariables {
649
+ const gv = block.header.globalVariables;
650
+ return {
651
+ chainId: gv.chainId,
652
+ version: gv.version,
653
+ slotNumber: gv.slotNumber,
654
+ coinbase: gv.coinbase,
655
+ feeRecipient: gv.feeRecipient,
656
+ gasFees: gv.gasFees,
657
+ };
658
+ }
659
+
660
+ /**
661
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
662
+ */
663
+ private async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
664
+ try {
665
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
666
+ if (!lastBlockHeader) {
667
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
668
+ return;
669
+ }
670
+
671
+ // Get the last full block to determine checkpoint number
672
+ const lastBlock = await this.blockSource.getL2BlockNew(lastBlockHeader.getBlockNumber());
673
+ if (!lastBlock) {
674
+ this.log.warn(`Failed to get last block for blob upload`, proposalInfo);
675
+ return;
676
+ }
677
+
678
+ const blocks = await this.getBlocksForSlot(proposal.slotNumber, lastBlockHeader, lastBlock.checkpointNumber);
679
+ if (blocks.length === 0) {
680
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
681
+ return;
682
+ }
683
+
684
+ const blobFields = blocks.flatMap(b => b.toBlobFields());
685
+ const blobs: Blob[] = getBlobsPerL1Block(blobFields);
686
+ await this.blobClient.sendBlobsToFilestore(blobs);
687
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
688
+ ...proposalInfo,
689
+ numBlobs: blobs.length,
690
+ });
691
+ } catch (err) {
692
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
693
+ }
398
694
  }
399
695
 
400
696
  private slashInvalidBlock(proposal: BlockProposal) {
@@ -424,40 +720,55 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
424
720
  ]);
425
721
  }
426
722
 
427
- // TODO(palla/mbps): Block proposal should not require a checkpoint proposal
428
723
  async createBlockProposal(
429
- blockNumber: BlockNumber,
430
- header: CheckpointHeader,
724
+ blockHeader: BlockHeader,
725
+ indexWithinCheckpoint: number,
726
+ inHash: Fr,
431
727
  archive: Fr,
432
728
  txs: Tx[],
433
729
  proposerAddress: EthAddress | undefined,
434
730
  options: BlockProposalOptions,
435
731
  ): Promise<BlockProposal> {
436
732
  // TODO(palla/mbps): Prevent double proposals properly
437
- // if (this.previousProposal?.slotNumber === header.slotNumber) {
733
+ // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
438
734
  // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
439
735
  // return Promise.resolve(undefined);
440
736
  // }
441
737
 
442
- this.log.info(`Assembling block proposal for block ${blockNumber} slot ${header.slotNumber}`);
443
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
444
- ...options,
445
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
446
- });
738
+ this.log.info(
739
+ `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
740
+ );
741
+ const newProposal = await this.validationService.createBlockProposal(
742
+ blockHeader,
743
+ indexWithinCheckpoint,
744
+ inHash,
745
+ archive,
746
+ txs,
747
+ proposerAddress,
748
+ {
749
+ ...options,
750
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
751
+ },
752
+ );
447
753
  this.previousProposal = newProposal;
448
754
  return newProposal;
449
755
  }
450
756
 
451
- // TODO(palla/mbps): Effectively create a checkpoint proposal different from a block proposal
452
- createCheckpointProposal(
453
- header: CheckpointHeader,
757
+ async createCheckpointProposal(
758
+ checkpointHeader: CheckpointHeader,
454
759
  archive: Fr,
455
- txs: Tx[],
760
+ lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
456
761
  proposerAddress: EthAddress | undefined,
457
- options: BlockProposalOptions,
458
- ): Promise<BlockProposal> {
459
- this.log.info(`Assembling checkpoint proposal for slot ${header.slotNumber}`);
460
- return this.createBlockProposal(0 as BlockNumber, header, archive, txs, proposerAddress, options);
762
+ options: CheckpointProposalOptions,
763
+ ): Promise<CheckpointProposal> {
764
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
765
+ return await this.validationService.createCheckpointProposal(
766
+ checkpointHeader,
767
+ archive,
768
+ lastBlockInfo,
769
+ proposerAddress,
770
+ options,
771
+ );
461
772
  }
462
773
 
463
774
  async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
@@ -471,24 +782,28 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
471
782
  return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
472
783
  }
473
784
 
474
- async collectOwnAttestations(proposal: BlockProposal): Promise<BlockAttestation[]> {
475
- const slot = proposal.payload.header.slotNumber;
785
+ async collectOwnAttestations(proposal: CheckpointProposal): Promise<CheckpointAttestation[]> {
786
+ const slot = proposal.slotNumber;
476
787
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
477
788
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
478
- const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
789
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
479
790
 
480
791
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
481
792
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
482
793
  // due to inactivity for missed attestations.
483
- void this.p2pClient.broadcastAttestations(attestations).catch(err => {
794
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch(err => {
484
795
  this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
485
796
  });
486
797
  return attestations;
487
798
  }
488
799
 
489
- async collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]> {
490
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
491
- const slot = proposal.payload.header.slotNumber;
800
+ async collectAttestations(
801
+ proposal: CheckpointProposal,
802
+ required: number,
803
+ deadline: Date,
804
+ ): Promise<CheckpointAttestation[]> {
805
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
806
+ const slot = proposal.slotNumber;
492
807
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
493
808
 
494
809
  if (+deadline < this.dateProvider.now()) {
@@ -503,16 +818,16 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
503
818
  const proposalId = proposal.archive.toString();
504
819
  const myAddresses = this.getValidatorAddresses();
505
820
 
506
- let attestations: BlockAttestation[] = [];
821
+ let attestations: CheckpointAttestation[] = [];
507
822
  while (true) {
508
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
823
+ // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
509
824
  // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
510
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter(
825
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter(
511
826
  attestation => {
512
- if (!attestation.payload.equals(proposal.payload)) {
827
+ if (!attestation.archive.equals(proposal.archive)) {
513
828
  this.log.warn(
514
- `Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`,
515
- { attestationPayload: attestation.payload, proposalPayload: proposal.payload },
829
+ `Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`,
830
+ { attestationArchive: attestation.archive.toString(), proposalArchive: proposal.archive.toString() },
516
831
  );
517
832
  return false;
518
833
  }
@@ -553,15 +868,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
553
868
  }
554
869
  }
555
870
 
556
- private async createBlockAttestationsFromProposal(
557
- proposal: BlockProposal,
558
- attestors: EthAddress[] = [],
559
- ): Promise<BlockAttestation[]> {
560
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
561
- await this.p2pClient.addAttestations(attestations);
562
- return attestations;
563
- }
564
-
565
871
  private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
566
872
  const authRequest = AuthRequest.fromBuffer(msg);
567
873
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);