@aztec/validator-client 0.0.1-commit.d3ec352c → 0.0.1-commit.d6f2b3f94

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 +21 -11
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +339 -83
  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 +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 -21
  50. package/dest/validator.d.ts.map +1 -1
  51. package/dest/validator.js +416 -56
  52. package/package.json +21 -11
  53. package/src/block_proposal_handler.ts +260 -49
  54. package/src/checkpoint_builder.ts +314 -0
  55. package/src/config.ts +15 -7
  56. package/src/duties/validation_service.ts +155 -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 +571 -84
package/dest/validator.js CHANGED
@@ -1,14 +1,23 @@
1
+ import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
+ import { BlockNumber } from '@aztec/foundation/branded-types';
3
+ import { TimeoutError } from '@aztec/foundation/error';
1
4
  import { createLogger } from '@aztec/foundation/log';
5
+ import { retryUntil } from '@aztec/foundation/retry';
2
6
  import { RunningPromise } from '@aztec/foundation/running-promise';
3
7
  import { sleep } from '@aztec/foundation/sleep';
4
8
  import { DateProvider } from '@aztec/foundation/timer';
5
9
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
6
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';
7
13
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
8
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';
9
17
  import { EventEmitter } from 'events';
10
18
  import { BlockProposalHandler } from './block_proposal_handler.js';
11
19
  import { ValidationService } from './duties/validation_service.js';
20
+ import { HAKeyStore } from './key_store/ha_key_store.js';
12
21
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
13
22
  import { ValidatorMetrics } from './metrics.js';
14
23
  // We maintain a set of proposers who have proposed invalid blocks.
@@ -26,7 +35,12 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
26
35
  epochCache;
27
36
  p2pClient;
28
37
  blockProposalHandler;
38
+ blockSource;
39
+ checkpointsBuilder;
40
+ worldState;
41
+ l1ToL2MessageSource;
29
42
  config;
43
+ blobClient;
30
44
  dateProvider;
31
45
  tracer;
32
46
  validationService;
@@ -34,13 +48,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
34
48
  log;
35
49
  // Whether it has already registered handlers on the p2p client
36
50
  hasRegisteredHandlers;
37
- // Used to check if we are sending the same proposal twice
38
- previousProposal;
51
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
52
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
39
53
  lastEpochForCommitteeUpdateLoop;
40
54
  epochCacheUpdateLoop;
41
55
  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();
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();
44
59
  // Create child logger with fisherman prefix if in fisherman mode
45
60
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
46
61
  this.tracer = telemetry.getTracer('Validator');
@@ -94,13 +109,23 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
94
109
  this.log.error(`Error updating epoch committee`, err);
95
110
  }
96
111
  }
97
- static new(config, blockBuilder, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
112
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
98
113
  const metrics = new ValidatorMetrics(telemetry);
99
114
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
100
115
  txsPermitted: !config.disableTransactions
101
116
  });
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);
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);
104
129
  return validator;
105
130
  }
106
131
  getValidatorAddresses() {
@@ -109,12 +134,8 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
109
134
  getBlockProposalHandler() {
110
135
  return this.blockProposalHandler;
111
136
  }
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);
137
+ signWithAddress(addr, msg, context) {
138
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
118
139
  }
119
140
  getCoinbaseForAttestor(attestor) {
120
141
  return this.keyStore.getCoinbaseAddress(attestor);
@@ -136,6 +157,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
136
157
  this.log.warn(`Validator client already started`);
137
158
  return;
138
159
  }
160
+ await this.keyStore.start();
139
161
  await this.registerHandlers();
140
162
  const myAddresses = this.getValidatorAddresses();
141
163
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
@@ -148,46 +170,75 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
148
170
  }
149
171
  async stop() {
150
172
  await this.epochCacheUpdateLoop.stop();
173
+ await this.keyStore.stop();
151
174
  }
152
175
  /** Register handlers on the p2p client */ async registerHandlers() {
153
176
  if (!this.hasRegisteredHandlers) {
154
177
  this.hasRegisteredHandlers = true;
155
178
  this.log.debug(`Registering validator handlers for p2p client`);
156
- const handler = (block, proposalSender)=>this.attestToProposal(block, proposalSender);
157
- 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
+ });
158
195
  const myAddresses = this.getValidatorAddresses();
159
196
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
160
197
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
161
198
  }
162
199
  }
163
- 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) {
164
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);
165
209
  const proposer = proposal.getSender();
166
210
  // Reject proposals with invalid signatures
167
211
  if (!proposer) {
168
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
169
- return undefined;
212
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
213
+ return false;
170
214
  }
171
- // 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)
172
224
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
173
225
  const partOfCommittee = inCommittee.length > 0;
174
226
  const proposalInfo = {
175
227
  ...proposal.toBlockInfo(),
176
228
  proposer: proposer.toString()
177
229
  };
178
- this.log.info(`Received proposal for slot ${slotNumber}`, {
230
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
179
231
  ...proposalInfo,
180
232
  txHashes: proposal.txHashes.map((t)=>t.toString()),
181
233
  fishermanMode: this.config.fishermanMode || false
182
234
  });
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.
235
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
185
236
  // In fisherman mode, we always reexecute to validate proposals.
186
237
  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);
238
+ const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.blobClient.canUpload();
239
+ const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
189
240
  if (!validationResult.isValid) {
190
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
241
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
191
242
  const reason = validationResult.reason || 'unknown';
192
243
  // Classify failure reason: bad proposal vs node issue
193
244
  const badProposalReasons = [
@@ -200,30 +251,95 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
200
251
  if (badProposalReasons.includes(reason)) {
201
252
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
202
253
  } else {
203
- // Node issues so we can't attest
254
+ // Node issues so we can't validate
204
255
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
205
256
  }
206
257
  // 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) {
258
+ if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
208
259
  this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
209
260
  this.slashInvalidBlock(proposal);
210
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
+ });
211
300
  return undefined;
212
301
  }
213
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
214
331
  // In fisherman mode, we still create attestations for validation even if not in committee
215
332
  if (!partOfCommittee && !this.config.fishermanMode) {
216
333
  this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
217
334
  return undefined;
218
335
  }
219
336
  // 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}`, {
337
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
221
338
  ...proposalInfo,
222
339
  inCommittee: partOfCommittee,
223
340
  fishermanMode: this.config.fishermanMode || false
224
341
  });
225
342
  this.metrics.incSuccessfulAttestations(inCommittee.length);
226
- // If the above function does not throw an error, then we can attest to the proposal
227
343
  // Determine which validators should attest
228
344
  let attestors;
229
345
  if (partOfCommittee) {
@@ -240,13 +356,197 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
240
356
  }
241
357
  if (this.config.fishermanMode) {
242
358
  // 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}`, {
359
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
244
360
  ...proposalInfo,
245
361
  attestors: attestors.map((a)=>a.toString())
246
362
  });
247
363
  return undefined;
248
364
  }
249
- 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
+ }
250
550
  }
251
551
  slashInvalidBlock(proposal) {
252
552
  const proposer = proposal.getSender();
@@ -270,42 +570,103 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
270
570
  }
271
571
  ]);
272
572
  }
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);
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
+ }
277
620
  }
278
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
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, {
279
623
  ...options,
280
624
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
281
625
  });
282
- this.previousProposal = newProposal;
626
+ this.lastProposedBlock = newProposal;
627
+ return newProposal;
628
+ }
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;
283
641
  return newProposal;
284
642
  }
285
643
  async broadcastBlockProposal(proposal) {
286
644
  await this.p2pClient.broadcastProposal(proposal);
287
645
  }
288
- async signAttestationsAndSigners(attestationsAndSigners, proposer) {
289
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
646
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber) {
647
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
290
648
  }
291
649
  async collectOwnAttestations(proposal) {
292
- const slot = proposal.payload.header.slotNumber;
650
+ const slot = proposal.slotNumber;
293
651
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
294
652
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
295
653
  inCommittee
296
654
  });
297
- const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
655
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
656
+ if (!attestations) {
657
+ return [];
658
+ }
298
659
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
299
660
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
300
661
  // due to inactivity for missed attestations.
301
- void this.p2pClient.broadcastAttestations(attestations).catch((err)=>{
662
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch((err)=>{
302
663
  this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
303
664
  });
304
665
  return attestations;
305
666
  }
306
667
  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;
668
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
669
+ const slot = proposal.slotNumber;
309
670
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
310
671
  if (+deadline < this.dateProvider.now()) {
311
672
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
@@ -316,13 +677,13 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
316
677
  const myAddresses = this.getValidatorAddresses();
317
678
  let attestations = [];
318
679
  while(true){
319
- // 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
320
681
  // 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
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()
326
687
  });
327
688
  return false;
328
689
  }
@@ -354,11 +715,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
354
715
  await sleep(this.config.attestationPollingIntervalMs);
355
716
  }
356
717
  }
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
718
  async handleAuthRequest(peer, msg) {
363
719
  const authRequest = AuthRequest.fromBuffer(msg);
364
720
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
@@ -373,7 +729,11 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
373
729
  return Buffer.alloc(0);
374
730
  }
375
731
  const payloadToSign = authRequest.getPayloadToSign();
376
- 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);
377
737
  const authResponse = new AuthResponse(statusMessage, signature);
378
738
  return authResponse.toBuffer();
379
739
  }