@aztec/validator-client 0.0.1-commit.fcb71a6 → 0.0.1-commit.ff7989d6c

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 (69) hide show
  1. package/README.md +285 -0
  2. package/dest/block_proposal_handler.d.ts +21 -11
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +327 -85
  5. package/dest/checkpoint_builder.d.ts +66 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +175 -0
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +16 -8
  11. package/dest/duties/validation_service.d.ts +41 -12
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +109 -26
  14. package/dest/factory.d.ts +13 -10
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +2 -2
  17. package/dest/index.d.ts +3 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +2 -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 +8 -4
  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 -5
  35. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  36. package/dest/key_store/web3signer_key_store.js +8 -4
  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/tx_validator/index.d.ts +3 -0
  41. package/dest/tx_validator/index.d.ts.map +1 -0
  42. package/dest/tx_validator/index.js +2 -0
  43. package/dest/tx_validator/nullifier_cache.d.ts +14 -0
  44. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
  45. package/dest/tx_validator/nullifier_cache.js +24 -0
  46. package/dest/tx_validator/tx_validator_factory.d.ts +19 -0
  47. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  48. package/dest/tx_validator/tx_validator_factory.js +54 -0
  49. package/dest/validator.d.ts +73 -24
  50. package/dest/validator.d.ts.map +1 -1
  51. package/dest/validator.js +452 -91
  52. package/package.json +21 -13
  53. package/src/block_proposal_handler.ts +246 -57
  54. package/src/checkpoint_builder.ts +321 -0
  55. package/src/config.ts +15 -7
  56. package/src/duties/validation_service.ts +160 -31
  57. package/src/factory.ts +17 -11
  58. package/src/index.ts +2 -0
  59. package/src/key_store/ha_key_store.ts +269 -0
  60. package/src/key_store/index.ts +1 -0
  61. package/src/key_store/interface.ts +44 -5
  62. package/src/key_store/local_key_store.ts +13 -4
  63. package/src/key_store/node_keystore_adapter.ts +27 -4
  64. package/src/key_store/web3signer_key_store.ts +17 -4
  65. package/src/metrics.ts +45 -33
  66. package/src/tx_validator/index.ts +2 -0
  67. package/src/tx_validator/nullifier_cache.ts +30 -0
  68. package/src/tx_validator/tx_validator_factory.ts +154 -0
  69. package/src/validator.ts +615 -120
package/src/validator.ts CHANGED
@@ -1,33 +1,62 @@
1
- import type { FileStoreBlobClient } from '@aztec/blob-client/filestore';
2
- import { getBlobsPerL1Block } from '@aztec/blob-lib';
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
2
+ import { type Blob, getBlobsPerL1Block } from '@aztec/blob-lib';
3
3
  import type { EpochCache } from '@aztec/epoch-cache';
4
- import { BlockNumber, EpochNumber } from '@aztec/foundation/branded-types';
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';
5
12
  import { Fr } from '@aztec/foundation/curves/bn254';
13
+ import { TimeoutError } from '@aztec/foundation/error';
6
14
  import type { EthAddress } from '@aztec/foundation/eth-address';
7
15
  import type { Signature } from '@aztec/foundation/eth-signature';
8
- 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';
9
18
  import { RunningPromise } from '@aztec/foundation/running-promise';
10
19
  import { sleep } from '@aztec/foundation/sleep';
11
20
  import { DateProvider } from '@aztec/foundation/timer';
12
21
  import type { KeystoreManager } from '@aztec/node-keystore';
13
- import type { P2P, PeerId, TxProvider } from '@aztec/p2p';
22
+ import type { DuplicateAttestationInfo, DuplicateProposalInfo, P2P, PeerId } from '@aztec/p2p';
14
23
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
15
24
  import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
16
25
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
17
- import type { CommitteeAttestationsAndSigners, L2BlockSource } from '@aztec/stdlib/block';
18
- import type { IFullNodeBlockBuilder, Validator, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
19
- import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
20
- 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';
21
44
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
22
- import type { Tx } from '@aztec/stdlib/tx';
45
+ import type { BlockHeader, CheckpointGlobalVariables, Tx } from '@aztec/stdlib/tx';
23
46
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
24
- import { Attributes, type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
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';
25
51
 
26
52
  import { EventEmitter } from 'events';
27
53
  import type { TypedDataDefinition } from 'viem';
28
54
 
29
55
  import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
56
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
30
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';
31
60
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
32
61
  import { ValidatorMetrics } from './metrics.js';
33
62
 
@@ -49,25 +78,35 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
49
78
  private validationService: ValidationService;
50
79
  private metrics: ValidatorMetrics;
51
80
  private log: Logger;
52
-
53
81
  // Whether it has already registered handlers on the p2p client
54
82
  private hasRegisteredHandlers = false;
55
83
 
56
- // Used to check if we are sending the same proposal twice
57
- 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;
58
89
 
59
90
  private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
60
91
  private epochCacheUpdateLoop: RunningPromise;
61
92
 
62
93
  private proposersOfInvalidBlocks: Set<string> = new Set();
63
94
 
95
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */
96
+ private lastAttestedProposal?: CheckpointProposalCore;
97
+
64
98
  protected constructor(
65
- private keyStore: NodeKeystoreAdapter,
99
+ private keyStore: ExtendedValidatorKeyStore,
66
100
  private epochCache: EpochCache,
67
101
  private p2pClient: P2P,
68
102
  private blockProposalHandler: BlockProposalHandler,
103
+ private blockSource: L2BlockSource,
104
+ private checkpointsBuilder: FullNodeCheckpointsBuilder,
105
+ private worldState: WorldStateSynchronizer,
106
+ private l1ToL2MessageSource: L1ToL2MessageSource,
69
107
  private config: ValidatorClientFullConfig,
70
- private fileStoreBlobUploadClient: FileStoreBlobClient | undefined,
108
+ private blobClient: BlobClientInterface,
109
+ private haSigner: ValidatorHASigner | undefined,
71
110
  private dateProvider: DateProvider = new DateProvider(),
72
111
  telemetry: TelemetryClient = getTelemetryClient(),
73
112
  log = createLogger('validator'),
@@ -141,16 +180,17 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
141
180
  }
142
181
  }
143
182
 
144
- static new(
183
+ static async new(
145
184
  config: ValidatorClientFullConfig,
146
- blockBuilder: IFullNodeBlockBuilder,
185
+ checkpointsBuilder: FullNodeCheckpointsBuilder,
186
+ worldState: WorldStateSynchronizer,
147
187
  epochCache: EpochCache,
148
188
  p2pClient: P2P,
149
- blockSource: L2BlockSource,
189
+ blockSource: L2BlockSource & L2BlockSink,
150
190
  l1ToL2MessageSource: L1ToL2MessageSource,
151
- txProvider: TxProvider,
191
+ txProvider: ITxProvider,
152
192
  keyStoreManager: KeystoreManager,
153
- fileStoreBlobUploadClient?: FileStoreBlobClient,
193
+ blobClient: BlobClientInterface,
154
194
  dateProvider: DateProvider = new DateProvider(),
155
195
  telemetry: TelemetryClient = getTelemetryClient(),
156
196
  ) {
@@ -159,24 +199,45 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
159
199
  txsPermitted: !config.disableTransactions,
160
200
  });
161
201
  const blockProposalHandler = new BlockProposalHandler(
162
- blockBuilder,
202
+ checkpointsBuilder,
203
+ worldState,
163
204
  blockSource,
164
205
  l1ToL2MessageSource,
165
206
  txProvider,
166
207
  blockProposalValidator,
208
+ epochCache,
167
209
  config,
168
210
  metrics,
169
211
  dateProvider,
170
212
  telemetry,
171
213
  );
172
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
+
173
229
  const validator = new ValidatorClient(
174
- NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager),
230
+ validatorKeyStore,
175
231
  epochCache,
176
232
  p2pClient,
177
233
  blockProposalHandler,
234
+ blockSource,
235
+ checkpointsBuilder,
236
+ worldState,
237
+ l1ToL2MessageSource,
178
238
  config,
179
- fileStoreBlobUploadClient,
239
+ blobClient,
240
+ haSigner,
180
241
  dateProvider,
181
242
  telemetry,
182
243
  );
@@ -194,18 +255,8 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
194
255
  return this.blockProposalHandler;
195
256
  }
196
257
 
197
- // Proxy method for backwards compatibility with tests
198
- public reExecuteTransactions(
199
- proposal: BlockProposal,
200
- blockNumber: BlockNumber,
201
- txs: any[],
202
- l1ToL2Messages: Fr[],
203
- ): Promise<any> {
204
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
205
- }
206
-
207
- public signWithAddress(addr: EthAddress, msg: TypedDataDefinition) {
208
- return this.keyStore.signTypedDataWithAddress(addr, msg);
258
+ public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
259
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
209
260
  }
210
261
 
211
262
  public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
@@ -224,12 +275,36 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
224
275
  this.config = { ...this.config, ...config };
225
276
  }
226
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
+
227
300
  public async start() {
228
301
  if (this.epochCacheUpdateLoop.isRunning()) {
229
302
  this.log.warn(`Validator client already started`);
230
303
  return;
231
304
  }
232
305
 
306
+ await this.keyStore.start();
307
+
233
308
  await this.registerHandlers();
234
309
 
235
310
  const myAddresses = this.getValidatorAddresses();
@@ -245,6 +320,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
245
320
 
246
321
  public async stop() {
247
322
  await this.epochCacheUpdateLoop.stop();
323
+ await this.keyStore.stop();
248
324
  }
249
325
 
250
326
  /** Register handlers on the p2p client */
@@ -253,9 +329,29 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
253
329
  this.hasRegisteredHandlers = true;
254
330
  this.log.debug(`Registering validator handlers for p2p client`);
255
331
 
256
- const handler = (block: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> =>
257
- this.attestToProposal(block, proposalSender);
258
- 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
+ });
259
355
 
260
356
  const myAddresses = this.getValidatorAddresses();
261
357
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
@@ -264,33 +360,47 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
264
360
  }
265
361
  }
266
362
 
267
- @trackSpan('validator.attestToProposal', (proposal, proposalSender) => ({
268
- [Attributes.BLOCK_HASH]: proposal.payload.header.hash.toString(),
269
- [Attributes.PEER_ID]: proposalSender.toString(),
270
- }))
271
- async attestToProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> {
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> {
272
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
+
273
375
  const proposer = proposal.getSender();
274
376
 
275
377
  // Reject proposals with invalid signatures
276
378
  if (!proposer) {
277
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
278
- return undefined;
379
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
380
+ return false;
279
381
  }
280
382
 
281
- // 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)
282
393
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
283
394
  const partOfCommittee = inCommittee.length > 0;
284
395
 
285
396
  const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
286
- this.log.info(`Received proposal for slot ${slotNumber}`, {
397
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
287
398
  ...proposalInfo,
288
399
  txHashes: proposal.txHashes.map(t => t.toString()),
289
400
  fishermanMode: this.config.fishermanMode || false,
290
401
  });
291
402
 
292
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
293
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
403
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
294
404
  // In fisherman mode, we always reexecute to validate proposals.
295
405
  const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
296
406
  this.config;
@@ -299,16 +409,16 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
299
409
  (slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
300
410
  (partOfCommittee && validatorReexecute) ||
301
411
  alwaysReexecuteBlockProposals ||
302
- this.fileStoreBlobUploadClient;
412
+ this.blobClient.canUpload();
303
413
 
304
414
  const validationResult = await this.blockProposalHandler.handleBlockProposal(
305
415
  proposal,
306
416
  proposalSender,
307
- !!shouldReexecute,
417
+ !!shouldReexecute && !escapeHatchOpen,
308
418
  );
309
419
 
310
420
  if (!validationResult.isValid) {
311
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
421
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
312
422
 
313
423
  const reason = validationResult.reason || 'unknown';
314
424
  // Classify failure reason: bad proposal vs node issue
@@ -323,12 +433,13 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
323
433
  if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
324
434
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
325
435
  } else {
326
- // Node issues so we can't attest
436
+ // Node issues so we can't validate
327
437
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
328
438
  }
329
439
 
330
440
  // Slash invalid block proposals (can happen even when not in committee)
331
441
  if (
442
+ !escapeHatchOpen &&
332
443
  validationResult.reason &&
333
444
  SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) &&
334
445
  slashBroadcastedInvalidBlockPenalty > 0n
@@ -336,9 +447,98 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
336
447
  this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
337
448
  this.slashInvalidBlock(proposal);
338
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`);
339
484
  return undefined;
340
485
  }
341
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
+ );
507
+ return undefined;
508
+ }
509
+
510
+ // Check that I have any address in current committee before attesting
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
+
342
542
  // Check that I have any address in current committee before attesting
343
543
  // In fisherman mode, we still create attestations for validation even if not in committee
344
544
  if (!partOfCommittee && !this.config.fishermanMode) {
@@ -347,7 +547,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
347
547
  }
348
548
 
349
549
  // Provided all of the above checks pass, we can attest to the proposal
350
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} proposal for slot ${slotNumber}`, {
550
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
351
551
  ...proposalInfo,
352
552
  inCommittee: partOfCommittee,
353
553
  fishermanMode: this.config.fishermanMode || false,
@@ -355,21 +555,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
355
555
 
356
556
  this.metrics.incSuccessfulAttestations(inCommittee.length);
357
557
 
358
- // Upload blobs to filestore after successful re-execution (fire-and-forget)
359
- if (validationResult.reexecutionResult?.block && this.fileStoreBlobUploadClient) {
360
- void Promise.resolve().then(async () => {
361
- try {
362
- const blobFields = validationResult.reexecutionResult!.block.getCheckpointBlobFields();
363
- const blobs = getBlobsPerL1Block(blobFields);
364
- await this.fileStoreBlobUploadClient!.saveBlobs(blobs, true);
365
- this.log.debug(`Uploaded ${blobs.length} blobs to filestore from re-execution`, proposalInfo);
366
- } catch (err) {
367
- this.log.warn(`Failed to upload blobs from re-execution`, err);
368
- }
369
- });
370
- }
371
-
372
- // If the above function does not throw an error, then we can attest to the proposal
373
558
  // Determine which validators should attest
374
559
  let attestors: EthAddress[];
375
560
  if (partOfCommittee) {
@@ -388,13 +573,234 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
388
573
 
389
574
  if (this.config.fishermanMode) {
390
575
  // bail out early and don't save attestations to the pool in fisherman mode
391
- this.log.info(`Creating attestations for proposal for slot ${slotNumber}`, {
576
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
392
577
  ...proposalInfo,
393
578
  attestors: attestors.map(a => a.toString()),
394
579
  });
395
580
  return undefined;
396
581
  }
397
- return this.createBlockAttestationsFromProposal(proposal, attestors);
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
+ }
398
804
  }
399
805
 
400
806
  private slashInvalidBlock(proposal: BlockProposal) {
@@ -424,40 +830,126 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
424
830
  ]);
425
831
  }
426
832
 
427
- // TODO(palla/mbps): Block proposal should not require a checkpoint proposal
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),
875
+ },
876
+ ]);
877
+ }
878
+
428
879
  async createBlockProposal(
429
- blockNumber: BlockNumber,
430
- header: CheckpointHeader,
880
+ blockHeader: BlockHeader,
881
+ indexWithinCheckpoint: IndexWithinCheckpoint,
882
+ inHash: Fr,
431
883
  archive: Fr,
432
884
  txs: Tx[],
433
885
  proposerAddress: EthAddress | undefined,
434
- options: BlockProposalOptions,
886
+ options: BlockProposalOptions = {},
435
887
  ): Promise<BlockProposal> {
436
- // TODO(palla/mbps): Prevent double proposals properly
437
- // if (this.previousProposal?.slotNumber === header.slotNumber) {
438
- // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
439
- // return Promise.resolve(undefined);
440
- // }
441
-
442
- this.log.info(`Assembling block proposal for block ${blockNumber} slot ${header.slotNumber}`);
443
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
444
- ...options,
445
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
446
- });
447
- this.previousProposal = newProposal;
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
+ }
900
+ }
901
+
902
+ this.log.info(
903
+ `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
904
+ );
905
+ const newProposal = await this.validationService.createBlockProposal(
906
+ blockHeader,
907
+ indexWithinCheckpoint,
908
+ inHash,
909
+ archive,
910
+ txs,
911
+ proposerAddress,
912
+ {
913
+ ...options,
914
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
915
+ },
916
+ );
917
+ this.lastProposedBlock = newProposal;
448
918
  return newProposal;
449
919
  }
450
920
 
451
- // TODO(palla/mbps): Effectively create a checkpoint proposal different from a block proposal
452
- createCheckpointProposal(
453
- header: CheckpointHeader,
921
+ async createCheckpointProposal(
922
+ checkpointHeader: CheckpointHeader,
454
923
  archive: Fr,
455
- txs: Tx[],
924
+ feeAssetPriceModifier: bigint,
925
+ lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
456
926
  proposerAddress: EthAddress | undefined,
457
- options: BlockProposalOptions,
458
- ): Promise<BlockProposal> {
459
- this.log.info(`Assembling checkpoint proposal for slot ${header.slotNumber}`);
460
- return this.createBlockProposal(0 as BlockNumber, header, archive, txs, proposerAddress, options);
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,
950
+ );
951
+ this.lastProposedCheckpoint = newProposal;
952
+ return newProposal;
461
953
  }
462
954
 
463
955
  async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
@@ -467,28 +959,38 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
467
959
  async signAttestationsAndSigners(
468
960
  attestationsAndSigners: CommitteeAttestationsAndSigners,
469
961
  proposer: EthAddress,
962
+ slot: SlotNumber,
963
+ blockNumber: BlockNumber | CheckpointNumber,
470
964
  ): Promise<Signature> {
471
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
965
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
472
966
  }
473
967
 
474
- async collectOwnAttestations(proposal: BlockProposal): Promise<BlockAttestation[]> {
475
- const slot = proposal.payload.header.slotNumber;
968
+ async collectOwnAttestations(proposal: CheckpointProposal): Promise<CheckpointAttestation[]> {
969
+ const slot = proposal.slotNumber;
476
970
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
477
971
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
478
- const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
972
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
973
+
974
+ if (!attestations) {
975
+ return [];
976
+ }
479
977
 
480
978
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
481
979
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
482
980
  // due to inactivity for missed attestations.
483
- void this.p2pClient.broadcastAttestations(attestations).catch(err => {
981
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch(err => {
484
982
  this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
485
983
  });
486
984
  return attestations;
487
985
  }
488
986
 
489
- async collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]> {
490
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
491
- const slot = proposal.payload.header.slotNumber;
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;
492
994
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
493
995
 
494
996
  if (+deadline < this.dateProvider.now()) {
@@ -503,16 +1005,16 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
503
1005
  const proposalId = proposal.archive.toString();
504
1006
  const myAddresses = this.getValidatorAddresses();
505
1007
 
506
- let attestations: BlockAttestation[] = [];
1008
+ let attestations: CheckpointAttestation[] = [];
507
1009
  while (true) {
508
- // 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
509
1011
  // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
510
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter(
1012
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter(
511
1013
  attestation => {
512
- if (!attestation.payload.equals(proposal.payload)) {
1014
+ if (!attestation.archive.equals(proposal.archive)) {
513
1015
  this.log.warn(
514
- `Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`,
515
- { 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() },
516
1018
  );
517
1019
  return false;
518
1020
  }
@@ -553,15 +1055,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
553
1055
  }
554
1056
  }
555
1057
 
556
- private async createBlockAttestationsFromProposal(
557
- proposal: BlockProposal,
558
- attestors: EthAddress[] = [],
559
- ): Promise<BlockAttestation[]> {
560
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
561
- await this.p2pClient.addAttestations(attestations);
562
- return attestations;
563
- }
564
-
565
1058
  private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
566
1059
  const authRequest = AuthRequest.fromBuffer(msg);
567
1060
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);
@@ -580,7 +1073,9 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
580
1073
  }
581
1074
 
582
1075
  const payloadToSign = authRequest.getPayloadToSign();
583
- 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);
584
1079
  const authResponse = new AuthResponse(statusMessage, signature);
585
1080
  return authResponse.toBuffer();
586
1081
  }