@aztec/validator-client 0.0.1-commit.e558bd1c → 0.0.1-commit.e588bc7e5

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