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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +325 -0
  2. package/dest/checkpoint_builder.d.ts +79 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +251 -0
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +52 -13
  8. package/dest/duties/validation_service.d.ts +44 -16
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +104 -34
  11. package/dest/factory.d.ts +22 -11
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +11 -5
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -1
  17. package/dest/key_store/ha_key_store.d.ts +99 -0
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  19. package/dest/key_store/ha_key_store.js +208 -0
  20. package/dest/key_store/index.d.ts +2 -1
  21. package/dest/key_store/index.d.ts.map +1 -1
  22. package/dest/key_store/index.js +1 -0
  23. package/dest/key_store/interface.d.ts +36 -6
  24. package/dest/key_store/interface.d.ts.map +1 -1
  25. package/dest/key_store/local_key_store.d.ts +10 -5
  26. package/dest/key_store/local_key_store.d.ts.map +1 -1
  27. package/dest/key_store/local_key_store.js +9 -5
  28. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  29. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  30. package/dest/key_store/node_keystore_adapter.js +18 -4
  31. package/dest/key_store/web3signer_key_store.d.ts +10 -11
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +9 -5
  34. package/dest/metrics.d.ts +16 -3
  35. package/dest/metrics.d.ts.map +1 -1
  36. package/dest/metrics.js +58 -30
  37. package/dest/proposal_handler.d.ts +134 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +1072 -0
  40. package/dest/validator.d.ts +87 -24
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +520 -90
  43. package/package.json +24 -14
  44. package/src/checkpoint_builder.ts +417 -0
  45. package/src/config.ts +52 -11
  46. package/src/duties/validation_service.ts +170 -46
  47. package/src/factory.ts +37 -11
  48. package/src/index.ts +2 -1
  49. package/src/key_store/ha_key_store.ts +269 -0
  50. package/src/key_store/index.ts +1 -0
  51. package/src/key_store/interface.ts +44 -5
  52. package/src/key_store/local_key_store.ts +14 -5
  53. package/src/key_store/node_keystore_adapter.ts +28 -5
  54. package/src/key_store/web3signer_key_store.ts +18 -5
  55. package/src/metrics.ts +81 -33
  56. package/src/proposal_handler.ts +1161 -0
  57. package/src/validator.ts +739 -134
  58. package/dest/block_proposal_handler.d.ts +0 -52
  59. package/dest/block_proposal_handler.d.ts.map +0 -1
  60. package/dest/block_proposal_handler.js +0 -286
  61. package/src/block_proposal_handler.ts +0 -343
package/dest/validator.js CHANGED
@@ -1,51 +1,98 @@
1
+ import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
3
+ import { FifoSet } from '@aztec/foundation/fifo-set';
1
4
  import { createLogger } from '@aztec/foundation/log';
2
5
  import { RunningPromise } from '@aztec/foundation/running-promise';
3
6
  import { sleep } from '@aztec/foundation/sleep';
4
7
  import { DateProvider } from '@aztec/foundation/timer';
5
8
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
6
- import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
9
+ import { OffenseType, WANT_TO_CLEAR_SLASH_EVENT, WANT_TO_SLASH_EVENT, getOffenseTypeName } from '@aztec/slasher';
10
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
7
11
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
8
12
  import { getTelemetryClient } from '@aztec/telemetry-client';
13
+ import { createHASigner, createLocalSignerWithProtection, createSignerFromSharedDb } from '@aztec/validator-ha-signer/factory';
14
+ import { DutyType } from '@aztec/validator-ha-signer/types';
9
15
  import { EventEmitter } from 'events';
10
- import { BlockProposalHandler } from './block_proposal_handler.js';
11
16
  import { ValidationService } from './duties/validation_service.js';
17
+ import { HAKeyStore } from './key_store/ha_key_store.js';
12
18
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
13
19
  import { ValidatorMetrics } from './metrics.js';
20
+ import { ProposalHandler } from './proposal_handler.js';
14
21
  // We maintain a set of proposers who have proposed invalid blocks.
15
22
  // Just cap the set to avoid unbounded growth.
16
23
  const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
24
+ const MAX_TRACKED_INVALID_PROPOSAL_SLOTS = 1000;
25
+ const MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS = 1000;
26
+ const MAX_TRACKED_BAD_ATTESTATIONS = 10_000;
17
27
  // What errors from the block proposal handler result in slashing
18
28
  const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
19
29
  'state_mismatch',
20
- 'failed_txs'
30
+ 'failed_txs',
31
+ 'global_variables_mismatch',
32
+ 'invalid_proposal',
33
+ 'parent_block_wrong_slot',
34
+ 'in_hash_mismatch'
21
35
  ];
36
+ const SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT = {
37
+ // enabled
38
+ ['invalid_fee_asset_price_modifier']: true,
39
+ ['checkpoint_header_mismatch']: true,
40
+ // These late mismatches should normally be caught by earlier checks, but if reached after validating the local
41
+ // checkpoint inputs, the proposer-signed payload disagrees with deterministic recomputation.
42
+ ['archive_mismatch']: true,
43
+ ['out_hash_mismatch']: true,
44
+ ['no_blocks_for_slot']: true,
45
+ ['too_many_blocks_in_checkpoint']: true,
46
+ ['checkpoint_validation_failed']: true,
47
+ ['last_block_archive_mismatch']: true,
48
+ // disabled
49
+ ['invalid_signature']: false,
50
+ ['last_block_not_found']: false,
51
+ ['block_fetch_error']: false,
52
+ ['checkpoint_already_published']: false
53
+ };
22
54
  /**
23
55
  * Validator Client
24
56
  */ export class ValidatorClient extends EventEmitter {
25
57
  keyStore;
26
58
  epochCache;
27
59
  p2pClient;
28
- blockProposalHandler;
60
+ proposalHandler;
61
+ blockSource;
62
+ checkpointsBuilder;
63
+ worldState;
64
+ l1ToL2MessageSource;
29
65
  config;
66
+ blobClient;
67
+ slashingProtectionSigner;
30
68
  dateProvider;
31
- log;
32
69
  tracer;
33
70
  validationService;
34
71
  metrics;
72
+ log;
35
73
  // Whether it has already registered handlers on the p2p client
36
74
  hasRegisteredHandlers;
37
- // Used to check if we are sending the same proposal twice
38
- previousProposal;
75
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
76
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
39
77
  lastEpochForCommitteeUpdateLoop;
40
78
  epochCacheUpdateLoop;
79
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */ lastAttestedEpochByAttester;
41
80
  proposersOfInvalidBlocks;
42
- constructor(keyStore, epochCache, p2pClient, blockProposalHandler, config, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
43
- super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.blockProposalHandler = blockProposalHandler, this.config = config, this.dateProvider = dateProvider, this.log = log, this.hasRegisteredHandlers = false, this.proposersOfInvalidBlocks = new Set();
81
+ slotsWithInvalidProposals;
82
+ invalidCheckpointProposalOffenseKeys;
83
+ badAttestationOffenseKeys;
84
+ slotsWithProposalEquivocation;
85
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
86
+ constructor(keyStore, epochCache, p2pClient, proposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
87
+ super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.proposalHandler = proposalHandler, this.blockSource = blockSource, this.checkpointsBuilder = checkpointsBuilder, this.worldState = worldState, this.l1ToL2MessageSource = l1ToL2MessageSource, this.config = config, this.blobClient = blobClient, this.slashingProtectionSigner = slashingProtectionSigner, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.lastAttestedEpochByAttester = new Map(), this.proposersOfInvalidBlocks = FifoSet.withLimit(MAX_PROPOSERS_OF_INVALID_BLOCKS), this.slotsWithInvalidProposals = FifoSet.withLimit(MAX_TRACKED_INVALID_PROPOSAL_SLOTS), this.invalidCheckpointProposalOffenseKeys = FifoSet.withLimit(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS), this.badAttestationOffenseKeys = FifoSet.withLimit(MAX_TRACKED_BAD_ATTESTATIONS), this.slotsWithProposalEquivocation = FifoSet.withLimit(MAX_TRACKED_INVALID_PROPOSAL_SLOTS);
88
+ // Create child logger with fisherman prefix if in fisherman mode
89
+ this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
44
90
  this.tracer = telemetry.getTracer('Validator');
45
91
  this.metrics = new ValidatorMetrics(telemetry);
46
- this.validationService = new ValidationService(keyStore, log.createChild('validation-service'));
92
+ this.validationService = new ValidationService(keyStore, this.getSignatureContext(), this.log.createChild('validation-service'));
93
+ this.proposalHandler.setCheckpointProposalValidationFailureCallback((proposal, result, proposalInfo)=>this.handleInvalidCheckpointProposal(proposal, result, proposalInfo));
47
94
  // Refresh epoch cache every second to trigger alert if participation in committee changes
48
- this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), log, 1000);
95
+ this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
49
96
  const myAddresses = this.getValidatorAddresses();
50
97
  this.log.verbose(`Initialized validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
51
98
  }
@@ -77,6 +124,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
77
124
  this.log.trace(`No committee found for slot`);
78
125
  return;
79
126
  }
127
+ this.metrics.setCurrentEpoch(epoch);
80
128
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
81
129
  const me = this.getValidatorAddresses();
82
130
  const committeeSet = new Set(committee.map((v)=>v.toString()));
@@ -92,27 +140,64 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
92
140
  this.log.error(`Error updating epoch committee`, err);
93
141
  }
94
142
  }
95
- static new(config, blockBuilder, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
143
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, reexecutionTracker, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), slashingProtectionDb) {
96
144
  const metrics = new ValidatorMetrics(telemetry);
97
145
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
98
- txsPermitted: !config.disableTransactions
146
+ txsPermitted: !config.disableTransactions,
147
+ maxTxsPerBlock: config.validateMaxTxsPerBlock,
148
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint,
149
+ skipSlotValidation: config.skipProposalSlotValidation,
150
+ signatureContext: {
151
+ chainId: config.l1ChainId,
152
+ rollupAddress: config.rollupAddress
153
+ }
99
154
  });
100
- const blockProposalHandler = new BlockProposalHandler(blockBuilder, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, config, metrics, dateProvider, telemetry);
101
- const validator = new ValidatorClient(NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager), epochCache, p2pClient, blockProposalHandler, config, dateProvider, telemetry);
155
+ const proposalHandler = new ProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, blobClient, reexecutionTracker, metrics, dateProvider, telemetry, undefined);
156
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
157
+ let slashingProtectionSigner;
158
+ if (slashingProtectionDb) {
159
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
160
+ ({ signer: slashingProtectionSigner } = createSignerFromSharedDb(slashingProtectionDb, config, {
161
+ telemetryClient: telemetry,
162
+ dateProvider
163
+ }));
164
+ } else if (config.haSigningEnabled) {
165
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
166
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
167
+ const haConfig = {
168
+ ...config,
169
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
170
+ };
171
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
172
+ telemetryClient: telemetry,
173
+ dateProvider
174
+ }));
175
+ } else {
176
+ // Single-node mode: use LMDB-backed local signing protection.
177
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
178
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
179
+ telemetryClient: telemetry,
180
+ dateProvider
181
+ }));
182
+ }
183
+ const validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
184
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, proposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider, telemetry);
102
185
  return validator;
103
186
  }
104
187
  getValidatorAddresses() {
105
188
  return this.keyStore.getAddresses().filter((addr)=>!this.config.disabledValidators.some((disabled)=>disabled.equals(addr)));
106
189
  }
107
- getBlockProposalHandler() {
108
- return this.blockProposalHandler;
190
+ getProposalHandler() {
191
+ return this.proposalHandler;
109
192
  }
110
- // Proxy method for backwards compatibility with tests
111
- reExecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages) {
112
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
193
+ signWithAddress(addr, msg, context) {
194
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
113
195
  }
114
- signWithAddress(addr, msg) {
115
- return this.keyStore.signTypedDataWithAddress(addr, msg);
196
+ getSignatureContext() {
197
+ return {
198
+ chainId: this.config.l1ChainId,
199
+ rollupAddress: this.config.rollupAddress
200
+ };
116
201
  }
117
202
  getCoinbaseForAttestor(attestor) {
118
203
  return this.keyStore.getCoinbaseAddress(attestor);
@@ -123,69 +208,111 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
123
208
  getConfig() {
124
209
  return this.config;
125
210
  }
211
+ hasProposalEquivocation(slotNumber) {
212
+ return this.slotsWithProposalEquivocation.has(slotNumber);
213
+ }
214
+ hasInvalidProposals(slotNumber) {
215
+ return this.slotsWithInvalidProposals.has(slotNumber);
216
+ }
126
217
  updateConfig(config) {
127
218
  this.config = {
128
219
  ...this.config,
129
220
  ...config
130
221
  };
222
+ this.proposalHandler.updateConfig(config);
223
+ }
224
+ reloadKeystore(newManager) {
225
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
226
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
227
+ this.validationService = new ValidationService(this.keyStore, this.getSignatureContext(), this.log.createChild('validation-service'));
131
228
  }
132
229
  async start() {
133
230
  if (this.epochCacheUpdateLoop.isRunning()) {
134
231
  this.log.warn(`Validator client already started`);
135
232
  return;
136
233
  }
234
+ await this.keyStore.start();
137
235
  await this.registerHandlers();
138
236
  const myAddresses = this.getValidatorAddresses();
139
237
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
238
+ this.log.info(`Started validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
140
239
  if (inCommittee.length > 0) {
141
- this.log.info(`Started validator with addresses in current validator committee: ${inCommittee.map((a)=>a.toString()).join(', ')}`);
142
- } else {
143
- this.log.info(`Started validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
240
+ this.log.info(`Addresses in current validator committee: ${inCommittee.map((a)=>a.toString()).join(', ')}`);
144
241
  }
145
242
  this.epochCacheUpdateLoop.start();
146
243
  return Promise.resolve();
147
244
  }
148
245
  async stop() {
149
246
  await this.epochCacheUpdateLoop.stop();
247
+ await this.keyStore.stop();
150
248
  }
151
249
  /** Register handlers on the p2p client */ async registerHandlers() {
152
250
  if (!this.hasRegisteredHandlers) {
153
251
  this.hasRegisteredHandlers = true;
154
252
  this.log.debug(`Registering validator handlers for p2p client`);
155
- const handler = (block, proposalSender)=>this.attestToProposal(block, proposalSender);
156
- this.p2pClient.registerBlockProposalHandler(handler);
253
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
254
+ const blockHandler = (block, proposalSender)=>this.validateBlockProposal(block, proposalSender);
255
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
256
+ // Checkpoint proposal handler - validates and creates attestations
257
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
258
+ // and processed separately via the block handler above.
259
+ const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
260
+ this.p2pClient.registerValidatorCheckpointProposalHandler(checkpointHandler);
261
+ // Duplicate proposal handler - triggers slashing for equivocation
262
+ this.p2pClient.registerDuplicateProposalCallback((info)=>{
263
+ this.handleDuplicateProposal(info);
264
+ });
265
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
266
+ this.p2pClient.registerDuplicateAttestationCallback((info)=>{
267
+ this.handleDuplicateAttestation(info);
268
+ });
269
+ this.p2pClient.registerCheckpointAttestationCallback((attestation)=>{
270
+ this.handleCheckpointAttestation(attestation);
271
+ });
157
272
  const myAddresses = this.getValidatorAddresses();
158
273
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
159
274
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
160
275
  }
161
276
  }
162
- async attestToProposal(proposal, proposalSender) {
163
- const slotNumber = proposal.slotNumber.toBigInt();
277
+ /**
278
+ * Validate a block proposal from a peer.
279
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
280
+ * @returns true if the proposal is valid, false otherwise
281
+ */ async validateBlockProposal(proposal, proposalSender) {
282
+ const slotNumber = proposal.slotNumber;
283
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
284
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
285
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
164
286
  const proposer = proposal.getSender();
165
287
  // Reject proposals with invalid signatures
166
288
  if (!proposer) {
167
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
168
- return undefined;
289
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
290
+ return false;
169
291
  }
170
- // Check that I have any address in current committee before attesting
292
+ // Log self-proposals from HA peers (same validator key on different nodes)
293
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
294
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
295
+ proposer: proposer.toString(),
296
+ slotNumber
297
+ });
298
+ }
299
+ // Check if we're in the committee (for metrics purposes)
171
300
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
172
301
  const partOfCommittee = inCommittee.length > 0;
173
302
  const proposalInfo = {
174
303
  ...proposal.toBlockInfo(),
175
304
  proposer: proposer.toString()
176
305
  };
177
- this.log.info(`Received proposal for slot ${slotNumber}`, {
306
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
178
307
  ...proposalInfo,
179
- txHashes: proposal.txHashes.map((t)=>t.toString())
308
+ txHashes: proposal.txHashes.map((t)=>t.toString()),
309
+ fishermanMode: this.config.fishermanMode || false
180
310
  });
181
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
182
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
183
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals } = this.config;
184
- const shouldReexecute = slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals;
185
- const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute);
311
+ // Reexecute outside the escape hatch so slashing observers can detect invalid proposals even when penalties are 0.
312
+ const validationResult = await this.proposalHandler.handleBlockProposal(proposal, proposalSender, !escapeHatchOpen);
186
313
  if (!validationResult.isValid) {
187
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
188
314
  const reason = validationResult.reason || 'unknown';
315
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
189
316
  // Classify failure reason: bad proposal vs node issue
190
317
  const badProposalReasons = [
191
318
  'invalid_proposal',
@@ -197,26 +324,182 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
197
324
  if (badProposalReasons.includes(reason)) {
198
325
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
199
326
  } else {
200
- // Node issues so we can't attest
327
+ // Node issues so we can't validate
201
328
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
202
329
  }
203
- // Slash invalid block proposals (can happen even when not in committee)
204
- if (validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
205
- this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
330
+ if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason)) {
331
+ this.log.info(`Detected invalid block proposal offense`, {
332
+ ...proposalInfo,
333
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
334
+ offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL)
335
+ });
206
336
  this.slashInvalidBlock(proposal);
337
+ this.markInvalidProposalSlot(proposal.slotNumber);
207
338
  }
339
+ return false;
340
+ }
341
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
342
+ ...proposalInfo,
343
+ inCommittee: partOfCommittee,
344
+ fishermanMode: this.config.fishermanMode || false,
345
+ escapeHatchOpen
346
+ });
347
+ if (escapeHatchOpen) {
348
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
349
+ return false;
350
+ }
351
+ return true;
352
+ }
353
+ /**
354
+ * Validate and attest to a checkpoint proposal from a peer.
355
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
356
+ * the lastBlock is extracted and processed separately via the block handler.
357
+ * @returns Checkpoint attestations if valid, undefined otherwise
358
+ */ async attestToCheckpointProposal(proposal, _proposalSender) {
359
+ const proposalSlotNumber = proposal.slotNumber;
360
+ const proposer = proposal.getSender();
361
+ // If escape hatch is open for this slot's epoch, do not attest.
362
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposalSlotNumber)) {
363
+ this.log.warn(`Escape hatch open for slot ${proposalSlotNumber}, skipping checkpoint attestation handling`);
208
364
  return undefined;
209
365
  }
366
+ // Early-out for equivocation: refuses if we've already attested to a higher slot.
367
+ if (!this.shouldAttestToSlot(proposalSlotNumber)) {
368
+ return undefined;
369
+ }
370
+ // Ignore proposals from ourselves (may happen in HA setups)
371
+ if (proposer && this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
372
+ this.log.debug(`Ignoring block proposal from self for slot ${proposalSlotNumber}`, {
373
+ proposer: proposer.toString(),
374
+ proposalSlotNumber
375
+ });
376
+ return undefined;
377
+ }
378
+ // Check that I have any address in the committee where this checkpoint will land before attesting
379
+ const inCommittee = await this.epochCache.filterInCommittee(proposalSlotNumber, this.getValidatorAddresses());
380
+ const partOfCommittee = inCommittee.length > 0;
381
+ const proposalInfo = {
382
+ proposalSlotNumber,
383
+ archive: proposal.archive.toString(),
384
+ proposer: proposer?.toString()
385
+ };
386
+ this.log.info(`Received checkpoint proposal for slot ${proposalSlotNumber}`, {
387
+ ...proposalInfo,
388
+ fishermanMode: this.config.fishermanMode || false
389
+ });
390
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set).
391
+ // Uses the cached result from the all-nodes callback if available (avoids double validation).
392
+ let checkpointNumber;
393
+ if (this.config.skipCheckpointProposalValidation) {
394
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposalSlotNumber}`, proposalInfo);
395
+ checkpointNumber = CheckpointNumber(0);
396
+ } else {
397
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
398
+ if (!validationResult.isValid) {
399
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
400
+ return undefined;
401
+ }
402
+ checkpointNumber = validationResult.checkpointNumber;
403
+ }
210
404
  // Check that I have any address in current committee before attesting
211
- if (!partOfCommittee) {
405
+ // In fisherman mode, we still create attestations for validation even if not in committee
406
+ if (!partOfCommittee && !this.config.fishermanMode) {
212
407
  this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
213
408
  return undefined;
214
409
  }
215
410
  // Provided all of the above checks pass, we can attest to the proposal
216
- this.log.info(`Attesting to proposal for slot ${slotNumber}`, proposalInfo);
411
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`, {
412
+ ...proposalInfo,
413
+ inCommittee: partOfCommittee,
414
+ fishermanMode: this.config.fishermanMode || false
415
+ });
217
416
  this.metrics.incSuccessfulAttestations(inCommittee.length);
218
- // If the above function does not throw an error, then we can attest to the proposal
219
- return this.createBlockAttestationsFromProposal(proposal, inCommittee);
417
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
418
+ const proposalEpoch = getEpochAtSlot(proposalSlotNumber, this.epochCache.getL1Constants());
419
+ for (const attester of inCommittee){
420
+ const key = attester.toString();
421
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
422
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
423
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
424
+ this.metrics.incAttestedEpochCount(attester);
425
+ }
426
+ }
427
+ // Determine which validators should attest
428
+ let attestors;
429
+ if (partOfCommittee) {
430
+ attestors = inCommittee;
431
+ } else if (this.config.fishermanMode) {
432
+ // In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
433
+ attestors = this.getValidatorAddresses();
434
+ } else {
435
+ attestors = [];
436
+ }
437
+ // Only create attestations if we have attestors
438
+ if (attestors.length === 0) {
439
+ return undefined;
440
+ }
441
+ if (this.config.fishermanMode) {
442
+ // bail out early and don't save attestations to the pool in fisherman mode
443
+ this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
444
+ ...proposalInfo,
445
+ attestors: attestors.map((a)=>a.toString())
446
+ });
447
+ return undefined;
448
+ }
449
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors, checkpointNumber);
450
+ }
451
+ /**
452
+ * Checks if we should attest to a slot based on equivocation prevention rules.
453
+ * @returns true if we should attest, false if we should skip
454
+ */ shouldAttestToSlot(slotNumber) {
455
+ // If attestToEquivocatedProposals is true, always allow
456
+ if (this.config.attestToEquivocatedProposals) {
457
+ return true;
458
+ }
459
+ // Check if incoming slot is strictly greater than last attested
460
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
461
+ this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
462
+ return false;
463
+ }
464
+ return true;
465
+ }
466
+ async createCheckpointAttestationsFromProposal(proposal, attestors = [], checkpointNumber) {
467
+ // Equivocation check: must happen right before signing to minimize the race window
468
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
469
+ return undefined;
470
+ }
471
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors, checkpointNumber);
472
+ // Track the proposal we attested to (to prevent equivocation)
473
+ this.lastAttestedProposal = proposal;
474
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
475
+ return attestations;
476
+ }
477
+ /**
478
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
479
+ */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
480
+ try {
481
+ const lastBlockHeader = (await this.blockSource.getBlockData({
482
+ archive: proposal.archive
483
+ }))?.header;
484
+ if (!lastBlockHeader) {
485
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
486
+ return;
487
+ }
488
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
489
+ if (blocks.length === 0) {
490
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
491
+ return;
492
+ }
493
+ const blobFields = blocks.flatMap((b)=>b.toBlobFields());
494
+ const blobs = await getBlobsPerL1Block(blobFields);
495
+ await this.blobClient.sendBlobsToFilestore(blobs);
496
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
497
+ ...proposalInfo,
498
+ numBlobs: blobs.length
499
+ });
500
+ } catch (err) {
501
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
502
+ }
220
503
  }
221
504
  slashInvalidBlock(proposal) {
222
505
  const proposer = proposal.getSender();
@@ -225,77 +508,225 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
225
508
  this.log.warn(`Cannot slash proposal with invalid signature`);
226
509
  return;
227
510
  }
228
- // Trim the set if it's too big.
229
- if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
230
- // remove oldest proposer. `values` is guaranteed to be in insertion order.
231
- this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value);
232
- }
233
511
  this.proposersOfInvalidBlocks.add(proposer.toString());
234
512
  this.emit(WANT_TO_SLASH_EVENT, [
235
513
  {
236
514
  validator: proposer,
237
515
  amount: this.config.slashBroadcastedInvalidBlockPenalty,
238
516
  offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
239
- epochOrSlot: proposal.slotNumber.toBigInt()
517
+ epochOrSlot: BigInt(proposal.slotNumber)
518
+ }
519
+ ]);
520
+ }
521
+ handleInvalidCheckpointProposal(proposal, result, proposalInfo) {
522
+ if (!SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT[result.reason]) {
523
+ return;
524
+ }
525
+ this.markInvalidProposalSlot(proposal.slotNumber);
526
+ if (this.slashInvalidCheckpointProposal(proposal)) {
527
+ this.log.info(`Detected invalid checkpoint proposal offense`, {
528
+ ...proposalInfo,
529
+ reason: result.reason,
530
+ amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
531
+ offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL)
532
+ });
533
+ }
534
+ }
535
+ slashInvalidCheckpointProposal(proposal) {
536
+ const proposer = proposal.getSender();
537
+ if (!proposer) {
538
+ this.log.warn(`Cannot slash checkpoint proposal with invalid signature`, {
539
+ slotNumber: proposal.slotNumber,
540
+ archive: proposal.archive.toString()
541
+ });
542
+ return false;
543
+ }
544
+ const offenseType = OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL;
545
+ const offenseKey = `${proposer.toString()}:${offenseType}:${proposal.slotNumber}`;
546
+ if (!this.invalidCheckpointProposalOffenseKeys.addIfAbsent(offenseKey)) {
547
+ return false;
548
+ }
549
+ this.emit(WANT_TO_SLASH_EVENT, [
550
+ {
551
+ validator: proposer,
552
+ amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
553
+ offenseType,
554
+ epochOrSlot: BigInt(proposal.slotNumber)
555
+ }
556
+ ]);
557
+ return true;
558
+ }
559
+ markInvalidProposalSlot(slotNumber) {
560
+ this.slotsWithInvalidProposals.add(slotNumber);
561
+ }
562
+ handleCheckpointAttestation(attestation) {
563
+ const slotNumber = attestation.slotNumber;
564
+ if (!this.slotsWithInvalidProposals.has(slotNumber) || this.slotsWithProposalEquivocation.has(slotNumber)) {
565
+ return;
566
+ }
567
+ const attester = attestation.getSender();
568
+ if (!attester) {
569
+ this.log.warn(`Cannot slash checkpoint attestation with invalid signature`, {
570
+ slotNumber,
571
+ archive: attestation.archive.toString()
572
+ });
573
+ return;
574
+ }
575
+ this.slashAttestedToInvalidCheckpointProposal(slotNumber, attester);
576
+ }
577
+ slashAttestedToInvalidCheckpointProposal(slotNumber, attester) {
578
+ const offenseKey = `${attester.toString()}:${OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL}:${slotNumber}`;
579
+ if (!this.badAttestationOffenseKeys.addIfAbsent(offenseKey)) {
580
+ return;
581
+ }
582
+ this.log.info(`Detected attestation to invalid checkpoint proposal offense`, {
583
+ attester: attester.toString(),
584
+ slotNumber,
585
+ amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
586
+ offenseType: getOffenseTypeName(OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL)
587
+ });
588
+ this.emit(WANT_TO_SLASH_EVENT, [
589
+ {
590
+ validator: attester,
591
+ amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
592
+ offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
593
+ epochOrSlot: BigInt(slotNumber)
594
+ }
595
+ ]);
596
+ }
597
+ /**
598
+ * Handle detection of a duplicate proposal (equivocation).
599
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
600
+ */ handleDuplicateProposal(info) {
601
+ const { slot, proposer, type } = info;
602
+ this.slotsWithProposalEquivocation.add(slot);
603
+ this.log.info(`Detected duplicate ${type} proposal offense from ${proposer.toString()} at slot ${slot}`, {
604
+ proposer: proposer.toString(),
605
+ slot,
606
+ type,
607
+ amount: this.config.slashDuplicateProposalPenalty,
608
+ offenseType: getOffenseTypeName(OffenseType.DUPLICATE_PROPOSAL)
609
+ });
610
+ this.emit(WANT_TO_SLASH_EVENT, [
611
+ {
612
+ validator: proposer,
613
+ amount: this.config.slashDuplicateProposalPenalty,
614
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
615
+ epochOrSlot: BigInt(slot)
616
+ }
617
+ ]);
618
+ this.emit(WANT_TO_CLEAR_SLASH_EVENT, [
619
+ {
620
+ offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
621
+ epochOrSlot: BigInt(slot)
240
622
  }
241
623
  ]);
242
624
  }
243
- async createBlockProposal(blockNumber, header, archive, stateReference, txs, proposerAddress, options) {
244
- if (this.previousProposal?.slotNumber.equals(header.slotNumber)) {
245
- this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
246
- return Promise.resolve(undefined);
625
+ /**
626
+ * Handle detection of a duplicate attestation (equivocation).
627
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
628
+ */ handleDuplicateAttestation(info) {
629
+ const { slot, attester } = info;
630
+ this.log.info(`Detected duplicate attestation offense from ${attester.toString()} at slot ${slot}`, {
631
+ attester: attester.toString(),
632
+ slot,
633
+ amount: this.config.slashDuplicateAttestationPenalty,
634
+ offenseType: getOffenseTypeName(OffenseType.DUPLICATE_ATTESTATION)
635
+ });
636
+ this.emit(WANT_TO_SLASH_EVENT, [
637
+ {
638
+ validator: attester,
639
+ amount: this.config.slashDuplicateAttestationPenalty,
640
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
641
+ epochOrSlot: BigInt(slot)
642
+ }
643
+ ]);
644
+ }
645
+ async createBlockProposal(blockHeader, checkpointNumber, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
646
+ // Validate that we're not creating a proposal for an older or equal position
647
+ if (this.lastProposedBlock) {
648
+ const lastSlot = this.lastProposedBlock.slotNumber;
649
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
650
+ const newSlot = blockHeader.globalVariables.slotNumber;
651
+ if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
652
+ throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
653
+ }
247
654
  }
248
- const newProposal = await this.validationService.createBlockProposal(header, archive, stateReference, txs, proposerAddress, {
655
+ this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
656
+ const newProposal = await this.validationService.createBlockProposal(blockHeader, checkpointNumber, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
249
657
  ...options,
250
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
658
+ broadcastInvalidBlockProposal: options.broadcastInvalidBlockProposal || this.config.broadcastInvalidBlockProposal
251
659
  });
252
- this.previousProposal = newProposal;
660
+ this.lastProposedBlock = newProposal;
661
+ return newProposal;
662
+ }
663
+ async createCheckpointProposal(checkpointHeader, archive, checkpointNumber, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options = {}) {
664
+ // Validate that we're not creating a proposal for an older or equal slot
665
+ if (this.lastProposedCheckpoint) {
666
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
667
+ const newSlot = checkpointHeader.slotNumber;
668
+ if (newSlot <= lastSlot) {
669
+ throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
670
+ }
671
+ }
672
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
673
+ const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, checkpointNumber, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options);
674
+ this.lastProposedCheckpoint = newProposal;
675
+ // Self-record this slot's outcome on the re-execution tracker. Proposers don't run their
676
+ // own proposals through `handleCheckpointProposal`, so without this call the proposer's
677
+ // sentinel would see no outcome for slots it proposed and would mis-attribute itself as
678
+ // inactive. We pass the locally-computed `archive` (not `newProposal.archive`, which may
679
+ // be intentionally corrupted under test-only flags); from the proposer's local-view
680
+ // perspective the work it just completed is valid by definition.
681
+ this.proposalHandler.recordOwnCheckpointProposalAsValid(checkpointHeader.slotNumber, archive, checkpointNumber);
253
682
  return newProposal;
254
683
  }
255
684
  async broadcastBlockProposal(proposal) {
256
685
  await this.p2pClient.broadcastProposal(proposal);
257
686
  }
258
- async signAttestationsAndSigners(attestationsAndSigners, proposer) {
259
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
687
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber) {
688
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber);
260
689
  }
261
- async collectOwnAttestations(proposal) {
262
- const slot = proposal.payload.header.slotNumber.toBigInt();
690
+ async collectOwnAttestations(proposal, checkpointNumber) {
691
+ const slot = proposal.slotNumber;
263
692
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
264
693
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
265
694
  inCommittee
266
695
  });
267
- return this.createBlockAttestationsFromProposal(proposal, inCommittee);
696
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
697
+ if (!attestations) {
698
+ return [];
699
+ }
700
+ // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
701
+ // other nodes can see that our validators did attest to this block proposal, and do not slash us
702
+ // due to inactivity for missed attestations.
703
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch((err)=>{
704
+ this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
705
+ });
706
+ return attestations;
268
707
  }
269
- async collectAttestations(proposal, required, deadline) {
270
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
271
- const slot = proposal.payload.header.slotNumber.toBigInt();
708
+ async collectAttestations(proposal, required, deadline, checkpointNumber) {
709
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
710
+ const slot = proposal.slotNumber;
272
711
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
273
712
  if (+deadline < this.dateProvider.now()) {
274
713
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
275
714
  throw new AttestationTimeoutError(0, required, slot);
276
715
  }
277
- await this.collectOwnAttestations(proposal);
278
- const proposalId = proposal.archive.toString();
716
+ await this.collectOwnAttestations(proposal, checkpointNumber);
717
+ const proposalPayloadHash = proposal.getPayloadHash();
279
718
  const myAddresses = this.getValidatorAddresses();
280
719
  let attestations = [];
281
720
  while(true){
282
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
283
- // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
284
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
285
- if (!attestation.payload.equals(proposal.payload)) {
286
- this.log.warn(`Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`, {
287
- attestationPayload: attestation.payload,
288
- proposalPayload: proposal.payload
289
- });
290
- return false;
291
- }
292
- return true;
293
- });
721
+ // The pool already filters by proposal payload hash; if any attestation slips through with a
722
+ // mismatched payload hash, drop it defensively. Equivocations are emitted as separate slash
723
+ // events from libp2p_service.
724
+ const collectedAttestations = await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
294
725
  // Log new attestations we collected
295
726
  const oldSenders = attestations.map((attestation)=>attestation.getSender());
296
727
  for (const collected of collectedAttestations){
297
728
  const collectedSender = collected.getSender();
298
- // Skip attestations with invalid signatures
729
+ // Skip attestations with invalid signatures. Should not happen as we don't add invalid attestations to our pool.
299
730
  if (!collectedSender) {
300
731
  this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
301
732
  continue;
@@ -317,11 +748,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
317
748
  await sleep(this.config.attestationPollingIntervalMs);
318
749
  }
319
750
  }
320
- async createBlockAttestationsFromProposal(proposal, attestors = []) {
321
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
322
- await this.p2pClient.addAttestations(attestations);
323
- return attestations;
324
- }
325
751
  async handleAuthRequest(peer, msg) {
326
752
  const authRequest = AuthRequest.fromBuffer(msg);
327
753
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
@@ -336,7 +762,11 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
336
762
  return Buffer.alloc(0);
337
763
  }
338
764
  const payloadToSign = authRequest.getPayloadToSign();
339
- const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
765
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
766
+ const context = {
767
+ dutyType: DutyType.AUTH_REQUEST
768
+ };
769
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
340
770
  const authResponse = new AuthResponse(statusMessage, signature);
341
771
  return authResponse.toBuffer();
342
772
  }