@aztec/validator-client 0.0.1-commit.b655e406 → 0.0.1-commit.c0b82b2

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 (57) hide show
  1. package/README.md +285 -0
  2. package/dest/block_proposal_handler.d.ts +25 -14
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +339 -93
  5. package/dest/checkpoint_builder.d.ts +69 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +180 -0
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +20 -7
  11. package/dest/duties/validation_service.d.ts +42 -13
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +113 -31
  14. package/dest/factory.d.ts +13 -8
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +2 -2
  17. package/dest/index.d.ts +2 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +1 -0
  20. package/dest/key_store/ha_key_store.d.ts +99 -0
  21. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  22. package/dest/key_store/ha_key_store.js +208 -0
  23. package/dest/key_store/index.d.ts +2 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +1 -0
  26. package/dest/key_store/interface.d.ts +36 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/local_key_store.d.ts +10 -5
  29. package/dest/key_store/local_key_store.d.ts.map +1 -1
  30. package/dest/key_store/local_key_store.js +9 -5
  31. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  32. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  33. package/dest/key_store/node_keystore_adapter.js +18 -4
  34. package/dest/key_store/web3signer_key_store.d.ts +10 -11
  35. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  36. package/dest/key_store/web3signer_key_store.js +9 -5
  37. package/dest/metrics.d.ts +4 -3
  38. package/dest/metrics.d.ts.map +1 -1
  39. package/dest/metrics.js +34 -30
  40. package/dest/validator.d.ts +75 -22
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +498 -65
  43. package/package.json +24 -14
  44. package/src/block_proposal_handler.ts +265 -73
  45. package/src/checkpoint_builder.ts +328 -0
  46. package/src/config.ts +20 -6
  47. package/src/duties/validation_service.ts +164 -38
  48. package/src/factory.ts +17 -8
  49. package/src/index.ts +1 -0
  50. package/src/key_store/ha_key_store.ts +269 -0
  51. package/src/key_store/index.ts +1 -0
  52. package/src/key_store/interface.ts +44 -5
  53. package/src/key_store/local_key_store.ts +14 -5
  54. package/src/key_store/node_keystore_adapter.ts +28 -5
  55. package/src/key_store/web3signer_key_store.ts +18 -5
  56. package/src/metrics.ts +45 -33
  57. package/src/validator.ts +669 -97
package/src/validator.ts CHANGED
@@ -1,30 +1,62 @@
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';
4
+ import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
5
+ import {
6
+ BlockNumber,
7
+ CheckpointNumber,
8
+ EpochNumber,
9
+ IndexWithinCheckpoint,
10
+ SlotNumber,
11
+ } from '@aztec/foundation/branded-types';
12
+ import { Fr } from '@aztec/foundation/curves/bn254';
13
+ import { TimeoutError } from '@aztec/foundation/error';
2
14
  import type { EthAddress } from '@aztec/foundation/eth-address';
3
15
  import type { Signature } from '@aztec/foundation/eth-signature';
4
- import { Fr } from '@aztec/foundation/fields';
5
- import { type Logger, createLogger } from '@aztec/foundation/log';
16
+ import { type LogData, type Logger, createLogger } from '@aztec/foundation/log';
17
+ import { retryUntil } from '@aztec/foundation/retry';
6
18
  import { RunningPromise } from '@aztec/foundation/running-promise';
7
19
  import { sleep } from '@aztec/foundation/sleep';
8
20
  import { DateProvider } from '@aztec/foundation/timer';
9
21
  import type { KeystoreManager } from '@aztec/node-keystore';
10
- import type { P2P, PeerId, TxProvider } from '@aztec/p2p';
22
+ import type { DuplicateAttestationInfo, DuplicateProposalInfo, P2P, PeerId } from '@aztec/p2p';
11
23
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
12
24
  import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
13
25
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
14
- import type { CommitteeAttestationsAndSigners, L2BlockSource } from '@aztec/stdlib/block';
15
- import type { IFullNodeBlockBuilder, Validator, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
16
- import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
17
- import type { BlockAttestation, BlockProposal, BlockProposalOptions } from '@aztec/stdlib/p2p';
26
+ import type { CommitteeAttestationsAndSigners, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
27
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
28
+ import type {
29
+ CreateCheckpointProposalLastBlockData,
30
+ ITxProvider,
31
+ Validator,
32
+ ValidatorClientFullConfig,
33
+ WorldStateSynchronizer,
34
+ } from '@aztec/stdlib/interfaces/server';
35
+ import { type L1ToL2MessageSource, accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
36
+ import {
37
+ type BlockProposal,
38
+ type BlockProposalOptions,
39
+ type CheckpointAttestation,
40
+ CheckpointProposal,
41
+ type CheckpointProposalCore,
42
+ type CheckpointProposalOptions,
43
+ } from '@aztec/stdlib/p2p';
18
44
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
19
- import type { StateReference, Tx } from '@aztec/stdlib/tx';
45
+ import type { BlockHeader, CheckpointGlobalVariables, Tx } from '@aztec/stdlib/tx';
20
46
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
21
47
  import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
48
+ import { createHASigner } from '@aztec/validator-ha-signer/factory';
49
+ import { DutyType, type SigningContext } from '@aztec/validator-ha-signer/types';
50
+ import type { ValidatorHASigner } from '@aztec/validator-ha-signer/validator-ha-signer';
22
51
 
23
52
  import { EventEmitter } from 'events';
24
53
  import type { TypedDataDefinition } from 'viem';
25
54
 
26
55
  import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
56
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
27
57
  import { ValidationService } from './duties/validation_service.js';
58
+ import { HAKeyStore } from './key_store/ha_key_store.js';
59
+ import type { ExtendedValidatorKeyStore } from './key_store/interface.js';
28
60
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
29
61
  import { ValidatorMetrics } from './metrics.js';
30
62
 
@@ -45,36 +77,52 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
45
77
  public readonly tracer: Tracer;
46
78
  private validationService: ValidationService;
47
79
  private metrics: ValidatorMetrics;
48
-
80
+ private log: Logger;
49
81
  // Whether it has already registered handlers on the p2p client
50
82
  private hasRegisteredHandlers = false;
51
83
 
52
- // Used to check if we are sending the same proposal twice
53
- private previousProposal?: BlockProposal;
84
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */
85
+ private lastProposedBlock?: BlockProposal;
86
+
87
+ /** Tracks the last checkpoint proposal we created. */
88
+ private lastProposedCheckpoint?: CheckpointProposal;
54
89
 
55
- private lastEpochForCommitteeUpdateLoop: bigint | undefined;
90
+ private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
56
91
  private epochCacheUpdateLoop: RunningPromise;
57
92
 
58
93
  private proposersOfInvalidBlocks: Set<string> = new Set();
59
94
 
95
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */
96
+ private lastAttestedProposal?: CheckpointProposalCore;
97
+
60
98
  protected constructor(
61
- private keyStore: NodeKeystoreAdapter,
99
+ private keyStore: ExtendedValidatorKeyStore,
62
100
  private epochCache: EpochCache,
63
101
  private p2pClient: P2P,
64
102
  private blockProposalHandler: BlockProposalHandler,
103
+ private blockSource: L2BlockSource,
104
+ private checkpointsBuilder: FullNodeCheckpointsBuilder,
105
+ private worldState: WorldStateSynchronizer,
106
+ private l1ToL2MessageSource: L1ToL2MessageSource,
65
107
  private config: ValidatorClientFullConfig,
108
+ private blobClient: BlobClientInterface,
109
+ private haSigner: ValidatorHASigner | undefined,
66
110
  private dateProvider: DateProvider = new DateProvider(),
67
111
  telemetry: TelemetryClient = getTelemetryClient(),
68
- private log = createLogger('validator'),
112
+ log = createLogger('validator'),
69
113
  ) {
70
114
  super();
115
+
116
+ // Create child logger with fisherman prefix if in fisherman mode
117
+ this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
118
+
71
119
  this.tracer = telemetry.getTracer('Validator');
72
120
  this.metrics = new ValidatorMetrics(telemetry);
73
121
 
74
- this.validationService = new ValidationService(keyStore, log.createChild('validation-service'));
122
+ this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
75
123
 
76
124
  // Refresh epoch cache every second to trigger alert if participation in committee changes
77
- this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), log, 1000);
125
+ this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
78
126
 
79
127
  const myAddresses = this.getValidatorAddresses();
80
128
  this.log.verbose(`Initialized validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
@@ -132,15 +180,17 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
132
180
  }
133
181
  }
134
182
 
135
- static new(
183
+ static async new(
136
184
  config: ValidatorClientFullConfig,
137
- blockBuilder: IFullNodeBlockBuilder,
185
+ checkpointsBuilder: FullNodeCheckpointsBuilder,
186
+ worldState: WorldStateSynchronizer,
138
187
  epochCache: EpochCache,
139
188
  p2pClient: P2P,
140
- blockSource: L2BlockSource,
189
+ blockSource: L2BlockSource & L2BlockSink,
141
190
  l1ToL2MessageSource: L1ToL2MessageSource,
142
- txProvider: TxProvider,
191
+ txProvider: ITxProvider,
143
192
  keyStoreManager: KeystoreManager,
193
+ blobClient: BlobClientInterface,
144
194
  dateProvider: DateProvider = new DateProvider(),
145
195
  telemetry: TelemetryClient = getTelemetryClient(),
146
196
  ) {
@@ -149,23 +199,45 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
149
199
  txsPermitted: !config.disableTransactions,
150
200
  });
151
201
  const blockProposalHandler = new BlockProposalHandler(
152
- blockBuilder,
202
+ checkpointsBuilder,
203
+ worldState,
153
204
  blockSource,
154
205
  l1ToL2MessageSource,
155
206
  txProvider,
156
207
  blockProposalValidator,
208
+ epochCache,
157
209
  config,
158
210
  metrics,
159
211
  dateProvider,
160
212
  telemetry,
161
213
  );
162
214
 
215
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
216
+ let validatorKeyStore: ExtendedValidatorKeyStore = nodeKeystoreAdapter;
217
+ let haSigner: ValidatorHASigner | undefined;
218
+ if (config.haSigningEnabled) {
219
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
220
+ const haConfig = {
221
+ ...config,
222
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000,
223
+ };
224
+ const { signer } = await createHASigner(haConfig, { telemetryClient: telemetry, dateProvider });
225
+ haSigner = signer;
226
+ validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, signer);
227
+ }
228
+
163
229
  const validator = new ValidatorClient(
164
- NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager),
230
+ validatorKeyStore,
165
231
  epochCache,
166
232
  p2pClient,
167
233
  blockProposalHandler,
234
+ blockSource,
235
+ checkpointsBuilder,
236
+ worldState,
237
+ l1ToL2MessageSource,
168
238
  config,
239
+ blobClient,
240
+ haSigner,
169
241
  dateProvider,
170
242
  telemetry,
171
243
  );
@@ -183,18 +255,8 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
183
255
  return this.blockProposalHandler;
184
256
  }
185
257
 
186
- // Proxy method for backwards compatibility with tests
187
- public reExecuteTransactions(
188
- proposal: BlockProposal,
189
- blockNumber: number,
190
- txs: any[],
191
- l1ToL2Messages: Fr[],
192
- ): Promise<any> {
193
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
194
- }
195
-
196
- public signWithAddress(addr: EthAddress, msg: TypedDataDefinition) {
197
- return this.keyStore.signTypedDataWithAddress(addr, msg);
258
+ public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
259
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
198
260
  }
199
261
 
200
262
  public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
@@ -213,24 +275,43 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
213
275
  this.config = { ...this.config, ...config };
214
276
  }
215
277
 
278
+ public reloadKeystore(newManager: KeystoreManager): void {
279
+ if (this.config.haSigningEnabled && !this.haSigner) {
280
+ this.log.warn(
281
+ 'HA signing is enabled in config but was not initialized at startup. ' +
282
+ 'Restart the node to enable HA signing.',
283
+ );
284
+ } else if (!this.config.haSigningEnabled && this.haSigner) {
285
+ this.log.warn(
286
+ 'HA signing was disabled via config update but the HA signer is still active. ' +
287
+ 'Restart the node to fully disable HA signing.',
288
+ );
289
+ }
290
+
291
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
292
+ if (this.haSigner) {
293
+ this.keyStore = new HAKeyStore(newAdapter, this.haSigner);
294
+ } else {
295
+ this.keyStore = newAdapter;
296
+ }
297
+ this.validationService = new ValidationService(this.keyStore, this.log.createChild('validation-service'));
298
+ }
299
+
216
300
  public async start() {
217
301
  if (this.epochCacheUpdateLoop.isRunning()) {
218
302
  this.log.warn(`Validator client already started`);
219
303
  return;
220
304
  }
221
305
 
306
+ await this.keyStore.start();
307
+
222
308
  await this.registerHandlers();
223
309
 
224
310
  const myAddresses = this.getValidatorAddresses();
225
311
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
312
+ this.log.info(`Started validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
226
313
  if (inCommittee.length > 0) {
227
- this.log.info(
228
- `Started validator with addresses in current validator committee: ${inCommittee
229
- .map(a => a.toString())
230
- .join(', ')}`,
231
- );
232
- } else {
233
- this.log.info(`Started validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
314
+ this.log.info(`Addresses in current validator committee: ${inCommittee.map(a => a.toString()).join(', ')}`);
234
315
  }
235
316
  this.epochCacheUpdateLoop.start();
236
317
 
@@ -239,6 +320,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
239
320
 
240
321
  public async stop() {
241
322
  await this.epochCacheUpdateLoop.stop();
323
+ await this.keyStore.stop();
242
324
  }
243
325
 
244
326
  /** Register handlers on the p2p client */
@@ -247,9 +329,29 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
247
329
  this.hasRegisteredHandlers = true;
248
330
  this.log.debug(`Registering validator handlers for p2p client`);
249
331
 
250
- const handler = (block: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> =>
251
- this.attestToProposal(block, proposalSender);
252
- this.p2pClient.registerBlockProposalHandler(handler);
332
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
333
+ const blockHandler = (block: BlockProposal, proposalSender: PeerId): Promise<boolean> =>
334
+ this.validateBlockProposal(block, proposalSender);
335
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
336
+
337
+ // Checkpoint proposal handler - validates and creates attestations
338
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
339
+ // and processed separately via the block handler above.
340
+ const checkpointHandler = (
341
+ checkpoint: CheckpointProposalCore,
342
+ proposalSender: PeerId,
343
+ ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
344
+ this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
345
+
346
+ // Duplicate proposal handler - triggers slashing for equivocation
347
+ this.p2pClient.registerDuplicateProposalCallback((info: DuplicateProposalInfo) => {
348
+ this.handleDuplicateProposal(info);
349
+ });
350
+
351
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
352
+ this.p2pClient.registerDuplicateAttestationCallback((info: DuplicateAttestationInfo) => {
353
+ this.handleDuplicateAttestation(info);
354
+ });
253
355
 
254
356
  const myAddresses = this.getValidatorAddresses();
255
357
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
@@ -258,42 +360,65 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
258
360
  }
259
361
  }
260
362
 
261
- async attestToProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> {
262
- const slotNumber = proposal.slotNumber.toBigInt();
363
+ /**
364
+ * Validate a block proposal from a peer.
365
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
366
+ * @returns true if the proposal is valid, false otherwise
367
+ */
368
+ async validateBlockProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<boolean> {
369
+ const slotNumber = proposal.slotNumber;
370
+
371
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
372
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
373
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
374
+
263
375
  const proposer = proposal.getSender();
264
376
 
265
377
  // Reject proposals with invalid signatures
266
378
  if (!proposer) {
267
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
268
- return undefined;
379
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
380
+ return false;
269
381
  }
270
382
 
271
- // Check that I have any address in current committee before attesting
383
+ // Ignore proposals from ourselves (may happen in HA setups)
384
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
385
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
386
+ proposer: proposer.toString(),
387
+ slotNumber,
388
+ });
389
+ return false;
390
+ }
391
+
392
+ // Check if we're in the committee (for metrics purposes)
272
393
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
273
394
  const partOfCommittee = inCommittee.length > 0;
274
395
 
275
396
  const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
276
- this.log.info(`Received proposal for slot ${slotNumber}`, {
397
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
277
398
  ...proposalInfo,
278
399
  txHashes: proposal.txHashes.map(t => t.toString()),
400
+ fishermanMode: this.config.fishermanMode || false,
279
401
  });
280
402
 
281
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
282
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
283
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals } = this.config;
403
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
404
+ // In fisherman mode, we always reexecute to validate proposals.
405
+ const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
406
+ this.config;
284
407
  const shouldReexecute =
408
+ fishermanMode ||
285
409
  (slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
286
410
  (partOfCommittee && validatorReexecute) ||
287
- alwaysReexecuteBlockProposals;
411
+ alwaysReexecuteBlockProposals ||
412
+ this.blobClient.canUpload();
288
413
 
289
414
  const validationResult = await this.blockProposalHandler.handleBlockProposal(
290
415
  proposal,
291
416
  proposalSender,
292
- !!shouldReexecute,
417
+ !!shouldReexecute && !escapeHatchOpen,
293
418
  );
294
419
 
295
420
  if (!validationResult.isValid) {
296
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
421
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
297
422
 
298
423
  const reason = validationResult.reason || 'unknown';
299
424
  // Classify failure reason: bad proposal vs node issue
@@ -308,12 +433,13 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
308
433
  if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
309
434
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
310
435
  } else {
311
- // Node issues so we can't attest
436
+ // Node issues so we can't validate
312
437
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
313
438
  }
314
439
 
315
440
  // Slash invalid block proposals (can happen even when not in committee)
316
441
  if (
442
+ !escapeHatchOpen &&
317
443
  validationResult.reason &&
318
444
  SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) &&
319
445
  slashBroadcastedInvalidBlockPenalty > 0n
@@ -321,21 +447,360 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
321
447
  this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
322
448
  this.slashInvalidBlock(proposal);
323
449
  }
450
+ return false;
451
+ }
452
+
453
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
454
+ ...proposalInfo,
455
+ inCommittee: partOfCommittee,
456
+ fishermanMode: this.config.fishermanMode || false,
457
+ escapeHatchOpen,
458
+ });
459
+
460
+ if (escapeHatchOpen) {
461
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
462
+ return false;
463
+ }
464
+
465
+ return true;
466
+ }
467
+
468
+ /**
469
+ * Validate and attest to a checkpoint proposal from a peer.
470
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
471
+ * the lastBlock is extracted and processed separately via the block handler.
472
+ * @returns Checkpoint attestations if valid, undefined otherwise
473
+ */
474
+ async attestToCheckpointProposal(
475
+ proposal: CheckpointProposalCore,
476
+ _proposalSender: PeerId,
477
+ ): Promise<CheckpointAttestation[] | undefined> {
478
+ const slotNumber = proposal.slotNumber;
479
+ const proposer = proposal.getSender();
480
+
481
+ // If escape hatch is open for this slot's epoch, do not attest.
482
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
483
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
484
+ return undefined;
485
+ }
486
+
487
+ // Reject proposals with invalid signatures
488
+ if (!proposer) {
489
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
490
+ return undefined;
491
+ }
492
+
493
+ // Ignore proposals from ourselves (may happen in HA setups)
494
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
495
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
496
+ proposer: proposer.toString(),
497
+ slotNumber,
498
+ });
499
+ return undefined;
500
+ }
501
+
502
+ // Validate fee asset price modifier is within allowed range
503
+ if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
504
+ this.log.warn(
505
+ `Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${slotNumber}`,
506
+ );
324
507
  return undefined;
325
508
  }
326
509
 
327
510
  // Check that I have any address in current committee before attesting
328
- if (!partOfCommittee) {
511
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
512
+ const partOfCommittee = inCommittee.length > 0;
513
+
514
+ const proposalInfo = {
515
+ slotNumber,
516
+ archive: proposal.archive.toString(),
517
+ proposer: proposer.toString(),
518
+ txCount: proposal.txHashes.length,
519
+ };
520
+ this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
521
+ ...proposalInfo,
522
+ txHashes: proposal.txHashes.map(t => t.toString()),
523
+ fishermanMode: this.config.fishermanMode || false,
524
+ });
525
+
526
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
527
+ if (this.config.skipCheckpointProposalValidation) {
528
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
529
+ } else {
530
+ const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
531
+ if (!validationResult.isValid) {
532
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
533
+ return undefined;
534
+ }
535
+ }
536
+
537
+ // Upload blobs to filestore if we can (fire and forget)
538
+ if (this.blobClient.canUpload()) {
539
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
540
+ }
541
+
542
+ // Check that I have any address in current committee before attesting
543
+ // In fisherman mode, we still create attestations for validation even if not in committee
544
+ if (!partOfCommittee && !this.config.fishermanMode) {
329
545
  this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
330
546
  return undefined;
331
547
  }
332
548
 
333
549
  // Provided all of the above checks pass, we can attest to the proposal
334
- this.log.info(`Attesting to proposal for slot ${slotNumber}`, proposalInfo);
550
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
551
+ ...proposalInfo,
552
+ inCommittee: partOfCommittee,
553
+ fishermanMode: this.config.fishermanMode || false,
554
+ });
555
+
335
556
  this.metrics.incSuccessfulAttestations(inCommittee.length);
336
557
 
337
- // If the above function does not throw an error, then we can attest to the proposal
338
- return this.createBlockAttestationsFromProposal(proposal, inCommittee);
558
+ // Determine which validators should attest
559
+ let attestors: EthAddress[];
560
+ if (partOfCommittee) {
561
+ attestors = inCommittee;
562
+ } else if (this.config.fishermanMode) {
563
+ // In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
564
+ attestors = this.getValidatorAddresses();
565
+ } else {
566
+ attestors = [];
567
+ }
568
+
569
+ // Only create attestations if we have attestors
570
+ if (attestors.length === 0) {
571
+ return undefined;
572
+ }
573
+
574
+ if (this.config.fishermanMode) {
575
+ // bail out early and don't save attestations to the pool in fisherman mode
576
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
577
+ ...proposalInfo,
578
+ attestors: attestors.map(a => a.toString()),
579
+ });
580
+ return undefined;
581
+ }
582
+
583
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors);
584
+ }
585
+
586
+ /**
587
+ * Checks if we should attest to a slot based on equivocation prevention rules.
588
+ * @returns true if we should attest, false if we should skip
589
+ */
590
+ private shouldAttestToSlot(slotNumber: SlotNumber): boolean {
591
+ // If attestToEquivocatedProposals is true, always allow
592
+ if (this.config.attestToEquivocatedProposals) {
593
+ return true;
594
+ }
595
+
596
+ // Check if incoming slot is strictly greater than last attested
597
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
598
+ this.log.warn(
599
+ `Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`,
600
+ );
601
+ return false;
602
+ }
603
+
604
+ return true;
605
+ }
606
+
607
+ private async createCheckpointAttestationsFromProposal(
608
+ proposal: CheckpointProposalCore,
609
+ attestors: EthAddress[] = [],
610
+ ): Promise<CheckpointAttestation[] | undefined> {
611
+ // Equivocation check: must happen right before signing to minimize the race window
612
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
613
+ return undefined;
614
+ }
615
+
616
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
617
+
618
+ // Track the proposal we attested to (to prevent equivocation)
619
+ this.lastAttestedProposal = proposal;
620
+
621
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
622
+ return attestations;
623
+ }
624
+
625
+ /**
626
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
627
+ * @returns Validation result with isValid flag and reason if invalid.
628
+ */
629
+ private async validateCheckpointProposal(
630
+ proposal: CheckpointProposalCore,
631
+ proposalInfo: LogData,
632
+ ): Promise<{ isValid: true } | { isValid: false; reason: string }> {
633
+ const slot = proposal.slotNumber;
634
+
635
+ // Timeout block syncing at the start of the next slot
636
+ const config = this.checkpointsBuilder.getConfig();
637
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
638
+ const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
639
+
640
+ // Wait for last block to sync by archive
641
+ let lastBlockHeader: BlockHeader | undefined;
642
+ try {
643
+ lastBlockHeader = await retryUntil(
644
+ async () => {
645
+ await this.blockSource.syncImmediate();
646
+ return this.blockSource.getBlockHeaderByArchive(proposal.archive);
647
+ },
648
+ `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
649
+ timeoutSeconds,
650
+ 0.5,
651
+ );
652
+ } catch (err) {
653
+ if (err instanceof TimeoutError) {
654
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
655
+ return { isValid: false, reason: 'last_block_not_found' };
656
+ }
657
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
658
+ return { isValid: false, reason: 'block_fetch_error' };
659
+ }
660
+
661
+ if (!lastBlockHeader) {
662
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
663
+ return { isValid: false, reason: 'last_block_not_found' };
664
+ }
665
+
666
+ // Get all full blocks for the slot and checkpoint
667
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
668
+ if (blocks.length === 0) {
669
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
670
+ return { isValid: false, reason: 'no_blocks_for_slot' };
671
+ }
672
+
673
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
674
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
675
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
676
+ return { isValid: false, reason: 'last_block_archive_mismatch' };
677
+ }
678
+
679
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
680
+ ...proposalInfo,
681
+ blockNumbers: blocks.map(b => b.number),
682
+ });
683
+
684
+ // Get checkpoint constants from first block
685
+ const firstBlock = blocks[0];
686
+ const constants = this.extractCheckpointConstants(firstBlock);
687
+ const checkpointNumber = firstBlock.checkpointNumber;
688
+
689
+ // Get L1-to-L2 messages for this checkpoint
690
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
691
+
692
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
693
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
694
+ const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch))
695
+ .filter(c => c.checkpointNumber < checkpointNumber)
696
+ .map(c => c.checkpointOutHash);
697
+
698
+ // Fork world state at the block before the first block
699
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
700
+ const fork = await this.worldState.fork(parentBlockNumber);
701
+
702
+ try {
703
+ // Create checkpoint builder with all existing blocks
704
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
705
+ checkpointNumber,
706
+ constants,
707
+ proposal.feeAssetPriceModifier,
708
+ l1ToL2Messages,
709
+ previousCheckpointOutHashes,
710
+ fork,
711
+ blocks,
712
+ this.log.getBindings(),
713
+ );
714
+
715
+ // Complete the checkpoint to get computed values
716
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
717
+
718
+ // Compare checkpoint header with proposal
719
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
720
+ this.log.warn(`Checkpoint header mismatch`, {
721
+ ...proposalInfo,
722
+ computed: computedCheckpoint.header.toInspect(),
723
+ proposal: proposal.checkpointHeader.toInspect(),
724
+ });
725
+ return { isValid: false, reason: 'checkpoint_header_mismatch' };
726
+ }
727
+
728
+ // Compare archive root with proposal
729
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
730
+ this.log.warn(`Archive root mismatch`, {
731
+ ...proposalInfo,
732
+ computed: computedCheckpoint.archive.root.toString(),
733
+ proposal: proposal.archive.toString(),
734
+ });
735
+ return { isValid: false, reason: 'archive_mismatch' };
736
+ }
737
+
738
+ // Check that the accumulated epoch out hash matches the value in the proposal.
739
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
740
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
741
+ const computedEpochOutHash = accumulateCheckpointOutHashes([...previousCheckpointOutHashes, checkpointOutHash]);
742
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
743
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
744
+ this.log.warn(`Epoch out hash mismatch`, {
745
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
746
+ computedEpochOutHash: computedEpochOutHash.toString(),
747
+ checkpointOutHash: checkpointOutHash.toString(),
748
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map(h => h.toString()),
749
+ ...proposalInfo,
750
+ });
751
+ return { isValid: false, reason: 'out_hash_mismatch' };
752
+ }
753
+
754
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
755
+ return { isValid: true };
756
+ } finally {
757
+ await fork.close();
758
+ }
759
+ }
760
+
761
+ /**
762
+ * Extract checkpoint global variables from a block.
763
+ */
764
+ private extractCheckpointConstants(block: L2Block): CheckpointGlobalVariables {
765
+ const gv = block.header.globalVariables;
766
+ return {
767
+ chainId: gv.chainId,
768
+ version: gv.version,
769
+ slotNumber: gv.slotNumber,
770
+ timestamp: gv.timestamp,
771
+ coinbase: gv.coinbase,
772
+ feeRecipient: gv.feeRecipient,
773
+ gasFees: gv.gasFees,
774
+ };
775
+ }
776
+
777
+ /**
778
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
779
+ */
780
+ protected async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
781
+ try {
782
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
783
+ if (!lastBlockHeader) {
784
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
785
+ return;
786
+ }
787
+
788
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
789
+ if (blocks.length === 0) {
790
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
791
+ return;
792
+ }
793
+
794
+ const blobFields = blocks.flatMap(b => b.toBlobFields());
795
+ const blobs: Blob[] = await getBlobsPerL1Block(blobFields);
796
+ await this.blobClient.sendBlobsToFilestore(blobs);
797
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
798
+ ...proposalInfo,
799
+ numBlobs: blobs.length,
800
+ });
801
+ } catch (err) {
802
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
803
+ }
339
804
  }
340
805
 
341
806
  private slashInvalidBlock(proposal: BlockProposal) {
@@ -360,34 +825,130 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
360
825
  validator: proposer,
361
826
  amount: this.config.slashBroadcastedInvalidBlockPenalty,
362
827
  offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
363
- epochOrSlot: proposal.slotNumber.toBigInt(),
828
+ epochOrSlot: BigInt(proposal.slotNumber),
829
+ },
830
+ ]);
831
+ }
832
+
833
+ /**
834
+ * Handle detection of a duplicate proposal (equivocation).
835
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
836
+ */
837
+ private handleDuplicateProposal(info: DuplicateProposalInfo): void {
838
+ const { slot, proposer, type } = info;
839
+
840
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
841
+ proposer: proposer.toString(),
842
+ slot,
843
+ type,
844
+ });
845
+
846
+ // Emit slash event
847
+ this.emit(WANT_TO_SLASH_EVENT, [
848
+ {
849
+ validator: proposer,
850
+ amount: this.config.slashDuplicateProposalPenalty,
851
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
852
+ epochOrSlot: BigInt(slot),
853
+ },
854
+ ]);
855
+ }
856
+
857
+ /**
858
+ * Handle detection of a duplicate attestation (equivocation).
859
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
860
+ */
861
+ private handleDuplicateAttestation(info: DuplicateAttestationInfo): void {
862
+ const { slot, attester } = info;
863
+
864
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
865
+ attester: attester.toString(),
866
+ slot,
867
+ });
868
+
869
+ this.emit(WANT_TO_SLASH_EVENT, [
870
+ {
871
+ validator: attester,
872
+ amount: this.config.slashDuplicateAttestationPenalty,
873
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
874
+ epochOrSlot: BigInt(slot),
364
875
  },
365
876
  ]);
366
877
  }
367
878
 
368
879
  async createBlockProposal(
369
- blockNumber: number,
370
- header: CheckpointHeader,
880
+ blockHeader: BlockHeader,
881
+ indexWithinCheckpoint: IndexWithinCheckpoint,
882
+ inHash: Fr,
371
883
  archive: Fr,
372
- stateReference: StateReference,
373
884
  txs: Tx[],
374
885
  proposerAddress: EthAddress | undefined,
375
- options: BlockProposalOptions,
376
- ): Promise<BlockProposal | undefined> {
377
- if (this.previousProposal?.slotNumber.equals(header.slotNumber)) {
378
- this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
379
- return Promise.resolve(undefined);
886
+ options: BlockProposalOptions = {},
887
+ ): Promise<BlockProposal> {
888
+ // Validate that we're not creating a proposal for an older or equal position
889
+ if (this.lastProposedBlock) {
890
+ const lastSlot = this.lastProposedBlock.slotNumber;
891
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
892
+ const newSlot = blockHeader.globalVariables.slotNumber;
893
+
894
+ if (newSlot < lastSlot || (newSlot === lastSlot && indexWithinCheckpoint <= lastIndex)) {
895
+ throw new Error(
896
+ `Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` +
897
+ `already proposed block for slot ${lastSlot} index ${lastIndex}`,
898
+ );
899
+ }
380
900
  }
381
901
 
902
+ this.log.info(
903
+ `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
904
+ );
382
905
  const newProposal = await this.validationService.createBlockProposal(
383
- header,
906
+ blockHeader,
907
+ indexWithinCheckpoint,
908
+ inHash,
384
909
  archive,
385
- stateReference,
386
910
  txs,
387
911
  proposerAddress,
388
- { ...options, broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal },
912
+ {
913
+ ...options,
914
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
915
+ },
916
+ );
917
+ this.lastProposedBlock = newProposal;
918
+ return newProposal;
919
+ }
920
+
921
+ async createCheckpointProposal(
922
+ checkpointHeader: CheckpointHeader,
923
+ archive: Fr,
924
+ feeAssetPriceModifier: bigint,
925
+ lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
926
+ proposerAddress: EthAddress | undefined,
927
+ options: CheckpointProposalOptions = {},
928
+ ): Promise<CheckpointProposal> {
929
+ // Validate that we're not creating a proposal for an older or equal slot
930
+ if (this.lastProposedCheckpoint) {
931
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
932
+ const newSlot = checkpointHeader.slotNumber;
933
+
934
+ if (newSlot <= lastSlot) {
935
+ throw new Error(
936
+ `Cannot create checkpoint proposal for slot ${newSlot}: ` +
937
+ `already proposed checkpoint for slot ${lastSlot}`,
938
+ );
939
+ }
940
+ }
941
+
942
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
943
+ const newProposal = await this.validationService.createCheckpointProposal(
944
+ checkpointHeader,
945
+ archive,
946
+ feeAssetPriceModifier,
947
+ lastBlockInfo,
948
+ proposerAddress,
949
+ options,
389
950
  );
390
- this.previousProposal = newProposal;
951
+ this.lastProposedCheckpoint = newProposal;
391
952
  return newProposal;
392
953
  }
393
954
 
@@ -398,20 +959,38 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
398
959
  async signAttestationsAndSigners(
399
960
  attestationsAndSigners: CommitteeAttestationsAndSigners,
400
961
  proposer: EthAddress,
962
+ slot: SlotNumber,
963
+ blockNumber: BlockNumber | CheckpointNumber,
401
964
  ): Promise<Signature> {
402
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
965
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
403
966
  }
404
967
 
405
- async collectOwnAttestations(proposal: BlockProposal): Promise<BlockAttestation[]> {
406
- const slot = proposal.payload.header.slotNumber.toBigInt();
968
+ async collectOwnAttestations(proposal: CheckpointProposal): Promise<CheckpointAttestation[]> {
969
+ const slot = proposal.slotNumber;
407
970
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
408
971
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
409
- return this.createBlockAttestationsFromProposal(proposal, inCommittee);
972
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
973
+
974
+ if (!attestations) {
975
+ return [];
976
+ }
977
+
978
+ // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
979
+ // other nodes can see that our validators did attest to this block proposal, and do not slash us
980
+ // due to inactivity for missed attestations.
981
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch(err => {
982
+ this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
983
+ });
984
+ return attestations;
410
985
  }
411
986
 
412
- async collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]> {
413
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
414
- const slot = proposal.payload.header.slotNumber.toBigInt();
987
+ async collectAttestations(
988
+ proposal: CheckpointProposal,
989
+ required: number,
990
+ deadline: Date,
991
+ ): Promise<CheckpointAttestation[]> {
992
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
993
+ const slot = proposal.slotNumber;
415
994
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
416
995
 
417
996
  if (+deadline < this.dateProvider.now()) {
@@ -426,16 +1005,16 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
426
1005
  const proposalId = proposal.archive.toString();
427
1006
  const myAddresses = this.getValidatorAddresses();
428
1007
 
429
- let attestations: BlockAttestation[] = [];
1008
+ let attestations: CheckpointAttestation[] = [];
430
1009
  while (true) {
431
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
1010
+ // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
432
1011
  // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
433
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter(
1012
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter(
434
1013
  attestation => {
435
- if (!attestation.payload.equals(proposal.payload)) {
1014
+ if (!attestation.archive.equals(proposal.archive)) {
436
1015
  this.log.warn(
437
- `Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`,
438
- { attestationPayload: attestation.payload, proposalPayload: proposal.payload },
1016
+ `Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`,
1017
+ { attestationArchive: attestation.archive.toString(), proposalArchive: proposal.archive.toString() },
439
1018
  );
440
1019
  return false;
441
1020
  }
@@ -476,15 +1055,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
476
1055
  }
477
1056
  }
478
1057
 
479
- private async createBlockAttestationsFromProposal(
480
- proposal: BlockProposal,
481
- attestors: EthAddress[] = [],
482
- ): Promise<BlockAttestation[]> {
483
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
484
- await this.p2pClient.addAttestations(attestations);
485
- return attestations;
486
- }
487
-
488
1058
  private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
489
1059
  const authRequest = AuthRequest.fromBuffer(msg);
490
1060
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);
@@ -503,7 +1073,9 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
503
1073
  }
504
1074
 
505
1075
  const payloadToSign = authRequest.getPayloadToSign();
506
- const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
1076
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
1077
+ const context: SigningContext = { dutyType: DutyType.AUTH_REQUEST };
1078
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
507
1079
  const authResponse = new AuthResponse(statusMessage, signature);
508
1080
  return authResponse.toBuffer();
509
1081
  }