@aztec/validator-client 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0

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 (61) hide show
  1. package/README.md +327 -0
  2. package/dest/checkpoint_builder.d.ts +81 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +259 -0
  5. package/dest/config.d.ts +9 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +56 -14
  8. package/dest/duties/validation_service.d.ts +44 -16
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +102 -31
  11. package/dest/factory.d.ts +22 -11
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +19 -6
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -1
  17. package/dest/key_store/ha_key_store.d.ts +99 -0
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  19. package/dest/key_store/ha_key_store.js +208 -0
  20. package/dest/key_store/index.d.ts +2 -1
  21. package/dest/key_store/index.d.ts.map +1 -1
  22. package/dest/key_store/index.js +1 -0
  23. package/dest/key_store/interface.d.ts +36 -6
  24. package/dest/key_store/interface.d.ts.map +1 -1
  25. package/dest/key_store/local_key_store.d.ts +10 -5
  26. package/dest/key_store/local_key_store.d.ts.map +1 -1
  27. package/dest/key_store/local_key_store.js +9 -5
  28. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  29. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  30. package/dest/key_store/node_keystore_adapter.js +18 -4
  31. package/dest/key_store/web3signer_key_store.d.ts +19 -6
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +41 -46
  34. package/dest/metrics.d.ts +16 -3
  35. package/dest/metrics.d.ts.map +1 -1
  36. package/dest/metrics.js +58 -30
  37. package/dest/proposal_handler.d.ts +165 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +1207 -0
  40. package/dest/validator.d.ts +93 -25
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +491 -89
  43. package/package.json +21 -11
  44. package/src/checkpoint_builder.ts +426 -0
  45. package/src/config.ts +63 -15
  46. package/src/duties/validation_service.ts +168 -41
  47. package/src/factory.ts +46 -12
  48. package/src/index.ts +2 -1
  49. package/src/key_store/ha_key_store.ts +269 -0
  50. package/src/key_store/index.ts +1 -0
  51. package/src/key_store/interface.ts +44 -5
  52. package/src/key_store/local_key_store.ts +14 -5
  53. package/src/key_store/node_keystore_adapter.ts +28 -5
  54. package/src/key_store/web3signer_key_store.ts +61 -64
  55. package/src/metrics.ts +81 -33
  56. package/src/proposal_handler.ts +1314 -0
  57. package/src/validator.ts +721 -139
  58. package/dest/block_proposal_handler.d.ts +0 -53
  59. package/dest/block_proposal_handler.d.ts.map +0 -1
  60. package/dest/block_proposal_handler.js +0 -290
  61. package/src/block_proposal_handler.ts +0 -344
package/src/validator.ts CHANGED
@@ -1,43 +1,82 @@
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
2
+ import { type Blob, getBlobsPerL1Block } from '@aztec/blob-lib';
1
3
  import type { EpochCache } from '@aztec/epoch-cache';
2
- import { BlockNumber, EpochNumber } from '@aztec/foundation/branded-types';
4
+ import { CheckpointNumber, EpochNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
6
  import type { EthAddress } from '@aztec/foundation/eth-address';
4
- import type { Signature } from '@aztec/foundation/eth-signature';
5
- import { Fr } from '@aztec/foundation/fields';
6
- import { type Logger, createLogger } from '@aztec/foundation/log';
7
+ import { Signature } from '@aztec/foundation/eth-signature';
8
+ import { FifoSet } from '@aztec/foundation/fifo-set';
9
+ import { type LogData, type Logger, createLogger } from '@aztec/foundation/log';
7
10
  import { RunningPromise } from '@aztec/foundation/running-promise';
8
11
  import { sleep } from '@aztec/foundation/sleep';
9
12
  import { DateProvider } from '@aztec/foundation/timer';
10
13
  import type { KeystoreManager } from '@aztec/node-keystore';
11
- import type { P2P, PeerId, TxProvider } from '@aztec/p2p';
14
+ import type { DuplicateAttestationInfo, DuplicateProposalInfo, OversizedProposalInfo, P2P, PeerId } from '@aztec/p2p';
12
15
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
13
- import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
16
+ import {
17
+ OffenseType,
18
+ WANT_TO_CLEAR_SLASH_EVENT,
19
+ WANT_TO_SLASH_EVENT,
20
+ type Watcher,
21
+ type WatcherEmitter,
22
+ getOffenseTypeName,
23
+ } from '@aztec/slasher';
14
24
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
15
- import type { CommitteeAttestationsAndSigners, L2BlockSource } from '@aztec/stdlib/block';
16
- import type { IFullNodeBlockBuilder, Validator, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
25
+ import type { CommitteeAttestationsAndSigners, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
26
+ import type { CheckpointReexecutionTracker } from '@aztec/stdlib/checkpoint';
27
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
28
+ import type {
29
+ ITxProvider,
30
+ Validator,
31
+ ValidatorClientFullConfig,
32
+ WorldStateSynchronizer,
33
+ } from '@aztec/stdlib/interfaces/server';
17
34
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
18
- import type { BlockAttestation, BlockProposal, BlockProposalOptions } from '@aztec/stdlib/p2p';
35
+ import {
36
+ type BlockProposal,
37
+ type BlockProposalOptions,
38
+ CheckpointAttestation,
39
+ CheckpointProposal,
40
+ type CheckpointProposalCore,
41
+ type CheckpointProposalOptions,
42
+ type CoordinationSignatureContext,
43
+ } from '@aztec/stdlib/p2p';
19
44
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
20
- import type { Tx } from '@aztec/stdlib/tx';
45
+ import { ConsensusTimetable } from '@aztec/stdlib/timetable';
46
+ import type { BlockHeader, Tx } from '@aztec/stdlib/tx';
21
47
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
22
48
  import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
49
+ import {
50
+ createHASigner,
51
+ createLocalSignerWithProtection,
52
+ createSignerFromSharedDb,
53
+ } from '@aztec/validator-ha-signer/factory';
54
+ import { DutyType, type SigningContext, type SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
55
+ import type { ValidatorHASigner } from '@aztec/validator-ha-signer/validator-ha-signer';
23
56
 
24
57
  import { EventEmitter } from 'events';
25
58
  import type { TypedDataDefinition } from 'viem';
26
59
 
27
- import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
60
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
61
+ import { DEFAULT_MAX_GOSSIP_CLOCK_DISPARITY_MS } from './config.js';
28
62
  import { ValidationService } from './duties/validation_service.js';
63
+ import { HAKeyStore } from './key_store/ha_key_store.js';
64
+ import type { ExtendedValidatorKeyStore } from './key_store/interface.js';
29
65
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
30
66
  import { ValidatorMetrics } from './metrics.js';
67
+ import {
68
+ type BlockProposalValidationFailureReason,
69
+ type CheckpointProposalValidationFailureResult,
70
+ ProposalHandler,
71
+ SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT,
72
+ SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT,
73
+ } from './proposal_handler.js';
31
74
 
32
75
  // We maintain a set of proposers who have proposed invalid blocks.
33
76
  // Just cap the set to avoid unbounded growth.
34
77
  const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
35
-
36
- // What errors from the block proposal handler result in slashing
37
- const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT: BlockProposalValidationFailureReason[] = [
38
- 'state_mismatch',
39
- 'failed_txs',
40
- ];
78
+ const MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS = 1000;
79
+ const MAX_TRACKED_BAD_ATTESTATIONS = 10_000;
41
80
 
42
81
  /**
43
82
  * Validator Client
@@ -47,24 +86,40 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
47
86
  private validationService: ValidationService;
48
87
  private metrics: ValidatorMetrics;
49
88
  private log: Logger;
50
-
51
89
  // Whether it has already registered handlers on the p2p client
52
90
  private hasRegisteredHandlers = false;
53
91
 
54
- // Used to check if we are sending the same proposal twice
55
- private previousProposal?: BlockProposal;
92
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */
93
+ private lastProposedBlock?: BlockProposal;
94
+
95
+ /** Tracks the last checkpoint proposal we created. */
96
+ private lastProposedCheckpoint?: CheckpointProposal;
56
97
 
57
98
  private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
58
99
  private epochCacheUpdateLoop: RunningPromise;
100
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */
101
+ private lastAttestedEpochByAttester: Map<string, EpochNumber> = new Map();
102
+
103
+ private proposersOfInvalidBlocks = FifoSet.withLimit<string>(MAX_PROPOSERS_OF_INVALID_BLOCKS);
104
+ private invalidCheckpointProposalOffenseKeys = FifoSet.withLimit<string>(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS);
105
+ private oversizedProposalOffenseKeys = FifoSet.withLimit<string>(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS);
106
+ private badAttestationOffenseKeys = FifoSet.withLimit<string>(MAX_TRACKED_BAD_ATTESTATIONS);
59
107
 
60
- private proposersOfInvalidBlocks: Set<string> = new Set();
108
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */
109
+ private lastAttestedProposal?: CheckpointProposalCore;
61
110
 
62
111
  protected constructor(
63
- private keyStore: NodeKeystoreAdapter,
112
+ private keyStore: ExtendedValidatorKeyStore,
64
113
  private epochCache: EpochCache,
65
114
  private p2pClient: P2P,
66
- private blockProposalHandler: BlockProposalHandler,
115
+ private proposalHandler: ProposalHandler,
116
+ private blockSource: L2BlockSource,
117
+ private checkpointsBuilder: FullNodeCheckpointsBuilder,
118
+ private worldState: WorldStateSynchronizer,
119
+ private l1ToL2MessageSource: L1ToL2MessageSource,
67
120
  private config: ValidatorClientFullConfig,
121
+ private blobClient: BlobClientInterface,
122
+ private slashingProtectionSigner: ValidatorHASigner,
68
123
  private dateProvider: DateProvider = new DateProvider(),
69
124
  telemetry: TelemetryClient = getTelemetryClient(),
70
125
  log = createLogger('validator'),
@@ -77,11 +132,17 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
77
132
  this.tracer = telemetry.getTracer('Validator');
78
133
  this.metrics = new ValidatorMetrics(telemetry);
79
134
 
80
- this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
135
+ this.validationService = new ValidationService(
136
+ keyStore,
137
+ this.getSignatureContext(),
138
+ this.log.createChild('validation-service'),
139
+ );
140
+ this.proposalHandler.setCheckpointProposalValidationFailureCallback((proposal, result, proposalInfo) =>
141
+ this.handleInvalidCheckpointProposal(proposal, result, proposalInfo),
142
+ );
81
143
 
82
144
  // Refresh epoch cache every second to trigger alert if participation in committee changes
83
145
  this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
84
-
85
146
  const myAddresses = this.getValidatorAddresses();
86
147
  this.log.verbose(`Initialized validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
87
148
  }
@@ -118,6 +179,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
118
179
  this.log.trace(`No committee found for slot`);
119
180
  return;
120
181
  }
182
+ this.metrics.setCurrentEpoch(epoch);
121
183
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
122
184
  const me = this.getValidatorAddresses();
123
185
  const committeeSet = new Set(committee.map(v => v.toString()));
@@ -138,40 +200,97 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
138
200
  }
139
201
  }
140
202
 
141
- static new(
203
+ static async new(
142
204
  config: ValidatorClientFullConfig,
143
- blockBuilder: IFullNodeBlockBuilder,
205
+ checkpointsBuilder: FullNodeCheckpointsBuilder,
206
+ worldState: WorldStateSynchronizer,
144
207
  epochCache: EpochCache,
145
208
  p2pClient: P2P,
146
- blockSource: L2BlockSource,
209
+ blockSource: L2BlockSource & L2BlockSink,
147
210
  l1ToL2MessageSource: L1ToL2MessageSource,
148
- txProvider: TxProvider,
211
+ txProvider: ITxProvider,
149
212
  keyStoreManager: KeystoreManager,
213
+ blobClient: BlobClientInterface,
214
+ reexecutionTracker: CheckpointReexecutionTracker,
150
215
  dateProvider: DateProvider = new DateProvider(),
151
216
  telemetry: TelemetryClient = getTelemetryClient(),
217
+ slashingProtectionDb?: SlashingProtectionDatabase,
152
218
  ) {
153
219
  const metrics = new ValidatorMetrics(telemetry);
154
- const blockProposalValidator = new BlockProposalValidator(epochCache, {
220
+ const consensusTimetable = new ConsensusTimetable({
221
+ l1Constants: epochCache.getL1Constants(),
222
+ blockDuration: config.blockDurationMs / 1000,
223
+ });
224
+ const blockProposalValidator = new BlockProposalValidator(epochCache, consensusTimetable, {
155
225
  txsPermitted: !config.disableTransactions,
226
+ maxTxsPerBlock: config.validateMaxTxsPerBlock,
227
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint,
228
+ skipSlotValidation: config.skipProposalSlotValidation,
229
+ signatureContext: {
230
+ chainId: config.l1ChainId,
231
+ rollupAddress: config.rollupAddress,
232
+ },
233
+ clockDisparityMs: config.maxGossipClockDisparityMs ?? DEFAULT_MAX_GOSSIP_CLOCK_DISPARITY_MS,
156
234
  });
157
- const blockProposalHandler = new BlockProposalHandler(
158
- blockBuilder,
235
+ const proposalHandler = new ProposalHandler(
236
+ checkpointsBuilder,
237
+ worldState,
159
238
  blockSource,
160
239
  l1ToL2MessageSource,
161
240
  txProvider,
162
241
  blockProposalValidator,
242
+ epochCache,
243
+ consensusTimetable,
163
244
  config,
245
+ blobClient,
246
+ reexecutionTracker,
164
247
  metrics,
165
248
  dateProvider,
166
249
  telemetry,
250
+ undefined,
167
251
  );
168
252
 
253
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
254
+ let slashingProtectionSigner: ValidatorHASigner;
255
+ if (slashingProtectionDb) {
256
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
257
+ ({ signer: slashingProtectionSigner } = createSignerFromSharedDb(slashingProtectionDb, config, {
258
+ telemetryClient: telemetry,
259
+ dateProvider,
260
+ }));
261
+ } else if (config.haSigningEnabled) {
262
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
263
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
264
+ const haConfig = {
265
+ ...config,
266
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000,
267
+ };
268
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
269
+ telemetryClient: telemetry,
270
+ dateProvider,
271
+ }));
272
+ } else {
273
+ // Single-node mode: use LMDB-backed local signing protection.
274
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
275
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
276
+ telemetryClient: telemetry,
277
+ dateProvider,
278
+ }));
279
+ }
280
+ const validatorKeyStore: ExtendedValidatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
281
+
169
282
  const validator = new ValidatorClient(
170
- NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager),
283
+ validatorKeyStore,
171
284
  epochCache,
172
285
  p2pClient,
173
- blockProposalHandler,
286
+ proposalHandler,
287
+ blockSource,
288
+ checkpointsBuilder,
289
+ worldState,
290
+ l1ToL2MessageSource,
174
291
  config,
292
+ blobClient,
293
+ slashingProtectionSigner,
175
294
  dateProvider,
176
295
  telemetry,
177
296
  );
@@ -185,22 +304,19 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
185
304
  .filter(addr => !this.config.disabledValidators.some(disabled => disabled.equals(addr)));
186
305
  }
187
306
 
188
- public getBlockProposalHandler() {
189
- return this.blockProposalHandler;
307
+ public getProposalHandler() {
308
+ return this.proposalHandler;
190
309
  }
191
310
 
192
- // Proxy method for backwards compatibility with tests
193
- public reExecuteTransactions(
194
- proposal: BlockProposal,
195
- blockNumber: BlockNumber,
196
- txs: any[],
197
- l1ToL2Messages: Fr[],
198
- ): Promise<any> {
199
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
311
+ public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
312
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
200
313
  }
201
314
 
202
- public signWithAddress(addr: EthAddress, msg: TypedDataDefinition) {
203
- return this.keyStore.signTypedDataWithAddress(addr, msg);
315
+ private getSignatureContext(): CoordinationSignatureContext {
316
+ return {
317
+ chainId: this.config.l1ChainId,
318
+ rollupAddress: this.config.rollupAddress,
319
+ };
204
320
  }
205
321
 
206
322
  public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
@@ -215,8 +331,27 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
215
331
  return this.config;
216
332
  }
217
333
 
334
+ public hasProposalEquivocation(slotNumber: SlotNumber): boolean {
335
+ return this.proposalHandler.hasProposalEquivocation(slotNumber);
336
+ }
337
+
338
+ public hasInvalidProposals(slotNumber: SlotNumber): boolean {
339
+ return this.proposalHandler.hasInvalidProposals(slotNumber);
340
+ }
341
+
218
342
  public updateConfig(config: Partial<ValidatorClientFullConfig>) {
219
343
  this.config = { ...this.config, ...config };
344
+ this.proposalHandler.updateConfig(config);
345
+ }
346
+
347
+ public reloadKeystore(newManager: KeystoreManager): void {
348
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
349
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
350
+ this.validationService = new ValidationService(
351
+ this.keyStore,
352
+ this.getSignatureContext(),
353
+ this.log.createChild('validation-service'),
354
+ );
220
355
  }
221
356
 
222
357
  public async start() {
@@ -225,6 +360,8 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
225
360
  return;
226
361
  }
227
362
 
363
+ await this.keyStore.start();
364
+
228
365
  await this.registerHandlers();
229
366
 
230
367
  const myAddresses = this.getValidatorAddresses();
@@ -240,6 +377,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
240
377
 
241
378
  public async stop() {
242
379
  await this.epochCacheUpdateLoop.stop();
380
+ await this.keyStore.stop();
243
381
  }
244
382
 
245
383
  /** Register handlers on the p2p client */
@@ -248,9 +386,38 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
248
386
  this.hasRegisteredHandlers = true;
249
387
  this.log.debug(`Registering validator handlers for p2p client`);
250
388
 
251
- const handler = (block: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> =>
252
- this.attestToProposal(block, proposalSender);
253
- this.p2pClient.registerBlockProposalHandler(handler);
389
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
390
+ const blockHandler = (block: BlockProposal, proposalSender: PeerId): Promise<boolean> =>
391
+ this.validateBlockProposal(block, proposalSender);
392
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
393
+
394
+ // Checkpoint proposal handler - validates and creates attestations
395
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
396
+ // and processed separately via the block handler above.
397
+ const checkpointHandler = (
398
+ checkpoint: CheckpointProposalCore,
399
+ proposalSender: PeerId,
400
+ ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
401
+ this.p2pClient.registerValidatorCheckpointProposalHandler(checkpointHandler);
402
+
403
+ // Duplicate proposal handler - triggers slashing for equivocation
404
+ this.p2pClient.registerDuplicateProposalCallback((info: DuplicateProposalInfo) => {
405
+ this.handleDuplicateProposal(info);
406
+ });
407
+
408
+ // Oversized proposal handler - triggers slashing for proposals beyond the per-checkpoint block limit
409
+ this.p2pClient.registerOversizedProposalCallback((info: OversizedProposalInfo) => {
410
+ this.handleOversizedProposal(info);
411
+ });
412
+
413
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
414
+ this.p2pClient.registerDuplicateAttestationCallback((info: DuplicateAttestationInfo) => {
415
+ this.handleDuplicateAttestation(info);
416
+ });
417
+
418
+ this.p2pClient.registerCheckpointAttestationCallback((attestation: CheckpointAttestation) => {
419
+ this.handleCheckpointAttestation(attestation);
420
+ });
254
421
 
255
422
  const myAddresses = this.getValidatorAddresses();
256
423
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
@@ -259,48 +426,53 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
259
426
  }
260
427
  }
261
428
 
262
- async attestToProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> {
429
+ /**
430
+ * Validate a block proposal from a peer.
431
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
432
+ * @returns true if the proposal is valid, false otherwise
433
+ */
434
+ async validateBlockProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<boolean> {
263
435
  const slotNumber = proposal.slotNumber;
436
+
437
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
438
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
439
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
440
+
264
441
  const proposer = proposal.getSender();
265
442
 
266
443
  // Reject proposals with invalid signatures
267
444
  if (!proposer) {
268
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
269
- return undefined;
445
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
446
+ return false;
270
447
  }
271
448
 
272
- // Check that I have any address in current committee before attesting
449
+ // Log self-proposals from HA peers (same validator key on different nodes)
450
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
451
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
452
+ proposer: proposer.toString(),
453
+ slotNumber,
454
+ });
455
+ }
456
+
457
+ // Check if we're in the committee (for metrics purposes)
273
458
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
274
459
  const partOfCommittee = inCommittee.length > 0;
275
460
 
276
461
  const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
277
- this.log.info(`Received proposal for slot ${slotNumber}`, {
462
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
278
463
  ...proposalInfo,
279
464
  txHashes: proposal.txHashes.map(t => t.toString()),
280
465
  fishermanMode: this.config.fishermanMode || false,
281
466
  });
282
467
 
283
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
284
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
285
- // In fisherman mode, we always reexecute to validate proposals.
286
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
287
- this.config;
288
- const shouldReexecute =
289
- fishermanMode ||
290
- (slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
291
- (partOfCommittee && validatorReexecute) ||
292
- alwaysReexecuteBlockProposals;
293
-
294
- const validationResult = await this.blockProposalHandler.handleBlockProposal(
295
- proposal,
296
- proposalSender,
297
- !!shouldReexecute,
298
- );
468
+ // Reexecute outside the escape hatch so slashing observers can detect invalid proposals even when penalties are 0.
469
+ const validationResult = await this.proposalHandler.handleBlockProposal(proposal, proposalSender, !escapeHatchOpen);
299
470
 
300
471
  if (!validationResult.isValid) {
301
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
302
-
303
472
  const reason = validationResult.reason || 'unknown';
473
+
474
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
475
+
304
476
  // Classify failure reason: bad proposal vs node issue
305
477
  const badProposalReasons: BlockProposalValidationFailureReason[] = [
306
478
  'invalid_proposal',
@@ -313,22 +485,103 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
313
485
  if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
314
486
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
315
487
  } else {
316
- // Node issues so we can't attest
488
+ // Node issues so we can't validate
317
489
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
318
490
  }
319
491
 
320
- // Slash invalid block proposals (can happen even when not in committee)
321
492
  if (
493
+ !escapeHatchOpen &&
322
494
  validationResult.reason &&
323
- SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) &&
324
- slashBroadcastedInvalidBlockPenalty > 0n
495
+ SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason)
325
496
  ) {
326
- this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
497
+ this.log.info(`Detected invalid block proposal offense`, {
498
+ ...proposalInfo,
499
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
500
+ offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL),
501
+ });
327
502
  this.slashInvalidBlock(proposal);
503
+ this.markInvalidProposalSlot(proposal.slotNumber);
328
504
  }
505
+ return false;
506
+ }
507
+
508
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
509
+ ...proposalInfo,
510
+ inCommittee: partOfCommittee,
511
+ fishermanMode: this.config.fishermanMode || false,
512
+ escapeHatchOpen,
513
+ });
514
+
515
+ if (escapeHatchOpen) {
516
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
517
+ return false;
518
+ }
519
+
520
+ return true;
521
+ }
522
+
523
+ /**
524
+ * Validate and attest to a checkpoint proposal from a peer.
525
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
526
+ * the lastBlock is extracted and processed separately via the block handler.
527
+ * @returns Checkpoint attestations if valid, undefined otherwise
528
+ */
529
+ async attestToCheckpointProposal(
530
+ proposal: CheckpointProposalCore,
531
+ _proposalSender: PeerId,
532
+ ): Promise<CheckpointAttestation[] | undefined> {
533
+ const proposalSlotNumber = proposal.slotNumber;
534
+ const proposer = proposal.getSender();
535
+
536
+ // If escape hatch is open for this slot's epoch, do not attest.
537
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposalSlotNumber)) {
538
+ this.log.warn(`Escape hatch open for slot ${proposalSlotNumber}, skipping checkpoint attestation handling`);
329
539
  return undefined;
330
540
  }
331
541
 
542
+ // Early-out for equivocation: refuses if we've already attested to a higher slot.
543
+ if (!this.shouldAttestToSlot(proposalSlotNumber)) {
544
+ return undefined;
545
+ }
546
+
547
+ // Ignore proposals from ourselves (may happen in HA setups)
548
+ if (proposer && this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
549
+ this.log.debug(`Not attesting to block proposal from self for slot ${proposalSlotNumber}`, {
550
+ proposer: proposer.toString(),
551
+ proposalSlotNumber,
552
+ });
553
+ return undefined;
554
+ }
555
+
556
+ // Check that I have any address in the committee where this checkpoint will land before attesting
557
+ const inCommittee = await this.epochCache.filterInCommittee(proposalSlotNumber, this.getValidatorAddresses());
558
+ const partOfCommittee = inCommittee.length > 0;
559
+
560
+ const proposalInfo = {
561
+ proposalSlotNumber,
562
+ archive: proposal.archive.toString(),
563
+ proposer: proposer?.toString(),
564
+ };
565
+ this.log.info(`Received checkpoint proposal for slot ${proposalSlotNumber}`, {
566
+ ...proposalInfo,
567
+ fishermanMode: this.config.fishermanMode || false,
568
+ });
569
+
570
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set).
571
+ // Uses the cached result from the all-nodes callback if available (avoids double validation).
572
+ let checkpointNumber: CheckpointNumber;
573
+ if (this.config.skipCheckpointProposalValidation) {
574
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposalSlotNumber}`, proposalInfo);
575
+ checkpointNumber = CheckpointNumber(0);
576
+ } else {
577
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
578
+ if (!validationResult.isValid) {
579
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
580
+ return undefined;
581
+ }
582
+ checkpointNumber = validationResult.checkpointNumber;
583
+ }
584
+
332
585
  // Check that I have any address in current committee before attesting
333
586
  // In fisherman mode, we still create attestations for validation even if not in committee
334
587
  if (!partOfCommittee && !this.config.fishermanMode) {
@@ -337,15 +590,28 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
337
590
  }
338
591
 
339
592
  // Provided all of the above checks pass, we can attest to the proposal
340
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} proposal for slot ${slotNumber}`, {
341
- ...proposalInfo,
342
- inCommittee: partOfCommittee,
343
- fishermanMode: this.config.fishermanMode || false,
344
- });
593
+ this.log.info(
594
+ `${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`,
595
+ {
596
+ ...proposalInfo,
597
+ inCommittee: partOfCommittee,
598
+ fishermanMode: this.config.fishermanMode || false,
599
+ },
600
+ );
345
601
 
346
602
  this.metrics.incSuccessfulAttestations(inCommittee.length);
347
603
 
348
- // If the above function does not throw an error, then we can attest to the proposal
604
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
605
+ const proposalEpoch = getEpochAtSlot(proposalSlotNumber, this.epochCache.getL1Constants());
606
+ for (const attester of inCommittee) {
607
+ const key = attester.toString();
608
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
609
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
610
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
611
+ this.metrics.incAttestedEpochCount(attester);
612
+ }
613
+ }
614
+
349
615
  // Determine which validators should attest
350
616
  let attestors: EthAddress[];
351
617
  if (partOfCommittee) {
@@ -364,13 +630,83 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
364
630
 
365
631
  if (this.config.fishermanMode) {
366
632
  // bail out early and don't save attestations to the pool in fisherman mode
367
- this.log.info(`Creating attestations for proposal for slot ${slotNumber}`, {
633
+ this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
368
634
  ...proposalInfo,
369
635
  attestors: attestors.map(a => a.toString()),
370
636
  });
371
637
  return undefined;
372
638
  }
373
- return this.createBlockAttestationsFromProposal(proposal, attestors);
639
+
640
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors, checkpointNumber);
641
+ }
642
+
643
+ /**
644
+ * Checks if we should attest to a slot based on equivocation prevention rules.
645
+ * @returns true if we should attest, false if we should skip
646
+ */
647
+ private shouldAttestToSlot(slotNumber: SlotNumber): boolean {
648
+ // If attestToEquivocatedProposals is true, always allow
649
+ if (this.config.attestToEquivocatedProposals) {
650
+ return true;
651
+ }
652
+
653
+ // Check if incoming slot is strictly greater than last attested
654
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
655
+ this.log.warn(
656
+ `Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`,
657
+ );
658
+ return false;
659
+ }
660
+
661
+ return true;
662
+ }
663
+
664
+ private async createCheckpointAttestationsFromProposal(
665
+ proposal: CheckpointProposalCore,
666
+ attestors: EthAddress[] = [],
667
+ checkpointNumber: CheckpointNumber,
668
+ ): Promise<CheckpointAttestation[] | undefined> {
669
+ // Equivocation check: must happen right before signing to minimize the race window
670
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
671
+ return undefined;
672
+ }
673
+
674
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors, checkpointNumber);
675
+
676
+ // Track the proposal we attested to (to prevent equivocation)
677
+ this.lastAttestedProposal = proposal;
678
+
679
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
680
+ return attestations;
681
+ }
682
+
683
+ /**
684
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
685
+ */
686
+ protected async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
687
+ try {
688
+ const lastBlockHeader = (await this.blockSource.getBlockData({ archive: proposal.archive }))?.header;
689
+ if (!lastBlockHeader) {
690
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
691
+ return;
692
+ }
693
+
694
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
695
+ if (blocks.length === 0) {
696
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
697
+ return;
698
+ }
699
+
700
+ const blobFields = blocks.flatMap(b => b.toBlobFields());
701
+ const blobs: Blob[] = await getBlobsPerL1Block(blobFields);
702
+ await this.blobClient.sendBlobsToFilestore(blobs);
703
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
704
+ ...proposalInfo,
705
+ numBlobs: blobs.length,
706
+ });
707
+ } catch (err) {
708
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
709
+ }
374
710
  }
375
711
 
376
712
  private slashInvalidBlock(proposal: BlockProposal) {
@@ -382,12 +718,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
382
718
  return;
383
719
  }
384
720
 
385
- // Trim the set if it's too big.
386
- if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
387
- // remove oldest proposer. `values` is guaranteed to be in insertion order.
388
- this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value!);
389
- }
390
-
391
721
  this.proposersOfInvalidBlocks.add(proposer.toString());
392
722
 
393
723
  this.emit(WANT_TO_SLASH_EVENT, [
@@ -400,24 +730,274 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
400
730
  ]);
401
731
  }
402
732
 
733
+ private handleInvalidCheckpointProposal(
734
+ proposal: CheckpointProposalCore,
735
+ result: CheckpointProposalValidationFailureResult,
736
+ proposalInfo: LogData,
737
+ ): void {
738
+ if (!SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT[result.reason]) {
739
+ return;
740
+ }
741
+
742
+ // The slot is already marked invalid by the all-nodes checkpoint handler that invokes this callback,
743
+ // so we only emit the proposer slash event here.
744
+ if (this.slashInvalidCheckpointProposal(proposal)) {
745
+ this.log.info(`Detected invalid checkpoint proposal offense`, {
746
+ ...proposalInfo,
747
+ reason: result.reason,
748
+ amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
749
+ offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL),
750
+ });
751
+ }
752
+ }
753
+
754
+ private slashInvalidCheckpointProposal(proposal: CheckpointProposalCore): boolean {
755
+ const proposer = proposal.getSender();
756
+ if (!proposer) {
757
+ this.log.warn(`Cannot slash checkpoint proposal with invalid signature`, {
758
+ slotNumber: proposal.slotNumber,
759
+ archive: proposal.archive.toString(),
760
+ });
761
+ return false;
762
+ }
763
+
764
+ const offenseType = OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL;
765
+ const offenseKey = `${proposer.toString()}:${offenseType}:${proposal.slotNumber}`;
766
+ if (!this.invalidCheckpointProposalOffenseKeys.addIfAbsent(offenseKey)) {
767
+ return false;
768
+ }
769
+
770
+ this.emit(WANT_TO_SLASH_EVENT, [
771
+ {
772
+ validator: proposer,
773
+ amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
774
+ offenseType,
775
+ epochOrSlot: BigInt(proposal.slotNumber),
776
+ },
777
+ ]);
778
+ return true;
779
+ }
780
+
781
+ private markInvalidProposalSlot(slotNumber: SlotNumber): void {
782
+ this.proposalHandler.markInvalidProposalSlot(slotNumber);
783
+ }
784
+
785
+ private handleCheckpointAttestation(attestation: CheckpointAttestation): void {
786
+ const slotNumber = attestation.slotNumber;
787
+ if (
788
+ !this.proposalHandler.hasInvalidProposals(slotNumber) ||
789
+ this.proposalHandler.hasProposalEquivocation(slotNumber)
790
+ ) {
791
+ return;
792
+ }
793
+
794
+ const attester = attestation.getSender();
795
+ if (!attester) {
796
+ this.log.warn(`Cannot slash checkpoint attestation with invalid signature`, {
797
+ slotNumber,
798
+ archive: attestation.archive.toString(),
799
+ });
800
+ return;
801
+ }
802
+
803
+ this.slashAttestedToInvalidCheckpointProposal(slotNumber, attester);
804
+ }
805
+
806
+ private slashAttestedToInvalidCheckpointProposal(slotNumber: SlotNumber, attester: EthAddress): void {
807
+ const offenseKey = `${attester.toString()}:${OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL}:${slotNumber}`;
808
+ if (!this.badAttestationOffenseKeys.addIfAbsent(offenseKey)) {
809
+ return;
810
+ }
811
+
812
+ this.log.info(`Detected attestation to invalid checkpoint proposal offense`, {
813
+ attester: attester.toString(),
814
+ slotNumber,
815
+ amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
816
+ offenseType: getOffenseTypeName(OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL),
817
+ });
818
+
819
+ this.emit(WANT_TO_SLASH_EVENT, [
820
+ {
821
+ validator: attester,
822
+ amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
823
+ offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
824
+ epochOrSlot: BigInt(slotNumber),
825
+ },
826
+ ]);
827
+ }
828
+
829
+ /**
830
+ * Handle detection of an oversized block proposal: one whose index within its checkpoint lands at or
831
+ * beyond the consensus per-checkpoint block limit. A single signed proposal at an illegal index is
832
+ * self-contained evidence, so emit an invalid-block-proposal slash event for the proposer, deduped per
833
+ * (proposer, slot) since the p2p layer reports every oversized proposal it stores.
834
+ */
835
+ private handleOversizedProposal(info: OversizedProposalInfo): void {
836
+ const { slot, proposer } = info;
837
+ const offenseType = OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL;
838
+ if (!this.oversizedProposalOffenseKeys.addIfAbsent(`${proposer.toString()}:${offenseType}:${slot}`)) {
839
+ return;
840
+ }
841
+
842
+ this.log.info(`Detected oversized block proposal offense from ${proposer.toString()} at slot ${slot}`, {
843
+ proposer: proposer.toString(),
844
+ slot,
845
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
846
+ offenseType: getOffenseTypeName(offenseType),
847
+ });
848
+
849
+ this.emit(WANT_TO_SLASH_EVENT, [
850
+ {
851
+ validator: proposer,
852
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
853
+ offenseType,
854
+ epochOrSlot: BigInt(slot),
855
+ },
856
+ ]);
857
+ }
858
+
859
+ /**
860
+ * Handle detection of a duplicate proposal (equivocation).
861
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
862
+ */
863
+ private handleDuplicateProposal(info: DuplicateProposalInfo): void {
864
+ const { slot, proposer, type } = info;
865
+ this.proposalHandler.markProposalEquivocation(slot);
866
+
867
+ this.log.info(`Detected duplicate ${type} proposal offense from ${proposer.toString()} at slot ${slot}`, {
868
+ proposer: proposer.toString(),
869
+ slot,
870
+ type,
871
+ amount: this.config.slashDuplicateProposalPenalty,
872
+ offenseType: getOffenseTypeName(OffenseType.DUPLICATE_PROPOSAL),
873
+ });
874
+
875
+ this.emit(WANT_TO_SLASH_EVENT, [
876
+ {
877
+ validator: proposer,
878
+ amount: this.config.slashDuplicateProposalPenalty,
879
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
880
+ epochOrSlot: BigInt(slot),
881
+ },
882
+ ]);
883
+
884
+ this.emit(WANT_TO_CLEAR_SLASH_EVENT, [
885
+ {
886
+ offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
887
+ epochOrSlot: BigInt(slot),
888
+ },
889
+ ]);
890
+ }
891
+
892
+ /**
893
+ * Handle detection of a duplicate attestation (equivocation).
894
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
895
+ */
896
+ private handleDuplicateAttestation(info: DuplicateAttestationInfo): void {
897
+ const { slot, attester } = info;
898
+
899
+ this.log.info(`Detected duplicate attestation offense from ${attester.toString()} at slot ${slot}`, {
900
+ attester: attester.toString(),
901
+ slot,
902
+ amount: this.config.slashDuplicateAttestationPenalty,
903
+ offenseType: getOffenseTypeName(OffenseType.DUPLICATE_ATTESTATION),
904
+ });
905
+
906
+ this.emit(WANT_TO_SLASH_EVENT, [
907
+ {
908
+ validator: attester,
909
+ amount: this.config.slashDuplicateAttestationPenalty,
910
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
911
+ epochOrSlot: BigInt(slot),
912
+ },
913
+ ]);
914
+ }
915
+
403
916
  async createBlockProposal(
404
- blockNumber: BlockNumber,
405
- header: CheckpointHeader,
917
+ blockHeader: BlockHeader,
918
+ checkpointNumber: CheckpointNumber,
919
+ indexWithinCheckpoint: IndexWithinCheckpoint,
920
+ inHash: Fr,
406
921
  archive: Fr,
407
922
  txs: Tx[],
408
923
  proposerAddress: EthAddress | undefined,
409
- options: BlockProposalOptions,
410
- ): Promise<BlockProposal | undefined> {
411
- if (this.previousProposal?.slotNumber === header.slotNumber) {
412
- this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
413
- return Promise.resolve(undefined);
924
+ options: BlockProposalOptions = {},
925
+ ): Promise<BlockProposal> {
926
+ // Validate that we're not creating a proposal for an older or equal position
927
+ if (this.lastProposedBlock) {
928
+ const lastSlot = this.lastProposedBlock.slotNumber;
929
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
930
+ const newSlot = blockHeader.globalVariables.slotNumber;
931
+
932
+ if (newSlot < lastSlot || (newSlot === lastSlot && indexWithinCheckpoint <= lastIndex)) {
933
+ throw new Error(
934
+ `Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` +
935
+ `already proposed block for slot ${lastSlot} index ${lastIndex}`,
936
+ );
937
+ }
414
938
  }
415
939
 
416
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
417
- ...options,
418
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
419
- });
420
- this.previousProposal = newProposal;
940
+ this.log.info(
941
+ `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
942
+ );
943
+ const newProposal = await this.validationService.createBlockProposal(
944
+ blockHeader,
945
+ checkpointNumber,
946
+ indexWithinCheckpoint,
947
+ inHash,
948
+ archive,
949
+ txs,
950
+ proposerAddress,
951
+ {
952
+ ...options,
953
+ broadcastInvalidBlockProposal:
954
+ options.broadcastInvalidBlockProposal || this.config.broadcastInvalidBlockProposal,
955
+ },
956
+ );
957
+ this.lastProposedBlock = newProposal;
958
+ return newProposal;
959
+ }
960
+
961
+ async createCheckpointProposal(
962
+ checkpointHeader: CheckpointHeader,
963
+ archive: Fr,
964
+ checkpointNumber: CheckpointNumber,
965
+ feeAssetPriceModifier: bigint,
966
+ lastBlockProposal: BlockProposal | undefined,
967
+ proposerAddress: EthAddress | undefined,
968
+ options: CheckpointProposalOptions = {},
969
+ ): Promise<CheckpointProposal> {
970
+ // Validate that we're not creating a proposal for an older or equal slot
971
+ if (this.lastProposedCheckpoint) {
972
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
973
+ const newSlot = checkpointHeader.slotNumber;
974
+
975
+ if (newSlot <= lastSlot) {
976
+ throw new Error(
977
+ `Cannot create checkpoint proposal for slot ${newSlot}: ` +
978
+ `already proposed checkpoint for slot ${lastSlot}`,
979
+ );
980
+ }
981
+ }
982
+
983
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
984
+ const newProposal = await this.validationService.createCheckpointProposal(
985
+ checkpointHeader,
986
+ archive,
987
+ checkpointNumber,
988
+ feeAssetPriceModifier,
989
+ lastBlockProposal,
990
+ proposerAddress,
991
+ options,
992
+ );
993
+ this.lastProposedCheckpoint = newProposal;
994
+ // Self-record this slot's outcome on the re-execution tracker. Proposers don't run their
995
+ // own proposals through `handleCheckpointProposal`, so without this call the proposer's
996
+ // sentinel would see no outcome for slots it proposed and would mis-attribute itself as
997
+ // inactive. We pass the locally-computed `archive` (not `newProposal.archive`, which may
998
+ // be intentionally corrupted under test-only flags); from the proposer's local-view
999
+ // perspective the work it just completed is valid by definition.
1000
+ this.proposalHandler.recordOwnCheckpointProposalAsValid(checkpointHeader.slotNumber, archive, checkpointNumber);
421
1001
  return newProposal;
422
1002
  }
423
1003
 
@@ -428,28 +1008,47 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
428
1008
  async signAttestationsAndSigners(
429
1009
  attestationsAndSigners: CommitteeAttestationsAndSigners,
430
1010
  proposer: EthAddress,
1011
+ slot: SlotNumber,
1012
+ checkpointNumber: CheckpointNumber,
431
1013
  ): Promise<Signature> {
432
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
1014
+ return await this.validationService.signAttestationsAndSigners(
1015
+ attestationsAndSigners,
1016
+ proposer,
1017
+ slot,
1018
+ checkpointNumber,
1019
+ );
433
1020
  }
434
1021
 
435
- async collectOwnAttestations(proposal: BlockProposal): Promise<BlockAttestation[]> {
436
- const slot = proposal.payload.header.slotNumber;
1022
+ async collectOwnAttestations(
1023
+ proposal: CheckpointProposal,
1024
+ checkpointNumber: CheckpointNumber,
1025
+ ): Promise<CheckpointAttestation[]> {
1026
+ const slot = proposal.slotNumber;
437
1027
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
438
1028
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
439
- const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
1029
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
1030
+
1031
+ if (!attestations) {
1032
+ return [];
1033
+ }
440
1034
 
441
1035
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
442
1036
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
443
1037
  // due to inactivity for missed attestations.
444
- void this.p2pClient.broadcastAttestations(attestations).catch(err => {
1038
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch(err => {
445
1039
  this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
446
1040
  });
447
1041
  return attestations;
448
1042
  }
449
1043
 
450
- async collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]> {
451
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
452
- const slot = proposal.payload.header.slotNumber;
1044
+ async collectAttestations(
1045
+ proposal: CheckpointProposal,
1046
+ required: number,
1047
+ deadline: Date,
1048
+ checkpointNumber: CheckpointNumber,
1049
+ ): Promise<CheckpointAttestation[]> {
1050
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
1051
+ const slot = proposal.slotNumber;
453
1052
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
454
1053
 
455
1054
  if (+deadline < this.dateProvider.now()) {
@@ -459,33 +1058,23 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
459
1058
  throw new AttestationTimeoutError(0, required, slot);
460
1059
  }
461
1060
 
462
- await this.collectOwnAttestations(proposal);
1061
+ await this.collectOwnAttestations(proposal, checkpointNumber);
463
1062
 
464
- const proposalId = proposal.archive.toString();
1063
+ const proposalPayloadHash = proposal.getPayloadHash();
465
1064
  const myAddresses = this.getValidatorAddresses();
466
1065
 
467
- let attestations: BlockAttestation[] = [];
1066
+ let attestations: CheckpointAttestation[] = [];
468
1067
  while (true) {
469
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
470
- // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
471
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter(
472
- attestation => {
473
- if (!attestation.payload.equals(proposal.payload)) {
474
- this.log.warn(
475
- `Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`,
476
- { attestationPayload: attestation.payload, proposalPayload: proposal.payload },
477
- );
478
- return false;
479
- }
480
- return true;
481
- },
482
- );
1068
+ // The pool already filters by proposal payload hash; if any attestation slips through with a
1069
+ // mismatched payload hash, drop it defensively. Equivocations are emitted as separate slash
1070
+ // events from libp2p_service.
1071
+ const collectedAttestations = await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
483
1072
 
484
1073
  // Log new attestations we collected
485
1074
  const oldSenders = attestations.map(attestation => attestation.getSender());
486
1075
  for (const collected of collectedAttestations) {
487
1076
  const collectedSender = collected.getSender();
488
- // Skip attestations with invalid signatures
1077
+ // Skip attestations with invalid signatures. Should not happen as we don't add invalid attestations to our pool.
489
1078
  if (!collectedSender) {
490
1079
  this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
491
1080
  continue;
@@ -514,15 +1103,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
514
1103
  }
515
1104
  }
516
1105
 
517
- private async createBlockAttestationsFromProposal(
518
- proposal: BlockProposal,
519
- attestors: EthAddress[] = [],
520
- ): Promise<BlockAttestation[]> {
521
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
522
- await this.p2pClient.addAttestations(attestations);
523
- return attestations;
524
- }
525
-
526
1106
  private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
527
1107
  const authRequest = AuthRequest.fromBuffer(msg);
528
1108
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);
@@ -541,7 +1121,9 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
541
1121
  }
542
1122
 
543
1123
  const payloadToSign = authRequest.getPayloadToSign();
544
- const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
1124
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
1125
+ const context: SigningContext = { dutyType: DutyType.AUTH_REQUEST };
1126
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
545
1127
  const authResponse = new AuthResponse(statusMessage, signature);
546
1128
  return authResponse.toBuffer();
547
1129
  }