@aztec/validator-client 0.0.1-commit.54489865 → 0.0.1-commit.5914bae

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 (53) hide show
  1. package/README.md +62 -18
  2. package/dest/checkpoint_builder.d.ts +23 -14
  3. package/dest/checkpoint_builder.d.ts.map +1 -1
  4. package/dest/checkpoint_builder.js +125 -41
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +24 -0
  8. package/dest/duties/validation_service.d.ts +2 -2
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +6 -12
  11. package/dest/factory.d.ts +7 -4
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +6 -5
  14. package/dest/index.d.ts +2 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -2
  17. package/dest/key_store/ha_key_store.d.ts +1 -1
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -1
  19. package/dest/key_store/ha_key_store.js +3 -3
  20. package/dest/metrics.d.ts +10 -2
  21. package/dest/metrics.d.ts.map +1 -1
  22. package/dest/metrics.js +12 -0
  23. package/dest/proposal_handler.d.ts +94 -0
  24. package/dest/proposal_handler.d.ts.map +1 -0
  25. package/dest/{block_proposal_handler.js → proposal_handler.js} +373 -67
  26. package/dest/validator.d.ts +35 -21
  27. package/dest/validator.d.ts.map +1 -1
  28. package/dest/validator.js +164 -206
  29. package/package.json +19 -19
  30. package/src/checkpoint_builder.ts +145 -38
  31. package/src/config.ts +24 -0
  32. package/src/duties/validation_service.ts +12 -11
  33. package/src/factory.ts +9 -3
  34. package/src/index.ts +1 -2
  35. package/src/key_store/ha_key_store.ts +3 -3
  36. package/src/metrics.ts +19 -1
  37. package/src/proposal_handler.ts +903 -0
  38. package/src/validator.ts +222 -230
  39. package/dest/block_proposal_handler.d.ts +0 -63
  40. package/dest/block_proposal_handler.d.ts.map +0 -1
  41. package/dest/tx_validator/index.d.ts +0 -3
  42. package/dest/tx_validator/index.d.ts.map +0 -1
  43. package/dest/tx_validator/index.js +0 -2
  44. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  45. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  46. package/dest/tx_validator/nullifier_cache.js +0 -24
  47. package/dest/tx_validator/tx_validator_factory.d.ts +0 -19
  48. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  49. package/dest/tx_validator/tx_validator_factory.js +0 -54
  50. package/src/block_proposal_handler.ts +0 -555
  51. package/src/tx_validator/index.ts +0 -2
  52. package/src/tx_validator/nullifier_cache.ts +0 -30
  53. package/src/tx_validator/tx_validator_factory.ts +0 -154
package/src/validator.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
- import { type Blob, getBlobsPerL1Block } from '@aztec/blob-lib';
3
2
  import type { EpochCache } from '@aztec/epoch-cache';
4
3
  import {
5
4
  BlockNumber,
@@ -9,20 +8,18 @@ import {
9
8
  SlotNumber,
10
9
  } from '@aztec/foundation/branded-types';
11
10
  import { Fr } from '@aztec/foundation/curves/bn254';
12
- import { TimeoutError } from '@aztec/foundation/error';
13
11
  import type { EthAddress } from '@aztec/foundation/eth-address';
14
12
  import type { Signature } from '@aztec/foundation/eth-signature';
15
- import { type LogData, type Logger, createLogger } from '@aztec/foundation/log';
16
- import { retryUntil } from '@aztec/foundation/retry';
13
+ import { type Logger, createLogger } from '@aztec/foundation/log';
17
14
  import { RunningPromise } from '@aztec/foundation/running-promise';
18
15
  import { sleep } from '@aztec/foundation/sleep';
19
16
  import { DateProvider } from '@aztec/foundation/timer';
20
17
  import type { KeystoreManager } from '@aztec/node-keystore';
21
- import type { P2P, PeerId } from '@aztec/p2p';
18
+ import type { DuplicateAttestationInfo, DuplicateProposalInfo, P2P, PeerId } from '@aztec/p2p';
22
19
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
23
20
  import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
24
21
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
25
- import type { CommitteeAttestationsAndSigners, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
22
+ import type { CommitteeAttestationsAndSigners, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
26
23
  import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
27
24
  import type {
28
25
  CreateCheckpointProposalLastBlockData,
@@ -31,32 +28,33 @@ import type {
31
28
  ValidatorClientFullConfig,
32
29
  WorldStateSynchronizer,
33
30
  } from '@aztec/stdlib/interfaces/server';
34
- import { type L1ToL2MessageSource, accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
35
- import type {
36
- BlockProposal,
37
- BlockProposalOptions,
38
- CheckpointAttestation,
39
- CheckpointProposalCore,
40
- CheckpointProposalOptions,
31
+ import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
32
+ import {
33
+ type BlockProposal,
34
+ type BlockProposalOptions,
35
+ type CheckpointAttestation,
36
+ CheckpointProposal,
37
+ type CheckpointProposalCore,
38
+ type CheckpointProposalOptions,
41
39
  } from '@aztec/stdlib/p2p';
42
- import { CheckpointProposal } from '@aztec/stdlib/p2p';
43
40
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
44
- import type { BlockHeader, CheckpointGlobalVariables, Tx } from '@aztec/stdlib/tx';
41
+ import type { BlockHeader, Tx } from '@aztec/stdlib/tx';
45
42
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
46
43
  import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
47
- import { createHASigner } from '@aztec/validator-ha-signer/factory';
48
- import { DutyType, type SigningContext } from '@aztec/validator-ha-signer/types';
44
+ import { createHASigner, createSignerFromSharedDb } from '@aztec/validator-ha-signer/factory';
45
+ import { DutyType, type SigningContext, type SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
46
+ import type { ValidatorHASigner } from '@aztec/validator-ha-signer/validator-ha-signer';
49
47
 
50
48
  import { EventEmitter } from 'events';
51
49
  import type { TypedDataDefinition } from 'viem';
52
50
 
53
- import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
54
51
  import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
55
52
  import { ValidationService } from './duties/validation_service.js';
56
53
  import { HAKeyStore } from './key_store/ha_key_store.js';
57
54
  import type { ExtendedValidatorKeyStore } from './key_store/interface.js';
58
55
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
59
56
  import { ValidatorMetrics } from './metrics.js';
57
+ import { type BlockProposalValidationFailureReason, ProposalHandler } from './proposal_handler.js';
60
58
 
61
59
  // We maintain a set of proposers who have proposed invalid blocks.
62
60
  // Just cap the set to avoid unbounded growth.
@@ -76,29 +74,33 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
76
74
  private validationService: ValidationService;
77
75
  private metrics: ValidatorMetrics;
78
76
  private log: Logger;
79
-
80
77
  // Whether it has already registered handlers on the p2p client
81
78
  private hasRegisteredHandlers = false;
82
79
 
83
- // Used to check if we are sending the same proposal twice
84
- private previousProposal?: BlockProposal;
80
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */
81
+ private lastProposedBlock?: BlockProposal;
82
+
83
+ /** Tracks the last checkpoint proposal we created. */
84
+ private lastProposedCheckpoint?: CheckpointProposal;
85
85
 
86
86
  private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
87
87
  private epochCacheUpdateLoop: RunningPromise;
88
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */
89
+ private lastAttestedEpochByAttester: Map<string, EpochNumber> = new Map();
88
90
 
89
91
  private proposersOfInvalidBlocks: Set<string> = new Set();
90
92
 
93
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */
94
+ private lastAttestedProposal?: CheckpointProposalCore;
95
+
91
96
  protected constructor(
92
97
  private keyStore: ExtendedValidatorKeyStore,
93
98
  private epochCache: EpochCache,
94
99
  private p2pClient: P2P,
95
- private blockProposalHandler: BlockProposalHandler,
96
- private blockSource: L2BlockSource,
97
- private checkpointsBuilder: FullNodeCheckpointsBuilder,
98
- private worldState: WorldStateSynchronizer,
99
- private l1ToL2MessageSource: L1ToL2MessageSource,
100
+ private proposalHandler: ProposalHandler,
100
101
  private config: ValidatorClientFullConfig,
101
102
  private blobClient: BlobClientInterface,
103
+ private haSigner: ValidatorHASigner | undefined,
102
104
  private dateProvider: DateProvider = new DateProvider(),
103
105
  telemetry: TelemetryClient = getTelemetryClient(),
104
106
  log = createLogger('validator'),
@@ -152,6 +154,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
152
154
  this.log.trace(`No committee found for slot`);
153
155
  return;
154
156
  }
157
+ this.metrics.setCurrentEpoch(epoch);
155
158
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
156
159
  const me = this.getValidatorAddresses();
157
160
  const committeeSet = new Set(committee.map(v => v.toString()));
@@ -185,12 +188,14 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
185
188
  blobClient: BlobClientInterface,
186
189
  dateProvider: DateProvider = new DateProvider(),
187
190
  telemetry: TelemetryClient = getTelemetryClient(),
191
+ slashingProtectionDb?: SlashingProtectionDatabase,
188
192
  ) {
189
193
  const metrics = new ValidatorMetrics(telemetry);
190
194
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
191
195
  txsPermitted: !config.disableTransactions,
196
+ maxTxsPerBlock: config.validateMaxTxsPerBlock,
192
197
  });
193
- const blockProposalHandler = new BlockProposalHandler(
198
+ const proposalHandler = new ProposalHandler(
194
199
  checkpointsBuilder,
195
200
  worldState,
196
201
  blockSource,
@@ -199,33 +204,39 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
199
204
  blockProposalValidator,
200
205
  epochCache,
201
206
  config,
207
+ blobClient,
202
208
  metrics,
203
209
  dateProvider,
204
210
  telemetry,
205
211
  );
206
212
 
207
- let validatorKeyStore: ExtendedValidatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
208
- if (config.haSigningEnabled) {
213
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
214
+ let validatorKeyStore: ExtendedValidatorKeyStore = nodeKeystoreAdapter;
215
+ let haSigner: ValidatorHASigner | undefined;
216
+ if (slashingProtectionDb) {
217
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
218
+ const { signer } = createSignerFromSharedDb(slashingProtectionDb, config);
219
+ haSigner = signer;
220
+ validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, signer);
221
+ } else if (config.haSigningEnabled) {
209
222
  // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
210
223
  const haConfig = {
211
224
  ...config,
212
225
  maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000,
213
226
  };
214
227
  const { signer } = await createHASigner(haConfig);
215
- validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
228
+ haSigner = signer;
229
+ validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, signer);
216
230
  }
217
231
 
218
232
  const validator = new ValidatorClient(
219
233
  validatorKeyStore,
220
234
  epochCache,
221
235
  p2pClient,
222
- blockProposalHandler,
223
- blockSource,
224
- checkpointsBuilder,
225
- worldState,
226
- l1ToL2MessageSource,
236
+ proposalHandler,
227
237
  config,
228
238
  blobClient,
239
+ haSigner,
229
240
  dateProvider,
230
241
  telemetry,
231
242
  );
@@ -239,8 +250,8 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
239
250
  .filter(addr => !this.config.disabledValidators.some(disabled => disabled.equals(addr)));
240
251
  }
241
252
 
242
- public getBlockProposalHandler() {
243
- return this.blockProposalHandler;
253
+ public getProposalHandler() {
254
+ return this.proposalHandler;
244
255
  }
245
256
 
246
257
  public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
@@ -263,6 +274,28 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
263
274
  this.config = { ...this.config, ...config };
264
275
  }
265
276
 
277
+ public reloadKeystore(newManager: KeystoreManager): void {
278
+ if (this.config.haSigningEnabled && !this.haSigner) {
279
+ this.log.warn(
280
+ 'HA signing is enabled in config but was not initialized at startup. ' +
281
+ 'Restart the node to enable HA signing.',
282
+ );
283
+ } else if (!this.config.haSigningEnabled && this.haSigner) {
284
+ this.log.warn(
285
+ 'HA signing was disabled via config update but the HA signer is still active. ' +
286
+ 'Restart the node to fully disable HA signing.',
287
+ );
288
+ }
289
+
290
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
291
+ if (this.haSigner) {
292
+ this.keyStore = new HAKeyStore(newAdapter, this.haSigner);
293
+ } else {
294
+ this.keyStore = newAdapter;
295
+ }
296
+ this.validationService = new ValidationService(this.keyStore, this.log.createChild('validation-service'));
297
+ }
298
+
266
299
  public async start() {
267
300
  if (this.epochCacheUpdateLoop.isRunning()) {
268
301
  this.log.warn(`Validator client already started`);
@@ -309,6 +342,16 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
309
342
  ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
310
343
  this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
311
344
 
345
+ // Duplicate proposal handler - triggers slashing for equivocation
346
+ this.p2pClient.registerDuplicateProposalCallback((info: DuplicateProposalInfo) => {
347
+ this.handleDuplicateProposal(info);
348
+ });
349
+
350
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
351
+ this.p2pClient.registerDuplicateAttestationCallback((info: DuplicateAttestationInfo) => {
352
+ this.handleDuplicateAttestation(info);
353
+ });
354
+
312
355
  const myAddresses = this.getValidatorAddresses();
313
356
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
314
357
 
@@ -336,6 +379,14 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
336
379
  return false;
337
380
  }
338
381
 
382
+ // Log self-proposals from HA peers (same validator key on different nodes)
383
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
384
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
385
+ proposer: proposer.toString(),
386
+ slotNumber,
387
+ });
388
+ }
389
+
339
390
  // Check if we're in the committee (for metrics purposes)
340
391
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
341
392
  const partOfCommittee = inCommittee.length > 0;
@@ -358,16 +409,17 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
358
409
  alwaysReexecuteBlockProposals ||
359
410
  this.blobClient.canUpload();
360
411
 
361
- const validationResult = await this.blockProposalHandler.handleBlockProposal(
412
+ const validationResult = await this.proposalHandler.handleBlockProposal(
362
413
  proposal,
363
414
  proposalSender,
364
415
  !!shouldReexecute && !escapeHatchOpen,
365
416
  );
366
417
 
367
418
  if (!validationResult.isValid) {
368
- this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
369
-
370
419
  const reason = validationResult.reason || 'unknown';
420
+
421
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
422
+
371
423
  // Classify failure reason: bad proposal vs node issue
372
424
  const badProposalReasons: BlockProposalValidationFailureReason[] = [
373
425
  'invalid_proposal',
@@ -431,44 +483,40 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
431
483
  return undefined;
432
484
  }
433
485
 
434
- // Reject proposals with invalid signatures
435
- if (!proposer) {
436
- this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
486
+ // Ignore proposals from ourselves (may happen in HA setups)
487
+ if (proposer && this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
488
+ this.log.debug(`Ignoring block proposal from self for slot ${slotNumber}`, {
489
+ proposer: proposer.toString(),
490
+ slotNumber,
491
+ });
437
492
  return undefined;
438
493
  }
439
494
 
440
- // Check that I have any address in current committee before attesting
495
+ // Check that I have any address in the committee where this checkpoint will land before attesting
441
496
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
442
497
  const partOfCommittee = inCommittee.length > 0;
443
498
 
444
499
  const proposalInfo = {
445
500
  slotNumber,
446
501
  archive: proposal.archive.toString(),
447
- proposer: proposer.toString(),
448
- txCount: proposal.txHashes.length,
502
+ proposer: proposer?.toString(),
449
503
  };
450
504
  this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
451
505
  ...proposalInfo,
452
- txHashes: proposal.txHashes.map(t => t.toString()),
453
506
  fishermanMode: this.config.fishermanMode || false,
454
507
  });
455
508
 
456
- // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
509
+ // Validate the checkpoint proposal and upload blobs (unless skipCheckpointProposalValidation is set)
457
510
  if (this.config.skipCheckpointProposalValidation) {
458
511
  this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
459
512
  } else {
460
- const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
513
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
461
514
  if (!validationResult.isValid) {
462
515
  this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
463
516
  return undefined;
464
517
  }
465
518
  }
466
519
 
467
- // Upload blobs to filestore if we can (fire and forget)
468
- if (this.blobClient.canUpload()) {
469
- void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
470
- }
471
-
472
520
  // Check that I have any address in current committee before attesting
473
521
  // In fisherman mode, we still create attestations for validation even if not in committee
474
522
  if (!partOfCommittee && !this.config.fishermanMode) {
@@ -485,6 +533,17 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
485
533
 
486
534
  this.metrics.incSuccessfulAttestations(inCommittee.length);
487
535
 
536
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
537
+ const proposalEpoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
538
+ for (const attester of inCommittee) {
539
+ const key = attester.toString();
540
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
541
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
542
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
543
+ this.metrics.incAttestedEpochCount(attester);
544
+ }
545
+ }
546
+
488
547
  // Determine which validators should attest
489
548
  let attestors: EthAddress[];
490
549
  if (partOfCommittee) {
@@ -510,188 +569,46 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
510
569
  return undefined;
511
570
  }
512
571
 
513
- return this.createCheckpointAttestationsFromProposal(proposal, attestors);
514
- }
515
-
516
- private async createCheckpointAttestationsFromProposal(
517
- proposal: CheckpointProposalCore,
518
- attestors: EthAddress[] = [],
519
- ): Promise<CheckpointAttestation[]> {
520
- const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
521
- await this.p2pClient.addCheckpointAttestations(attestations);
522
- return attestations;
572
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors);
523
573
  }
524
574
 
525
575
  /**
526
- * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
527
- * @returns Validation result with isValid flag and reason if invalid.
576
+ * Checks if we should attest to a slot based on equivocation prevention rules.
577
+ * @returns true if we should attest, false if we should skip
528
578
  */
529
- private async validateCheckpointProposal(
530
- proposal: CheckpointProposalCore,
531
- proposalInfo: LogData,
532
- ): Promise<{ isValid: true } | { isValid: false; reason: string }> {
533
- const slot = proposal.slotNumber;
534
- const timeoutSeconds = 10; // TODO(palla/mbps): This should map to the timetable settings
535
-
536
- // Wait for last block to sync by archive
537
- let lastBlockHeader: BlockHeader | undefined;
538
- try {
539
- lastBlockHeader = await retryUntil(
540
- async () => {
541
- await this.blockSource.syncImmediate();
542
- return this.blockSource.getBlockHeaderByArchive(proposal.archive);
543
- },
544
- `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
545
- timeoutSeconds,
546
- 0.5,
547
- );
548
- } catch (err) {
549
- if (err instanceof TimeoutError) {
550
- this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
551
- return { isValid: false, reason: 'last_block_not_found' };
552
- }
553
- this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
554
- return { isValid: false, reason: 'block_fetch_error' };
555
- }
556
-
557
- if (!lastBlockHeader) {
558
- this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
559
- return { isValid: false, reason: 'last_block_not_found' };
560
- }
561
-
562
- // Get all full blocks for the slot and checkpoint
563
- const blocks = await this.blockSource.getBlocksForSlot(slot);
564
- if (blocks.length === 0) {
565
- this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
566
- return { isValid: false, reason: 'no_blocks_for_slot' };
579
+ private shouldAttestToSlot(slotNumber: SlotNumber): boolean {
580
+ // If attestToEquivocatedProposals is true, always allow
581
+ if (this.config.attestToEquivocatedProposals) {
582
+ return true;
567
583
  }
568
584
 
569
- this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
570
- ...proposalInfo,
571
- blockNumbers: blocks.map(b => b.number),
572
- });
573
-
574
- // Get checkpoint constants from first block
575
- const firstBlock = blocks[0];
576
- const constants = this.extractCheckpointConstants(firstBlock);
577
- const checkpointNumber = firstBlock.checkpointNumber;
578
-
579
- // Get L1-to-L2 messages for this checkpoint
580
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
581
-
582
- // Compute the previous checkpoint out hashes for the epoch.
583
- // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch the
584
- // actual checkpoints and the blocks/txs in them.
585
- const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
586
- const previousCheckpoints = (await this.blockSource.getCheckpointsForEpoch(epoch))
587
- .filter(b => b.number < checkpointNumber)
588
- .sort((a, b) => a.number - b.number);
589
- const previousCheckpointOutHashes = previousCheckpoints.map(c => c.getCheckpointOutHash());
590
-
591
- // Fork world state at the block before the first block
592
- const parentBlockNumber = BlockNumber(firstBlock.number - 1);
593
- const fork = await this.worldState.fork(parentBlockNumber);
594
-
595
- try {
596
- // Create checkpoint builder with all existing blocks
597
- const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
598
- checkpointNumber,
599
- constants,
600
- l1ToL2Messages,
601
- previousCheckpointOutHashes,
602
- fork,
603
- blocks,
604
- this.log.getBindings(),
585
+ // Check if incoming slot is strictly greater than last attested
586
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
587
+ this.log.warn(
588
+ `Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`,
605
589
  );
606
-
607
- // Complete the checkpoint to get computed values
608
- const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
609
-
610
- // Compare checkpoint header with proposal
611
- if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
612
- this.log.warn(`Checkpoint header mismatch`, {
613
- ...proposalInfo,
614
- computed: computedCheckpoint.header.toInspect(),
615
- proposal: proposal.checkpointHeader.toInspect(),
616
- });
617
- return { isValid: false, reason: 'checkpoint_header_mismatch' };
618
- }
619
-
620
- // Compare archive root with proposal
621
- if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
622
- this.log.warn(`Archive root mismatch`, {
623
- ...proposalInfo,
624
- computed: computedCheckpoint.archive.root.toString(),
625
- proposal: proposal.archive.toString(),
626
- });
627
- return { isValid: false, reason: 'archive_mismatch' };
628
- }
629
-
630
- // Check that the accumulated epoch out hash matches the value in the proposal.
631
- // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
632
- const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
633
- const computedEpochOutHash = accumulateCheckpointOutHashes([...previousCheckpointOutHashes, checkpointOutHash]);
634
- const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
635
- if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
636
- this.log.warn(`Epoch out hash mismatch`, {
637
- proposalEpochOutHash: proposalEpochOutHash.toString(),
638
- computedEpochOutHash: computedEpochOutHash.toString(),
639
- checkpointOutHash: checkpointOutHash.toString(),
640
- previousCheckpointOutHashes: previousCheckpointOutHashes.map(h => h.toString()),
641
- ...proposalInfo,
642
- });
643
- return { isValid: false, reason: 'out_hash_mismatch' };
644
- }
645
-
646
- this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
647
- return { isValid: true };
648
- } finally {
649
- await fork.close();
590
+ return false;
650
591
  }
651
- }
652
592
 
653
- /**
654
- * Extract checkpoint global variables from a block.
655
- */
656
- private extractCheckpointConstants(block: L2Block): CheckpointGlobalVariables {
657
- const gv = block.header.globalVariables;
658
- return {
659
- chainId: gv.chainId,
660
- version: gv.version,
661
- slotNumber: gv.slotNumber,
662
- coinbase: gv.coinbase,
663
- feeRecipient: gv.feeRecipient,
664
- gasFees: gv.gasFees,
665
- };
593
+ return true;
666
594
  }
667
595
 
668
- /**
669
- * Uploads blobs for a checkpoint to the filestore (fire and forget).
670
- */
671
- private async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
672
- try {
673
- const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
674
- if (!lastBlockHeader) {
675
- this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
676
- return;
677
- }
596
+ private async createCheckpointAttestationsFromProposal(
597
+ proposal: CheckpointProposalCore,
598
+ attestors: EthAddress[] = [],
599
+ ): Promise<CheckpointAttestation[] | undefined> {
600
+ // Equivocation check: must happen right before signing to minimize the race window
601
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
602
+ return undefined;
603
+ }
678
604
 
679
- const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
680
- if (blocks.length === 0) {
681
- this.log.warn(`No blocks found for blob upload`, proposalInfo);
682
- return;
683
- }
605
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
684
606
 
685
- const blobFields = blocks.flatMap(b => b.toBlobFields());
686
- const blobs: Blob[] = getBlobsPerL1Block(blobFields);
687
- await this.blobClient.sendBlobsToFilestore(blobs);
688
- this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
689
- ...proposalInfo,
690
- numBlobs: blobs.length,
691
- });
692
- } catch (err) {
693
- this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
694
- }
607
+ // Track the proposal we attested to (to prevent equivocation)
608
+ this.lastAttestedProposal = proposal;
609
+
610
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
611
+ return attestations;
695
612
  }
696
613
 
697
614
  private slashInvalidBlock(proposal: BlockProposal) {
@@ -721,6 +638,52 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
721
638
  ]);
722
639
  }
723
640
 
641
+ /**
642
+ * Handle detection of a duplicate proposal (equivocation).
643
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
644
+ */
645
+ private handleDuplicateProposal(info: DuplicateProposalInfo): void {
646
+ const { slot, proposer, type } = info;
647
+
648
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
649
+ proposer: proposer.toString(),
650
+ slot,
651
+ type,
652
+ });
653
+
654
+ // Emit slash event
655
+ this.emit(WANT_TO_SLASH_EVENT, [
656
+ {
657
+ validator: proposer,
658
+ amount: this.config.slashDuplicateProposalPenalty,
659
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
660
+ epochOrSlot: BigInt(slot),
661
+ },
662
+ ]);
663
+ }
664
+
665
+ /**
666
+ * Handle detection of a duplicate attestation (equivocation).
667
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
668
+ */
669
+ private handleDuplicateAttestation(info: DuplicateAttestationInfo): void {
670
+ const { slot, attester } = info;
671
+
672
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
673
+ attester: attester.toString(),
674
+ slot,
675
+ });
676
+
677
+ this.emit(WANT_TO_SLASH_EVENT, [
678
+ {
679
+ validator: attester,
680
+ amount: this.config.slashDuplicateAttestationPenalty,
681
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
682
+ epochOrSlot: BigInt(slot),
683
+ },
684
+ ]);
685
+ }
686
+
724
687
  async createBlockProposal(
725
688
  blockHeader: BlockHeader,
726
689
  indexWithinCheckpoint: IndexWithinCheckpoint,
@@ -730,11 +693,19 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
730
693
  proposerAddress: EthAddress | undefined,
731
694
  options: BlockProposalOptions = {},
732
695
  ): Promise<BlockProposal> {
733
- // TODO(palla/mbps): Prevent double proposals properly
734
- // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
735
- // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
736
- // return Promise.resolve(undefined);
737
- // }
696
+ // Validate that we're not creating a proposal for an older or equal position
697
+ if (this.lastProposedBlock) {
698
+ const lastSlot = this.lastProposedBlock.slotNumber;
699
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
700
+ const newSlot = blockHeader.globalVariables.slotNumber;
701
+
702
+ if (newSlot < lastSlot || (newSlot === lastSlot && indexWithinCheckpoint <= lastIndex)) {
703
+ throw new Error(
704
+ `Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` +
705
+ `already proposed block for slot ${lastSlot} index ${lastIndex}`,
706
+ );
707
+ }
708
+ }
738
709
 
739
710
  this.log.info(
740
711
  `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
@@ -751,25 +722,42 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
751
722
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
752
723
  },
753
724
  );
754
- this.previousProposal = newProposal;
725
+ this.lastProposedBlock = newProposal;
755
726
  return newProposal;
756
727
  }
757
728
 
758
729
  async createCheckpointProposal(
759
730
  checkpointHeader: CheckpointHeader,
760
731
  archive: Fr,
732
+ feeAssetPriceModifier: bigint,
761
733
  lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
762
734
  proposerAddress: EthAddress | undefined,
763
735
  options: CheckpointProposalOptions = {},
764
736
  ): Promise<CheckpointProposal> {
737
+ // Validate that we're not creating a proposal for an older or equal slot
738
+ if (this.lastProposedCheckpoint) {
739
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
740
+ const newSlot = checkpointHeader.slotNumber;
741
+
742
+ if (newSlot <= lastSlot) {
743
+ throw new Error(
744
+ `Cannot create checkpoint proposal for slot ${newSlot}: ` +
745
+ `already proposed checkpoint for slot ${lastSlot}`,
746
+ );
747
+ }
748
+ }
749
+
765
750
  this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
766
- return await this.validationService.createCheckpointProposal(
751
+ const newProposal = await this.validationService.createCheckpointProposal(
767
752
  checkpointHeader,
768
753
  archive,
754
+ feeAssetPriceModifier,
769
755
  lastBlockInfo,
770
756
  proposerAddress,
771
757
  options,
772
758
  );
759
+ this.lastProposedCheckpoint = newProposal;
760
+ return newProposal;
773
761
  }
774
762
 
775
763
  async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
@@ -791,6 +779,10 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
791
779
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
792
780
  const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
793
781
 
782
+ if (!attestations) {
783
+ return [];
784
+ }
785
+
794
786
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
795
787
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
796
788
  // due to inactivity for missed attestations.