@aztec/validator-client 0.0.1-commit.1142ef1 → 0.0.1-commit.125b3452

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +96 -24
  2. package/dest/block_proposal_handler.d.ts +12 -11
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +132 -77
  5. package/dest/checkpoint_builder.d.ts +32 -25
  6. package/dest/checkpoint_builder.d.ts.map +1 -1
  7. package/dest/checkpoint_builder.js +144 -49
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +33 -14
  11. package/dest/duties/validation_service.d.ts +20 -7
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +69 -22
  14. package/dest/factory.d.ts +2 -2
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +3 -2
  17. package/dest/index.d.ts +1 -2
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +0 -1
  20. package/dest/key_store/ha_key_store.d.ts +99 -0
  21. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  22. package/dest/key_store/ha_key_store.js +208 -0
  23. package/dest/key_store/index.d.ts +2 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +1 -0
  26. package/dest/key_store/interface.d.ts +36 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/local_key_store.d.ts +10 -5
  29. package/dest/key_store/local_key_store.d.ts.map +1 -1
  30. package/dest/key_store/local_key_store.js +8 -4
  31. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  32. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  33. package/dest/key_store/node_keystore_adapter.js +18 -4
  34. package/dest/key_store/web3signer_key_store.d.ts +10 -5
  35. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  36. package/dest/key_store/web3signer_key_store.js +8 -4
  37. package/dest/metrics.d.ts +12 -3
  38. package/dest/metrics.d.ts.map +1 -1
  39. package/dest/metrics.js +46 -5
  40. package/dest/validator.d.ts +45 -18
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +263 -99
  43. package/package.json +21 -17
  44. package/src/block_proposal_handler.ts +163 -95
  45. package/src/checkpoint_builder.ts +206 -61
  46. package/src/config.ts +32 -13
  47. package/src/duties/validation_service.ts +94 -25
  48. package/src/factory.ts +2 -0
  49. package/src/index.ts +0 -1
  50. package/src/key_store/ha_key_store.ts +269 -0
  51. package/src/key_store/index.ts +1 -0
  52. package/src/key_store/interface.ts +44 -5
  53. package/src/key_store/local_key_store.ts +13 -4
  54. package/src/key_store/node_keystore_adapter.ts +27 -4
  55. package/src/key_store/web3signer_key_store.ts +17 -4
  56. package/src/metrics.ts +63 -6
  57. package/src/validator.ts +329 -118
  58. package/dest/tx_validator/index.d.ts +0 -3
  59. package/dest/tx_validator/index.d.ts.map +0 -1
  60. package/dest/tx_validator/index.js +0 -2
  61. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  62. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  63. package/dest/tx_validator/nullifier_cache.js +0 -24
  64. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  65. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  66. package/dest/tx_validator/tx_validator_factory.js +0 -53
  67. package/src/tx_validator/index.ts +0 -2
  68. package/src/tx_validator/nullifier_cache.ts +0 -30
  69. package/src/tx_validator/tx_validator_factory.ts +0 -133
package/dest/validator.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
3
+ import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
3
4
  import { TimeoutError } from '@aztec/foundation/error';
4
5
  import { createLogger } from '@aztec/foundation/log';
5
6
  import { retryUntil } from '@aztec/foundation/retry';
@@ -8,11 +9,17 @@ import { sleep } from '@aztec/foundation/sleep';
8
9
  import { DateProvider } from '@aztec/foundation/timer';
9
10
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
10
11
  import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
12
+ import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
13
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
14
+ import { accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
11
15
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
12
16
  import { getTelemetryClient } from '@aztec/telemetry-client';
17
+ import { createHASigner, createLocalSignerWithProtection } from '@aztec/validator-ha-signer/factory';
18
+ import { DutyType } from '@aztec/validator-ha-signer/types';
13
19
  import { EventEmitter } from 'events';
14
20
  import { BlockProposalHandler } from './block_proposal_handler.js';
15
21
  import { ValidationService } from './duties/validation_service.js';
22
+ import { HAKeyStore } from './key_store/ha_key_store.js';
16
23
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
17
24
  import { ValidatorMetrics } from './metrics.js';
18
25
  // We maintain a set of proposers who have proposed invalid blocks.
@@ -36,6 +43,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
36
43
  l1ToL2MessageSource;
37
44
  config;
38
45
  blobClient;
46
+ slashingProtectionSigner;
39
47
  dateProvider;
40
48
  tracer;
41
49
  validationService;
@@ -43,17 +51,15 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
43
51
  log;
44
52
  // Whether it has already registered handlers on the p2p client
45
53
  hasRegisteredHandlers;
46
- // Used to check if we are sending the same proposal twice
47
- previousProposal;
54
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
55
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
48
56
  lastEpochForCommitteeUpdateLoop;
49
57
  epochCacheUpdateLoop;
58
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */ lastAttestedEpochByAttester;
50
59
  proposersOfInvalidBlocks;
51
- // TODO(palla/mbps): Remove this once checkpoint validation is stable and we can validate all blocks properly.
52
- // Tracks slots for which we have successfully validated a block proposal, so we can attest to checkpoint proposals for those slots.
53
- // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
54
- validatedBlockSlots;
55
- constructor(keyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
56
- 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(), this.validatedBlockSlots = new Set();
60
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
61
+ constructor(keyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
62
+ 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.slashingProtectionSigner = slashingProtectionSigner, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.lastAttestedEpochByAttester = new Map(), this.proposersOfInvalidBlocks = new Set();
57
63
  // Create child logger with fisherman prefix if in fisherman mode
58
64
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
59
65
  this.tracer = telemetry.getTracer('Validator');
@@ -92,6 +98,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
92
98
  this.log.trace(`No committee found for slot`);
93
99
  return;
94
100
  }
101
+ this.metrics.setCurrentEpoch(epoch);
95
102
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
96
103
  const me = this.getValidatorAddresses();
97
104
  const committeeSet = new Set(committee.map((v)=>v.toString()));
@@ -107,13 +114,36 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
107
114
  this.log.error(`Error updating epoch committee`, err);
108
115
  }
109
116
  }
110
- static new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
117
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
111
118
  const metrics = new ValidatorMetrics(telemetry);
112
119
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
113
- txsPermitted: !config.disableTransactions
120
+ txsPermitted: !config.disableTransactions,
121
+ maxTxsPerBlock: config.validateMaxTxsPerBlock
114
122
  });
115
- const blockProposalHandler = new BlockProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, config, metrics, dateProvider, telemetry);
116
- const validator = new ValidatorClient(NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager), epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider, telemetry);
123
+ const blockProposalHandler = new BlockProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, metrics, dateProvider, telemetry);
124
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
125
+ let slashingProtectionSigner;
126
+ if (config.haSigningEnabled) {
127
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
128
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
129
+ const haConfig = {
130
+ ...config,
131
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
132
+ };
133
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
134
+ telemetryClient: telemetry,
135
+ dateProvider
136
+ }));
137
+ } else {
138
+ // Single-node mode: use LMDB-backed local signing protection.
139
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
140
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
141
+ telemetryClient: telemetry,
142
+ dateProvider
143
+ }));
144
+ }
145
+ const validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
146
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider, telemetry);
117
147
  return validator;
118
148
  }
119
149
  getValidatorAddresses() {
@@ -122,8 +152,8 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
122
152
  getBlockProposalHandler() {
123
153
  return this.blockProposalHandler;
124
154
  }
125
- signWithAddress(addr, msg) {
126
- return this.keyStore.signTypedDataWithAddress(addr, msg);
155
+ signWithAddress(addr, msg, context) {
156
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
127
157
  }
128
158
  getCoinbaseForAttestor(attestor) {
129
159
  return this.keyStore.getCoinbaseAddress(attestor);
@@ -140,11 +170,17 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
140
170
  ...config
141
171
  };
142
172
  }
173
+ reloadKeystore(newManager) {
174
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
175
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
176
+ this.validationService = new ValidationService(this.keyStore, this.log.createChild('validation-service'));
177
+ }
143
178
  async start() {
144
179
  if (this.epochCacheUpdateLoop.isRunning()) {
145
180
  this.log.warn(`Validator client already started`);
146
181
  return;
147
182
  }
183
+ await this.keyStore.start();
148
184
  await this.registerHandlers();
149
185
  const myAddresses = this.getValidatorAddresses();
150
186
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
@@ -157,6 +193,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
157
193
  }
158
194
  async stop() {
159
195
  await this.epochCacheUpdateLoop.stop();
196
+ await this.keyStore.stop();
160
197
  }
161
198
  /** Register handlers on the p2p client */ async registerHandlers() {
162
199
  if (!this.hasRegisteredHandlers) {
@@ -170,6 +207,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
170
207
  // and processed separately via the block handler above.
171
208
  const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
172
209
  this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
210
+ // Duplicate proposal handler - triggers slashing for equivocation
211
+ this.p2pClient.registerDuplicateProposalCallback((info)=>{
212
+ this.handleDuplicateProposal(info);
213
+ });
214
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
215
+ this.p2pClient.registerDuplicateAttestationCallback((info)=>{
216
+ this.handleDuplicateAttestation(info);
217
+ });
173
218
  const myAddresses = this.getValidatorAddresses();
174
219
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
175
220
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
@@ -181,12 +226,23 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
181
226
  * @returns true if the proposal is valid, false otherwise
182
227
  */ async validateBlockProposal(proposal, proposalSender) {
183
228
  const slotNumber = proposal.slotNumber;
229
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
230
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
231
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
184
232
  const proposer = proposal.getSender();
185
233
  // Reject proposals with invalid signatures
186
234
  if (!proposer) {
187
235
  this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
188
236
  return false;
189
237
  }
238
+ // Ignore proposals from ourselves (may happen in HA setups)
239
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
240
+ this.log.debug(`Ignoring block proposal from self for slot ${slotNumber}`, {
241
+ proposer: proposer.toString(),
242
+ slotNumber
243
+ });
244
+ return false;
245
+ }
190
246
  // Check if we're in the committee (for metrics purposes)
191
247
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
192
248
  const partOfCommittee = inCommittee.length > 0;
@@ -203,10 +259,10 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
203
259
  // In fisherman mode, we always reexecute to validate proposals.
204
260
  const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
205
261
  const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.blobClient.canUpload();
206
- const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute);
262
+ const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
207
263
  if (!validationResult.isValid) {
208
- this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
209
264
  const reason = validationResult.reason || 'unknown';
265
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
210
266
  // Classify failure reason: bad proposal vs node issue
211
267
  const badProposalReasons = [
212
268
  'invalid_proposal',
@@ -222,7 +278,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
222
278
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
223
279
  }
224
280
  // Slash invalid block proposals (can happen even when not in committee)
225
- if (validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
281
+ if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
226
282
  this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
227
283
  this.slashInvalidBlock(proposal);
228
284
  }
@@ -231,11 +287,13 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
231
287
  this.log.info(`Validated block proposal for slot ${slotNumber}`, {
232
288
  ...proposalInfo,
233
289
  inCommittee: partOfCommittee,
234
- fishermanMode: this.config.fishermanMode || false
290
+ fishermanMode: this.config.fishermanMode || false,
291
+ escapeHatchOpen
235
292
  });
236
- // TODO(palla/mbps): Remove this once checkpoint validation is stable.
237
- // Track that we successfully validated a block for this slot, so we can attest to checkpoint proposals for it.
238
- this.validatedBlockSlots.add(slotNumber);
293
+ if (escapeHatchOpen) {
294
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
295
+ return false;
296
+ }
239
297
  return true;
240
298
  }
241
299
  /**
@@ -246,35 +304,44 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
246
304
  */ async attestToCheckpointProposal(proposal, _proposalSender) {
247
305
  const slotNumber = proposal.slotNumber;
248
306
  const proposer = proposal.getSender();
307
+ // If escape hatch is open for this slot's epoch, do not attest.
308
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
309
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
310
+ return undefined;
311
+ }
249
312
  // Reject proposals with invalid signatures
250
313
  if (!proposer) {
251
314
  this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
252
315
  return undefined;
253
316
  }
317
+ // Ignore proposals from ourselves (may happen in HA setups)
318
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
319
+ this.log.debug(`Ignoring block proposal from self for slot ${slotNumber}`, {
320
+ proposer: proposer.toString(),
321
+ slotNumber
322
+ });
323
+ return undefined;
324
+ }
325
+ // Validate fee asset price modifier is within allowed range
326
+ if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
327
+ this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${slotNumber}`);
328
+ return undefined;
329
+ }
254
330
  // Check that I have any address in current committee before attesting
255
331
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
256
332
  const partOfCommittee = inCommittee.length > 0;
257
333
  const proposalInfo = {
258
334
  slotNumber,
259
335
  archive: proposal.archive.toString(),
260
- proposer: proposer.toString(),
261
- txCount: proposal.txHashes.length
336
+ proposer: proposer.toString()
262
337
  };
263
338
  this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
264
339
  ...proposalInfo,
265
- txHashes: proposal.txHashes.map((t)=>t.toString()),
266
340
  fishermanMode: this.config.fishermanMode || false
267
341
  });
268
- // TODO(palla/mbps): Remove this once checkpoint validation is stable.
269
- // Check that we have successfully validated a block for this slot before attesting to the checkpoint.
270
- if (!this.validatedBlockSlots.has(slotNumber)) {
271
- this.log.warn(`No validated block found for slot ${slotNumber}, refusing to attest to checkpoint`, proposalInfo);
272
- return undefined;
273
- }
274
342
  // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
275
- // TODO(palla/mbps): Change default to false once checkpoint validation is stable.
276
- if (this.config.skipCheckpointProposalValidation !== false) {
277
- this.log.verbose(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
343
+ if (this.config.skipCheckpointProposalValidation) {
344
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
278
345
  } else {
279
346
  const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
280
347
  if (!validationResult.isValid) {
@@ -299,6 +366,16 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
299
366
  fishermanMode: this.config.fishermanMode || false
300
367
  });
301
368
  this.metrics.incSuccessfulAttestations(inCommittee.length);
369
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
370
+ const proposalEpoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
371
+ for (const attester of inCommittee){
372
+ const key = attester.toString();
373
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
374
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
375
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
376
+ this.metrics.incAttestedEpochCount(attester);
377
+ }
378
+ }
302
379
  // Determine which validators should attest
303
380
  let attestors;
304
381
  if (partOfCommittee) {
@@ -321,11 +398,32 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
321
398
  });
322
399
  return undefined;
323
400
  }
324
- return this.createCheckpointAttestationsFromProposal(proposal, attestors);
401
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors);
402
+ }
403
+ /**
404
+ * Checks if we should attest to a slot based on equivocation prevention rules.
405
+ * @returns true if we should attest, false if we should skip
406
+ */ shouldAttestToSlot(slotNumber) {
407
+ // If attestToEquivocatedProposals is true, always allow
408
+ if (this.config.attestToEquivocatedProposals) {
409
+ return true;
410
+ }
411
+ // Check if incoming slot is strictly greater than last attested
412
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
413
+ this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
414
+ return false;
415
+ }
416
+ return true;
325
417
  }
326
418
  async createCheckpointAttestationsFromProposal(proposal, attestors = []) {
419
+ // Equivocation check: must happen right before signing to minimize the race window
420
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
421
+ return undefined;
422
+ }
327
423
  const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
328
- await this.p2pClient.addCheckpointAttestations(attestations);
424
+ // Track the proposal we attested to (to prevent equivocation)
425
+ this.lastAttestedProposal = proposal;
426
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
329
427
  return attestations;
330
428
  }
331
429
  /**
@@ -333,7 +431,10 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
333
431
  * @returns Validation result with isValid flag and reason if invalid.
334
432
  */ async validateCheckpointProposal(proposal, proposalInfo) {
335
433
  const slot = proposal.slotNumber;
336
- const timeoutSeconds = 10;
434
+ // Timeout block syncing at the start of the next slot
435
+ const config = this.checkpointsBuilder.getConfig();
436
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
437
+ const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
337
438
  // Wait for last block to sync by archive
338
439
  let lastBlockHeader;
339
440
  try {
@@ -362,18 +463,8 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
362
463
  reason: 'last_block_not_found'
363
464
  };
364
465
  }
365
- // Get the last full block to determine checkpoint number
366
- const lastBlock = await this.blockSource.getL2BlockNew(lastBlockHeader.getBlockNumber());
367
- if (!lastBlock) {
368
- this.log.warn(`Last block ${lastBlockHeader.getBlockNumber()} not found`, proposalInfo);
369
- return {
370
- isValid: false,
371
- reason: 'last_block_not_found'
372
- };
373
- }
374
- const checkpointNumber = lastBlock.checkpointNumber;
375
466
  // Get all full blocks for the slot and checkpoint
376
- const blocks = await this.getBlocksForSlot(slot, lastBlockHeader, checkpointNumber);
467
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
377
468
  if (blocks.length === 0) {
378
469
  this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
379
470
  return {
@@ -381,6 +472,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
381
472
  reason: 'no_blocks_for_slot'
382
473
  };
383
474
  }
475
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
476
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
477
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
478
+ return {
479
+ isValid: false,
480
+ reason: 'last_block_archive_mismatch'
481
+ };
482
+ }
384
483
  this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
385
484
  ...proposalInfo,
386
485
  blockNumbers: blocks.map((b)=>b.number)
@@ -388,14 +487,18 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
388
487
  // Get checkpoint constants from first block
389
488
  const firstBlock = blocks[0];
390
489
  const constants = this.extractCheckpointConstants(firstBlock);
490
+ const checkpointNumber = firstBlock.checkpointNumber;
391
491
  // Get L1-to-L2 messages for this checkpoint
392
492
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
493
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
494
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
495
+ const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
393
496
  // Fork world state at the block before the first block
394
497
  const parentBlockNumber = BlockNumber(firstBlock.number - 1);
395
498
  const fork = await this.worldState.fork(parentBlockNumber);
396
499
  try {
397
500
  // Create checkpoint builder with all existing blocks
398
- const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, l1ToL2Messages, fork, blocks);
501
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
399
502
  // Complete the checkpoint to get computed values
400
503
  const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
401
504
  // Compare checkpoint header with proposal
@@ -422,6 +525,43 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
422
525
  reason: 'archive_mismatch'
423
526
  };
424
527
  }
528
+ // Check that the accumulated epoch out hash matches the value in the proposal.
529
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
530
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
531
+ const computedEpochOutHash = accumulateCheckpointOutHashes([
532
+ ...previousCheckpointOutHashes,
533
+ checkpointOutHash
534
+ ]);
535
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
536
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
537
+ this.log.warn(`Epoch out hash mismatch`, {
538
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
539
+ computedEpochOutHash: computedEpochOutHash.toString(),
540
+ checkpointOutHash: checkpointOutHash.toString(),
541
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map((h)=>h.toString()),
542
+ ...proposalInfo
543
+ });
544
+ return {
545
+ isValid: false,
546
+ reason: 'out_hash_mismatch'
547
+ };
548
+ }
549
+ // Final round of validations on the checkpoint, just in case.
550
+ try {
551
+ validateCheckpoint(computedCheckpoint, {
552
+ rollupManaLimit: this.checkpointsBuilder.getConfig().rollupManaLimit,
553
+ maxDABlockGas: this.config.validateMaxDABlockGas,
554
+ maxL2BlockGas: this.config.validateMaxL2BlockGas,
555
+ maxTxsPerBlock: this.config.validateMaxTxsPerBlock,
556
+ maxTxsPerCheckpoint: this.config.validateMaxTxsPerCheckpoint
557
+ });
558
+ } catch (err) {
559
+ this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
560
+ return {
561
+ isValid: false,
562
+ reason: 'checkpoint_validation_failed'
563
+ };
564
+ }
425
565
  this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
426
566
  return {
427
567
  isValid: true
@@ -431,36 +571,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
431
571
  }
432
572
  }
433
573
  /**
434
- * Get all full blocks for a given slot and checkpoint by walking backwards from the last block.
435
- * Returns blocks in ascending order (earliest to latest).
436
- * TODO(palla/mbps): Add getL2BlocksForSlot() to L2BlockSource interface for efficiency.
437
- */ async getBlocksForSlot(slot, lastBlockHeader, checkpointNumber) {
438
- const blocks = [];
439
- let currentHeader = lastBlockHeader;
440
- const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
441
- while(currentHeader.getSlot() === slot){
442
- const block = await this.blockSource.getL2BlockNew(currentHeader.getBlockNumber());
443
- if (!block) {
444
- this.log.warn(`Block ${currentHeader.getBlockNumber()} not found while getting blocks for slot ${slot}`);
445
- break;
446
- }
447
- if (block.checkpointNumber !== checkpointNumber) {
448
- break;
449
- }
450
- blocks.unshift(block);
451
- const prevArchive = currentHeader.lastArchive.root;
452
- if (prevArchive.equals(genesisArchiveRoot)) {
453
- break;
454
- }
455
- const prevHeader = await this.blockSource.getBlockHeaderByArchive(prevArchive);
456
- if (!prevHeader || prevHeader.getSlot() !== slot) {
457
- break;
458
- }
459
- currentHeader = prevHeader;
460
- }
461
- return blocks;
462
- }
463
- /**
464
574
  * Extract checkpoint global variables from a block.
465
575
  */ extractCheckpointConstants(block) {
466
576
  const gv = block.header.globalVariables;
@@ -468,6 +578,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
468
578
  chainId: gv.chainId,
469
579
  version: gv.version,
470
580
  slotNumber: gv.slotNumber,
581
+ timestamp: gv.timestamp,
471
582
  coinbase: gv.coinbase,
472
583
  feeRecipient: gv.feeRecipient,
473
584
  gasFees: gv.gasFees
@@ -482,19 +593,13 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
482
593
  this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
483
594
  return;
484
595
  }
485
- // Get the last full block to determine checkpoint number
486
- const lastBlock = await this.blockSource.getL2BlockNew(lastBlockHeader.getBlockNumber());
487
- if (!lastBlock) {
488
- this.log.warn(`Failed to get last block for blob upload`, proposalInfo);
489
- return;
490
- }
491
- const blocks = await this.getBlocksForSlot(proposal.slotNumber, lastBlockHeader, lastBlock.checkpointNumber);
596
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
492
597
  if (blocks.length === 0) {
493
598
  this.log.warn(`No blocks found for blob upload`, proposalInfo);
494
599
  return;
495
600
  }
496
601
  const blobFields = blocks.flatMap((b)=>b.toBlobFields());
497
- const blobs = getBlobsPerL1Block(blobFields);
602
+ const blobs = await getBlobsPerL1Block(blobFields);
498
603
  await this.blobClient.sendBlobsToFilestore(blobs);
499
604
  this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
500
605
  ...proposalInfo,
@@ -526,29 +631,81 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
526
631
  }
527
632
  ]);
528
633
  }
529
- async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options) {
530
- // TODO(palla/mbps): Prevent double proposals properly
531
- // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
532
- // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
533
- // return Promise.resolve(undefined);
534
- // }
634
+ /**
635
+ * Handle detection of a duplicate proposal (equivocation).
636
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
637
+ */ handleDuplicateProposal(info) {
638
+ const { slot, proposer, type } = info;
639
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
640
+ proposer: proposer.toString(),
641
+ slot,
642
+ type
643
+ });
644
+ // Emit slash event
645
+ this.emit(WANT_TO_SLASH_EVENT, [
646
+ {
647
+ validator: proposer,
648
+ amount: this.config.slashDuplicateProposalPenalty,
649
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
650
+ epochOrSlot: BigInt(slot)
651
+ }
652
+ ]);
653
+ }
654
+ /**
655
+ * Handle detection of a duplicate attestation (equivocation).
656
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
657
+ */ handleDuplicateAttestation(info) {
658
+ const { slot, attester } = info;
659
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
660
+ attester: attester.toString(),
661
+ slot
662
+ });
663
+ this.emit(WANT_TO_SLASH_EVENT, [
664
+ {
665
+ validator: attester,
666
+ amount: this.config.slashDuplicateAttestationPenalty,
667
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
668
+ epochOrSlot: BigInt(slot)
669
+ }
670
+ ]);
671
+ }
672
+ async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
673
+ // Validate that we're not creating a proposal for an older or equal position
674
+ if (this.lastProposedBlock) {
675
+ const lastSlot = this.lastProposedBlock.slotNumber;
676
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
677
+ const newSlot = blockHeader.globalVariables.slotNumber;
678
+ if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
679
+ throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
680
+ }
681
+ }
535
682
  this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
536
683
  const newProposal = await this.validationService.createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
537
684
  ...options,
538
685
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
539
686
  });
540
- this.previousProposal = newProposal;
687
+ this.lastProposedBlock = newProposal;
541
688
  return newProposal;
542
689
  }
543
- async createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options) {
690
+ async createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAddress, options = {}) {
691
+ // Validate that we're not creating a proposal for an older or equal slot
692
+ if (this.lastProposedCheckpoint) {
693
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
694
+ const newSlot = checkpointHeader.slotNumber;
695
+ if (newSlot <= lastSlot) {
696
+ throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
697
+ }
698
+ }
544
699
  this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
545
- return await this.validationService.createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options);
700
+ const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAddress, options);
701
+ this.lastProposedCheckpoint = newProposal;
702
+ return newProposal;
546
703
  }
547
704
  async broadcastBlockProposal(proposal) {
548
705
  await this.p2pClient.broadcastProposal(proposal);
549
706
  }
550
- async signAttestationsAndSigners(attestationsAndSigners, proposer) {
551
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
707
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber) {
708
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
552
709
  }
553
710
  async collectOwnAttestations(proposal) {
554
711
  const slot = proposal.slotNumber;
@@ -557,6 +714,9 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
557
714
  inCommittee
558
715
  });
559
716
  const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
717
+ if (!attestations) {
718
+ return [];
719
+ }
560
720
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
561
721
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
562
722
  // due to inactivity for missed attestations.
@@ -630,7 +790,11 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
630
790
  return Buffer.alloc(0);
631
791
  }
632
792
  const payloadToSign = authRequest.getPayloadToSign();
633
- const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
793
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
794
+ const context = {
795
+ dutyType: DutyType.AUTH_REQUEST
796
+ };
797
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
634
798
  const authResponse = new AuthResponse(statusMessage, signature);
635
799
  return authResponse.toBuffer();
636
800
  }