@aztec/validator-client 0.0.1-commit.f2ce05ee → 0.0.1-commit.f5a9928

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 (56) hide show
  1. package/README.md +54 -10
  2. package/dest/checkpoint_builder.d.ts +32 -11
  3. package/dest/checkpoint_builder.d.ts.map +1 -1
  4. package/dest/checkpoint_builder.js +136 -47
  5. package/dest/config.d.ts +9 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +45 -7
  8. package/dest/duties/validation_service.d.ts +12 -13
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +33 -45
  11. package/dest/factory.d.ts +11 -5
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +8 -7
  14. package/dest/index.d.ts +2 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -2
  17. package/dest/key_store/ha_key_store.js +1 -1
  18. package/dest/key_store/web3signer_key_store.d.ts +10 -2
  19. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  20. package/dest/key_store/web3signer_key_store.js +32 -41
  21. package/dest/metrics.d.ts +14 -2
  22. package/dest/metrics.d.ts.map +1 -1
  23. package/dest/metrics.js +27 -1
  24. package/dest/proposal_handler.d.ts +173 -0
  25. package/dest/proposal_handler.d.ts.map +1 -0
  26. package/dest/proposal_handler.js +1302 -0
  27. package/dest/validator.d.ts +62 -26
  28. package/dest/validator.d.ts.map +1 -1
  29. package/dest/validator.js +347 -238
  30. package/package.json +19 -19
  31. package/src/checkpoint_builder.ts +156 -42
  32. package/src/config.ts +53 -9
  33. package/src/duties/validation_service.ts +59 -54
  34. package/src/factory.ts +20 -7
  35. package/src/index.ts +1 -2
  36. package/src/key_store/ha_key_store.ts +1 -1
  37. package/src/key_store/web3signer_key_store.ts +43 -59
  38. package/src/metrics.ts +39 -1
  39. package/src/proposal_handler.ts +1418 -0
  40. package/src/validator.ts +480 -286
  41. package/dest/block_proposal_handler.d.ts +0 -63
  42. package/dest/block_proposal_handler.d.ts.map +0 -1
  43. package/dest/block_proposal_handler.js +0 -546
  44. package/dest/tx_validator/index.d.ts +0 -3
  45. package/dest/tx_validator/index.d.ts.map +0 -1
  46. package/dest/tx_validator/index.js +0 -2
  47. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  48. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  49. package/dest/tx_validator/nullifier_cache.js +0 -24
  50. package/dest/tx_validator/tx_validator_factory.d.ts +0 -19
  51. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  52. package/dest/tx_validator/tx_validator_factory.js +0 -54
  53. package/src/block_proposal_handler.ts +0 -555
  54. package/src/tx_validator/index.ts +0 -2
  55. package/src/tx_validator/nullifier_cache.ts +0 -30
  56. package/src/tx_validator/tx_validator_factory.ts +0 -154
package/dest/validator.js CHANGED
@@ -1,46 +1,43 @@
1
1
  import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
3
- import { TimeoutError } from '@aztec/foundation/error';
2
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
3
+ import { FifoSet } from '@aztec/foundation/fifo-set';
4
4
  import { createLogger } from '@aztec/foundation/log';
5
- import { retryUntil } from '@aztec/foundation/retry';
6
5
  import { RunningPromise } from '@aztec/foundation/running-promise';
7
6
  import { sleep } from '@aztec/foundation/sleep';
8
7
  import { DateProvider } from '@aztec/foundation/timer';
9
- import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
10
- import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
8
+ import { AuthRequest, AuthResponse, ReqRespSubProtocol } from '@aztec/p2p';
9
+ import { OffenseType, WANT_TO_CLEAR_SLASH_EVENT, WANT_TO_SLASH_EVENT, getOffenseTypeName } from '@aztec/slasher';
11
10
  import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
12
- import { accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
11
+ import { ConsensusTimetable } from '@aztec/stdlib/timetable';
13
12
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
14
13
  import { getTelemetryClient } from '@aztec/telemetry-client';
15
- import { createHASigner } from '@aztec/validator-ha-signer/factory';
14
+ import { createHASigner, createLocalSignerWithProtection, createSignerFromSharedDb } from '@aztec/validator-ha-signer/factory';
16
15
  import { DutyType } from '@aztec/validator-ha-signer/types';
17
16
  import { EventEmitter } from 'events';
18
- import { BlockProposalHandler } from './block_proposal_handler.js';
19
17
  import { ValidationService } from './duties/validation_service.js';
20
18
  import { HAKeyStore } from './key_store/ha_key_store.js';
21
19
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
22
20
  import { ValidatorMetrics } from './metrics.js';
21
+ import { ProposalHandler, SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT, SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT } from './proposal_handler.js';
23
22
  // We maintain a set of proposers who have proposed invalid blocks.
24
23
  // Just cap the set to avoid unbounded growth.
25
24
  const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
26
- // What errors from the block proposal handler result in slashing
27
- const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
28
- 'state_mismatch',
29
- 'failed_txs'
30
- ];
25
+ const MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS = 1000;
26
+ const MAX_TRACKED_BAD_ATTESTATIONS = 10_000;
31
27
  /**
32
28
  * Validator Client
33
29
  */ export class ValidatorClient extends EventEmitter {
34
30
  keyStore;
35
31
  epochCache;
36
32
  p2pClient;
37
- blockProposalHandler;
33
+ proposalHandler;
38
34
  blockSource;
39
35
  checkpointsBuilder;
40
36
  worldState;
41
37
  l1ToL2MessageSource;
42
38
  config;
43
39
  blobClient;
40
+ slashingProtectionSigner;
44
41
  dateProvider;
45
42
  tracer;
46
43
  validationService;
@@ -48,18 +45,24 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
48
45
  log;
49
46
  // Whether it has already registered handlers on the p2p client
50
47
  hasRegisteredHandlers;
51
- // Used to check if we are sending the same proposal twice
52
- previousProposal;
48
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
49
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
53
50
  lastEpochForCommitteeUpdateLoop;
54
51
  epochCacheUpdateLoop;
52
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */ lastAttestedEpochByAttester;
55
53
  proposersOfInvalidBlocks;
56
- constructor(keyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
57
- super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.blockProposalHandler = blockProposalHandler, this.blockSource = blockSource, this.checkpointsBuilder = checkpointsBuilder, this.worldState = worldState, this.l1ToL2MessageSource = l1ToL2MessageSource, this.config = config, this.blobClient = blobClient, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.proposersOfInvalidBlocks = new Set();
54
+ invalidCheckpointProposalOffenseKeys;
55
+ oversizedProposalOffenseKeys;
56
+ badAttestationOffenseKeys;
57
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
58
+ constructor(keyStore, epochCache, p2pClient, proposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
59
+ 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.invalidCheckpointProposalOffenseKeys = FifoSet.withLimit(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS), this.oversizedProposalOffenseKeys = FifoSet.withLimit(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS), this.badAttestationOffenseKeys = FifoSet.withLimit(MAX_TRACKED_BAD_ATTESTATIONS);
58
60
  // Create child logger with fisherman prefix if in fisherman mode
59
61
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
60
62
  this.tracer = telemetry.getTracer('Validator');
61
63
  this.metrics = new ValidatorMetrics(telemetry);
62
- this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
64
+ this.validationService = new ValidationService(keyStore, this.getSignatureContext(), this.log.createChild('validation-service'));
65
+ this.proposalHandler.setCheckpointProposalValidationFailureCallback((proposal, result, proposalInfo)=>this.handleInvalidCheckpointProposal(proposal, result, proposalInfo));
63
66
  // Refresh epoch cache every second to trigger alert if participation in committee changes
64
67
  this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
65
68
  const myAddresses = this.getValidatorAddresses();
@@ -93,6 +96,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
93
96
  this.log.trace(`No committee found for slot`);
94
97
  return;
95
98
  }
99
+ this.metrics.setCurrentEpoch(epoch);
96
100
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
97
101
  const me = this.getValidatorAddresses();
98
102
  const committeeSet = new Set(committee.map((v)=>v.toString()));
@@ -108,34 +112,59 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
108
112
  this.log.error(`Error updating epoch committee`, err);
109
113
  }
110
114
  }
111
- static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
115
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, reexecutionTracker, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), slashingProtectionDb) {
112
116
  const metrics = new ValidatorMetrics(telemetry);
113
- const blockProposalValidator = new BlockProposalValidator(epochCache, {
114
- txsPermitted: !config.disableTransactions
117
+ const consensusTimetable = new ConsensusTimetable({
118
+ l1Constants: epochCache.getL1Constants(),
119
+ blockDuration: config.blockDurationMs / 1000
115
120
  });
116
- const blockProposalHandler = new BlockProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, metrics, dateProvider, telemetry);
117
- let validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
118
- if (config.haSigningEnabled) {
121
+ const proposalHandler = new ProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, epochCache, consensusTimetable, config, blobClient, reexecutionTracker, metrics, dateProvider, telemetry, undefined);
122
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
123
+ let slashingProtectionSigner;
124
+ if (slashingProtectionDb) {
125
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
126
+ ({ signer: slashingProtectionSigner } = createSignerFromSharedDb(slashingProtectionDb, config, {
127
+ telemetryClient: telemetry,
128
+ dateProvider
129
+ }));
130
+ } else if (config.haSigningEnabled) {
131
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
119
132
  // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
120
133
  const haConfig = {
121
134
  ...config,
122
135
  maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
123
136
  };
124
- const { signer } = await createHASigner(haConfig);
125
- validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
137
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
138
+ telemetryClient: telemetry,
139
+ dateProvider
140
+ }));
141
+ } else {
142
+ // Single-node mode: use LMDB-backed local signing protection.
143
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
144
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
145
+ telemetryClient: telemetry,
146
+ dateProvider
147
+ }));
126
148
  }
127
- const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider, telemetry);
149
+ const validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
150
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, proposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider, telemetry);
128
151
  return validator;
129
152
  }
130
153
  getValidatorAddresses() {
131
154
  return this.keyStore.getAddresses().filter((addr)=>!this.config.disabledValidators.some((disabled)=>disabled.equals(addr)));
132
155
  }
133
- getBlockProposalHandler() {
134
- return this.blockProposalHandler;
156
+ getProposalHandler() {
157
+ return this.proposalHandler;
135
158
  }
136
159
  signWithAddress(addr, msg, context) {
137
160
  return this.keyStore.signTypedDataWithAddress(addr, msg, context);
138
161
  }
162
+ getSignatureContext() {
163
+ return {
164
+ chainId: this.config.l1ChainId,
165
+ rollupAddress: this.config.rollupAddress
166
+ };
167
+ }
139
168
  getCoinbaseForAttestor(attestor) {
140
169
  return this.keyStore.getCoinbaseAddress(attestor);
141
170
  }
@@ -145,11 +174,23 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
145
174
  getConfig() {
146
175
  return this.config;
147
176
  }
177
+ hasProposalEquivocation(slotNumber) {
178
+ return this.proposalHandler.hasProposalEquivocation(slotNumber);
179
+ }
180
+ hasInvalidProposals(slotNumber) {
181
+ return this.proposalHandler.hasInvalidProposals(slotNumber);
182
+ }
148
183
  updateConfig(config) {
149
184
  this.config = {
150
185
  ...this.config,
151
186
  ...config
152
187
  };
188
+ this.proposalHandler.updateConfig(config);
189
+ }
190
+ reloadKeystore(newManager) {
191
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
192
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
193
+ this.validationService = new ValidationService(this.keyStore, this.getSignatureContext(), this.log.createChild('validation-service'));
153
194
  }
154
195
  async start() {
155
196
  if (this.epochCacheUpdateLoop.isRunning()) {
@@ -182,11 +223,22 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
182
223
  // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
183
224
  // and processed separately via the block handler above.
184
225
  const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
185
- this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
226
+ this.p2pClient.registerValidatorCheckpointProposalHandler(checkpointHandler);
186
227
  // Duplicate proposal handler - triggers slashing for equivocation
187
228
  this.p2pClient.registerDuplicateProposalCallback((info)=>{
188
229
  this.handleDuplicateProposal(info);
189
230
  });
231
+ // Oversized proposal handler - triggers slashing for proposals beyond the per-checkpoint block limit
232
+ this.p2pClient.registerOversizedProposalCallback((info)=>{
233
+ this.handleOversizedProposal(info);
234
+ });
235
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
236
+ this.p2pClient.registerDuplicateAttestationCallback((info)=>{
237
+ this.handleDuplicateAttestation(info);
238
+ });
239
+ this.p2pClient.registerCheckpointAttestationCallback((attestation)=>{
240
+ this.handleCheckpointAttestation(attestation);
241
+ });
190
242
  const myAddresses = this.getValidatorAddresses();
191
243
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
192
244
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
@@ -207,6 +259,13 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
207
259
  this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
208
260
  return false;
209
261
  }
262
+ // Log self-proposals from HA peers (same validator key on different nodes)
263
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
264
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
265
+ proposer: proposer.toString(),
266
+ slotNumber
267
+ });
268
+ }
210
269
  // Check if we're in the committee (for metrics purposes)
211
270
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
212
271
  const partOfCommittee = inCommittee.length > 0;
@@ -219,21 +278,20 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
219
278
  txHashes: proposal.txHashes.map((t)=>t.toString()),
220
279
  fishermanMode: this.config.fishermanMode || false
221
280
  });
222
- // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
223
- // In fisherman mode, we always reexecute to validate proposals.
224
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
225
- const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.blobClient.canUpload();
226
- const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
281
+ // Reexecute outside the escape hatch so slashing observers can detect invalid proposals even when penalties are 0.
282
+ const validationResult = await this.proposalHandler.handleBlockProposal(proposal, proposalSender, !escapeHatchOpen);
227
283
  if (!validationResult.isValid) {
228
- this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
229
284
  const reason = validationResult.reason || 'unknown';
285
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
230
286
  // Classify failure reason: bad proposal vs node issue
231
287
  const badProposalReasons = [
232
288
  'invalid_proposal',
233
289
  'state_mismatch',
234
290
  'failed_txs',
235
291
  'in_hash_mismatch',
236
- 'parent_block_wrong_slot'
292
+ 'parent_block_wrong_slot',
293
+ 'duplicate_txs',
294
+ 'invalid_embedded_txs'
237
295
  ];
238
296
  if (badProposalReasons.includes(reason)) {
239
297
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
@@ -241,10 +299,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
241
299
  // Node issues so we can't validate
242
300
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
243
301
  }
244
- // Slash invalid block proposals (can happen even when not in committee)
245
- if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
246
- this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
302
+ if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason)) {
303
+ this.log.info(`Detected invalid block proposal offense`, {
304
+ ...proposalInfo,
305
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
306
+ offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL)
307
+ });
247
308
  this.slashInvalidBlock(proposal);
309
+ this.markInvalidProposalSlot(proposal.slotNumber);
248
310
  }
249
311
  return false;
250
312
  }
@@ -266,45 +328,50 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
266
328
  * the lastBlock is extracted and processed separately via the block handler.
267
329
  * @returns Checkpoint attestations if valid, undefined otherwise
268
330
  */ async attestToCheckpointProposal(proposal, _proposalSender) {
269
- const slotNumber = proposal.slotNumber;
331
+ const proposalSlotNumber = proposal.slotNumber;
270
332
  const proposer = proposal.getSender();
271
333
  // If escape hatch is open for this slot's epoch, do not attest.
272
- if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
273
- this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
334
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposalSlotNumber)) {
335
+ this.log.warn(`Escape hatch open for slot ${proposalSlotNumber}, skipping checkpoint attestation handling`);
274
336
  return undefined;
275
337
  }
276
- // Reject proposals with invalid signatures
277
- if (!proposer) {
278
- this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
338
+ // Early-out for equivocation: refuses if we've already attested to a higher slot.
339
+ if (!this.shouldAttestToSlot(proposalSlotNumber)) {
279
340
  return undefined;
280
341
  }
281
- // Check that I have any address in current committee before attesting
282
- const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
342
+ // Ignore proposals from ourselves (may happen in HA setups)
343
+ if (proposer && this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
344
+ this.log.debug(`Not attesting to block proposal from self for slot ${proposalSlotNumber}`, {
345
+ proposer: proposer.toString(),
346
+ proposalSlotNumber
347
+ });
348
+ return undefined;
349
+ }
350
+ // Check that I have any address in the committee where this checkpoint will land before attesting
351
+ const inCommittee = await this.epochCache.filterInCommittee(proposalSlotNumber, this.getValidatorAddresses());
283
352
  const partOfCommittee = inCommittee.length > 0;
284
353
  const proposalInfo = {
285
- slotNumber,
354
+ proposalSlotNumber,
286
355
  archive: proposal.archive.toString(),
287
- proposer: proposer.toString(),
288
- txCount: proposal.txHashes.length
356
+ proposer: proposer?.toString()
289
357
  };
290
- this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
358
+ this.log.info(`Received checkpoint proposal for slot ${proposalSlotNumber}`, {
291
359
  ...proposalInfo,
292
- txHashes: proposal.txHashes.map((t)=>t.toString()),
293
360
  fishermanMode: this.config.fishermanMode || false
294
361
  });
295
- // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
362
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set).
363
+ // Uses the cached result from the all-nodes callback if available (avoids double validation).
364
+ let checkpointNumber;
296
365
  if (this.config.skipCheckpointProposalValidation) {
297
- this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
366
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposalSlotNumber}`, proposalInfo);
367
+ checkpointNumber = CheckpointNumber(0);
298
368
  } else {
299
- const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
369
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
300
370
  if (!validationResult.isValid) {
301
371
  this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
302
372
  return undefined;
303
373
  }
304
- }
305
- // Upload blobs to filestore if we can (fire and forget)
306
- if (this.blobClient.canUpload()) {
307
- void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
374
+ checkpointNumber = validationResult.checkpointNumber;
308
375
  }
309
376
  // Check that I have any address in current committee before attesting
310
377
  // In fisherman mode, we still create attestations for validation even if not in committee
@@ -313,12 +380,22 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
313
380
  return undefined;
314
381
  }
315
382
  // Provided all of the above checks pass, we can attest to the proposal
316
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
383
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`, {
317
384
  ...proposalInfo,
318
385
  inCommittee: partOfCommittee,
319
386
  fishermanMode: this.config.fishermanMode || false
320
387
  });
321
388
  this.metrics.incSuccessfulAttestations(inCommittee.length);
389
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
390
+ const proposalEpoch = getEpochAtSlot(proposalSlotNumber, this.epochCache.getL1Constants());
391
+ for (const attester of inCommittee){
392
+ const key = attester.toString();
393
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
394
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
395
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
396
+ this.metrics.incAttestedEpochCount(attester);
397
+ }
398
+ }
322
399
  // Determine which validators should attest
323
400
  let attestors;
324
401
  if (partOfCommittee) {
@@ -335,157 +412,47 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
335
412
  }
336
413
  if (this.config.fishermanMode) {
337
414
  // bail out early and don't save attestations to the pool in fisherman mode
338
- this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
415
+ this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
339
416
  ...proposalInfo,
340
417
  attestors: attestors.map((a)=>a.toString())
341
418
  });
342
419
  return undefined;
343
420
  }
344
- return this.createCheckpointAttestationsFromProposal(proposal, attestors);
345
- }
346
- async createCheckpointAttestationsFromProposal(proposal, attestors = []) {
347
- const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
348
- await this.p2pClient.addOwnCheckpointAttestations(attestations);
349
- return attestations;
421
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors, checkpointNumber);
350
422
  }
351
423
  /**
352
- * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
353
- * @returns Validation result with isValid flag and reason if invalid.
354
- */ async validateCheckpointProposal(proposal, proposalInfo) {
355
- const slot = proposal.slotNumber;
356
- const timeoutSeconds = 10; // TODO(palla/mbps): This should map to the timetable settings
357
- // Wait for last block to sync by archive
358
- let lastBlockHeader;
359
- try {
360
- lastBlockHeader = await retryUntil(async ()=>{
361
- await this.blockSource.syncImmediate();
362
- return this.blockSource.getBlockHeaderByArchive(proposal.archive);
363
- }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
364
- } catch (err) {
365
- if (err instanceof TimeoutError) {
366
- this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
367
- return {
368
- isValid: false,
369
- reason: 'last_block_not_found'
370
- };
371
- }
372
- this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
373
- return {
374
- isValid: false,
375
- reason: 'block_fetch_error'
376
- };
424
+ * Checks if we should attest to a slot based on equivocation prevention rules.
425
+ * @returns true if we should attest, false if we should skip
426
+ */ shouldAttestToSlot(slotNumber) {
427
+ // If attestToEquivocatedProposals is true, always allow
428
+ if (this.config.attestToEquivocatedProposals) {
429
+ return true;
377
430
  }
378
- if (!lastBlockHeader) {
379
- this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
380
- return {
381
- isValid: false,
382
- reason: 'last_block_not_found'
383
- };
384
- }
385
- // Get all full blocks for the slot and checkpoint
386
- const blocks = await this.blockSource.getBlocksForSlot(slot);
387
- if (blocks.length === 0) {
388
- this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
389
- return {
390
- isValid: false,
391
- reason: 'no_blocks_for_slot'
392
- };
393
- }
394
- this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
395
- ...proposalInfo,
396
- blockNumbers: blocks.map((b)=>b.number)
397
- });
398
- // Get checkpoint constants from first block
399
- const firstBlock = blocks[0];
400
- const constants = this.extractCheckpointConstants(firstBlock);
401
- const checkpointNumber = firstBlock.checkpointNumber;
402
- // Get L1-to-L2 messages for this checkpoint
403
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
404
- // Compute the previous checkpoint out hashes for the epoch.
405
- // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch the
406
- // actual checkpoints and the blocks/txs in them.
407
- const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
408
- const previousCheckpoints = (await this.blockSource.getCheckpointsForEpoch(epoch)).filter((b)=>b.number < checkpointNumber).sort((a, b)=>a.number - b.number);
409
- const previousCheckpointOutHashes = previousCheckpoints.map((c)=>c.getCheckpointOutHash());
410
- // Fork world state at the block before the first block
411
- const parentBlockNumber = BlockNumber(firstBlock.number - 1);
412
- const fork = await this.worldState.fork(parentBlockNumber);
413
- try {
414
- // Create checkpoint builder with all existing blocks
415
- const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
416
- // Complete the checkpoint to get computed values
417
- const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
418
- // Compare checkpoint header with proposal
419
- if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
420
- this.log.warn(`Checkpoint header mismatch`, {
421
- ...proposalInfo,
422
- computed: computedCheckpoint.header.toInspect(),
423
- proposal: proposal.checkpointHeader.toInspect()
424
- });
425
- return {
426
- isValid: false,
427
- reason: 'checkpoint_header_mismatch'
428
- };
429
- }
430
- // Compare archive root with proposal
431
- if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
432
- this.log.warn(`Archive root mismatch`, {
433
- ...proposalInfo,
434
- computed: computedCheckpoint.archive.root.toString(),
435
- proposal: proposal.archive.toString()
436
- });
437
- return {
438
- isValid: false,
439
- reason: 'archive_mismatch'
440
- };
441
- }
442
- // Check that the accumulated epoch out hash matches the value in the proposal.
443
- // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
444
- const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
445
- const computedEpochOutHash = accumulateCheckpointOutHashes([
446
- ...previousCheckpointOutHashes,
447
- checkpointOutHash
448
- ]);
449
- const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
450
- if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
451
- this.log.warn(`Epoch out hash mismatch`, {
452
- proposalEpochOutHash: proposalEpochOutHash.toString(),
453
- computedEpochOutHash: computedEpochOutHash.toString(),
454
- checkpointOutHash: checkpointOutHash.toString(),
455
- previousCheckpointOutHashes: previousCheckpointOutHashes.map((h)=>h.toString()),
456
- ...proposalInfo
457
- });
458
- return {
459
- isValid: false,
460
- reason: 'out_hash_mismatch'
461
- };
462
- }
463
- this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
464
- return {
465
- isValid: true
466
- };
467
- } finally{
468
- await fork.close();
431
+ // Check if incoming slot is strictly greater than last attested
432
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
433
+ this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
434
+ return false;
469
435
  }
436
+ return true;
470
437
  }
471
- /**
472
- * Extract checkpoint global variables from a block.
473
- */ extractCheckpointConstants(block) {
474
- const gv = block.header.globalVariables;
475
- return {
476
- chainId: gv.chainId,
477
- version: gv.version,
478
- slotNumber: gv.slotNumber,
479
- coinbase: gv.coinbase,
480
- feeRecipient: gv.feeRecipient,
481
- gasFees: gv.gasFees
482
- };
438
+ async createCheckpointAttestationsFromProposal(proposal, attestors = [], checkpointNumber) {
439
+ // Equivocation check: must happen right before signing to minimize the race window
440
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
441
+ return undefined;
442
+ }
443
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors, checkpointNumber);
444
+ // Track the proposal we attested to (to prevent equivocation)
445
+ this.lastAttestedProposal = proposal;
446
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
447
+ return attestations;
483
448
  }
484
449
  /**
485
450
  * Uploads blobs for a checkpoint to the filestore (fire and forget).
486
451
  */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
487
452
  try {
488
- const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
453
+ const lastBlockHeader = (await this.blockSource.getBlockData({
454
+ archive: proposal.archive
455
+ }))?.header;
489
456
  if (!lastBlockHeader) {
490
457
  this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
491
458
  return;
@@ -496,7 +463,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
496
463
  return;
497
464
  }
498
465
  const blobFields = blocks.flatMap((b)=>b.toBlobFields());
499
- const blobs = getBlobsPerL1Block(blobFields);
466
+ const blobs = await getBlobsPerL1Block(blobFields);
500
467
  await this.blobClient.sendBlobsToFilestore(blobs);
501
468
  this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
502
469
  ...proposalInfo,
@@ -513,11 +480,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
513
480
  this.log.warn(`Cannot slash proposal with invalid signature`);
514
481
  return;
515
482
  }
516
- // Trim the set if it's too big.
517
- if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
518
- // remove oldest proposer. `values` is guaranteed to be in insertion order.
519
- this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value);
520
- }
521
483
  this.proposersOfInvalidBlocks.add(proposer.toString());
522
484
  this.emit(WANT_TO_SLASH_EVENT, [
523
485
  {
@@ -528,17 +490,122 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
528
490
  }
529
491
  ]);
530
492
  }
493
+ handleInvalidCheckpointProposal(proposal, result, proposalInfo) {
494
+ if (!SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT[result.reason]) {
495
+ return;
496
+ }
497
+ // The slot is already marked invalid by the all-nodes checkpoint handler that invokes this callback,
498
+ // so we only emit the proposer slash event here.
499
+ if (this.slashInvalidCheckpointProposal(proposal)) {
500
+ this.log.info(`Detected invalid checkpoint proposal offense`, {
501
+ ...proposalInfo,
502
+ reason: result.reason,
503
+ amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
504
+ offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL)
505
+ });
506
+ }
507
+ }
508
+ slashInvalidCheckpointProposal(proposal) {
509
+ const proposer = proposal.getSender();
510
+ if (!proposer) {
511
+ this.log.warn(`Cannot slash checkpoint proposal with invalid signature`, {
512
+ slotNumber: proposal.slotNumber,
513
+ archive: proposal.archive.toString()
514
+ });
515
+ return false;
516
+ }
517
+ const offenseType = OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL;
518
+ const offenseKey = `${proposer.toString()}:${offenseType}:${proposal.slotNumber}`;
519
+ if (!this.invalidCheckpointProposalOffenseKeys.addIfAbsent(offenseKey)) {
520
+ return false;
521
+ }
522
+ this.emit(WANT_TO_SLASH_EVENT, [
523
+ {
524
+ validator: proposer,
525
+ amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
526
+ offenseType,
527
+ epochOrSlot: BigInt(proposal.slotNumber)
528
+ }
529
+ ]);
530
+ return true;
531
+ }
532
+ markInvalidProposalSlot(slotNumber) {
533
+ this.proposalHandler.markInvalidProposalSlot(slotNumber);
534
+ }
535
+ handleCheckpointAttestation(attestation) {
536
+ const slotNumber = attestation.slotNumber;
537
+ if (!this.proposalHandler.hasInvalidProposals(slotNumber) || this.proposalHandler.hasProposalEquivocation(slotNumber)) {
538
+ return;
539
+ }
540
+ const attester = attestation.getSender();
541
+ if (!attester) {
542
+ this.log.warn(`Cannot slash checkpoint attestation with invalid signature`, {
543
+ slotNumber,
544
+ archive: attestation.archive.toString()
545
+ });
546
+ return;
547
+ }
548
+ this.slashAttestedToInvalidCheckpointProposal(slotNumber, attester);
549
+ }
550
+ slashAttestedToInvalidCheckpointProposal(slotNumber, attester) {
551
+ const offenseKey = `${attester.toString()}:${OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL}:${slotNumber}`;
552
+ if (!this.badAttestationOffenseKeys.addIfAbsent(offenseKey)) {
553
+ return;
554
+ }
555
+ this.log.info(`Detected attestation to invalid checkpoint proposal offense`, {
556
+ attester: attester.toString(),
557
+ slotNumber,
558
+ amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
559
+ offenseType: getOffenseTypeName(OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL)
560
+ });
561
+ this.emit(WANT_TO_SLASH_EVENT, [
562
+ {
563
+ validator: attester,
564
+ amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
565
+ offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
566
+ epochOrSlot: BigInt(slotNumber)
567
+ }
568
+ ]);
569
+ }
570
+ /**
571
+ * Handle detection of an oversized block proposal: one whose index within its checkpoint lands at or
572
+ * beyond the consensus per-checkpoint block limit. A single signed proposal at an illegal index is
573
+ * self-contained evidence, so emit an invalid-block-proposal slash event for the proposer, deduped per
574
+ * (proposer, slot) since the p2p layer reports every oversized proposal it stores.
575
+ */ handleOversizedProposal(info) {
576
+ const { slot, proposer } = info;
577
+ const offenseType = OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL;
578
+ if (!this.oversizedProposalOffenseKeys.addIfAbsent(`${proposer.toString()}:${offenseType}:${slot}`)) {
579
+ return;
580
+ }
581
+ this.log.info(`Detected oversized block proposal offense from ${proposer.toString()} at slot ${slot}`, {
582
+ proposer: proposer.toString(),
583
+ slot,
584
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
585
+ offenseType: getOffenseTypeName(offenseType)
586
+ });
587
+ this.emit(WANT_TO_SLASH_EVENT, [
588
+ {
589
+ validator: proposer,
590
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
591
+ offenseType,
592
+ epochOrSlot: BigInt(slot)
593
+ }
594
+ ]);
595
+ }
531
596
  /**
532
597
  * Handle detection of a duplicate proposal (equivocation).
533
598
  * Emits a slash event when a proposer sends multiple proposals for the same position.
534
599
  */ handleDuplicateProposal(info) {
535
600
  const { slot, proposer, type } = info;
536
- this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
601
+ this.proposalHandler.markProposalEquivocation(slot);
602
+ this.log.info(`Detected duplicate ${type} proposal offense from ${proposer.toString()} at slot ${slot}`, {
537
603
  proposer: proposer.toString(),
538
604
  slot,
539
- type
605
+ type,
606
+ amount: this.config.slashDuplicateProposalPenalty,
607
+ offenseType: getOffenseTypeName(OffenseType.DUPLICATE_PROPOSAL)
540
608
  });
541
- // Emit slash event
542
609
  this.emit(WANT_TO_SLASH_EVENT, [
543
610
  {
544
611
  validator: proposer,
@@ -547,38 +614,88 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
547
614
  epochOrSlot: BigInt(slot)
548
615
  }
549
616
  ]);
617
+ this.emit(WANT_TO_CLEAR_SLASH_EVENT, [
618
+ {
619
+ offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
620
+ epochOrSlot: BigInt(slot)
621
+ }
622
+ ]);
550
623
  }
551
- async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
552
- // TODO(palla/mbps): Prevent double proposals properly
553
- // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
554
- // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
555
- // return Promise.resolve(undefined);
556
- // }
624
+ /**
625
+ * Handle detection of a duplicate attestation (equivocation).
626
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
627
+ */ handleDuplicateAttestation(info) {
628
+ const { slot, attester } = info;
629
+ this.log.info(`Detected duplicate attestation offense from ${attester.toString()} at slot ${slot}`, {
630
+ attester: attester.toString(),
631
+ slot,
632
+ amount: this.config.slashDuplicateAttestationPenalty,
633
+ offenseType: getOffenseTypeName(OffenseType.DUPLICATE_ATTESTATION)
634
+ });
635
+ this.emit(WANT_TO_SLASH_EVENT, [
636
+ {
637
+ validator: attester,
638
+ amount: this.config.slashDuplicateAttestationPenalty,
639
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
640
+ epochOrSlot: BigInt(slot)
641
+ }
642
+ ]);
643
+ }
644
+ async createBlockProposal(blockHeader, checkpointNumber, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
645
+ // Validate that we're not creating a proposal for an older or equal position
646
+ if (this.lastProposedBlock) {
647
+ const lastSlot = this.lastProposedBlock.slotNumber;
648
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
649
+ const newSlot = blockHeader.globalVariables.slotNumber;
650
+ if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
651
+ throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
652
+ }
653
+ }
557
654
  this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
558
- const newProposal = await this.validationService.createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
655
+ const newProposal = await this.validationService.createBlockProposal(blockHeader, checkpointNumber, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
559
656
  ...options,
560
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
657
+ broadcastInvalidBlockProposal: options.broadcastInvalidBlockProposal || this.config.broadcastInvalidBlockProposal
561
658
  });
562
- this.previousProposal = newProposal;
659
+ this.lastProposedBlock = newProposal;
563
660
  return newProposal;
564
661
  }
565
- async createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options = {}) {
662
+ async createCheckpointProposal(checkpointHeader, archive, checkpointNumber, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options = {}) {
663
+ // Validate that we're not creating a proposal for an older or equal slot
664
+ if (this.lastProposedCheckpoint) {
665
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
666
+ const newSlot = checkpointHeader.slotNumber;
667
+ if (newSlot <= lastSlot) {
668
+ throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
669
+ }
670
+ }
566
671
  this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
567
- return await this.validationService.createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options);
672
+ const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, checkpointNumber, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options);
673
+ this.lastProposedCheckpoint = newProposal;
674
+ // Self-record this slot's outcome on the re-execution tracker. Proposers don't run their
675
+ // own proposals through `handleCheckpointProposal`, so without this call the proposer's
676
+ // sentinel would see no outcome for slots it proposed and would mis-attribute itself as
677
+ // inactive. We pass the locally-computed `archive` (not `newProposal.archive`, which may
678
+ // be intentionally corrupted under test-only flags); from the proposer's local-view
679
+ // perspective the work it just completed is valid by definition.
680
+ this.proposalHandler.recordOwnCheckpointProposalAsValid(checkpointHeader.slotNumber, archive, checkpointNumber);
681
+ return newProposal;
568
682
  }
569
683
  async broadcastBlockProposal(proposal) {
570
684
  await this.p2pClient.broadcastProposal(proposal);
571
685
  }
572
- async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber) {
573
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
686
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber) {
687
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber);
574
688
  }
575
- async collectOwnAttestations(proposal) {
689
+ async collectOwnAttestations(proposal, checkpointNumber) {
576
690
  const slot = proposal.slotNumber;
577
691
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
578
692
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
579
693
  inCommittee
580
694
  });
581
- const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
695
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
696
+ if (!attestations) {
697
+ return [];
698
+ }
582
699
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
583
700
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
584
701
  // due to inactivity for missed attestations.
@@ -587,7 +704,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
587
704
  });
588
705
  return attestations;
589
706
  }
590
- async collectAttestations(proposal, required, deadline) {
707
+ async collectAttestations(proposal, required, deadline, checkpointNumber) {
591
708
  // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
592
709
  const slot = proposal.slotNumber;
593
710
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
@@ -595,28 +712,20 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
595
712
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
596
713
  throw new AttestationTimeoutError(0, required, slot);
597
714
  }
598
- await this.collectOwnAttestations(proposal);
599
- const proposalId = proposal.archive.toString();
715
+ await this.collectOwnAttestations(proposal, checkpointNumber);
716
+ const proposalPayloadHash = proposal.getPayloadHash();
600
717
  const myAddresses = this.getValidatorAddresses();
601
718
  let attestations = [];
602
719
  while(true){
603
- // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
604
- // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
605
- const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
606
- if (!attestation.archive.equals(proposal.archive)) {
607
- this.log.warn(`Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`, {
608
- attestationArchive: attestation.archive.toString(),
609
- proposalArchive: proposal.archive.toString()
610
- });
611
- return false;
612
- }
613
- return true;
614
- });
720
+ // The pool already filters by proposal payload hash; if any attestation slips through with a
721
+ // mismatched payload hash, drop it defensively. Equivocations are emitted as separate slash
722
+ // events from libp2p_service.
723
+ const collectedAttestations = await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
615
724
  // Log new attestations we collected
616
725
  const oldSenders = attestations.map((attestation)=>attestation.getSender());
617
726
  for (const collected of collectedAttestations){
618
727
  const collectedSender = collected.getSender();
619
- // Skip attestations with invalid signatures
728
+ // Skip attestations with invalid signatures. Should not happen as we don't add invalid attestations to our pool.
620
729
  if (!collectedSender) {
621
730
  this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
622
731
  continue;