@aztec/validator-client 0.0.1-commit.6230efd → 0.0.1-commit.64b6bbb

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