@aztec/validator-client 0.0.1-commit.03f7ef2 → 0.0.1-commit.04852196a

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