@aztec/validator-client 0.0.1-commit.03f7ef2 → 0.0.1-commit.04d373f

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 +48 -14
  8. package/dest/duties/validation_service.d.ts +43 -15
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +101 -30
  11. package/dest/factory.d.ts +22 -13
  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 +8 -4
  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 -5
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +8 -4
  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 +135 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +1111 -0
  40. package/dest/validator.d.ts +85 -26
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +475 -105
  43. package/package.json +21 -13
  44. package/src/checkpoint_builder.ts +417 -0
  45. package/src/config.ts +47 -12
  46. package/src/duties/validation_service.ts +167 -40
  47. package/src/factory.ts +37 -14
  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 +13 -4
  53. package/src/key_store/node_keystore_adapter.ts +27 -4
  54. package/src/key_store/web3signer_key_store.ts +17 -4
  55. package/src/metrics.ts +81 -33
  56. package/src/proposal_handler.ts +1207 -0
  57. package/src/validator.ts +692 -160
  58. package/dest/block_proposal_handler.d.ts +0 -53
  59. package/dest/block_proposal_handler.d.ts.map +0 -1
  60. package/dest/block_proposal_handler.js +0 -290
  61. package/src/block_proposal_handler.ts +0 -346
package/dest/validator.js CHANGED
@@ -1,34 +1,70 @@
1
1
  import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
3
+ import { FifoSet } from '@aztec/foundation/fifo-set';
2
4
  import { createLogger } from '@aztec/foundation/log';
3
5
  import { RunningPromise } from '@aztec/foundation/running-promise';
4
6
  import { sleep } from '@aztec/foundation/sleep';
5
7
  import { DateProvider } from '@aztec/foundation/timer';
6
8
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
7
- 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';
8
11
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
9
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';
10
15
  import { EventEmitter } from 'events';
11
- import { BlockProposalHandler } from './block_proposal_handler.js';
12
16
  import { ValidationService } from './duties/validation_service.js';
17
+ import { HAKeyStore } from './key_store/ha_key_store.js';
13
18
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
14
19
  import { ValidatorMetrics } from './metrics.js';
20
+ import { ProposalHandler } from './proposal_handler.js';
15
21
  // We maintain a set of proposers who have proposed invalid blocks.
16
22
  // Just cap the set to avoid unbounded growth.
17
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;
18
27
  // What errors from the block proposal handler result in slashing
19
28
  const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
20
29
  'state_mismatch',
21
- 'failed_txs'
30
+ 'failed_txs',
31
+ 'global_variables_mismatch',
32
+ 'invalid_proposal',
33
+ 'parent_block_wrong_slot',
34
+ 'in_hash_mismatch'
22
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
+ };
23
54
  /**
24
55
  * Validator Client
25
56
  */ export class ValidatorClient extends EventEmitter {
26
57
  keyStore;
27
58
  epochCache;
28
59
  p2pClient;
29
- blockProposalHandler;
60
+ proposalHandler;
61
+ blockSource;
62
+ checkpointsBuilder;
63
+ worldState;
64
+ l1ToL2MessageSource;
30
65
  config;
31
- fileStoreBlobUploadClient;
66
+ blobClient;
67
+ slashingProtectionSigner;
32
68
  dateProvider;
33
69
  tracer;
34
70
  validationService;
@@ -36,18 +72,25 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
36
72
  log;
37
73
  // Whether it has already registered handlers on the p2p client
38
74
  hasRegisteredHandlers;
39
- // Used to check if we are sending the same proposal twice
40
- previousProposal;
75
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
76
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
41
77
  lastEpochForCommitteeUpdateLoop;
42
78
  epochCacheUpdateLoop;
79
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */ lastAttestedEpochByAttester;
43
80
  proposersOfInvalidBlocks;
44
- constructor(keyStore, epochCache, p2pClient, blockProposalHandler, config, fileStoreBlobUploadClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
45
- super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.blockProposalHandler = blockProposalHandler, this.config = config, this.fileStoreBlobUploadClient = fileStoreBlobUploadClient, this.dateProvider = dateProvider, 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);
46
88
  // Create child logger with fisherman prefix if in fisherman mode
47
89
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
48
90
  this.tracer = telemetry.getTracer('Validator');
49
91
  this.metrics = new ValidatorMetrics(telemetry);
50
- this.validationService = new ValidationService(keyStore, this.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));
51
94
  // Refresh epoch cache every second to trigger alert if participation in committee changes
52
95
  this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
53
96
  const myAddresses = this.getValidatorAddresses();
@@ -81,6 +124,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
81
124
  this.log.trace(`No committee found for slot`);
82
125
  return;
83
126
  }
127
+ this.metrics.setCurrentEpoch(epoch);
84
128
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
85
129
  const me = this.getValidatorAddresses();
86
130
  const committeeSet = new Set(committee.map((v)=>v.toString()));
@@ -96,27 +140,64 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
96
140
  this.log.error(`Error updating epoch committee`, err);
97
141
  }
98
142
  }
99
- static new(config, blockBuilder, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, fileStoreBlobUploadClient, 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) {
100
144
  const metrics = new ValidatorMetrics(telemetry);
101
145
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
102
- 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
+ }
103
154
  });
104
- const blockProposalHandler = new BlockProposalHandler(blockBuilder, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, config, metrics, dateProvider, telemetry);
105
- const validator = new ValidatorClient(NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager), epochCache, p2pClient, blockProposalHandler, config, fileStoreBlobUploadClient, 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);
106
185
  return validator;
107
186
  }
108
187
  getValidatorAddresses() {
109
188
  return this.keyStore.getAddresses().filter((addr)=>!this.config.disabledValidators.some((disabled)=>disabled.equals(addr)));
110
189
  }
111
- getBlockProposalHandler() {
112
- return this.blockProposalHandler;
190
+ getProposalHandler() {
191
+ return this.proposalHandler;
113
192
  }
114
- // Proxy method for backwards compatibility with tests
115
- reExecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages) {
116
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
193
+ signWithAddress(addr, msg, context) {
194
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
117
195
  }
118
- signWithAddress(addr, msg) {
119
- return this.keyStore.signTypedDataWithAddress(addr, msg);
196
+ getSignatureContext() {
197
+ return {
198
+ chainId: this.config.l1ChainId,
199
+ rollupAddress: this.config.rollupAddress
200
+ };
120
201
  }
121
202
  getCoinbaseForAttestor(attestor) {
122
203
  return this.keyStore.getCoinbaseAddress(attestor);
@@ -127,17 +208,30 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
127
208
  getConfig() {
128
209
  return this.config;
129
210
  }
211
+ hasProposalEquivocation(slotNumber) {
212
+ return this.slotsWithProposalEquivocation.has(slotNumber);
213
+ }
214
+ hasInvalidProposals(slotNumber) {
215
+ return this.slotsWithInvalidProposals.has(slotNumber);
216
+ }
130
217
  updateConfig(config) {
131
218
  this.config = {
132
219
  ...this.config,
133
220
  ...config
134
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'));
135
228
  }
136
229
  async start() {
137
230
  if (this.epochCacheUpdateLoop.isRunning()) {
138
231
  this.log.warn(`Validator client already started`);
139
232
  return;
140
233
  }
234
+ await this.keyStore.start();
141
235
  await this.registerHandlers();
142
236
  const myAddresses = this.getValidatorAddresses();
143
237
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
@@ -150,47 +244,75 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
150
244
  }
151
245
  async stop() {
152
246
  await this.epochCacheUpdateLoop.stop();
247
+ await this.keyStore.stop();
153
248
  }
154
249
  /** Register handlers on the p2p client */ async registerHandlers() {
155
250
  if (!this.hasRegisteredHandlers) {
156
251
  this.hasRegisteredHandlers = true;
157
252
  this.log.debug(`Registering validator handlers for p2p client`);
158
- const handler = (block, proposalSender)=>this.attestToProposal(block, proposalSender);
159
- 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
+ });
160
272
  const myAddresses = this.getValidatorAddresses();
161
273
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
162
274
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
163
275
  }
164
276
  }
165
- async attestToProposal(proposal, proposalSender) {
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) {
166
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);
167
286
  const proposer = proposal.getSender();
168
287
  // Reject proposals with invalid signatures
169
288
  if (!proposer) {
170
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
171
- return undefined;
289
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
290
+ return false;
172
291
  }
173
- // 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)
174
300
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
175
301
  const partOfCommittee = inCommittee.length > 0;
176
302
  const proposalInfo = {
177
303
  ...proposal.toBlockInfo(),
178
304
  proposer: proposer.toString()
179
305
  };
180
- this.log.info(`Received proposal for slot ${slotNumber}`, {
306
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
181
307
  ...proposalInfo,
182
308
  txHashes: proposal.txHashes.map((t)=>t.toString()),
183
309
  fishermanMode: this.config.fishermanMode || false
184
310
  });
185
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
186
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
187
- // In fisherman mode, we always reexecute to validate proposals.
188
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
189
- const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.fileStoreBlobUploadClient;
190
- 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);
191
313
  if (!validationResult.isValid) {
192
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
193
314
  const reason = validationResult.reason || 'unknown';
315
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
194
316
  // Classify failure reason: bad proposal vs node issue
195
317
  const badProposalReasons = [
196
318
  'invalid_proposal',
@@ -202,16 +324,83 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
202
324
  if (badProposalReasons.includes(reason)) {
203
325
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
204
326
  } else {
205
- // Node issues so we can't attest
327
+ // Node issues so we can't validate
206
328
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
207
329
  }
208
- // Slash invalid block proposals (can happen even when not in committee)
209
- if (validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
210
- 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
+ });
211
336
  this.slashInvalidBlock(proposal);
337
+ this.markInvalidProposalSlot(proposal.slotNumber);
212
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`);
364
+ return undefined;
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
+ });
213
376
  return undefined;
214
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
+ }
215
404
  // Check that I have any address in current committee before attesting
216
405
  // In fisherman mode, we still create attestations for validation even if not in committee
217
406
  if (!partOfCommittee && !this.config.fishermanMode) {
@@ -219,26 +408,22 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
219
408
  return undefined;
220
409
  }
221
410
  // Provided all of the above checks pass, we can attest to the proposal
222
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} proposal for slot ${slotNumber}`, {
411
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`, {
223
412
  ...proposalInfo,
224
413
  inCommittee: partOfCommittee,
225
414
  fishermanMode: this.config.fishermanMode || false
226
415
  });
227
416
  this.metrics.incSuccessfulAttestations(inCommittee.length);
228
- // Upload blobs to filestore after successful re-execution (fire-and-forget)
229
- if (validationResult.reexecutionResult?.block && this.fileStoreBlobUploadClient) {
230
- void Promise.resolve().then(async ()=>{
231
- try {
232
- const blobFields = validationResult.reexecutionResult.block.getCheckpointBlobFields();
233
- const blobs = getBlobsPerL1Block(blobFields);
234
- await this.fileStoreBlobUploadClient.saveBlobs(blobs, true);
235
- this.log.debug(`Uploaded ${blobs.length} blobs to filestore from re-execution`, proposalInfo);
236
- } catch (err) {
237
- this.log.warn(`Failed to upload blobs from re-execution`, err);
238
- }
239
- });
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
+ }
240
426
  }
241
- // If the above function does not throw an error, then we can attest to the proposal
242
427
  // Determine which validators should attest
243
428
  let attestors;
244
429
  if (partOfCommittee) {
@@ -255,13 +440,66 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
255
440
  }
256
441
  if (this.config.fishermanMode) {
257
442
  // bail out early and don't save attestations to the pool in fisherman mode
258
- this.log.info(`Creating attestations for proposal for slot ${slotNumber}`, {
443
+ this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
259
444
  ...proposalInfo,
260
445
  attestors: attestors.map((a)=>a.toString())
261
446
  });
262
447
  return undefined;
263
448
  }
264
- return this.createBlockAttestationsFromProposal(proposal, attestors);
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
+ }
265
503
  }
266
504
  slashInvalidBlock(proposal) {
267
505
  const proposer = proposal.getSender();
@@ -270,11 +508,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
270
508
  this.log.warn(`Cannot slash proposal with invalid signature`);
271
509
  return;
272
510
  }
273
- // Trim the set if it's too big.
274
- if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
275
- // remove oldest proposer. `values` is guaranteed to be in insertion order.
276
- this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value);
277
- }
278
511
  this.proposersOfInvalidBlocks.add(proposer.toString());
279
512
  this.emit(WANT_TO_SLASH_EVENT, [
280
513
  {
@@ -285,77 +518,215 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
285
518
  }
286
519
  ]);
287
520
  }
288
- // TODO(palla/mbps): Block proposal should not require a checkpoint proposal
289
- async createBlockProposal(blockNumber, header, archive, txs, proposerAddress, options) {
290
- // TODO(palla/mbps): Prevent double proposals properly
291
- // if (this.previousProposal?.slotNumber === header.slotNumber) {
292
- // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
293
- // return Promise.resolve(undefined);
294
- // }
295
- this.log.info(`Assembling block proposal for block ${blockNumber} slot ${header.slotNumber}`);
296
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
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)
622
+ }
623
+ ]);
624
+ }
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
+ }
654
+ }
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, {
297
657
  ...options,
298
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
658
+ broadcastInvalidBlockProposal: options.broadcastInvalidBlockProposal || this.config.broadcastInvalidBlockProposal
299
659
  });
300
- this.previousProposal = newProposal;
660
+ this.lastProposedBlock = newProposal;
301
661
  return newProposal;
302
662
  }
303
- // TODO(palla/mbps): Effectively create a checkpoint proposal different from a block proposal
304
- createCheckpointProposal(header, archive, txs, proposerAddress, options) {
305
- this.log.info(`Assembling checkpoint proposal for slot ${header.slotNumber}`);
306
- return this.createBlockProposal(0, header, archive, txs, proposerAddress, options);
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);
682
+ return newProposal;
307
683
  }
308
684
  async broadcastBlockProposal(proposal) {
309
685
  await this.p2pClient.broadcastProposal(proposal);
310
686
  }
311
- async signAttestationsAndSigners(attestationsAndSigners, proposer) {
312
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
687
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber) {
688
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber);
313
689
  }
314
- async collectOwnAttestations(proposal) {
315
- const slot = proposal.payload.header.slotNumber;
690
+ async collectOwnAttestations(proposal, checkpointNumber) {
691
+ const slot = proposal.slotNumber;
316
692
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
317
693
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
318
694
  inCommittee
319
695
  });
320
- const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
696
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
697
+ if (!attestations) {
698
+ return [];
699
+ }
321
700
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
322
701
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
323
702
  // due to inactivity for missed attestations.
324
- void this.p2pClient.broadcastAttestations(attestations).catch((err)=>{
703
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch((err)=>{
325
704
  this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
326
705
  });
327
706
  return attestations;
328
707
  }
329
- async collectAttestations(proposal, required, deadline) {
330
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
331
- const slot = proposal.payload.header.slotNumber;
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;
332
711
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
333
712
  if (+deadline < this.dateProvider.now()) {
334
713
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
335
714
  throw new AttestationTimeoutError(0, required, slot);
336
715
  }
337
- await this.collectOwnAttestations(proposal);
338
- const proposalId = proposal.archive.toString();
716
+ await this.collectOwnAttestations(proposal, checkpointNumber);
717
+ const proposalPayloadHash = proposal.getPayloadHash();
339
718
  const myAddresses = this.getValidatorAddresses();
340
719
  let attestations = [];
341
720
  while(true){
342
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
343
- // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
344
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
345
- if (!attestation.payload.equals(proposal.payload)) {
346
- this.log.warn(`Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`, {
347
- attestationPayload: attestation.payload,
348
- proposalPayload: proposal.payload
349
- });
350
- return false;
351
- }
352
- return true;
353
- });
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);
354
725
  // Log new attestations we collected
355
726
  const oldSenders = attestations.map((attestation)=>attestation.getSender());
356
727
  for (const collected of collectedAttestations){
357
728
  const collectedSender = collected.getSender();
358
- // Skip attestations with invalid signatures
729
+ // Skip attestations with invalid signatures. Should not happen as we don't add invalid attestations to our pool.
359
730
  if (!collectedSender) {
360
731
  this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
361
732
  continue;
@@ -377,11 +748,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
377
748
  await sleep(this.config.attestationPollingIntervalMs);
378
749
  }
379
750
  }
380
- async createBlockAttestationsFromProposal(proposal, attestors = []) {
381
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
382
- await this.p2pClient.addAttestations(attestations);
383
- return attestations;
384
- }
385
751
  async handleAuthRequest(peer, msg) {
386
752
  const authRequest = AuthRequest.fromBuffer(msg);
387
753
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
@@ -396,7 +762,11 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
396
762
  return Buffer.alloc(0);
397
763
  }
398
764
  const payloadToSign = authRequest.getPayloadToSign();
399
- 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);
400
770
  const authResponse = new AuthResponse(statusMessage, signature);
401
771
  return authResponse.toBuffer();
402
772
  }