@aztec/validator-client 0.0.1-commit.21caa21 → 0.0.1-commit.21ecf947b

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 +285 -0
  2. package/dest/block_proposal_handler.d.ts +23 -12
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +340 -84
  5. package/dest/checkpoint_builder.d.ts +66 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +175 -0
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +16 -8
  11. package/dest/duties/validation_service.d.ts +42 -13
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +111 -28
  14. package/dest/factory.d.ts +13 -8
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +2 -2
  17. package/dest/index.d.ts +3 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +2 -0
  20. package/dest/key_store/ha_key_store.d.ts +99 -0
  21. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  22. package/dest/key_store/ha_key_store.js +208 -0
  23. package/dest/key_store/index.d.ts +2 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +1 -0
  26. package/dest/key_store/interface.d.ts +36 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/local_key_store.d.ts +10 -5
  29. package/dest/key_store/local_key_store.d.ts.map +1 -1
  30. package/dest/key_store/local_key_store.js +9 -5
  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 +9 -5
  37. package/dest/metrics.d.ts +4 -3
  38. package/dest/metrics.d.ts.map +1 -1
  39. package/dest/metrics.js +34 -30
  40. package/dest/tx_validator/index.d.ts +3 -0
  41. package/dest/tx_validator/index.d.ts.map +1 -0
  42. package/dest/tx_validator/index.js +2 -0
  43. package/dest/tx_validator/nullifier_cache.d.ts +14 -0
  44. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
  45. package/dest/tx_validator/nullifier_cache.js +24 -0
  46. package/dest/tx_validator/tx_validator_factory.d.ts +19 -0
  47. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  48. package/dest/tx_validator/tx_validator_factory.js +54 -0
  49. package/dest/validator.d.ts +67 -20
  50. package/dest/validator.d.ts.map +1 -1
  51. package/dest/validator.js +425 -56
  52. package/package.json +23 -13
  53. package/src/block_proposal_handler.ts +268 -53
  54. package/src/checkpoint_builder.ts +321 -0
  55. package/src/config.ts +15 -7
  56. package/src/duties/validation_service.ts +162 -33
  57. package/src/factory.ts +17 -8
  58. package/src/index.ts +2 -0
  59. package/src/key_store/ha_key_store.ts +269 -0
  60. package/src/key_store/index.ts +1 -0
  61. package/src/key_store/interface.ts +44 -5
  62. package/src/key_store/local_key_store.ts +14 -5
  63. package/src/key_store/node_keystore_adapter.ts +28 -5
  64. package/src/key_store/web3signer_key_store.ts +18 -5
  65. package/src/metrics.ts +45 -33
  66. package/src/tx_validator/index.ts +2 -0
  67. package/src/tx_validator/nullifier_cache.ts +30 -0
  68. package/src/tx_validator/tx_validator_factory.ts +154 -0
  69. package/src/validator.ts +587 -84
package/dest/validator.js CHANGED
@@ -1,14 +1,24 @@
1
+ import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
+ import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
3
+ import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
+ import { TimeoutError } from '@aztec/foundation/error';
1
5
  import { createLogger } from '@aztec/foundation/log';
6
+ import { retryUntil } from '@aztec/foundation/retry';
2
7
  import { RunningPromise } from '@aztec/foundation/running-promise';
3
8
  import { sleep } from '@aztec/foundation/sleep';
4
9
  import { DateProvider } from '@aztec/foundation/timer';
5
10
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
6
11
  import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
12
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
13
+ import { accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
7
14
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
8
15
  import { getTelemetryClient } from '@aztec/telemetry-client';
16
+ import { createHASigner } from '@aztec/validator-ha-signer/factory';
17
+ import { DutyType } from '@aztec/validator-ha-signer/types';
9
18
  import { EventEmitter } from 'events';
10
19
  import { BlockProposalHandler } from './block_proposal_handler.js';
11
20
  import { ValidationService } from './duties/validation_service.js';
21
+ import { HAKeyStore } from './key_store/ha_key_store.js';
12
22
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
13
23
  import { ValidatorMetrics } from './metrics.js';
14
24
  // We maintain a set of proposers who have proposed invalid blocks.
@@ -26,7 +36,12 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
26
36
  epochCache;
27
37
  p2pClient;
28
38
  blockProposalHandler;
39
+ blockSource;
40
+ checkpointsBuilder;
41
+ worldState;
42
+ l1ToL2MessageSource;
29
43
  config;
44
+ blobClient;
30
45
  dateProvider;
31
46
  tracer;
32
47
  validationService;
@@ -34,13 +49,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
34
49
  log;
35
50
  // Whether it has already registered handlers on the p2p client
36
51
  hasRegisteredHandlers;
37
- // Used to check if we are sending the same proposal twice
38
- previousProposal;
52
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
53
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
39
54
  lastEpochForCommitteeUpdateLoop;
40
55
  epochCacheUpdateLoop;
41
56
  proposersOfInvalidBlocks;
42
- constructor(keyStore, epochCache, p2pClient, blockProposalHandler, config, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
43
- super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.blockProposalHandler = blockProposalHandler, this.config = config, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.proposersOfInvalidBlocks = new Set();
57
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
58
+ constructor(keyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
59
+ 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();
44
60
  // Create child logger with fisherman prefix if in fisherman mode
45
61
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
46
62
  this.tracer = telemetry.getTracer('Validator');
@@ -94,13 +110,23 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
94
110
  this.log.error(`Error updating epoch committee`, err);
95
111
  }
96
112
  }
97
- static new(config, blockBuilder, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
113
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
98
114
  const metrics = new ValidatorMetrics(telemetry);
99
115
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
100
116
  txsPermitted: !config.disableTransactions
101
117
  });
102
- const blockProposalHandler = new BlockProposalHandler(blockBuilder, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, config, metrics, dateProvider, telemetry);
103
- const validator = new ValidatorClient(NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager), epochCache, p2pClient, blockProposalHandler, config, dateProvider, telemetry);
118
+ const blockProposalHandler = new BlockProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, metrics, dateProvider, telemetry);
119
+ let validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
120
+ if (config.haSigningEnabled) {
121
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
122
+ const haConfig = {
123
+ ...config,
124
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
125
+ };
126
+ const { signer } = await createHASigner(haConfig);
127
+ validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
128
+ }
129
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider, telemetry);
104
130
  return validator;
105
131
  }
106
132
  getValidatorAddresses() {
@@ -109,12 +135,8 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
109
135
  getBlockProposalHandler() {
110
136
  return this.blockProposalHandler;
111
137
  }
112
- // Proxy method for backwards compatibility with tests
113
- reExecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages) {
114
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
115
- }
116
- signWithAddress(addr, msg) {
117
- return this.keyStore.signTypedDataWithAddress(addr, msg);
138
+ signWithAddress(addr, msg, context) {
139
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
118
140
  }
119
141
  getCoinbaseForAttestor(attestor) {
120
142
  return this.keyStore.getCoinbaseAddress(attestor);
@@ -136,6 +158,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
136
158
  this.log.warn(`Validator client already started`);
137
159
  return;
138
160
  }
161
+ await this.keyStore.start();
139
162
  await this.registerHandlers();
140
163
  const myAddresses = this.getValidatorAddresses();
141
164
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
@@ -148,46 +171,75 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
148
171
  }
149
172
  async stop() {
150
173
  await this.epochCacheUpdateLoop.stop();
174
+ await this.keyStore.stop();
151
175
  }
152
176
  /** Register handlers on the p2p client */ async registerHandlers() {
153
177
  if (!this.hasRegisteredHandlers) {
154
178
  this.hasRegisteredHandlers = true;
155
179
  this.log.debug(`Registering validator handlers for p2p client`);
156
- const handler = (block, proposalSender)=>this.attestToProposal(block, proposalSender);
157
- this.p2pClient.registerBlockProposalHandler(handler);
180
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
181
+ const blockHandler = (block, proposalSender)=>this.validateBlockProposal(block, proposalSender);
182
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
183
+ // Checkpoint proposal handler - validates and creates attestations
184
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
185
+ // and processed separately via the block handler above.
186
+ const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
187
+ this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
188
+ // Duplicate proposal handler - triggers slashing for equivocation
189
+ this.p2pClient.registerDuplicateProposalCallback((info)=>{
190
+ this.handleDuplicateProposal(info);
191
+ });
192
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
193
+ this.p2pClient.registerDuplicateAttestationCallback((info)=>{
194
+ this.handleDuplicateAttestation(info);
195
+ });
158
196
  const myAddresses = this.getValidatorAddresses();
159
197
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
160
198
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
161
199
  }
162
200
  }
163
- async attestToProposal(proposal, proposalSender) {
201
+ /**
202
+ * Validate a block proposal from a peer.
203
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
204
+ * @returns true if the proposal is valid, false otherwise
205
+ */ async validateBlockProposal(proposal, proposalSender) {
164
206
  const slotNumber = proposal.slotNumber;
207
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
208
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
209
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
165
210
  const proposer = proposal.getSender();
166
211
  // Reject proposals with invalid signatures
167
212
  if (!proposer) {
168
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
169
- return undefined;
213
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
214
+ return false;
170
215
  }
171
- // Check that I have any address in current committee before attesting
216
+ // Ignore proposals from ourselves (may happen in HA setups)
217
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
218
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
219
+ proposer: proposer.toString(),
220
+ slotNumber
221
+ });
222
+ return false;
223
+ }
224
+ // Check if we're in the committee (for metrics purposes)
172
225
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
173
226
  const partOfCommittee = inCommittee.length > 0;
174
227
  const proposalInfo = {
175
228
  ...proposal.toBlockInfo(),
176
229
  proposer: proposer.toString()
177
230
  };
178
- this.log.info(`Received proposal for slot ${slotNumber}`, {
231
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
179
232
  ...proposalInfo,
180
233
  txHashes: proposal.txHashes.map((t)=>t.toString()),
181
234
  fishermanMode: this.config.fishermanMode || false
182
235
  });
183
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
184
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
236
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
185
237
  // In fisherman mode, we always reexecute to validate proposals.
186
238
  const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
187
- const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals;
188
- const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute);
239
+ const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.blobClient.canUpload();
240
+ const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
189
241
  if (!validationResult.isValid) {
190
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
242
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
191
243
  const reason = validationResult.reason || 'unknown';
192
244
  // Classify failure reason: bad proposal vs node issue
193
245
  const badProposalReasons = [
@@ -200,30 +252,100 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
200
252
  if (badProposalReasons.includes(reason)) {
201
253
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
202
254
  } else {
203
- // Node issues so we can't attest
255
+ // Node issues so we can't validate
204
256
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
205
257
  }
206
258
  // Slash invalid block proposals (can happen even when not in committee)
207
- if (validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
259
+ if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
208
260
  this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
209
261
  this.slashInvalidBlock(proposal);
210
262
  }
263
+ return false;
264
+ }
265
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
266
+ ...proposalInfo,
267
+ inCommittee: partOfCommittee,
268
+ fishermanMode: this.config.fishermanMode || false,
269
+ escapeHatchOpen
270
+ });
271
+ if (escapeHatchOpen) {
272
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
273
+ return false;
274
+ }
275
+ return true;
276
+ }
277
+ /**
278
+ * Validate and attest to a checkpoint proposal from a peer.
279
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
280
+ * the lastBlock is extracted and processed separately via the block handler.
281
+ * @returns Checkpoint attestations if valid, undefined otherwise
282
+ */ async attestToCheckpointProposal(proposal, _proposalSender) {
283
+ const slotNumber = proposal.slotNumber;
284
+ const proposer = proposal.getSender();
285
+ // If escape hatch is open for this slot's epoch, do not attest.
286
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
287
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
288
+ return undefined;
289
+ }
290
+ // Reject proposals with invalid signatures
291
+ if (!proposer) {
292
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
293
+ return undefined;
294
+ }
295
+ // Ignore proposals from ourselves (may happen in HA setups)
296
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
297
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
298
+ proposer: proposer.toString(),
299
+ slotNumber
300
+ });
301
+ return undefined;
302
+ }
303
+ // Validate fee asset price modifier is within allowed range
304
+ if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
305
+ this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${slotNumber}`);
211
306
  return undefined;
212
307
  }
213
308
  // Check that I have any address in current committee before attesting
309
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
310
+ const partOfCommittee = inCommittee.length > 0;
311
+ const proposalInfo = {
312
+ slotNumber,
313
+ archive: proposal.archive.toString(),
314
+ proposer: proposer.toString(),
315
+ txCount: proposal.txHashes.length
316
+ };
317
+ this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
318
+ ...proposalInfo,
319
+ txHashes: proposal.txHashes.map((t)=>t.toString()),
320
+ fishermanMode: this.config.fishermanMode || false
321
+ });
322
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
323
+ if (this.config.skipCheckpointProposalValidation) {
324
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
325
+ } else {
326
+ const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
327
+ if (!validationResult.isValid) {
328
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
329
+ return undefined;
330
+ }
331
+ }
332
+ // Upload blobs to filestore if we can (fire and forget)
333
+ if (this.blobClient.canUpload()) {
334
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
335
+ }
336
+ // Check that I have any address in current committee before attesting
214
337
  // In fisherman mode, we still create attestations for validation even if not in committee
215
338
  if (!partOfCommittee && !this.config.fishermanMode) {
216
339
  this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
217
340
  return undefined;
218
341
  }
219
342
  // Provided all of the above checks pass, we can attest to the proposal
220
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} proposal for slot ${slotNumber}`, {
343
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
221
344
  ...proposalInfo,
222
345
  inCommittee: partOfCommittee,
223
346
  fishermanMode: this.config.fishermanMode || false
224
347
  });
225
348
  this.metrics.incSuccessfulAttestations(inCommittee.length);
226
- // If the above function does not throw an error, then we can attest to the proposal
227
349
  // Determine which validators should attest
228
350
  let attestors;
229
351
  if (partOfCommittee) {
@@ -240,13 +362,200 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
240
362
  }
241
363
  if (this.config.fishermanMode) {
242
364
  // bail out early and don't save attestations to the pool in fisherman mode
243
- this.log.info(`Creating attestations for proposal for slot ${slotNumber}`, {
365
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
244
366
  ...proposalInfo,
245
367
  attestors: attestors.map((a)=>a.toString())
246
368
  });
247
369
  return undefined;
248
370
  }
249
- return this.createBlockAttestationsFromProposal(proposal, attestors);
371
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors);
372
+ }
373
+ /**
374
+ * Checks if we should attest to a slot based on equivocation prevention rules.
375
+ * @returns true if we should attest, false if we should skip
376
+ */ shouldAttestToSlot(slotNumber) {
377
+ // If attestToEquivocatedProposals is true, always allow
378
+ if (this.config.attestToEquivocatedProposals) {
379
+ return true;
380
+ }
381
+ // Check if incoming slot is strictly greater than last attested
382
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
383
+ this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
384
+ return false;
385
+ }
386
+ return true;
387
+ }
388
+ async createCheckpointAttestationsFromProposal(proposal, attestors = []) {
389
+ // Equivocation check: must happen right before signing to minimize the race window
390
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
391
+ return undefined;
392
+ }
393
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
394
+ // Track the proposal we attested to (to prevent equivocation)
395
+ this.lastAttestedProposal = proposal;
396
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
397
+ return attestations;
398
+ }
399
+ /**
400
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
401
+ * @returns Validation result with isValid flag and reason if invalid.
402
+ */ async validateCheckpointProposal(proposal, proposalInfo) {
403
+ const slot = proposal.slotNumber;
404
+ // Timeout block syncing at the start of the next slot
405
+ const config = this.checkpointsBuilder.getConfig();
406
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
407
+ const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
408
+ // Wait for last block to sync by archive
409
+ let lastBlockHeader;
410
+ try {
411
+ lastBlockHeader = await retryUntil(async ()=>{
412
+ await this.blockSource.syncImmediate();
413
+ return this.blockSource.getBlockHeaderByArchive(proposal.archive);
414
+ }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
415
+ } catch (err) {
416
+ if (err instanceof TimeoutError) {
417
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
418
+ return {
419
+ isValid: false,
420
+ reason: 'last_block_not_found'
421
+ };
422
+ }
423
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
424
+ return {
425
+ isValid: false,
426
+ reason: 'block_fetch_error'
427
+ };
428
+ }
429
+ if (!lastBlockHeader) {
430
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
431
+ return {
432
+ isValid: false,
433
+ reason: 'last_block_not_found'
434
+ };
435
+ }
436
+ // Get all full blocks for the slot and checkpoint
437
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
438
+ if (blocks.length === 0) {
439
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
440
+ return {
441
+ isValid: false,
442
+ reason: 'no_blocks_for_slot'
443
+ };
444
+ }
445
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
446
+ ...proposalInfo,
447
+ blockNumbers: blocks.map((b)=>b.number)
448
+ });
449
+ // Get checkpoint constants from first block
450
+ const firstBlock = blocks[0];
451
+ const constants = this.extractCheckpointConstants(firstBlock);
452
+ const checkpointNumber = firstBlock.checkpointNumber;
453
+ // Get L1-to-L2 messages for this checkpoint
454
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
455
+ // Compute the previous checkpoint out hashes for the epoch.
456
+ // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch the
457
+ // actual checkpoints and the blocks/txs in them.
458
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
459
+ const previousCheckpoints = (await this.blockSource.getCheckpointsForEpoch(epoch)).filter((b)=>b.number < checkpointNumber).sort((a, b)=>a.number - b.number);
460
+ const previousCheckpointOutHashes = previousCheckpoints.map((c)=>c.getCheckpointOutHash());
461
+ // Fork world state at the block before the first block
462
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
463
+ const fork = await this.worldState.fork(parentBlockNumber);
464
+ try {
465
+ // Create checkpoint builder with all existing blocks
466
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
467
+ // Complete the checkpoint to get computed values
468
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
469
+ // Compare checkpoint header with proposal
470
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
471
+ this.log.warn(`Checkpoint header mismatch`, {
472
+ ...proposalInfo,
473
+ computed: computedCheckpoint.header.toInspect(),
474
+ proposal: proposal.checkpointHeader.toInspect()
475
+ });
476
+ return {
477
+ isValid: false,
478
+ reason: 'checkpoint_header_mismatch'
479
+ };
480
+ }
481
+ // Compare archive root with proposal
482
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
483
+ this.log.warn(`Archive root mismatch`, {
484
+ ...proposalInfo,
485
+ computed: computedCheckpoint.archive.root.toString(),
486
+ proposal: proposal.archive.toString()
487
+ });
488
+ return {
489
+ isValid: false,
490
+ reason: 'archive_mismatch'
491
+ };
492
+ }
493
+ // Check that the accumulated epoch out hash matches the value in the proposal.
494
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
495
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
496
+ const computedEpochOutHash = accumulateCheckpointOutHashes([
497
+ ...previousCheckpointOutHashes,
498
+ checkpointOutHash
499
+ ]);
500
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
501
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
502
+ this.log.warn(`Epoch out hash mismatch`, {
503
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
504
+ computedEpochOutHash: computedEpochOutHash.toString(),
505
+ checkpointOutHash: checkpointOutHash.toString(),
506
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map((h)=>h.toString()),
507
+ ...proposalInfo
508
+ });
509
+ return {
510
+ isValid: false,
511
+ reason: 'out_hash_mismatch'
512
+ };
513
+ }
514
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
515
+ return {
516
+ isValid: true
517
+ };
518
+ } finally{
519
+ await fork.close();
520
+ }
521
+ }
522
+ /**
523
+ * Extract checkpoint global variables from a block.
524
+ */ extractCheckpointConstants(block) {
525
+ const gv = block.header.globalVariables;
526
+ return {
527
+ chainId: gv.chainId,
528
+ version: gv.version,
529
+ slotNumber: gv.slotNumber,
530
+ coinbase: gv.coinbase,
531
+ feeRecipient: gv.feeRecipient,
532
+ gasFees: gv.gasFees
533
+ };
534
+ }
535
+ /**
536
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
537
+ */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
538
+ try {
539
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
540
+ if (!lastBlockHeader) {
541
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
542
+ return;
543
+ }
544
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
545
+ if (blocks.length === 0) {
546
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
547
+ return;
548
+ }
549
+ const blobFields = blocks.flatMap((b)=>b.toBlobFields());
550
+ const blobs = getBlobsPerL1Block(blobFields);
551
+ await this.blobClient.sendBlobsToFilestore(blobs);
552
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
553
+ ...proposalInfo,
554
+ numBlobs: blobs.length
555
+ });
556
+ } catch (err) {
557
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
558
+ }
250
559
  }
251
560
  slashInvalidBlock(proposal) {
252
561
  const proposer = proposal.getSender();
@@ -270,42 +579,103 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
270
579
  }
271
580
  ]);
272
581
  }
273
- async createBlockProposal(blockNumber, header, archive, txs, proposerAddress, options) {
274
- if (this.previousProposal?.slotNumber === header.slotNumber) {
275
- this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
276
- return Promise.resolve(undefined);
582
+ /**
583
+ * Handle detection of a duplicate proposal (equivocation).
584
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
585
+ */ handleDuplicateProposal(info) {
586
+ const { slot, proposer, type } = info;
587
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
588
+ proposer: proposer.toString(),
589
+ slot,
590
+ type
591
+ });
592
+ // Emit slash event
593
+ this.emit(WANT_TO_SLASH_EVENT, [
594
+ {
595
+ validator: proposer,
596
+ amount: this.config.slashDuplicateProposalPenalty,
597
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
598
+ epochOrSlot: BigInt(slot)
599
+ }
600
+ ]);
601
+ }
602
+ /**
603
+ * Handle detection of a duplicate attestation (equivocation).
604
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
605
+ */ handleDuplicateAttestation(info) {
606
+ const { slot, attester } = info;
607
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
608
+ attester: attester.toString(),
609
+ slot
610
+ });
611
+ this.emit(WANT_TO_SLASH_EVENT, [
612
+ {
613
+ validator: attester,
614
+ amount: this.config.slashDuplicateAttestationPenalty,
615
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
616
+ epochOrSlot: BigInt(slot)
617
+ }
618
+ ]);
619
+ }
620
+ async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
621
+ // Validate that we're not creating a proposal for an older or equal position
622
+ if (this.lastProposedBlock) {
623
+ const lastSlot = this.lastProposedBlock.slotNumber;
624
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
625
+ const newSlot = blockHeader.globalVariables.slotNumber;
626
+ if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
627
+ throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
628
+ }
277
629
  }
278
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
630
+ this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
631
+ const newProposal = await this.validationService.createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
279
632
  ...options,
280
633
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
281
634
  });
282
- this.previousProposal = newProposal;
635
+ this.lastProposedBlock = newProposal;
636
+ return newProposal;
637
+ }
638
+ async createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAddress, options = {}) {
639
+ // Validate that we're not creating a proposal for an older or equal slot
640
+ if (this.lastProposedCheckpoint) {
641
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
642
+ const newSlot = checkpointHeader.slotNumber;
643
+ if (newSlot <= lastSlot) {
644
+ throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
645
+ }
646
+ }
647
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
648
+ const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAddress, options);
649
+ this.lastProposedCheckpoint = newProposal;
283
650
  return newProposal;
284
651
  }
285
652
  async broadcastBlockProposal(proposal) {
286
653
  await this.p2pClient.broadcastProposal(proposal);
287
654
  }
288
- async signAttestationsAndSigners(attestationsAndSigners, proposer) {
289
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
655
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber) {
656
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
290
657
  }
291
658
  async collectOwnAttestations(proposal) {
292
- const slot = proposal.payload.header.slotNumber;
659
+ const slot = proposal.slotNumber;
293
660
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
294
661
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
295
662
  inCommittee
296
663
  });
297
- const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
664
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
665
+ if (!attestations) {
666
+ return [];
667
+ }
298
668
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
299
669
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
300
670
  // due to inactivity for missed attestations.
301
- void this.p2pClient.broadcastAttestations(attestations).catch((err)=>{
671
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch((err)=>{
302
672
  this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
303
673
  });
304
674
  return attestations;
305
675
  }
306
676
  async collectAttestations(proposal, required, deadline) {
307
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
308
- const slot = proposal.payload.header.slotNumber;
677
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
678
+ const slot = proposal.slotNumber;
309
679
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
310
680
  if (+deadline < this.dateProvider.now()) {
311
681
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
@@ -316,13 +686,13 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
316
686
  const myAddresses = this.getValidatorAddresses();
317
687
  let attestations = [];
318
688
  while(true){
319
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
689
+ // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
320
690
  // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
321
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
322
- if (!attestation.payload.equals(proposal.payload)) {
323
- this.log.warn(`Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`, {
324
- attestationPayload: attestation.payload,
325
- proposalPayload: proposal.payload
691
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
692
+ if (!attestation.archive.equals(proposal.archive)) {
693
+ this.log.warn(`Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`, {
694
+ attestationArchive: attestation.archive.toString(),
695
+ proposalArchive: proposal.archive.toString()
326
696
  });
327
697
  return false;
328
698
  }
@@ -354,11 +724,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
354
724
  await sleep(this.config.attestationPollingIntervalMs);
355
725
  }
356
726
  }
357
- async createBlockAttestationsFromProposal(proposal, attestors = []) {
358
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
359
- await this.p2pClient.addAttestations(attestations);
360
- return attestations;
361
- }
362
727
  async handleAuthRequest(peer, msg) {
363
728
  const authRequest = AuthRequest.fromBuffer(msg);
364
729
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
@@ -373,7 +738,11 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
373
738
  return Buffer.alloc(0);
374
739
  }
375
740
  const payloadToSign = authRequest.getPayloadToSign();
376
- const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
741
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
742
+ const context = {
743
+ dutyType: DutyType.AUTH_REQUEST
744
+ };
745
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
377
746
  const authResponse = new AuthResponse(statusMessage, signature);
378
747
  return authResponse.toBuffer();
379
748
  }