@aztec/validator-client 0.0.1-commit.fffb133c → 0.0.1-dev

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 (53) hide show
  1. package/README.md +62 -18
  2. package/dest/checkpoint_builder.d.ts +26 -14
  3. package/dest/checkpoint_builder.d.ts.map +1 -1
  4. package/dest/checkpoint_builder.js +136 -45
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +26 -3
  8. package/dest/duties/validation_service.d.ts +3 -4
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +11 -22
  11. package/dest/factory.d.ts +7 -4
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +6 -5
  14. package/dest/index.d.ts +2 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -2
  17. package/dest/key_store/ha_key_store.d.ts +1 -1
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -1
  19. package/dest/key_store/ha_key_store.js +3 -3
  20. package/dest/metrics.d.ts +12 -3
  21. package/dest/metrics.d.ts.map +1 -1
  22. package/dest/metrics.js +46 -5
  23. package/dest/proposal_handler.d.ts +94 -0
  24. package/dest/proposal_handler.d.ts.map +1 -0
  25. package/dest/{block_proposal_handler.js → proposal_handler.js} +376 -69
  26. package/dest/validator.d.ts +37 -24
  27. package/dest/validator.d.ts.map +1 -1
  28. package/dest/validator.js +167 -215
  29. package/package.json +19 -17
  30. package/src/checkpoint_builder.ts +183 -50
  31. package/src/config.ts +26 -3
  32. package/src/duties/validation_service.ts +18 -24
  33. package/src/factory.ts +9 -3
  34. package/src/index.ts +1 -2
  35. package/src/key_store/ha_key_store.ts +3 -3
  36. package/src/metrics.ts +63 -6
  37. package/src/proposal_handler.ts +903 -0
  38. package/src/validator.ts +228 -248
  39. package/dest/block_proposal_handler.d.ts +0 -64
  40. package/dest/block_proposal_handler.d.ts.map +0 -1
  41. package/dest/tx_validator/index.d.ts +0 -3
  42. package/dest/tx_validator/index.d.ts.map +0 -1
  43. package/dest/tx_validator/index.js +0 -2
  44. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  45. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  46. package/dest/tx_validator/nullifier_cache.js +0 -24
  47. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  48. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  49. package/dest/tx_validator/tx_validator_factory.js +0 -54
  50. package/src/block_proposal_handler.ts +0 -554
  51. package/src/tx_validator/index.ts +0 -2
  52. package/src/tx_validator/nullifier_cache.ts +0 -30
  53. package/src/tx_validator/tx_validator_factory.ts +0 -135
package/dest/validator.js CHANGED
@@ -1,8 +1,4 @@
1
- import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
3
- import { TimeoutError } from '@aztec/foundation/error';
4
1
  import { createLogger } from '@aztec/foundation/log';
5
- import { retryUntil } from '@aztec/foundation/retry';
6
2
  import { RunningPromise } from '@aztec/foundation/running-promise';
7
3
  import { sleep } from '@aztec/foundation/sleep';
8
4
  import { DateProvider } from '@aztec/foundation/timer';
@@ -11,14 +7,14 @@ import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
11
7
  import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
12
8
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
13
9
  import { getTelemetryClient } from '@aztec/telemetry-client';
14
- import { createHASigner } from '@aztec/validator-ha-signer/factory';
10
+ import { createHASigner, createSignerFromSharedDb } from '@aztec/validator-ha-signer/factory';
15
11
  import { DutyType } from '@aztec/validator-ha-signer/types';
16
12
  import { EventEmitter } from 'events';
17
- import { BlockProposalHandler } from './block_proposal_handler.js';
18
13
  import { ValidationService } from './duties/validation_service.js';
19
14
  import { HAKeyStore } from './key_store/ha_key_store.js';
20
15
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
21
16
  import { ValidatorMetrics } from './metrics.js';
17
+ import { ProposalHandler } from './proposal_handler.js';
22
18
  // We maintain a set of proposers who have proposed invalid blocks.
23
19
  // Just cap the set to avoid unbounded growth.
24
20
  const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
@@ -33,13 +29,10 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
33
29
  keyStore;
34
30
  epochCache;
35
31
  p2pClient;
36
- blockProposalHandler;
37
- blockSource;
38
- checkpointsBuilder;
39
- worldState;
40
- l1ToL2MessageSource;
32
+ proposalHandler;
41
33
  config;
42
34
  blobClient;
35
+ haSigner;
43
36
  dateProvider;
44
37
  tracer;
45
38
  validationService;
@@ -47,17 +40,15 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
47
40
  log;
48
41
  // Whether it has already registered handlers on the p2p client
49
42
  hasRegisteredHandlers;
50
- // Used to check if we are sending the same proposal twice
51
- previousProposal;
43
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
44
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
52
45
  lastEpochForCommitteeUpdateLoop;
53
46
  epochCacheUpdateLoop;
47
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */ lastAttestedEpochByAttester;
54
48
  proposersOfInvalidBlocks;
55
- // TODO(palla/mbps): Remove this once checkpoint validation is stable and we can validate all blocks properly.
56
- // Tracks slots for which we have successfully validated a block proposal, so we can attest to checkpoint proposals for those slots.
57
- // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
58
- validatedBlockSlots;
59
- constructor(keyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
60
- super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.blockProposalHandler = blockProposalHandler, this.blockSource = blockSource, this.checkpointsBuilder = checkpointsBuilder, this.worldState = worldState, this.l1ToL2MessageSource = l1ToL2MessageSource, this.config = config, this.blobClient = blobClient, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.proposersOfInvalidBlocks = new Set(), this.validatedBlockSlots = new Set();
49
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
50
+ constructor(keyStore, epochCache, p2pClient, proposalHandler, config, blobClient, haSigner, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
51
+ super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.proposalHandler = proposalHandler, this.config = config, this.blobClient = blobClient, this.haSigner = haSigner, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.lastAttestedEpochByAttester = new Map(), this.proposersOfInvalidBlocks = new Set();
61
52
  // Create child logger with fisherman prefix if in fisherman mode
62
53
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
63
54
  this.tracer = telemetry.getTracer('Validator');
@@ -96,6 +87,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
96
87
  this.log.trace(`No committee found for slot`);
97
88
  return;
98
89
  }
90
+ this.metrics.setCurrentEpoch(epoch);
99
91
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
100
92
  const me = this.getValidatorAddresses();
101
93
  const committeeSet = new Set(committee.map((v)=>v.toString()));
@@ -111,30 +103,39 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
111
103
  this.log.error(`Error updating epoch committee`, err);
112
104
  }
113
105
  }
114
- static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
106
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), slashingProtectionDb) {
115
107
  const metrics = new ValidatorMetrics(telemetry);
116
108
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
117
- txsPermitted: !config.disableTransactions
109
+ txsPermitted: !config.disableTransactions,
110
+ maxTxsPerBlock: config.validateMaxTxsPerBlock
118
111
  });
119
- const blockProposalHandler = new BlockProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, metrics, dateProvider, telemetry);
120
- let validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
121
- if (config.haSigningEnabled) {
112
+ const proposalHandler = new ProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, blobClient, metrics, dateProvider, telemetry);
113
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
114
+ let validatorKeyStore = nodeKeystoreAdapter;
115
+ let haSigner;
116
+ if (slashingProtectionDb) {
117
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
118
+ const { signer } = createSignerFromSharedDb(slashingProtectionDb, config);
119
+ haSigner = signer;
120
+ validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, signer);
121
+ } else if (config.haSigningEnabled) {
122
122
  // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
123
123
  const haConfig = {
124
124
  ...config,
125
125
  maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
126
126
  };
127
127
  const { signer } = await createHASigner(haConfig);
128
- validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
128
+ haSigner = signer;
129
+ validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, signer);
129
130
  }
130
- const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider, telemetry);
131
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, proposalHandler, config, blobClient, haSigner, dateProvider, telemetry);
131
132
  return validator;
132
133
  }
133
134
  getValidatorAddresses() {
134
135
  return this.keyStore.getAddresses().filter((addr)=>!this.config.disabledValidators.some((disabled)=>disabled.equals(addr)));
135
136
  }
136
- getBlockProposalHandler() {
137
- return this.blockProposalHandler;
137
+ getProposalHandler() {
138
+ return this.proposalHandler;
138
139
  }
139
140
  signWithAddress(addr, msg, context) {
140
141
  return this.keyStore.signTypedDataWithAddress(addr, msg, context);
@@ -154,6 +155,20 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
154
155
  ...config
155
156
  };
156
157
  }
158
+ reloadKeystore(newManager) {
159
+ if (this.config.haSigningEnabled && !this.haSigner) {
160
+ this.log.warn('HA signing is enabled in config but was not initialized at startup. ' + 'Restart the node to enable HA signing.');
161
+ } else if (!this.config.haSigningEnabled && this.haSigner) {
162
+ this.log.warn('HA signing was disabled via config update but the HA signer is still active. ' + 'Restart the node to fully disable HA signing.');
163
+ }
164
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
165
+ if (this.haSigner) {
166
+ this.keyStore = new HAKeyStore(newAdapter, this.haSigner);
167
+ } else {
168
+ this.keyStore = newAdapter;
169
+ }
170
+ this.validationService = new ValidationService(this.keyStore, this.log.createChild('validation-service'));
171
+ }
157
172
  async start() {
158
173
  if (this.epochCacheUpdateLoop.isRunning()) {
159
174
  this.log.warn(`Validator client already started`);
@@ -186,6 +201,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
186
201
  // and processed separately via the block handler above.
187
202
  const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
188
203
  this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
204
+ // Duplicate proposal handler - triggers slashing for equivocation
205
+ this.p2pClient.registerDuplicateProposalCallback((info)=>{
206
+ this.handleDuplicateProposal(info);
207
+ });
208
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
209
+ this.p2pClient.registerDuplicateAttestationCallback((info)=>{
210
+ this.handleDuplicateAttestation(info);
211
+ });
189
212
  const myAddresses = this.getValidatorAddresses();
190
213
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
191
214
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
@@ -206,6 +229,13 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
206
229
  this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
207
230
  return false;
208
231
  }
232
+ // Log self-proposals from HA peers (same validator key on different nodes)
233
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
234
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
235
+ proposer: proposer.toString(),
236
+ slotNumber
237
+ });
238
+ }
209
239
  // Check if we're in the committee (for metrics purposes)
210
240
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
211
241
  const partOfCommittee = inCommittee.length > 0;
@@ -222,10 +252,10 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
222
252
  // In fisherman mode, we always reexecute to validate proposals.
223
253
  const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
224
254
  const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.blobClient.canUpload();
225
- const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
255
+ const validationResult = await this.proposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
226
256
  if (!validationResult.isValid) {
227
- this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
228
257
  const reason = validationResult.reason || 'unknown';
258
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
229
259
  // Classify failure reason: bad proposal vs node issue
230
260
  const badProposalReasons = [
231
261
  'invalid_proposal',
@@ -257,9 +287,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
257
287
  this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
258
288
  return false;
259
289
  }
260
- // TODO(palla/mbps): Remove this once checkpoint validation is stable.
261
- // Track that we successfully validated a block for this slot, so we can attest to checkpoint proposals for it.
262
- this.validatedBlockSlots.add(slotNumber);
263
290
  return true;
264
291
  }
265
292
  /**
@@ -275,46 +302,36 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
275
302
  this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
276
303
  return undefined;
277
304
  }
278
- // Reject proposals with invalid signatures
279
- if (!proposer) {
280
- this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
305
+ // Ignore proposals from ourselves (may happen in HA setups)
306
+ if (proposer && this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
307
+ this.log.debug(`Ignoring block proposal from self for slot ${slotNumber}`, {
308
+ proposer: proposer.toString(),
309
+ slotNumber
310
+ });
281
311
  return undefined;
282
312
  }
283
- // Check that I have any address in current committee before attesting
313
+ // Check that I have any address in the committee where this checkpoint will land before attesting
284
314
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
285
315
  const partOfCommittee = inCommittee.length > 0;
286
316
  const proposalInfo = {
287
317
  slotNumber,
288
318
  archive: proposal.archive.toString(),
289
- proposer: proposer.toString(),
290
- txCount: proposal.txHashes.length
319
+ proposer: proposer?.toString()
291
320
  };
292
321
  this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
293
322
  ...proposalInfo,
294
- txHashes: proposal.txHashes.map((t)=>t.toString()),
295
323
  fishermanMode: this.config.fishermanMode || false
296
324
  });
297
- // TODO(palla/mbps): Remove this once checkpoint validation is stable.
298
- // Check that we have successfully validated a block for this slot before attesting to the checkpoint.
299
- if (!this.validatedBlockSlots.has(slotNumber)) {
300
- this.log.warn(`No validated block found for slot ${slotNumber}, refusing to attest to checkpoint`, proposalInfo);
301
- return undefined;
302
- }
303
- // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
304
- // TODO(palla/mbps): Change default to false once checkpoint validation is stable.
305
- if (this.config.skipCheckpointProposalValidation !== false) {
306
- this.log.verbose(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
325
+ // Validate the checkpoint proposal and upload blobs (unless skipCheckpointProposalValidation is set)
326
+ if (this.config.skipCheckpointProposalValidation) {
327
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
307
328
  } else {
308
- const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
329
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
309
330
  if (!validationResult.isValid) {
310
331
  this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
311
332
  return undefined;
312
333
  }
313
334
  }
314
- // Upload blobs to filestore if we can (fire and forget)
315
- if (this.blobClient.canUpload()) {
316
- void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
317
- }
318
335
  // Check that I have any address in current committee before attesting
319
336
  // In fisherman mode, we still create attestations for validation even if not in committee
320
337
  if (!partOfCommittee && !this.config.fishermanMode) {
@@ -328,6 +345,16 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
328
345
  fishermanMode: this.config.fishermanMode || false
329
346
  });
330
347
  this.metrics.incSuccessfulAttestations(inCommittee.length);
348
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
349
+ const proposalEpoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
350
+ for (const attester of inCommittee){
351
+ const key = attester.toString();
352
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
353
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
354
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
355
+ this.metrics.incAttestedEpochCount(attester);
356
+ }
357
+ }
331
358
  // Determine which validators should attest
332
359
  let attestors;
333
360
  if (partOfCommittee) {
@@ -350,163 +377,33 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
350
377
  });
351
378
  return undefined;
352
379
  }
353
- return this.createCheckpointAttestationsFromProposal(proposal, attestors);
354
- }
355
- async createCheckpointAttestationsFromProposal(proposal, attestors = []) {
356
- const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
357
- await this.p2pClient.addCheckpointAttestations(attestations);
358
- return attestations;
380
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors);
359
381
  }
360
382
  /**
361
- * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
362
- * @returns Validation result with isValid flag and reason if invalid.
363
- */ async validateCheckpointProposal(proposal, proposalInfo) {
364
- const slot = proposal.slotNumber;
365
- const timeoutSeconds = 10;
366
- // Wait for last block to sync by archive
367
- let lastBlockHeader;
368
- try {
369
- lastBlockHeader = await retryUntil(async ()=>{
370
- await this.blockSource.syncImmediate();
371
- return this.blockSource.getBlockHeaderByArchive(proposal.archive);
372
- }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
373
- } catch (err) {
374
- if (err instanceof TimeoutError) {
375
- this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
376
- return {
377
- isValid: false,
378
- reason: 'last_block_not_found'
379
- };
380
- }
381
- this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
382
- return {
383
- isValid: false,
384
- reason: 'block_fetch_error'
385
- };
386
- }
387
- if (!lastBlockHeader) {
388
- this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
389
- return {
390
- isValid: false,
391
- reason: 'last_block_not_found'
392
- };
383
+ * Checks if we should attest to a slot based on equivocation prevention rules.
384
+ * @returns true if we should attest, false if we should skip
385
+ */ shouldAttestToSlot(slotNumber) {
386
+ // If attestToEquivocatedProposals is true, always allow
387
+ if (this.config.attestToEquivocatedProposals) {
388
+ return true;
393
389
  }
394
- // Get all full blocks for the slot and checkpoint
395
- const blocks = await this.blockSource.getBlocksForSlot(slot);
396
- if (blocks.length === 0) {
397
- this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
398
- return {
399
- isValid: false,
400
- reason: 'no_blocks_for_slot'
401
- };
402
- }
403
- this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
404
- ...proposalInfo,
405
- blockNumbers: blocks.map((b)=>b.number)
406
- });
407
- // Get checkpoint constants from first block
408
- const firstBlock = blocks[0];
409
- const constants = this.extractCheckpointConstants(firstBlock);
410
- const checkpointNumber = firstBlock.checkpointNumber;
411
- // Get L1-to-L2 messages for this checkpoint
412
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
413
- // Compute the previous checkpoint out hashes for the epoch.
414
- // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch the
415
- // actual checkpoints and the blocks/txs in them.
416
- const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
417
- const previousCheckpoints = (await this.blockSource.getCheckpointsForEpoch(epoch)).filter((b)=>b.number < checkpointNumber).sort((a, b)=>a.number - b.number);
418
- const previousCheckpointOutHashes = previousCheckpoints.map((c)=>c.getCheckpointOutHash());
419
- // Fork world state at the block before the first block
420
- const parentBlockNumber = BlockNumber(firstBlock.number - 1);
421
- const fork = await this.worldState.fork(parentBlockNumber);
422
- try {
423
- // Create checkpoint builder with all existing blocks
424
- const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks);
425
- // Complete the checkpoint to get computed values
426
- const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
427
- // Compare checkpoint header with proposal
428
- if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
429
- this.log.warn(`Checkpoint header mismatch`, {
430
- ...proposalInfo,
431
- computed: computedCheckpoint.header.toInspect(),
432
- proposal: proposal.checkpointHeader.toInspect()
433
- });
434
- return {
435
- isValid: false,
436
- reason: 'checkpoint_header_mismatch'
437
- };
438
- }
439
- // Compare archive root with proposal
440
- if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
441
- this.log.warn(`Archive root mismatch`, {
442
- ...proposalInfo,
443
- computed: computedCheckpoint.archive.root.toString(),
444
- proposal: proposal.archive.toString()
445
- });
446
- return {
447
- isValid: false,
448
- reason: 'archive_mismatch'
449
- };
450
- }
451
- // Check that the accumulated out hash matches the value in the proposal.
452
- const computedOutHash = computedCheckpoint.getCheckpointOutHash();
453
- const proposalOutHash = proposal.checkpointHeader.epochOutHash;
454
- if (!computedOutHash.equals(proposalOutHash)) {
455
- this.log.warn(`Epoch out hash mismatch`, {
456
- proposalOutHash: proposalOutHash.toString(),
457
- computedOutHash: computedOutHash.toString(),
458
- ...proposalInfo
459
- });
460
- return {
461
- isValid: false,
462
- reason: 'out_hash_mismatch'
463
- };
464
- }
465
- this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
466
- return {
467
- isValid: true
468
- };
469
- } finally{
470
- await fork.close();
390
+ // Check if incoming slot is strictly greater than last attested
391
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
392
+ this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
393
+ return false;
471
394
  }
395
+ return true;
472
396
  }
473
- /**
474
- * Extract checkpoint global variables from a block.
475
- */ extractCheckpointConstants(block) {
476
- const gv = block.header.globalVariables;
477
- return {
478
- chainId: gv.chainId,
479
- version: gv.version,
480
- slotNumber: gv.slotNumber,
481
- coinbase: gv.coinbase,
482
- feeRecipient: gv.feeRecipient,
483
- gasFees: gv.gasFees
484
- };
485
- }
486
- /**
487
- * Uploads blobs for a checkpoint to the filestore (fire and forget).
488
- */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
489
- try {
490
- const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
491
- if (!lastBlockHeader) {
492
- this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
493
- return;
494
- }
495
- const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
496
- if (blocks.length === 0) {
497
- this.log.warn(`No blocks found for blob upload`, proposalInfo);
498
- return;
499
- }
500
- const blobFields = blocks.flatMap((b)=>b.toBlobFields());
501
- const blobs = getBlobsPerL1Block(blobFields);
502
- await this.blobClient.sendBlobsToFilestore(blobs);
503
- this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
504
- ...proposalInfo,
505
- numBlobs: blobs.length
506
- });
507
- } catch (err) {
508
- this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
397
+ async createCheckpointAttestationsFromProposal(proposal, attestors = []) {
398
+ // Equivocation check: must happen right before signing to minimize the race window
399
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
400
+ return undefined;
509
401
  }
402
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
403
+ // Track the proposal we attested to (to prevent equivocation)
404
+ this.lastAttestedProposal = proposal;
405
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
406
+ return attestations;
510
407
  }
511
408
  slashInvalidBlock(proposal) {
512
409
  const proposer = proposal.getSender();
@@ -530,23 +427,75 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
530
427
  }
531
428
  ]);
532
429
  }
533
- async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options) {
534
- // TODO(palla/mbps): Prevent double proposals properly
535
- // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
536
- // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
537
- // return Promise.resolve(undefined);
538
- // }
430
+ /**
431
+ * Handle detection of a duplicate proposal (equivocation).
432
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
433
+ */ handleDuplicateProposal(info) {
434
+ const { slot, proposer, type } = info;
435
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
436
+ proposer: proposer.toString(),
437
+ slot,
438
+ type
439
+ });
440
+ // Emit slash event
441
+ this.emit(WANT_TO_SLASH_EVENT, [
442
+ {
443
+ validator: proposer,
444
+ amount: this.config.slashDuplicateProposalPenalty,
445
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
446
+ epochOrSlot: BigInt(slot)
447
+ }
448
+ ]);
449
+ }
450
+ /**
451
+ * Handle detection of a duplicate attestation (equivocation).
452
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
453
+ */ handleDuplicateAttestation(info) {
454
+ const { slot, attester } = info;
455
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
456
+ attester: attester.toString(),
457
+ slot
458
+ });
459
+ this.emit(WANT_TO_SLASH_EVENT, [
460
+ {
461
+ validator: attester,
462
+ amount: this.config.slashDuplicateAttestationPenalty,
463
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
464
+ epochOrSlot: BigInt(slot)
465
+ }
466
+ ]);
467
+ }
468
+ async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
469
+ // Validate that we're not creating a proposal for an older or equal position
470
+ if (this.lastProposedBlock) {
471
+ const lastSlot = this.lastProposedBlock.slotNumber;
472
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
473
+ const newSlot = blockHeader.globalVariables.slotNumber;
474
+ if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
475
+ throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
476
+ }
477
+ }
539
478
  this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
540
479
  const newProposal = await this.validationService.createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
541
480
  ...options,
542
481
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
543
482
  });
544
- this.previousProposal = newProposal;
483
+ this.lastProposedBlock = newProposal;
545
484
  return newProposal;
546
485
  }
547
- async createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options) {
486
+ async createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options = {}) {
487
+ // Validate that we're not creating a proposal for an older or equal slot
488
+ if (this.lastProposedCheckpoint) {
489
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
490
+ const newSlot = checkpointHeader.slotNumber;
491
+ if (newSlot <= lastSlot) {
492
+ throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
493
+ }
494
+ }
548
495
  this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
549
- return await this.validationService.createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options);
496
+ const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options);
497
+ this.lastProposedCheckpoint = newProposal;
498
+ return newProposal;
550
499
  }
551
500
  async broadcastBlockProposal(proposal) {
552
501
  await this.p2pClient.broadcastProposal(proposal);
@@ -561,6 +510,9 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
561
510
  inCommittee
562
511
  });
563
512
  const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
513
+ if (!attestations) {
514
+ return [];
515
+ }
564
516
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
565
517
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
566
518
  // due to inactivity for missed attestations.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/validator-client",
3
- "version": "0.0.1-commit.fffb133c",
3
+ "version": "0.0.1-dev",
4
4
  "main": "dest/index.js",
5
5
  "type": "module",
6
6
  "exports": {
@@ -64,28 +64,30 @@
64
64
  ]
65
65
  },
66
66
  "dependencies": {
67
- "@aztec/blob-client": "0.0.1-commit.fffb133c",
68
- "@aztec/blob-lib": "0.0.1-commit.fffb133c",
69
- "@aztec/constants": "0.0.1-commit.fffb133c",
70
- "@aztec/epoch-cache": "0.0.1-commit.fffb133c",
71
- "@aztec/ethereum": "0.0.1-commit.fffb133c",
72
- "@aztec/foundation": "0.0.1-commit.fffb133c",
73
- "@aztec/node-keystore": "0.0.1-commit.fffb133c",
74
- "@aztec/noir-protocol-circuits-types": "0.0.1-commit.fffb133c",
75
- "@aztec/p2p": "0.0.1-commit.fffb133c",
76
- "@aztec/protocol-contracts": "0.0.1-commit.fffb133c",
77
- "@aztec/prover-client": "0.0.1-commit.fffb133c",
78
- "@aztec/simulator": "0.0.1-commit.fffb133c",
79
- "@aztec/slasher": "0.0.1-commit.fffb133c",
80
- "@aztec/stdlib": "0.0.1-commit.fffb133c",
81
- "@aztec/telemetry-client": "0.0.1-commit.fffb133c",
82
- "@aztec/validator-ha-signer": "0.0.1-commit.fffb133c",
67
+ "@aztec/blob-client": "0.0.1-dev",
68
+ "@aztec/blob-lib": "0.0.1-dev",
69
+ "@aztec/constants": "0.0.1-dev",
70
+ "@aztec/epoch-cache": "0.0.1-dev",
71
+ "@aztec/ethereum": "0.0.1-dev",
72
+ "@aztec/foundation": "0.0.1-dev",
73
+ "@aztec/node-keystore": "0.0.1-dev",
74
+ "@aztec/noir-protocol-circuits-types": "0.0.1-dev",
75
+ "@aztec/p2p": "0.0.1-dev",
76
+ "@aztec/protocol-contracts": "0.0.1-dev",
77
+ "@aztec/prover-client": "0.0.1-dev",
78
+ "@aztec/simulator": "0.0.1-dev",
79
+ "@aztec/slasher": "0.0.1-dev",
80
+ "@aztec/stdlib": "0.0.1-dev",
81
+ "@aztec/telemetry-client": "0.0.1-dev",
82
+ "@aztec/validator-ha-signer": "0.0.1-dev",
83
83
  "koa": "^2.16.1",
84
84
  "koa-router": "^13.1.1",
85
85
  "tslib": "^2.4.0",
86
86
  "viem": "npm:@aztec/viem@2.38.2"
87
87
  },
88
88
  "devDependencies": {
89
+ "@aztec/archiver": "0.0.1-dev",
90
+ "@aztec/world-state": "0.0.1-dev",
89
91
  "@electric-sql/pglite": "^0.3.14",
90
92
  "@jest/globals": "^30.0.0",
91
93
  "@types/jest": "^30.0.0",