@aztec/validator-client 0.0.1-commit.9b94fc1 → 0.0.1-commit.9badcec54

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 (61) hide show
  1. package/README.md +324 -0
  2. package/dest/checkpoint_builder.d.ts +79 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +251 -0
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +37 -13
  8. package/dest/duties/validation_service.d.ts +40 -13
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +93 -28
  11. package/dest/factory.d.ts +19 -11
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +6 -5
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -1
  17. package/dest/key_store/ha_key_store.d.ts +99 -0
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  19. package/dest/key_store/ha_key_store.js +208 -0
  20. package/dest/key_store/index.d.ts +2 -1
  21. package/dest/key_store/index.d.ts.map +1 -1
  22. package/dest/key_store/index.js +1 -0
  23. package/dest/key_store/interface.d.ts +36 -6
  24. package/dest/key_store/interface.d.ts.map +1 -1
  25. package/dest/key_store/local_key_store.d.ts +10 -5
  26. package/dest/key_store/local_key_store.d.ts.map +1 -1
  27. package/dest/key_store/local_key_store.js +9 -5
  28. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  29. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  30. package/dest/key_store/node_keystore_adapter.js +18 -4
  31. package/dest/key_store/web3signer_key_store.d.ts +10 -5
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +9 -5
  34. package/dest/metrics.d.ts +16 -3
  35. package/dest/metrics.d.ts.map +1 -1
  36. package/dest/metrics.js +58 -30
  37. package/dest/proposal_handler.d.ts +108 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +974 -0
  40. package/dest/validator.d.ts +73 -23
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +318 -65
  43. package/package.json +23 -13
  44. package/src/checkpoint_builder.ts +417 -0
  45. package/src/config.ts +36 -12
  46. package/src/duties/validation_service.ts +143 -33
  47. package/src/factory.ts +27 -11
  48. package/src/index.ts +2 -1
  49. package/src/key_store/ha_key_store.ts +269 -0
  50. package/src/key_store/index.ts +1 -0
  51. package/src/key_store/interface.ts +44 -5
  52. package/src/key_store/local_key_store.ts +14 -5
  53. package/src/key_store/node_keystore_adapter.ts +28 -5
  54. package/src/key_store/web3signer_key_store.ts +18 -5
  55. package/src/metrics.ts +81 -33
  56. package/src/proposal_handler.ts +1042 -0
  57. package/src/validator.ts +493 -101
  58. package/dest/block_proposal_handler.d.ts +0 -52
  59. package/dest/block_proposal_handler.d.ts.map +0 -1
  60. package/dest/block_proposal_handler.js +0 -290
  61. package/src/block_proposal_handler.ts +0 -341
package/dest/validator.js CHANGED
@@ -1,16 +1,22 @@
1
+ import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
1
3
  import { createLogger } from '@aztec/foundation/log';
2
4
  import { RunningPromise } from '@aztec/foundation/running-promise';
3
5
  import { sleep } from '@aztec/foundation/sleep';
4
6
  import { DateProvider } from '@aztec/foundation/timer';
5
7
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
6
8
  import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
9
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
7
10
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
8
11
  import { getTelemetryClient } from '@aztec/telemetry-client';
12
+ import { createHASigner, createLocalSignerWithProtection, createSignerFromSharedDb } from '@aztec/validator-ha-signer/factory';
13
+ import { DutyType } from '@aztec/validator-ha-signer/types';
9
14
  import { EventEmitter } from 'events';
10
- import { BlockProposalHandler } from './block_proposal_handler.js';
11
15
  import { ValidationService } from './duties/validation_service.js';
16
+ import { HAKeyStore } from './key_store/ha_key_store.js';
12
17
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
13
18
  import { ValidatorMetrics } from './metrics.js';
19
+ import { ProposalHandler } from './proposal_handler.js';
14
20
  // We maintain a set of proposers who have proposed invalid blocks.
15
21
  // Just cap the set to avoid unbounded growth.
16
22
  const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
@@ -25,8 +31,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
25
31
  keyStore;
26
32
  epochCache;
27
33
  p2pClient;
28
- blockProposalHandler;
34
+ proposalHandler;
35
+ blockSource;
36
+ checkpointsBuilder;
37
+ worldState;
38
+ l1ToL2MessageSource;
29
39
  config;
40
+ blobClient;
41
+ slashingProtectionSigner;
30
42
  dateProvider;
31
43
  tracer;
32
44
  validationService;
@@ -34,13 +46,15 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
34
46
  log;
35
47
  // Whether it has already registered handlers on the p2p client
36
48
  hasRegisteredHandlers;
37
- // Used to check if we are sending the same proposal twice
38
- previousProposal;
49
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
50
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
39
51
  lastEpochForCommitteeUpdateLoop;
40
52
  epochCacheUpdateLoop;
53
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */ lastAttestedEpochByAttester;
41
54
  proposersOfInvalidBlocks;
42
- constructor(keyStore, epochCache, p2pClient, blockProposalHandler, config, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
43
- super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.blockProposalHandler = blockProposalHandler, this.config = config, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.proposersOfInvalidBlocks = new Set();
55
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
56
+ constructor(keyStore, epochCache, p2pClient, proposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
57
+ 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();
44
58
  // Create child logger with fisherman prefix if in fisherman mode
45
59
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
46
60
  this.tracer = telemetry.getTracer('Validator');
@@ -79,6 +93,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
79
93
  this.log.trace(`No committee found for slot`);
80
94
  return;
81
95
  }
96
+ this.metrics.setCurrentEpoch(epoch);
82
97
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
83
98
  const me = this.getValidatorAddresses();
84
99
  const committeeSet = new Set(committee.map((v)=>v.toString()));
@@ -94,27 +109,52 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
94
109
  this.log.error(`Error updating epoch committee`, err);
95
110
  }
96
111
  }
97
- static new(config, blockBuilder, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
112
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), slashingProtectionDb) {
98
113
  const metrics = new ValidatorMetrics(telemetry);
99
114
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
100
- txsPermitted: !config.disableTransactions
115
+ txsPermitted: !config.disableTransactions,
116
+ maxTxsPerBlock: config.validateMaxTxsPerBlock
101
117
  });
102
- const blockProposalHandler = new BlockProposalHandler(blockBuilder, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, config, metrics, dateProvider, telemetry);
103
- const validator = new ValidatorClient(NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager), epochCache, p2pClient, blockProposalHandler, config, dateProvider, telemetry);
118
+ const proposalHandler = new ProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, blobClient, metrics, dateProvider, telemetry, undefined);
119
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
120
+ let slashingProtectionSigner;
121
+ if (slashingProtectionDb) {
122
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
123
+ ({ signer: slashingProtectionSigner } = createSignerFromSharedDb(slashingProtectionDb, config, {
124
+ telemetryClient: telemetry,
125
+ dateProvider
126
+ }));
127
+ } else if (config.haSigningEnabled) {
128
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
129
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
130
+ const haConfig = {
131
+ ...config,
132
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
133
+ };
134
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
135
+ telemetryClient: telemetry,
136
+ dateProvider
137
+ }));
138
+ } else {
139
+ // Single-node mode: use LMDB-backed local signing protection.
140
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
141
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
142
+ telemetryClient: telemetry,
143
+ dateProvider
144
+ }));
145
+ }
146
+ const validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
147
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, proposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider, telemetry);
104
148
  return validator;
105
149
  }
106
150
  getValidatorAddresses() {
107
151
  return this.keyStore.getAddresses().filter((addr)=>!this.config.disabledValidators.some((disabled)=>disabled.equals(addr)));
108
152
  }
109
- getBlockProposalHandler() {
110
- return this.blockProposalHandler;
111
- }
112
- // Proxy method for backwards compatibility with tests
113
- reExecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages) {
114
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
153
+ getProposalHandler() {
154
+ return this.proposalHandler;
115
155
  }
116
- signWithAddress(addr, msg) {
117
- return this.keyStore.signTypedDataWithAddress(addr, msg);
156
+ signWithAddress(addr, msg, context) {
157
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
118
158
  }
119
159
  getCoinbaseForAttestor(attestor) {
120
160
  return this.keyStore.getCoinbaseAddress(attestor);
@@ -131,11 +171,17 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
131
171
  ...config
132
172
  };
133
173
  }
174
+ reloadKeystore(newManager) {
175
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
176
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
177
+ this.validationService = new ValidationService(this.keyStore, this.log.createChild('validation-service'));
178
+ }
134
179
  async start() {
135
180
  if (this.epochCacheUpdateLoop.isRunning()) {
136
181
  this.log.warn(`Validator client already started`);
137
182
  return;
138
183
  }
184
+ await this.keyStore.start();
139
185
  await this.registerHandlers();
140
186
  const myAddresses = this.getValidatorAddresses();
141
187
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
@@ -148,47 +194,75 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
148
194
  }
149
195
  async stop() {
150
196
  await this.epochCacheUpdateLoop.stop();
197
+ await this.keyStore.stop();
151
198
  }
152
199
  /** Register handlers on the p2p client */ async registerHandlers() {
153
200
  if (!this.hasRegisteredHandlers) {
154
201
  this.hasRegisteredHandlers = true;
155
202
  this.log.debug(`Registering validator handlers for p2p client`);
156
- const handler = (block, proposalSender)=>this.attestToProposal(block, proposalSender);
157
- this.p2pClient.registerBlockProposalHandler(handler);
203
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
204
+ const blockHandler = (block, proposalSender)=>this.validateBlockProposal(block, proposalSender);
205
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
206
+ // Checkpoint proposal handler - validates and creates attestations
207
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
208
+ // and processed separately via the block handler above.
209
+ const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
210
+ this.p2pClient.registerValidatorCheckpointProposalHandler(checkpointHandler);
211
+ // Duplicate proposal handler - triggers slashing for equivocation
212
+ this.p2pClient.registerDuplicateProposalCallback((info)=>{
213
+ this.handleDuplicateProposal(info);
214
+ });
215
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
216
+ this.p2pClient.registerDuplicateAttestationCallback((info)=>{
217
+ this.handleDuplicateAttestation(info);
218
+ });
158
219
  const myAddresses = this.getValidatorAddresses();
159
220
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
160
221
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
161
222
  }
162
223
  }
163
- async attestToProposal(proposal, proposalSender) {
224
+ /**
225
+ * Validate a block proposal from a peer.
226
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
227
+ * @returns true if the proposal is valid, false otherwise
228
+ */ async validateBlockProposal(proposal, proposalSender) {
164
229
  const slotNumber = proposal.slotNumber;
230
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
231
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
232
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
165
233
  const proposer = proposal.getSender();
166
234
  // Reject proposals with invalid signatures
167
235
  if (!proposer) {
168
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
169
- return undefined;
236
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
237
+ return false;
170
238
  }
171
- // Check that I have any address in current committee before attesting
239
+ // Log self-proposals from HA peers (same validator key on different nodes)
240
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
241
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
242
+ proposer: proposer.toString(),
243
+ slotNumber
244
+ });
245
+ }
246
+ // Check if we're in the committee (for metrics purposes)
172
247
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
173
248
  const partOfCommittee = inCommittee.length > 0;
174
249
  const proposalInfo = {
175
250
  ...proposal.toBlockInfo(),
176
251
  proposer: proposer.toString()
177
252
  };
178
- this.log.info(`Received proposal for slot ${slotNumber}`, {
253
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
179
254
  ...proposalInfo,
180
255
  txHashes: proposal.txHashes.map((t)=>t.toString()),
181
256
  fishermanMode: this.config.fishermanMode || false
182
257
  });
183
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
184
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
258
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
185
259
  // In fisherman mode, we always reexecute to validate proposals.
186
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
187
- const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals;
188
- const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute);
260
+ const { slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
261
+ const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n || partOfCommittee || alwaysReexecuteBlockProposals || this.blobClient.canUpload();
262
+ const validationResult = await this.proposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
189
263
  if (!validationResult.isValid) {
190
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
191
264
  const reason = validationResult.reason || 'unknown';
265
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
192
266
  // Classify failure reason: bad proposal vs node issue
193
267
  const badProposalReasons = [
194
268
  'invalid_proposal',
@@ -200,16 +274,75 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
200
274
  if (badProposalReasons.includes(reason)) {
201
275
  this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
202
276
  } else {
203
- // Node issues so we can't attest
277
+ // Node issues so we can't validate
204
278
  this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
205
279
  }
206
280
  // Slash invalid block proposals (can happen even when not in committee)
207
- if (validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
281
+ if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
208
282
  this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
209
283
  this.slashInvalidBlock(proposal);
210
284
  }
285
+ return false;
286
+ }
287
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
288
+ ...proposalInfo,
289
+ inCommittee: partOfCommittee,
290
+ fishermanMode: this.config.fishermanMode || false,
291
+ escapeHatchOpen
292
+ });
293
+ if (escapeHatchOpen) {
294
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
295
+ return false;
296
+ }
297
+ return true;
298
+ }
299
+ /**
300
+ * Validate and attest to a checkpoint proposal from a peer.
301
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
302
+ * the lastBlock is extracted and processed separately via the block handler.
303
+ * @returns Checkpoint attestations if valid, undefined otherwise
304
+ */ async attestToCheckpointProposal(proposal, _proposalSender) {
305
+ const proposalSlotNumber = proposal.slotNumber;
306
+ const proposer = proposal.getSender();
307
+ // If escape hatch is open for this slot's epoch, do not attest.
308
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposalSlotNumber)) {
309
+ this.log.warn(`Escape hatch open for slot ${proposalSlotNumber}, skipping checkpoint attestation handling`);
211
310
  return undefined;
212
311
  }
312
+ // Ignore proposals from ourselves (may happen in HA setups)
313
+ if (proposer && this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
314
+ this.log.debug(`Ignoring block proposal from self for slot ${proposalSlotNumber}`, {
315
+ proposer: proposer.toString(),
316
+ proposalSlotNumber
317
+ });
318
+ return undefined;
319
+ }
320
+ // Check that I have any address in the committee where this checkpoint will land before attesting
321
+ const inCommittee = await this.epochCache.filterInCommittee(proposalSlotNumber, this.getValidatorAddresses());
322
+ const partOfCommittee = inCommittee.length > 0;
323
+ const proposalInfo = {
324
+ proposalSlotNumber,
325
+ archive: proposal.archive.toString(),
326
+ proposer: proposer?.toString()
327
+ };
328
+ this.log.info(`Received checkpoint proposal for slot ${proposalSlotNumber}`, {
329
+ ...proposalInfo,
330
+ fishermanMode: this.config.fishermanMode || false
331
+ });
332
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set).
333
+ // Uses the cached result from the all-nodes callback if available (avoids double validation).
334
+ let checkpointNumber;
335
+ if (this.config.skipCheckpointProposalValidation) {
336
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposalSlotNumber}`, proposalInfo);
337
+ checkpointNumber = CheckpointNumber(0);
338
+ } else {
339
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
340
+ if (!validationResult.isValid) {
341
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
342
+ return undefined;
343
+ }
344
+ checkpointNumber = validationResult.checkpointNumber;
345
+ }
213
346
  // Check that I have any address in current committee before attesting
214
347
  // In fisherman mode, we still create attestations for validation even if not in committee
215
348
  if (!partOfCommittee && !this.config.fishermanMode) {
@@ -217,13 +350,22 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
217
350
  return undefined;
218
351
  }
219
352
  // Provided all of the above checks pass, we can attest to the proposal
220
- this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} proposal for slot ${slotNumber}`, {
353
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`, {
221
354
  ...proposalInfo,
222
355
  inCommittee: partOfCommittee,
223
356
  fishermanMode: this.config.fishermanMode || false
224
357
  });
225
358
  this.metrics.incSuccessfulAttestations(inCommittee.length);
226
- // If the above function does not throw an error, then we can attest to the proposal
359
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
360
+ const proposalEpoch = getEpochAtSlot(proposalSlotNumber, this.epochCache.getL1Constants());
361
+ for (const attester of inCommittee){
362
+ const key = attester.toString();
363
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
364
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
365
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
366
+ this.metrics.incAttestedEpochCount(attester);
367
+ }
368
+ }
227
369
  // Determine which validators should attest
228
370
  let attestors;
229
371
  if (partOfCommittee) {
@@ -240,13 +382,64 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
240
382
  }
241
383
  if (this.config.fishermanMode) {
242
384
  // bail out early and don't save attestations to the pool in fisherman mode
243
- this.log.info(`Creating attestations for proposal for slot ${slotNumber}`, {
385
+ this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
244
386
  ...proposalInfo,
245
387
  attestors: attestors.map((a)=>a.toString())
246
388
  });
247
389
  return undefined;
248
390
  }
249
- return this.createBlockAttestationsFromProposal(proposal, attestors);
391
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors, checkpointNumber);
392
+ }
393
+ /**
394
+ * Checks if we should attest to a slot based on equivocation prevention rules.
395
+ * @returns true if we should attest, false if we should skip
396
+ */ shouldAttestToSlot(slotNumber) {
397
+ // If attestToEquivocatedProposals is true, always allow
398
+ if (this.config.attestToEquivocatedProposals) {
399
+ return true;
400
+ }
401
+ // Check if incoming slot is strictly greater than last attested
402
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
403
+ this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
404
+ return false;
405
+ }
406
+ return true;
407
+ }
408
+ async createCheckpointAttestationsFromProposal(proposal, attestors = [], checkpointNumber) {
409
+ // Equivocation check: must happen right before signing to minimize the race window
410
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
411
+ return undefined;
412
+ }
413
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors, checkpointNumber);
414
+ // Track the proposal we attested to (to prevent equivocation)
415
+ this.lastAttestedProposal = proposal;
416
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
417
+ return attestations;
418
+ }
419
+ /**
420
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
421
+ */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
422
+ try {
423
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
424
+ if (!lastBlockHeader) {
425
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
426
+ return;
427
+ }
428
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
429
+ if (blocks.length === 0) {
430
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
431
+ return;
432
+ }
433
+ const blobFields = blocks.flatMap((b)=>b.toBlobFields());
434
+ const blobs = await getBlobsPerL1Block(blobFields);
435
+ await this.blobClient.sendBlobsToFilestore(blobs);
436
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
437
+ ...proposalInfo,
438
+ numBlobs: blobs.length
439
+ });
440
+ } catch (err) {
441
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
442
+ }
250
443
  }
251
444
  slashInvalidBlock(proposal) {
252
445
  const proposer = proposal.getSender();
@@ -270,59 +463,120 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
270
463
  }
271
464
  ]);
272
465
  }
273
- async createBlockProposal(blockNumber, header, archive, txs, proposerAddress, options) {
274
- if (this.previousProposal?.slotNumber === header.slotNumber) {
275
- this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
276
- return Promise.resolve(undefined);
466
+ /**
467
+ * Handle detection of a duplicate proposal (equivocation).
468
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
469
+ */ handleDuplicateProposal(info) {
470
+ const { slot, proposer, type } = info;
471
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
472
+ proposer: proposer.toString(),
473
+ slot,
474
+ type
475
+ });
476
+ // Emit slash event
477
+ this.emit(WANT_TO_SLASH_EVENT, [
478
+ {
479
+ validator: proposer,
480
+ amount: this.config.slashDuplicateProposalPenalty,
481
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
482
+ epochOrSlot: BigInt(slot)
483
+ }
484
+ ]);
485
+ }
486
+ /**
487
+ * Handle detection of a duplicate attestation (equivocation).
488
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
489
+ */ handleDuplicateAttestation(info) {
490
+ const { slot, attester } = info;
491
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
492
+ attester: attester.toString(),
493
+ slot
494
+ });
495
+ this.emit(WANT_TO_SLASH_EVENT, [
496
+ {
497
+ validator: attester,
498
+ amount: this.config.slashDuplicateAttestationPenalty,
499
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
500
+ epochOrSlot: BigInt(slot)
501
+ }
502
+ ]);
503
+ }
504
+ async createBlockProposal(blockHeader, checkpointNumber, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
505
+ // Validate that we're not creating a proposal for an older or equal position
506
+ if (this.lastProposedBlock) {
507
+ const lastSlot = this.lastProposedBlock.slotNumber;
508
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
509
+ const newSlot = blockHeader.globalVariables.slotNumber;
510
+ if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
511
+ throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
512
+ }
277
513
  }
278
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
514
+ this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
515
+ const newProposal = await this.validationService.createBlockProposal(blockHeader, checkpointNumber, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
279
516
  ...options,
280
517
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
281
518
  });
282
- this.previousProposal = newProposal;
519
+ this.lastProposedBlock = newProposal;
520
+ return newProposal;
521
+ }
522
+ async createCheckpointProposal(checkpointHeader, archive, checkpointNumber, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options = {}) {
523
+ // Validate that we're not creating a proposal for an older or equal slot
524
+ if (this.lastProposedCheckpoint) {
525
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
526
+ const newSlot = checkpointHeader.slotNumber;
527
+ if (newSlot <= lastSlot) {
528
+ throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
529
+ }
530
+ }
531
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
532
+ const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, checkpointNumber, feeAssetPriceModifier, lastBlockProposal, proposerAddress, options);
533
+ this.lastProposedCheckpoint = newProposal;
283
534
  return newProposal;
284
535
  }
285
536
  async broadcastBlockProposal(proposal) {
286
537
  await this.p2pClient.broadcastProposal(proposal);
287
538
  }
288
- async signAttestationsAndSigners(attestationsAndSigners, proposer) {
289
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
539
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber) {
540
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, checkpointNumber);
290
541
  }
291
- async collectOwnAttestations(proposal) {
292
- const slot = proposal.payload.header.slotNumber;
542
+ async collectOwnAttestations(proposal, checkpointNumber) {
543
+ const slot = proposal.slotNumber;
293
544
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
294
545
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
295
546
  inCommittee
296
547
  });
297
- const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
548
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
549
+ if (!attestations) {
550
+ return [];
551
+ }
298
552
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
299
553
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
300
554
  // due to inactivity for missed attestations.
301
- void this.p2pClient.broadcastAttestations(attestations).catch((err)=>{
555
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch((err)=>{
302
556
  this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
303
557
  });
304
558
  return attestations;
305
559
  }
306
- async collectAttestations(proposal, required, deadline) {
307
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
308
- const slot = proposal.payload.header.slotNumber;
560
+ async collectAttestations(proposal, required, deadline, checkpointNumber) {
561
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
562
+ const slot = proposal.slotNumber;
309
563
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
310
564
  if (+deadline < this.dateProvider.now()) {
311
565
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
312
566
  throw new AttestationTimeoutError(0, required, slot);
313
567
  }
314
- await this.collectOwnAttestations(proposal);
568
+ await this.collectOwnAttestations(proposal, checkpointNumber);
315
569
  const proposalId = proposal.archive.toString();
316
570
  const myAddresses = this.getValidatorAddresses();
317
571
  let attestations = [];
318
572
  while(true){
319
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
573
+ // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
320
574
  // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
321
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
322
- if (!attestation.payload.equals(proposal.payload)) {
323
- this.log.warn(`Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`, {
324
- attestationPayload: attestation.payload,
325
- proposalPayload: proposal.payload
575
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
576
+ if (!attestation.archive.equals(proposal.archive)) {
577
+ this.log.warn(`Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`, {
578
+ attestationArchive: attestation.archive.toString(),
579
+ proposalArchive: proposal.archive.toString()
326
580
  });
327
581
  return false;
328
582
  }
@@ -354,11 +608,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
354
608
  await sleep(this.config.attestationPollingIntervalMs);
355
609
  }
356
610
  }
357
- async createBlockAttestationsFromProposal(proposal, attestors = []) {
358
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
359
- await this.p2pClient.addAttestations(attestations);
360
- return attestations;
361
- }
362
611
  async handleAuthRequest(peer, msg) {
363
612
  const authRequest = AuthRequest.fromBuffer(msg);
364
613
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
@@ -373,7 +622,11 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
373
622
  return Buffer.alloc(0);
374
623
  }
375
624
  const payloadToSign = authRequest.getPayloadToSign();
376
- const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
625
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
626
+ const context = {
627
+ dutyType: DutyType.AUTH_REQUEST
628
+ };
629
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
377
630
  const authResponse = new AuthResponse(statusMessage, signature);
378
631
  return authResponse.toBuffer();
379
632
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/validator-client",
3
- "version": "0.0.1-commit.9b94fc1",
3
+ "version": "0.0.1-commit.9badcec54",
4
4
  "main": "dest/index.js",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,8 +18,8 @@
18
18
  },
19
19
  "scripts": {
20
20
  "start": "node --no-warnings ./dest/bin",
21
- "build": "yarn clean && tsgo -b",
22
- "build:dev": "tsgo -b --watch",
21
+ "build": "yarn clean && ../scripts/tsc.sh",
22
+ "build:dev": "../scripts/tsc.sh --watch",
23
23
  "clean": "rm -rf ./dest .tsbuildinfo",
24
24
  "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
25
25
  },
@@ -64,25 +64,35 @@
64
64
  ]
65
65
  },
66
66
  "dependencies": {
67
- "@aztec/constants": "0.0.1-commit.9b94fc1",
68
- "@aztec/epoch-cache": "0.0.1-commit.9b94fc1",
69
- "@aztec/ethereum": "0.0.1-commit.9b94fc1",
70
- "@aztec/foundation": "0.0.1-commit.9b94fc1",
71
- "@aztec/node-keystore": "0.0.1-commit.9b94fc1",
72
- "@aztec/p2p": "0.0.1-commit.9b94fc1",
73
- "@aztec/slasher": "0.0.1-commit.9b94fc1",
74
- "@aztec/stdlib": "0.0.1-commit.9b94fc1",
75
- "@aztec/telemetry-client": "0.0.1-commit.9b94fc1",
67
+ "@aztec/blob-client": "0.0.1-commit.9badcec54",
68
+ "@aztec/blob-lib": "0.0.1-commit.9badcec54",
69
+ "@aztec/constants": "0.0.1-commit.9badcec54",
70
+ "@aztec/epoch-cache": "0.0.1-commit.9badcec54",
71
+ "@aztec/ethereum": "0.0.1-commit.9badcec54",
72
+ "@aztec/foundation": "0.0.1-commit.9badcec54",
73
+ "@aztec/node-keystore": "0.0.1-commit.9badcec54",
74
+ "@aztec/noir-protocol-circuits-types": "0.0.1-commit.9badcec54",
75
+ "@aztec/p2p": "0.0.1-commit.9badcec54",
76
+ "@aztec/protocol-contracts": "0.0.1-commit.9badcec54",
77
+ "@aztec/prover-client": "0.0.1-commit.9badcec54",
78
+ "@aztec/simulator": "0.0.1-commit.9badcec54",
79
+ "@aztec/slasher": "0.0.1-commit.9badcec54",
80
+ "@aztec/stdlib": "0.0.1-commit.9badcec54",
81
+ "@aztec/telemetry-client": "0.0.1-commit.9badcec54",
82
+ "@aztec/validator-ha-signer": "0.0.1-commit.9badcec54",
76
83
  "koa": "^2.16.1",
77
84
  "koa-router": "^13.1.1",
78
85
  "tslib": "^2.4.0",
79
86
  "viem": "npm:@aztec/viem@2.38.2"
80
87
  },
81
88
  "devDependencies": {
89
+ "@aztec/archiver": "0.0.1-commit.9badcec54",
90
+ "@aztec/world-state": "0.0.1-commit.9badcec54",
91
+ "@electric-sql/pglite": "^0.3.14",
82
92
  "@jest/globals": "^30.0.0",
83
93
  "@types/jest": "^30.0.0",
84
94
  "@types/node": "^22.15.17",
85
- "@typescript/native-preview": "7.0.0-dev.20251126.1",
95
+ "@typescript/native-preview": "7.0.0-dev.20260113.1",
86
96
  "jest": "^30.0.0",
87
97
  "jest-mock-extended": "^4.0.0",
88
98
  "ts-node": "^10.9.1",