@aztec/validator-client 0.0.1-commit.e558bd1c → 0.0.1-commit.e5a3663dd

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 (52) hide show
  1. package/README.md +51 -10
  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 +11 -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.js +1 -1
  18. package/dest/metrics.d.ts +14 -2
  19. package/dest/metrics.d.ts.map +1 -1
  20. package/dest/metrics.js +24 -0
  21. package/dest/proposal_handler.d.ts +108 -0
  22. package/dest/proposal_handler.d.ts.map +1 -0
  23. package/dest/proposal_handler.js +986 -0
  24. package/dest/validator.d.ts +41 -23
  25. package/dest/validator.d.ts.map +1 -1
  26. package/dest/validator.js +181 -200
  27. package/package.json +19 -19
  28. package/src/checkpoint_builder.ts +142 -39
  29. package/src/config.ts +33 -6
  30. package/src/duties/validation_service.ts +53 -53
  31. package/src/factory.ts +15 -3
  32. package/src/index.ts +1 -2
  33. package/src/key_store/ha_key_store.ts +1 -1
  34. package/src/metrics.ts +37 -1
  35. package/src/proposal_handler.ts +1052 -0
  36. package/src/validator.ts +265 -229
  37. package/dest/block_proposal_handler.d.ts +0 -63
  38. package/dest/block_proposal_handler.d.ts.map +0 -1
  39. package/dest/block_proposal_handler.js +0 -546
  40. package/dest/tx_validator/index.d.ts +0 -3
  41. package/dest/tx_validator/index.d.ts.map +0 -1
  42. package/dest/tx_validator/index.js +0 -2
  43. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  44. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  45. package/dest/tx_validator/nullifier_cache.js +0 -24
  46. package/dest/tx_validator/tx_validator_factory.d.ts +0 -19
  47. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  48. package/dest/tx_validator/tx_validator_factory.js +0 -54
  49. package/src/block_proposal_handler.ts +0 -555
  50. package/src/tx_validator/index.ts +0 -2
  51. package/src/tx_validator/nullifier_cache.ts +0 -30
  52. 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 { DuplicateProposalInfo, 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,19 @@ 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
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint,
205
+ signatureContext: {
206
+ chainId: config.l1ChainId,
207
+ rollupAddress: config.l1Contracts.rollupAddress,
208
+ },
192
209
  });
193
- const blockProposalHandler = new BlockProposalHandler(
210
+ const proposalHandler = new ProposalHandler(
194
211
  checkpointsBuilder,
195
212
  worldState,
196
213
  blockSource,
@@ -199,33 +216,54 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
199
216
  blockProposalValidator,
200
217
  epochCache,
201
218
  config,
219
+ blobClient,
202
220
  metrics,
203
221
  dateProvider,
204
222
  telemetry,
223
+ undefined,
205
224
  );
206
225
 
207
- let validatorKeyStore: ExtendedValidatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
208
- if (config.haSigningEnabled) {
226
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
227
+ let slashingProtectionSigner: ValidatorHASigner;
228
+ if (slashingProtectionDb) {
229
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
230
+ ({ signer: slashingProtectionSigner } = createSignerFromSharedDb(slashingProtectionDb, config, {
231
+ telemetryClient: telemetry,
232
+ dateProvider,
233
+ }));
234
+ } else if (config.haSigningEnabled) {
235
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
209
236
  // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
210
237
  const haConfig = {
211
238
  ...config,
212
239
  maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000,
213
240
  };
214
- const { signer } = await createHASigner(haConfig);
215
- validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
241
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
242
+ telemetryClient: telemetry,
243
+ dateProvider,
244
+ }));
245
+ } else {
246
+ // Single-node mode: use LMDB-backed local signing protection.
247
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
248
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
249
+ telemetryClient: telemetry,
250
+ dateProvider,
251
+ }));
216
252
  }
253
+ const validatorKeyStore: ExtendedValidatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
217
254
 
218
255
  const validator = new ValidatorClient(
219
256
  validatorKeyStore,
220
257
  epochCache,
221
258
  p2pClient,
222
- blockProposalHandler,
259
+ proposalHandler,
223
260
  blockSource,
224
261
  checkpointsBuilder,
225
262
  worldState,
226
263
  l1ToL2MessageSource,
227
264
  config,
228
265
  blobClient,
266
+ slashingProtectionSigner,
229
267
  dateProvider,
230
268
  telemetry,
231
269
  );
@@ -239,14 +277,21 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
239
277
  .filter(addr => !this.config.disabledValidators.some(disabled => disabled.equals(addr)));
240
278
  }
241
279
 
242
- public getBlockProposalHandler() {
243
- return this.blockProposalHandler;
280
+ public getProposalHandler() {
281
+ return this.proposalHandler;
244
282
  }
245
283
 
246
284
  public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
247
285
  return this.keyStore.signTypedDataWithAddress(addr, msg, context);
248
286
  }
249
287
 
288
+ private getSignatureContext(): CoordinationSignatureContext {
289
+ return {
290
+ chainId: this.config.l1ChainId,
291
+ rollupAddress: this.config.l1Contracts.rollupAddress,
292
+ };
293
+ }
294
+
250
295
  public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
251
296
  return this.keyStore.getCoinbaseAddress(attestor);
252
297
  }
@@ -263,6 +308,16 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
263
308
  this.config = { ...this.config, ...config };
264
309
  }
265
310
 
311
+ public reloadKeystore(newManager: KeystoreManager): void {
312
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
313
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
314
+ this.validationService = new ValidationService(
315
+ this.keyStore,
316
+ this.getSignatureContext(),
317
+ this.log.createChild('validation-service'),
318
+ );
319
+ }
320
+
266
321
  public async start() {
267
322
  if (this.epochCacheUpdateLoop.isRunning()) {
268
323
  this.log.warn(`Validator client already started`);
@@ -307,13 +362,18 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
307
362
  checkpoint: CheckpointProposalCore,
308
363
  proposalSender: PeerId,
309
364
  ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
310
- this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
365
+ this.p2pClient.registerValidatorCheckpointProposalHandler(checkpointHandler);
311
366
 
312
367
  // Duplicate proposal handler - triggers slashing for equivocation
313
368
  this.p2pClient.registerDuplicateProposalCallback((info: DuplicateProposalInfo) => {
314
369
  this.handleDuplicateProposal(info);
315
370
  });
316
371
 
372
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
373
+ this.p2pClient.registerDuplicateAttestationCallback((info: DuplicateAttestationInfo) => {
374
+ this.handleDuplicateAttestation(info);
375
+ });
376
+
317
377
  const myAddresses = this.getValidatorAddresses();
318
378
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
319
379
 
@@ -341,6 +401,14 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
341
401
  return false;
342
402
  }
343
403
 
404
+ // Log self-proposals from HA peers (same validator key on different nodes)
405
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
406
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
407
+ proposer: proposer.toString(),
408
+ slotNumber,
409
+ });
410
+ }
411
+
344
412
  // Check if we're in the committee (for metrics purposes)
345
413
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
346
414
  const partOfCommittee = inCommittee.length > 0;
@@ -354,25 +422,25 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
354
422
 
355
423
  // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
356
424
  // In fisherman mode, we always reexecute to validate proposals.
357
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
358
- this.config;
425
+ const { slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
359
426
  const shouldReexecute =
360
427
  fishermanMode ||
361
- (slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
362
- (partOfCommittee && validatorReexecute) ||
428
+ slashBroadcastedInvalidBlockPenalty > 0n ||
429
+ partOfCommittee ||
363
430
  alwaysReexecuteBlockProposals ||
364
431
  this.blobClient.canUpload();
365
432
 
366
- const validationResult = await this.blockProposalHandler.handleBlockProposal(
433
+ const validationResult = await this.proposalHandler.handleBlockProposal(
367
434
  proposal,
368
435
  proposalSender,
369
436
  !!shouldReexecute && !escapeHatchOpen,
370
437
  );
371
438
 
372
439
  if (!validationResult.isValid) {
373
- this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
374
-
375
440
  const reason = validationResult.reason || 'unknown';
441
+
442
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
443
+
376
444
  // Classify failure reason: bad proposal vs node issue
377
445
  const badProposalReasons: BlockProposalValidationFailureReason[] = [
378
446
  'invalid_proposal',
@@ -427,51 +495,51 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
427
495
  proposal: CheckpointProposalCore,
428
496
  _proposalSender: PeerId,
429
497
  ): Promise<CheckpointAttestation[] | undefined> {
430
- const slotNumber = proposal.slotNumber;
498
+ const proposalSlotNumber = proposal.slotNumber;
431
499
  const proposer = proposal.getSender();
432
500
 
433
501
  // If escape hatch is open for this slot's epoch, do not attest.
434
- if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
435
- this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
502
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposalSlotNumber)) {
503
+ this.log.warn(`Escape hatch open for slot ${proposalSlotNumber}, skipping checkpoint attestation handling`);
436
504
  return undefined;
437
505
  }
438
506
 
439
- // Reject proposals with invalid signatures
440
- if (!proposer) {
441
- this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
507
+ // Ignore proposals from ourselves (may happen in HA setups)
508
+ if (proposer && this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
509
+ this.log.debug(`Ignoring block proposal from self for slot ${proposalSlotNumber}`, {
510
+ proposer: proposer.toString(),
511
+ proposalSlotNumber,
512
+ });
442
513
  return undefined;
443
514
  }
444
515
 
445
- // Check that I have any address in current committee before attesting
446
- const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
516
+ // Check that I have any address in the committee where this checkpoint will land before attesting
517
+ const inCommittee = await this.epochCache.filterInCommittee(proposalSlotNumber, this.getValidatorAddresses());
447
518
  const partOfCommittee = inCommittee.length > 0;
448
519
 
449
520
  const proposalInfo = {
450
- slotNumber,
521
+ proposalSlotNumber,
451
522
  archive: proposal.archive.toString(),
452
- proposer: proposer.toString(),
453
- txCount: proposal.txHashes.length,
523
+ proposer: proposer?.toString(),
454
524
  };
455
- this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
525
+ this.log.info(`Received checkpoint proposal for slot ${proposalSlotNumber}`, {
456
526
  ...proposalInfo,
457
- txHashes: proposal.txHashes.map(t => t.toString()),
458
527
  fishermanMode: this.config.fishermanMode || false,
459
528
  });
460
529
 
461
- // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
530
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set).
531
+ // Uses the cached result from the all-nodes callback if available (avoids double validation).
532
+ let checkpointNumber: CheckpointNumber;
462
533
  if (this.config.skipCheckpointProposalValidation) {
463
- this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
534
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposalSlotNumber}`, proposalInfo);
535
+ checkpointNumber = CheckpointNumber(0);
464
536
  } else {
465
- const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
537
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
466
538
  if (!validationResult.isValid) {
467
539
  this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
468
540
  return undefined;
469
541
  }
470
- }
471
-
472
- // Upload blobs to filestore if we can (fire and forget)
473
- if (this.blobClient.canUpload()) {
474
- void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
542
+ checkpointNumber = validationResult.checkpointNumber;
475
543
  }
476
544
 
477
545
  // Check that I have any address in current committee before attesting
@@ -482,14 +550,28 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
482
550
  }
483
551
 
484
552
  // Provided all of the above checks pass, we can attest to the proposal
485
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
486
- ...proposalInfo,
487
- inCommittee: partOfCommittee,
488
- fishermanMode: this.config.fishermanMode || false,
489
- });
553
+ this.log.info(
554
+ `${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`,
555
+ {
556
+ ...proposalInfo,
557
+ inCommittee: partOfCommittee,
558
+ fishermanMode: this.config.fishermanMode || false,
559
+ },
560
+ );
490
561
 
491
562
  this.metrics.incSuccessfulAttestations(inCommittee.length);
492
563
 
564
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
565
+ const proposalEpoch = getEpochAtSlot(proposalSlotNumber, this.epochCache.getL1Constants());
566
+ for (const attester of inCommittee) {
567
+ const key = attester.toString();
568
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
569
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
570
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
571
+ this.metrics.incAttestedEpochCount(attester);
572
+ }
573
+ }
574
+
493
575
  // Determine which validators should attest
494
576
  let attestors: EthAddress[];
495
577
  if (partOfCommittee) {
@@ -508,172 +590,60 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
508
590
 
509
591
  if (this.config.fishermanMode) {
510
592
  // bail out early and don't save attestations to the pool in fisherman mode
511
- this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
593
+ this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
512
594
  ...proposalInfo,
513
595
  attestors: attestors.map(a => a.toString()),
514
596
  });
515
597
  return undefined;
516
598
  }
517
599
 
518
- return this.createCheckpointAttestationsFromProposal(proposal, attestors);
519
- }
520
-
521
- private async createCheckpointAttestationsFromProposal(
522
- proposal: CheckpointProposalCore,
523
- attestors: EthAddress[] = [],
524
- ): Promise<CheckpointAttestation[]> {
525
- const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
526
- await this.p2pClient.addOwnCheckpointAttestations(attestations);
527
- return attestations;
600
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors, checkpointNumber);
528
601
  }
529
602
 
530
603
  /**
531
- * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
532
- * @returns Validation result with isValid flag and reason if invalid.
604
+ * Checks if we should attest to a slot based on equivocation prevention rules.
605
+ * @returns true if we should attest, false if we should skip
533
606
  */
534
- private async validateCheckpointProposal(
535
- proposal: CheckpointProposalCore,
536
- proposalInfo: LogData,
537
- ): Promise<{ isValid: true } | { isValid: false; reason: string }> {
538
- const slot = proposal.slotNumber;
539
- const timeoutSeconds = 10; // TODO(palla/mbps): This should map to the timetable settings
607
+ private shouldAttestToSlot(slotNumber: SlotNumber): boolean {
608
+ // If attestToEquivocatedProposals is true, always allow
609
+ if (this.config.attestToEquivocatedProposals) {
610
+ return true;
611
+ }
540
612
 
541
- // Wait for last block to sync by archive
542
- let lastBlockHeader: BlockHeader | undefined;
543
- try {
544
- lastBlockHeader = await retryUntil(
545
- async () => {
546
- await this.blockSource.syncImmediate();
547
- return this.blockSource.getBlockHeaderByArchive(proposal.archive);
548
- },
549
- `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
550
- timeoutSeconds,
551
- 0.5,
613
+ // Check if incoming slot is strictly greater than last attested
614
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
615
+ this.log.warn(
616
+ `Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`,
552
617
  );
553
- } catch (err) {
554
- if (err instanceof TimeoutError) {
555
- this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
556
- return { isValid: false, reason: 'last_block_not_found' };
557
- }
558
- this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
559
- return { isValid: false, reason: 'block_fetch_error' };
618
+ return false;
560
619
  }
561
620
 
562
- if (!lastBlockHeader) {
563
- this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
564
- return { isValid: false, reason: 'last_block_not_found' };
565
- }
621
+ return true;
622
+ }
566
623
 
567
- // Get all full blocks for the slot and checkpoint
568
- const blocks = await this.blockSource.getBlocksForSlot(slot);
569
- if (blocks.length === 0) {
570
- this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
571
- return { isValid: false, reason: 'no_blocks_for_slot' };
624
+ private async createCheckpointAttestationsFromProposal(
625
+ proposal: CheckpointProposalCore,
626
+ attestors: EthAddress[] = [],
627
+ checkpointNumber: CheckpointNumber,
628
+ ): Promise<CheckpointAttestation[] | undefined> {
629
+ // Equivocation check: must happen right before signing to minimize the race window
630
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
631
+ return undefined;
572
632
  }
573
633
 
574
- this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
575
- ...proposalInfo,
576
- blockNumbers: blocks.map(b => b.number),
577
- });
578
-
579
- // Get checkpoint constants from first block
580
- const firstBlock = blocks[0];
581
- const constants = this.extractCheckpointConstants(firstBlock);
582
- const checkpointNumber = firstBlock.checkpointNumber;
634
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors, checkpointNumber);
583
635
 
584
- // Get L1-to-L2 messages for this checkpoint
585
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
636
+ // Track the proposal we attested to (to prevent equivocation)
637
+ this.lastAttestedProposal = proposal;
586
638
 
587
- // Compute the previous checkpoint out hashes for the epoch.
588
- // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch the
589
- // actual checkpoints and the blocks/txs in them.
590
- const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
591
- const previousCheckpoints = (await this.blockSource.getCheckpointsForEpoch(epoch))
592
- .filter(b => b.number < checkpointNumber)
593
- .sort((a, b) => a.number - b.number);
594
- const previousCheckpointOutHashes = previousCheckpoints.map(c => c.getCheckpointOutHash());
595
-
596
- // Fork world state at the block before the first block
597
- const parentBlockNumber = BlockNumber(firstBlock.number - 1);
598
- const fork = await this.worldState.fork(parentBlockNumber);
599
-
600
- try {
601
- // Create checkpoint builder with all existing blocks
602
- const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
603
- checkpointNumber,
604
- constants,
605
- l1ToL2Messages,
606
- previousCheckpointOutHashes,
607
- fork,
608
- blocks,
609
- this.log.getBindings(),
610
- );
611
-
612
- // Complete the checkpoint to get computed values
613
- const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
614
-
615
- // Compare checkpoint header with proposal
616
- if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
617
- this.log.warn(`Checkpoint header mismatch`, {
618
- ...proposalInfo,
619
- computed: computedCheckpoint.header.toInspect(),
620
- proposal: proposal.checkpointHeader.toInspect(),
621
- });
622
- return { isValid: false, reason: 'checkpoint_header_mismatch' };
623
- }
624
-
625
- // Compare archive root with proposal
626
- if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
627
- this.log.warn(`Archive root mismatch`, {
628
- ...proposalInfo,
629
- computed: computedCheckpoint.archive.root.toString(),
630
- proposal: proposal.archive.toString(),
631
- });
632
- return { isValid: false, reason: 'archive_mismatch' };
633
- }
634
-
635
- // Check that the accumulated epoch out hash matches the value in the proposal.
636
- // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
637
- const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
638
- const computedEpochOutHash = accumulateCheckpointOutHashes([...previousCheckpointOutHashes, checkpointOutHash]);
639
- const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
640
- if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
641
- this.log.warn(`Epoch out hash mismatch`, {
642
- proposalEpochOutHash: proposalEpochOutHash.toString(),
643
- computedEpochOutHash: computedEpochOutHash.toString(),
644
- checkpointOutHash: checkpointOutHash.toString(),
645
- previousCheckpointOutHashes: previousCheckpointOutHashes.map(h => h.toString()),
646
- ...proposalInfo,
647
- });
648
- return { isValid: false, reason: 'out_hash_mismatch' };
649
- }
650
-
651
- this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
652
- return { isValid: true };
653
- } finally {
654
- await fork.close();
655
- }
656
- }
657
-
658
- /**
659
- * Extract checkpoint global variables from a block.
660
- */
661
- private extractCheckpointConstants(block: L2Block): CheckpointGlobalVariables {
662
- const gv = block.header.globalVariables;
663
- return {
664
- chainId: gv.chainId,
665
- version: gv.version,
666
- slotNumber: gv.slotNumber,
667
- coinbase: gv.coinbase,
668
- feeRecipient: gv.feeRecipient,
669
- gasFees: gv.gasFees,
670
- };
639
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
640
+ return attestations;
671
641
  }
672
642
 
673
643
  /**
674
644
  * Uploads blobs for a checkpoint to the filestore (fire and forget).
675
645
  */
676
- private async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
646
+ protected async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
677
647
  try {
678
648
  const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
679
649
  if (!lastBlockHeader) {
@@ -688,7 +658,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
688
658
  }
689
659
 
690
660
  const blobFields = blocks.flatMap(b => b.toBlobFields());
691
- const blobs: Blob[] = getBlobsPerL1Block(blobFields);
661
+ const blobs: Blob[] = await getBlobsPerL1Block(blobFields);
692
662
  await this.blobClient.sendBlobsToFilestore(blobs);
693
663
  this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
694
664
  ...proposalInfo,
@@ -750,8 +720,31 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
750
720
  ]);
751
721
  }
752
722
 
723
+ /**
724
+ * Handle detection of a duplicate attestation (equivocation).
725
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
726
+ */
727
+ private handleDuplicateAttestation(info: DuplicateAttestationInfo): void {
728
+ const { slot, attester } = info;
729
+
730
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
731
+ attester: attester.toString(),
732
+ slot,
733
+ });
734
+
735
+ this.emit(WANT_TO_SLASH_EVENT, [
736
+ {
737
+ validator: attester,
738
+ amount: this.config.slashDuplicateAttestationPenalty,
739
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
740
+ epochOrSlot: BigInt(slot),
741
+ },
742
+ ]);
743
+ }
744
+
753
745
  async createBlockProposal(
754
746
  blockHeader: BlockHeader,
747
+ checkpointNumber: CheckpointNumber,
755
748
  indexWithinCheckpoint: IndexWithinCheckpoint,
756
749
  inHash: Fr,
757
750
  archive: Fr,
@@ -759,17 +752,26 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
759
752
  proposerAddress: EthAddress | undefined,
760
753
  options: BlockProposalOptions = {},
761
754
  ): Promise<BlockProposal> {
762
- // TODO(palla/mbps): Prevent double proposals properly
763
- // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
764
- // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
765
- // return Promise.resolve(undefined);
766
- // }
755
+ // Validate that we're not creating a proposal for an older or equal position
756
+ if (this.lastProposedBlock) {
757
+ const lastSlot = this.lastProposedBlock.slotNumber;
758
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
759
+ const newSlot = blockHeader.globalVariables.slotNumber;
760
+
761
+ if (newSlot < lastSlot || (newSlot === lastSlot && indexWithinCheckpoint <= lastIndex)) {
762
+ throw new Error(
763
+ `Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` +
764
+ `already proposed block for slot ${lastSlot} index ${lastIndex}`,
765
+ );
766
+ }
767
+ }
767
768
 
768
769
  this.log.info(
769
770
  `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
770
771
  );
771
772
  const newProposal = await this.validationService.createBlockProposal(
772
773
  blockHeader,
774
+ checkpointNumber,
773
775
  indexWithinCheckpoint,
774
776
  inHash,
775
777
  archive,
@@ -780,25 +782,44 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
780
782
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
781
783
  },
782
784
  );
783
- this.previousProposal = newProposal;
785
+ this.lastProposedBlock = newProposal;
784
786
  return newProposal;
785
787
  }
786
788
 
787
789
  async createCheckpointProposal(
788
790
  checkpointHeader: CheckpointHeader,
789
791
  archive: Fr,
790
- lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
792
+ checkpointNumber: CheckpointNumber,
793
+ feeAssetPriceModifier: bigint,
794
+ lastBlockProposal: BlockProposal | undefined,
791
795
  proposerAddress: EthAddress | undefined,
792
796
  options: CheckpointProposalOptions = {},
793
797
  ): Promise<CheckpointProposal> {
798
+ // Validate that we're not creating a proposal for an older or equal slot
799
+ if (this.lastProposedCheckpoint) {
800
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
801
+ const newSlot = checkpointHeader.slotNumber;
802
+
803
+ if (newSlot <= lastSlot) {
804
+ throw new Error(
805
+ `Cannot create checkpoint proposal for slot ${newSlot}: ` +
806
+ `already proposed checkpoint for slot ${lastSlot}`,
807
+ );
808
+ }
809
+ }
810
+
794
811
  this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
795
- return await this.validationService.createCheckpointProposal(
812
+ const newProposal = await this.validationService.createCheckpointProposal(
796
813
  checkpointHeader,
797
814
  archive,
798
- lastBlockInfo,
815
+ checkpointNumber,
816
+ feeAssetPriceModifier,
817
+ lastBlockProposal,
799
818
  proposerAddress,
800
819
  options,
801
820
  );
821
+ this.lastProposedCheckpoint = newProposal;
822
+ return newProposal;
802
823
  }
803
824
 
804
825
  async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
@@ -809,16 +830,28 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
809
830
  attestationsAndSigners: CommitteeAttestationsAndSigners,
810
831
  proposer: EthAddress,
811
832
  slot: SlotNumber,
812
- blockNumber: BlockNumber | CheckpointNumber,
833
+ checkpointNumber: CheckpointNumber,
813
834
  ): Promise<Signature> {
814
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
835
+ return await this.validationService.signAttestationsAndSigners(
836
+ attestationsAndSigners,
837
+ proposer,
838
+ slot,
839
+ checkpointNumber,
840
+ );
815
841
  }
816
842
 
817
- async collectOwnAttestations(proposal: CheckpointProposal): Promise<CheckpointAttestation[]> {
843
+ async collectOwnAttestations(
844
+ proposal: CheckpointProposal,
845
+ checkpointNumber: CheckpointNumber,
846
+ ): Promise<CheckpointAttestation[]> {
818
847
  const slot = proposal.slotNumber;
819
848
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
820
849
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
821
- const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
850
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
851
+
852
+ if (!attestations) {
853
+ return [];
854
+ }
822
855
 
823
856
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
824
857
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
@@ -833,6 +866,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
833
866
  proposal: CheckpointProposal,
834
867
  required: number,
835
868
  deadline: Date,
869
+ checkpointNumber: CheckpointNumber,
836
870
  ): Promise<CheckpointAttestation[]> {
837
871
  // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
838
872
  const slot = proposal.slotNumber;
@@ -845,7 +879,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
845
879
  throw new AttestationTimeoutError(0, required, slot);
846
880
  }
847
881
 
848
- await this.collectOwnAttestations(proposal);
882
+ await this.collectOwnAttestations(proposal, checkpointNumber);
849
883
 
850
884
  const proposalId = proposal.archive.toString();
851
885
  const myAddresses = this.getValidatorAddresses();
@@ -858,7 +892,9 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
858
892
  attestation => {
859
893
  if (!attestation.archive.equals(proposal.archive)) {
860
894
  this.log.warn(
861
- `Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`,
895
+ `Received attestation for slot ${slot} with mismatched archive from ${attestation
896
+ .getSender()
897
+ ?.toString()}`,
862
898
  { attestationArchive: attestation.archive.toString(), proposalArchive: proposal.archive.toString() },
863
899
  );
864
900
  return false;