@aztec/validator-client 0.0.1-commit.9d2bcf6d → 0.0.1-commit.9ef841308

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