@aztec/validator-client 0.0.1-commit.9372f48 → 0.0.1-commit.949a33fd8

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 (54) hide show
  1. package/README.md +60 -18
  2. package/dest/checkpoint_builder.d.ts +21 -8
  3. package/dest/checkpoint_builder.d.ts.map +1 -1
  4. package/dest/checkpoint_builder.js +124 -46
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +33 -7
  8. package/dest/duties/validation_service.d.ts +11 -12
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +27 -45
  11. package/dest/factory.d.ts +7 -4
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +10 -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 +14 -2
  21. package/dest/metrics.d.ts.map +1 -1
  22. package/dest/metrics.js +24 -0
  23. package/dest/proposal_handler.d.ts +108 -0
  24. package/dest/proposal_handler.d.ts.map +1 -0
  25. package/dest/proposal_handler.js +974 -0
  26. package/dest/validator.d.ts +46 -23
  27. package/dest/validator.d.ts.map +1 -1
  28. package/dest/validator.js +204 -200
  29. package/package.json +19 -19
  30. package/src/checkpoint_builder.ts +142 -39
  31. package/src/config.ts +33 -6
  32. package/src/duties/validation_service.ts +53 -53
  33. package/src/factory.ts +14 -3
  34. package/src/index.ts +1 -2
  35. package/src/key_store/ha_key_store.ts +3 -3
  36. package/src/metrics.ts +37 -1
  37. package/src/proposal_handler.ts +1042 -0
  38. package/src/validator.ts +293 -229
  39. package/dest/block_proposal_handler.d.ts +0 -63
  40. package/dest/block_proposal_handler.d.ts.map +0 -1
  41. package/dest/block_proposal_handler.js +0 -546
  42. package/dest/tx_validator/index.d.ts +0 -3
  43. package/dest/tx_validator/index.d.ts.map +0 -1
  44. package/dest/tx_validator/index.js +0 -2
  45. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  46. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  47. package/dest/tx_validator/nullifier_cache.js +0 -24
  48. package/dest/tx_validator/tx_validator_factory.d.ts +0 -19
  49. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  50. package/dest/tx_validator/tx_validator_factory.js +0 -54
  51. package/src/block_proposal_handler.ts +0 -555
  52. package/src/tx_validator/index.ts +0 -2
  53. package/src/tx_validator/nullifier_cache.ts +0 -30
  54. package/src/tx_validator/tx_validator_factory.ts +0 -154
package/src/validator.ts CHANGED
@@ -1,62 +1,59 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import { type Blob, getBlobsPerL1Block } from '@aztec/blob-lib';
3
3
  import type { EpochCache } from '@aztec/epoch-cache';
4
- import {
5
- BlockNumber,
6
- CheckpointNumber,
7
- EpochNumber,
8
- IndexWithinCheckpoint,
9
- SlotNumber,
10
- } from '@aztec/foundation/branded-types';
4
+ import { CheckpointNumber, EpochNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
11
5
  import { Fr } from '@aztec/foundation/curves/bn254';
12
- import { TimeoutError } from '@aztec/foundation/error';
13
6
  import type { EthAddress } from '@aztec/foundation/eth-address';
14
7
  import type { Signature } from '@aztec/foundation/eth-signature';
15
8
  import { type LogData, type Logger, createLogger } from '@aztec/foundation/log';
16
- import { retryUntil } from '@aztec/foundation/retry';
17
9
  import { RunningPromise } from '@aztec/foundation/running-promise';
18
10
  import { sleep } from '@aztec/foundation/sleep';
19
11
  import { DateProvider } from '@aztec/foundation/timer';
20
12
  import type { KeystoreManager } from '@aztec/node-keystore';
21
- import type { P2P, PeerId } from '@aztec/p2p';
13
+ import type { DuplicateAttestationInfo, DuplicateProposalInfo, P2P, PeerId } from '@aztec/p2p';
22
14
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
23
15
  import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
24
16
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
25
- import type { CommitteeAttestationsAndSigners, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
17
+ import type { CommitteeAttestationsAndSigners, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
26
18
  import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
27
19
  import type {
28
- CreateCheckpointProposalLastBlockData,
29
20
  ITxProvider,
30
21
  Validator,
31
22
  ValidatorClientFullConfig,
32
23
  WorldStateSynchronizer,
33
24
  } 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,
25
+ import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
26
+ import {
27
+ type BlockProposal,
28
+ type BlockProposalOptions,
29
+ type CheckpointAttestation,
30
+ CheckpointProposal,
31
+ type CheckpointProposalCore,
32
+ type CheckpointProposalOptions,
33
+ type CoordinationSignatureContext,
41
34
  } from '@aztec/stdlib/p2p';
42
- import { CheckpointProposal } from '@aztec/stdlib/p2p';
43
35
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
44
- import type { BlockHeader, CheckpointGlobalVariables, Tx } from '@aztec/stdlib/tx';
36
+ import type { BlockHeader, Tx } from '@aztec/stdlib/tx';
45
37
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
46
38
  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';
39
+ import {
40
+ createHASigner,
41
+ createLocalSignerWithProtection,
42
+ createSignerFromSharedDb,
43
+ } from '@aztec/validator-ha-signer/factory';
44
+ import { DutyType, type SigningContext, type SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
45
+ import type { ValidatorHASigner } from '@aztec/validator-ha-signer/validator-ha-signer';
49
46
 
50
47
  import { EventEmitter } from 'events';
51
48
  import type { TypedDataDefinition } from 'viem';
52
49
 
53
- import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
54
50
  import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
55
51
  import { ValidationService } from './duties/validation_service.js';
56
52
  import { HAKeyStore } from './key_store/ha_key_store.js';
57
53
  import type { ExtendedValidatorKeyStore } from './key_store/interface.js';
58
54
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
59
55
  import { ValidatorMetrics } from './metrics.js';
56
+ import { type BlockProposalValidationFailureReason, ProposalHandler } from './proposal_handler.js';
60
57
 
61
58
  // We maintain a set of proposers who have proposed invalid blocks.
62
59
  // Just cap the set to avoid unbounded growth.
@@ -76,29 +73,37 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
76
73
  private validationService: ValidationService;
77
74
  private metrics: ValidatorMetrics;
78
75
  private log: Logger;
79
-
80
76
  // Whether it has already registered handlers on the p2p client
81
77
  private hasRegisteredHandlers = false;
82
78
 
83
- // Used to check if we are sending the same proposal twice
84
- private previousProposal?: BlockProposal;
79
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */
80
+ private lastProposedBlock?: BlockProposal;
81
+
82
+ /** Tracks the last checkpoint proposal we created. */
83
+ private lastProposedCheckpoint?: CheckpointProposal;
85
84
 
86
85
  private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
87
86
  private epochCacheUpdateLoop: RunningPromise;
87
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */
88
+ private lastAttestedEpochByAttester: Map<string, EpochNumber> = new Map();
88
89
 
89
90
  private proposersOfInvalidBlocks: Set<string> = new Set();
90
91
 
92
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */
93
+ private lastAttestedProposal?: CheckpointProposalCore;
94
+
91
95
  protected constructor(
92
96
  private keyStore: ExtendedValidatorKeyStore,
93
97
  private epochCache: EpochCache,
94
98
  private p2pClient: P2P,
95
- private blockProposalHandler: BlockProposalHandler,
99
+ private proposalHandler: ProposalHandler,
96
100
  private blockSource: L2BlockSource,
97
101
  private checkpointsBuilder: FullNodeCheckpointsBuilder,
98
102
  private worldState: WorldStateSynchronizer,
99
103
  private l1ToL2MessageSource: L1ToL2MessageSource,
100
104
  private config: ValidatorClientFullConfig,
101
105
  private blobClient: BlobClientInterface,
106
+ private slashingProtectionSigner: ValidatorHASigner,
102
107
  private dateProvider: DateProvider = new DateProvider(),
103
108
  telemetry: TelemetryClient = getTelemetryClient(),
104
109
  log = createLogger('validator'),
@@ -111,7 +116,11 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
111
116
  this.tracer = telemetry.getTracer('Validator');
112
117
  this.metrics = new ValidatorMetrics(telemetry);
113
118
 
114
- this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
119
+ this.validationService = new ValidationService(
120
+ keyStore,
121
+ this.getSignatureContext(),
122
+ this.log.createChild('validation-service'),
123
+ );
115
124
 
116
125
  // Refresh epoch cache every second to trigger alert if participation in committee changes
117
126
  this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
@@ -152,6 +161,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
152
161
  this.log.trace(`No committee found for slot`);
153
162
  return;
154
163
  }
164
+ this.metrics.setCurrentEpoch(epoch);
155
165
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
156
166
  const me = this.getValidatorAddresses();
157
167
  const committeeSet = new Set(committee.map(v => v.toString()));
@@ -185,12 +195,18 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
185
195
  blobClient: BlobClientInterface,
186
196
  dateProvider: DateProvider = new DateProvider(),
187
197
  telemetry: TelemetryClient = getTelemetryClient(),
198
+ slashingProtectionDb?: SlashingProtectionDatabase,
188
199
  ) {
189
200
  const metrics = new ValidatorMetrics(telemetry);
190
201
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
191
202
  txsPermitted: !config.disableTransactions,
203
+ maxTxsPerBlock: config.validateMaxTxsPerBlock,
204
+ signatureContext: {
205
+ chainId: config.l1ChainId,
206
+ rollupAddress: config.l1Contracts.rollupAddress,
207
+ },
192
208
  });
193
- const blockProposalHandler = new BlockProposalHandler(
209
+ const proposalHandler = new ProposalHandler(
194
210
  checkpointsBuilder,
195
211
  worldState,
196
212
  blockSource,
@@ -199,33 +215,54 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
199
215
  blockProposalValidator,
200
216
  epochCache,
201
217
  config,
218
+ blobClient,
202
219
  metrics,
203
220
  dateProvider,
204
221
  telemetry,
222
+ undefined,
205
223
  );
206
224
 
207
- let validatorKeyStore: ExtendedValidatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
208
- if (config.haSigningEnabled) {
225
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
226
+ let slashingProtectionSigner: ValidatorHASigner;
227
+ if (slashingProtectionDb) {
228
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
229
+ ({ signer: slashingProtectionSigner } = createSignerFromSharedDb(slashingProtectionDb, config, {
230
+ telemetryClient: telemetry,
231
+ dateProvider,
232
+ }));
233
+ } else if (config.haSigningEnabled) {
234
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
209
235
  // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
210
236
  const haConfig = {
211
237
  ...config,
212
238
  maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000,
213
239
  };
214
- const { signer } = await createHASigner(haConfig);
215
- validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
240
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
241
+ telemetryClient: telemetry,
242
+ dateProvider,
243
+ }));
244
+ } else {
245
+ // Single-node mode: use LMDB-backed local signing protection.
246
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
247
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
248
+ telemetryClient: telemetry,
249
+ dateProvider,
250
+ }));
216
251
  }
252
+ const validatorKeyStore: ExtendedValidatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
217
253
 
218
254
  const validator = new ValidatorClient(
219
255
  validatorKeyStore,
220
256
  epochCache,
221
257
  p2pClient,
222
- blockProposalHandler,
258
+ proposalHandler,
223
259
  blockSource,
224
260
  checkpointsBuilder,
225
261
  worldState,
226
262
  l1ToL2MessageSource,
227
263
  config,
228
264
  blobClient,
265
+ slashingProtectionSigner,
229
266
  dateProvider,
230
267
  telemetry,
231
268
  );
@@ -239,14 +276,21 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
239
276
  .filter(addr => !this.config.disabledValidators.some(disabled => disabled.equals(addr)));
240
277
  }
241
278
 
242
- public getBlockProposalHandler() {
243
- return this.blockProposalHandler;
279
+ public getProposalHandler() {
280
+ return this.proposalHandler;
244
281
  }
245
282
 
246
283
  public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
247
284
  return this.keyStore.signTypedDataWithAddress(addr, msg, context);
248
285
  }
249
286
 
287
+ private getSignatureContext(): CoordinationSignatureContext {
288
+ return {
289
+ chainId: this.config.l1ChainId,
290
+ rollupAddress: this.config.l1Contracts.rollupAddress,
291
+ };
292
+ }
293
+
250
294
  public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
251
295
  return this.keyStore.getCoinbaseAddress(attestor);
252
296
  }
@@ -263,6 +307,16 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
263
307
  this.config = { ...this.config, ...config };
264
308
  }
265
309
 
310
+ public reloadKeystore(newManager: KeystoreManager): void {
311
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
312
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
313
+ this.validationService = new ValidationService(
314
+ this.keyStore,
315
+ this.getSignatureContext(),
316
+ this.log.createChild('validation-service'),
317
+ );
318
+ }
319
+
266
320
  public async start() {
267
321
  if (this.epochCacheUpdateLoop.isRunning()) {
268
322
  this.log.warn(`Validator client already started`);
@@ -307,7 +361,17 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
307
361
  checkpoint: CheckpointProposalCore,
308
362
  proposalSender: PeerId,
309
363
  ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
310
- this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
364
+ this.p2pClient.registerValidatorCheckpointProposalHandler(checkpointHandler);
365
+
366
+ // Duplicate proposal handler - triggers slashing for equivocation
367
+ this.p2pClient.registerDuplicateProposalCallback((info: DuplicateProposalInfo) => {
368
+ this.handleDuplicateProposal(info);
369
+ });
370
+
371
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
372
+ this.p2pClient.registerDuplicateAttestationCallback((info: DuplicateAttestationInfo) => {
373
+ this.handleDuplicateAttestation(info);
374
+ });
311
375
 
312
376
  const myAddresses = this.getValidatorAddresses();
313
377
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
@@ -336,6 +400,14 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
336
400
  return false;
337
401
  }
338
402
 
403
+ // Log self-proposals from HA peers (same validator key on different nodes)
404
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
405
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
406
+ proposer: proposer.toString(),
407
+ slotNumber,
408
+ });
409
+ }
410
+
339
411
  // Check if we're in the committee (for metrics purposes)
340
412
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
341
413
  const partOfCommittee = inCommittee.length > 0;
@@ -349,25 +421,25 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
349
421
 
350
422
  // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
351
423
  // In fisherman mode, we always reexecute to validate proposals.
352
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
353
- this.config;
424
+ const { slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
354
425
  const shouldReexecute =
355
426
  fishermanMode ||
356
- (slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
357
- (partOfCommittee && validatorReexecute) ||
427
+ slashBroadcastedInvalidBlockPenalty > 0n ||
428
+ partOfCommittee ||
358
429
  alwaysReexecuteBlockProposals ||
359
430
  this.blobClient.canUpload();
360
431
 
361
- const validationResult = await this.blockProposalHandler.handleBlockProposal(
432
+ const validationResult = await this.proposalHandler.handleBlockProposal(
362
433
  proposal,
363
434
  proposalSender,
364
435
  !!shouldReexecute && !escapeHatchOpen,
365
436
  );
366
437
 
367
438
  if (!validationResult.isValid) {
368
- this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
369
-
370
439
  const reason = validationResult.reason || 'unknown';
440
+
441
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
442
+
371
443
  // Classify failure reason: bad proposal vs node issue
372
444
  const badProposalReasons: BlockProposalValidationFailureReason[] = [
373
445
  'invalid_proposal',
@@ -422,51 +494,51 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
422
494
  proposal: CheckpointProposalCore,
423
495
  _proposalSender: PeerId,
424
496
  ): Promise<CheckpointAttestation[] | undefined> {
425
- const slotNumber = proposal.slotNumber;
497
+ const proposalSlotNumber = proposal.slotNumber;
426
498
  const proposer = proposal.getSender();
427
499
 
428
500
  // If escape hatch is open for this slot's epoch, do not attest.
429
- if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
430
- this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
501
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposalSlotNumber)) {
502
+ this.log.warn(`Escape hatch open for slot ${proposalSlotNumber}, skipping checkpoint attestation handling`);
431
503
  return undefined;
432
504
  }
433
505
 
434
- // Reject proposals with invalid signatures
435
- if (!proposer) {
436
- this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
506
+ // Ignore proposals from ourselves (may happen in HA setups)
507
+ if (proposer && this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
508
+ this.log.debug(`Ignoring block proposal from self for slot ${proposalSlotNumber}`, {
509
+ proposer: proposer.toString(),
510
+ proposalSlotNumber,
511
+ });
437
512
  return undefined;
438
513
  }
439
514
 
440
- // Check that I have any address in current committee before attesting
441
- const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
515
+ // Check that I have any address in the committee where this checkpoint will land before attesting
516
+ const inCommittee = await this.epochCache.filterInCommittee(proposalSlotNumber, this.getValidatorAddresses());
442
517
  const partOfCommittee = inCommittee.length > 0;
443
518
 
444
519
  const proposalInfo = {
445
- slotNumber,
520
+ proposalSlotNumber,
446
521
  archive: proposal.archive.toString(),
447
- proposer: proposer.toString(),
448
- txCount: proposal.txHashes.length,
522
+ proposer: proposer?.toString(),
449
523
  };
450
- this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
524
+ this.log.info(`Received checkpoint proposal for slot ${proposalSlotNumber}`, {
451
525
  ...proposalInfo,
452
- txHashes: proposal.txHashes.map(t => t.toString()),
453
526
  fishermanMode: this.config.fishermanMode || false,
454
527
  });
455
528
 
456
- // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
529
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set).
530
+ // Uses the cached result from the all-nodes callback if available (avoids double validation).
531
+ let checkpointNumber: CheckpointNumber;
457
532
  if (this.config.skipCheckpointProposalValidation) {
458
- this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
533
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposalSlotNumber}`, proposalInfo);
534
+ checkpointNumber = CheckpointNumber(0);
459
535
  } else {
460
- const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
536
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
461
537
  if (!validationResult.isValid) {
462
538
  this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
463
539
  return undefined;
464
540
  }
465
- }
466
-
467
- // Upload blobs to filestore if we can (fire and forget)
468
- if (this.blobClient.canUpload()) {
469
- void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
541
+ checkpointNumber = validationResult.checkpointNumber;
470
542
  }
471
543
 
472
544
  // Check that I have any address in current committee before attesting
@@ -477,14 +549,28 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
477
549
  }
478
550
 
479
551
  // Provided all of the above checks pass, we can attest to the proposal
480
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
481
- ...proposalInfo,
482
- inCommittee: partOfCommittee,
483
- fishermanMode: this.config.fishermanMode || false,
484
- });
552
+ this.log.info(
553
+ `${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`,
554
+ {
555
+ ...proposalInfo,
556
+ inCommittee: partOfCommittee,
557
+ fishermanMode: this.config.fishermanMode || false,
558
+ },
559
+ );
485
560
 
486
561
  this.metrics.incSuccessfulAttestations(inCommittee.length);
487
562
 
563
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
564
+ const proposalEpoch = getEpochAtSlot(proposalSlotNumber, this.epochCache.getL1Constants());
565
+ for (const attester of inCommittee) {
566
+ const key = attester.toString();
567
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
568
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
569
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
570
+ this.metrics.incAttestedEpochCount(attester);
571
+ }
572
+ }
573
+
488
574
  // Determine which validators should attest
489
575
  let attestors: EthAddress[];
490
576
  if (partOfCommittee) {
@@ -503,172 +589,60 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
503
589
 
504
590
  if (this.config.fishermanMode) {
505
591
  // bail out early and don't save attestations to the pool in fisherman mode
506
- this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
592
+ this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
507
593
  ...proposalInfo,
508
594
  attestors: attestors.map(a => a.toString()),
509
595
  });
510
596
  return undefined;
511
597
  }
512
598
 
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;
599
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors, checkpointNumber);
523
600
  }
524
601
 
525
602
  /**
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.
603
+ * Checks if we should attest to a slot based on equivocation prevention rules.
604
+ * @returns true if we should attest, false if we should skip
528
605
  */
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
606
+ private shouldAttestToSlot(slotNumber: SlotNumber): boolean {
607
+ // If attestToEquivocatedProposals is true, always allow
608
+ if (this.config.attestToEquivocatedProposals) {
609
+ return true;
610
+ }
535
611
 
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,
612
+ // Check if incoming slot is strictly greater than last attested
613
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
614
+ this.log.warn(
615
+ `Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`,
547
616
  );
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' };
617
+ return false;
555
618
  }
556
619
 
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
- }
620
+ return true;
621
+ }
561
622
 
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' };
623
+ private async createCheckpointAttestationsFromProposal(
624
+ proposal: CheckpointProposalCore,
625
+ attestors: EthAddress[] = [],
626
+ checkpointNumber: CheckpointNumber,
627
+ ): Promise<CheckpointAttestation[] | undefined> {
628
+ // Equivocation check: must happen right before signing to minimize the race window
629
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
630
+ return undefined;
567
631
  }
568
632
 
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());
633
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors, checkpointNumber);
590
634
 
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);
635
+ // Track the proposal we attested to (to prevent equivocation)
636
+ this.lastAttestedProposal = proposal;
594
637
 
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(),
605
- );
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();
650
- }
651
- }
652
-
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
- };
638
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
639
+ return attestations;
666
640
  }
667
641
 
668
642
  /**
669
643
  * Uploads blobs for a checkpoint to the filestore (fire and forget).
670
644
  */
671
- private async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
645
+ protected async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
672
646
  try {
673
647
  const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
674
648
  if (!lastBlockHeader) {
@@ -683,7 +657,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
683
657
  }
684
658
 
685
659
  const blobFields = blocks.flatMap(b => b.toBlobFields());
686
- const blobs: Blob[] = getBlobsPerL1Block(blobFields);
660
+ const blobs: Blob[] = await getBlobsPerL1Block(blobFields);
687
661
  await this.blobClient.sendBlobsToFilestore(blobs);
688
662
  this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
689
663
  ...proposalInfo,
@@ -721,8 +695,55 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
721
695
  ]);
722
696
  }
723
697
 
698
+ /**
699
+ * Handle detection of a duplicate proposal (equivocation).
700
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
701
+ */
702
+ private handleDuplicateProposal(info: DuplicateProposalInfo): void {
703
+ const { slot, proposer, type } = info;
704
+
705
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
706
+ proposer: proposer.toString(),
707
+ slot,
708
+ type,
709
+ });
710
+
711
+ // Emit slash event
712
+ this.emit(WANT_TO_SLASH_EVENT, [
713
+ {
714
+ validator: proposer,
715
+ amount: this.config.slashDuplicateProposalPenalty,
716
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
717
+ epochOrSlot: BigInt(slot),
718
+ },
719
+ ]);
720
+ }
721
+
722
+ /**
723
+ * Handle detection of a duplicate attestation (equivocation).
724
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
725
+ */
726
+ private handleDuplicateAttestation(info: DuplicateAttestationInfo): void {
727
+ const { slot, attester } = info;
728
+
729
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
730
+ attester: attester.toString(),
731
+ slot,
732
+ });
733
+
734
+ this.emit(WANT_TO_SLASH_EVENT, [
735
+ {
736
+ validator: attester,
737
+ amount: this.config.slashDuplicateAttestationPenalty,
738
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
739
+ epochOrSlot: BigInt(slot),
740
+ },
741
+ ]);
742
+ }
743
+
724
744
  async createBlockProposal(
725
745
  blockHeader: BlockHeader,
746
+ checkpointNumber: CheckpointNumber,
726
747
  indexWithinCheckpoint: IndexWithinCheckpoint,
727
748
  inHash: Fr,
728
749
  archive: Fr,
@@ -730,17 +751,26 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
730
751
  proposerAddress: EthAddress | undefined,
731
752
  options: BlockProposalOptions = {},
732
753
  ): 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
- // }
754
+ // Validate that we're not creating a proposal for an older or equal position
755
+ if (this.lastProposedBlock) {
756
+ const lastSlot = this.lastProposedBlock.slotNumber;
757
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
758
+ const newSlot = blockHeader.globalVariables.slotNumber;
759
+
760
+ if (newSlot < lastSlot || (newSlot === lastSlot && indexWithinCheckpoint <= lastIndex)) {
761
+ throw new Error(
762
+ `Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` +
763
+ `already proposed block for slot ${lastSlot} index ${lastIndex}`,
764
+ );
765
+ }
766
+ }
738
767
 
739
768
  this.log.info(
740
769
  `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
741
770
  );
742
771
  const newProposal = await this.validationService.createBlockProposal(
743
772
  blockHeader,
773
+ checkpointNumber,
744
774
  indexWithinCheckpoint,
745
775
  inHash,
746
776
  archive,
@@ -751,25 +781,44 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
751
781
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
752
782
  },
753
783
  );
754
- this.previousProposal = newProposal;
784
+ this.lastProposedBlock = newProposal;
755
785
  return newProposal;
756
786
  }
757
787
 
758
788
  async createCheckpointProposal(
759
789
  checkpointHeader: CheckpointHeader,
760
790
  archive: Fr,
761
- lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
791
+ checkpointNumber: CheckpointNumber,
792
+ feeAssetPriceModifier: bigint,
793
+ lastBlockProposal: BlockProposal | undefined,
762
794
  proposerAddress: EthAddress | undefined,
763
795
  options: CheckpointProposalOptions = {},
764
796
  ): Promise<CheckpointProposal> {
797
+ // Validate that we're not creating a proposal for an older or equal slot
798
+ if (this.lastProposedCheckpoint) {
799
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
800
+ const newSlot = checkpointHeader.slotNumber;
801
+
802
+ if (newSlot <= lastSlot) {
803
+ throw new Error(
804
+ `Cannot create checkpoint proposal for slot ${newSlot}: ` +
805
+ `already proposed checkpoint for slot ${lastSlot}`,
806
+ );
807
+ }
808
+ }
809
+
765
810
  this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
766
- return await this.validationService.createCheckpointProposal(
811
+ const newProposal = await this.validationService.createCheckpointProposal(
767
812
  checkpointHeader,
768
813
  archive,
769
- lastBlockInfo,
814
+ checkpointNumber,
815
+ feeAssetPriceModifier,
816
+ lastBlockProposal,
770
817
  proposerAddress,
771
818
  options,
772
819
  );
820
+ this.lastProposedCheckpoint = newProposal;
821
+ return newProposal;
773
822
  }
774
823
 
775
824
  async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
@@ -780,16 +829,28 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
780
829
  attestationsAndSigners: CommitteeAttestationsAndSigners,
781
830
  proposer: EthAddress,
782
831
  slot: SlotNumber,
783
- blockNumber: BlockNumber | CheckpointNumber,
832
+ checkpointNumber: CheckpointNumber,
784
833
  ): Promise<Signature> {
785
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
834
+ return await this.validationService.signAttestationsAndSigners(
835
+ attestationsAndSigners,
836
+ proposer,
837
+ slot,
838
+ checkpointNumber,
839
+ );
786
840
  }
787
841
 
788
- async collectOwnAttestations(proposal: CheckpointProposal): Promise<CheckpointAttestation[]> {
842
+ async collectOwnAttestations(
843
+ proposal: CheckpointProposal,
844
+ checkpointNumber: CheckpointNumber,
845
+ ): Promise<CheckpointAttestation[]> {
789
846
  const slot = proposal.slotNumber;
790
847
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
791
848
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
792
- const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
849
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
850
+
851
+ if (!attestations) {
852
+ return [];
853
+ }
793
854
 
794
855
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
795
856
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
@@ -804,6 +865,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
804
865
  proposal: CheckpointProposal,
805
866
  required: number,
806
867
  deadline: Date,
868
+ checkpointNumber: CheckpointNumber,
807
869
  ): Promise<CheckpointAttestation[]> {
808
870
  // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
809
871
  const slot = proposal.slotNumber;
@@ -816,7 +878,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
816
878
  throw new AttestationTimeoutError(0, required, slot);
817
879
  }
818
880
 
819
- await this.collectOwnAttestations(proposal);
881
+ await this.collectOwnAttestations(proposal, checkpointNumber);
820
882
 
821
883
  const proposalId = proposal.archive.toString();
822
884
  const myAddresses = this.getValidatorAddresses();
@@ -829,7 +891,9 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
829
891
  attestation => {
830
892
  if (!attestation.archive.equals(proposal.archive)) {
831
893
  this.log.warn(
832
- `Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`,
894
+ `Received attestation for slot ${slot} with mismatched archive from ${attestation
895
+ .getSender()
896
+ ?.toString()}`,
833
897
  { attestationArchive: attestation.archive.toString(), proposalArchive: proposal.archive.toString() },
834
898
  );
835
899
  return false;