@aztec/validator-client 0.0.1-commit.fce3e4f → 0.0.1-commit.ffe5b04ea

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 (57) hide show
  1. package/README.md +327 -0
  2. package/dest/block_proposal_handler.d.ts +25 -14
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +366 -105
  5. package/dest/checkpoint_builder.d.ts +76 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +228 -0
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +37 -8
  11. package/dest/duties/validation_service.d.ts +42 -13
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +105 -28
  14. package/dest/factory.d.ts +13 -8
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +4 -3
  17. package/dest/index.d.ts +2 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +1 -0
  20. package/dest/key_store/ha_key_store.d.ts +99 -0
  21. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  22. package/dest/key_store/ha_key_store.js +208 -0
  23. package/dest/key_store/index.d.ts +2 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +1 -0
  26. package/dest/key_store/interface.d.ts +36 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/local_key_store.d.ts +10 -5
  29. package/dest/key_store/local_key_store.d.ts.map +1 -1
  30. package/dest/key_store/local_key_store.js +9 -5
  31. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  32. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  33. package/dest/key_store/node_keystore_adapter.js +18 -4
  34. package/dest/key_store/web3signer_key_store.d.ts +10 -5
  35. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  36. package/dest/key_store/web3signer_key_store.js +9 -5
  37. package/dest/metrics.d.ts +12 -3
  38. package/dest/metrics.d.ts.map +1 -1
  39. package/dest/metrics.js +46 -30
  40. package/dest/validator.d.ts +76 -21
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +478 -57
  43. package/package.json +23 -13
  44. package/src/block_proposal_handler.ts +288 -75
  45. package/src/checkpoint_builder.ts +390 -0
  46. package/src/config.ts +36 -7
  47. package/src/duties/validation_service.ts +156 -33
  48. package/src/factory.ts +18 -8
  49. package/src/index.ts +1 -0
  50. package/src/key_store/ha_key_store.ts +269 -0
  51. package/src/key_store/index.ts +1 -0
  52. package/src/key_store/interface.ts +44 -5
  53. package/src/key_store/local_key_store.ts +14 -5
  54. package/src/key_store/node_keystore_adapter.ts +28 -5
  55. package/src/key_store/web3signer_key_store.ts +18 -5
  56. package/src/metrics.ts +63 -33
  57. package/src/validator.ts +640 -85
package/dest/validator.js CHANGED
@@ -1,14 +1,25 @@
1
+ import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
+ import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
3
+ import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
+ import { TimeoutError } from '@aztec/foundation/error';
1
5
  import { createLogger } from '@aztec/foundation/log';
6
+ import { retryUntil } from '@aztec/foundation/retry';
2
7
  import { RunningPromise } from '@aztec/foundation/running-promise';
3
8
  import { sleep } from '@aztec/foundation/sleep';
4
9
  import { DateProvider } from '@aztec/foundation/timer';
5
10
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
6
11
  import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
12
+ import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
13
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
14
+ import { accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
7
15
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
8
16
  import { getTelemetryClient } from '@aztec/telemetry-client';
17
+ import { createHASigner, createLocalSignerWithProtection } from '@aztec/validator-ha-signer/factory';
18
+ import { DutyType } from '@aztec/validator-ha-signer/types';
9
19
  import { EventEmitter } from 'events';
10
20
  import { BlockProposalHandler } from './block_proposal_handler.js';
11
21
  import { ValidationService } from './duties/validation_service.js';
22
+ import { HAKeyStore } from './key_store/ha_key_store.js';
12
23
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
13
24
  import { ValidatorMetrics } from './metrics.js';
14
25
  // We maintain a set of proposers who have proposed invalid blocks.
@@ -26,7 +37,13 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
26
37
  epochCache;
27
38
  p2pClient;
28
39
  blockProposalHandler;
40
+ blockSource;
41
+ checkpointsBuilder;
42
+ worldState;
43
+ l1ToL2MessageSource;
29
44
  config;
45
+ blobClient;
46
+ slashingProtectionSigner;
30
47
  dateProvider;
31
48
  tracer;
32
49
  validationService;
@@ -34,13 +51,15 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
34
51
  log;
35
52
  // Whether it has already registered handlers on the p2p client
36
53
  hasRegisteredHandlers;
37
- // Used to check if we are sending the same proposal twice
38
- previousProposal;
54
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
55
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
39
56
  lastEpochForCommitteeUpdateLoop;
40
57
  epochCacheUpdateLoop;
58
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */ lastAttestedEpochByAttester;
41
59
  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();
60
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
61
+ constructor(keyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
62
+ 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.slashingProtectionSigner = slashingProtectionSigner, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.lastAttestedEpochByAttester = new Map(), this.proposersOfInvalidBlocks = new Set();
44
63
  // Create child logger with fisherman prefix if in fisherman mode
45
64
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
46
65
  this.tracer = telemetry.getTracer('Validator');
@@ -79,6 +98,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
79
98
  this.log.trace(`No committee found for slot`);
80
99
  return;
81
100
  }
101
+ this.metrics.setCurrentEpoch(epoch);
82
102
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
83
103
  const me = this.getValidatorAddresses();
84
104
  const committeeSet = new Set(committee.map((v)=>v.toString()));
@@ -94,13 +114,36 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
94
114
  this.log.error(`Error updating epoch committee`, err);
95
115
  }
96
116
  }
97
- static new(config, blockBuilder, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
117
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
98
118
  const metrics = new ValidatorMetrics(telemetry);
99
119
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
100
- txsPermitted: !config.disableTransactions
120
+ txsPermitted: !config.disableTransactions,
121
+ maxTxsPerBlock: config.validateMaxTxsPerBlock
101
122
  });
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);
123
+ const blockProposalHandler = new BlockProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, metrics, dateProvider, telemetry);
124
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
125
+ let slashingProtectionSigner;
126
+ if (config.haSigningEnabled) {
127
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
128
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
129
+ const haConfig = {
130
+ ...config,
131
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
132
+ };
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
+ }));
144
+ }
145
+ const validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
146
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, slashingProtectionSigner, dateProvider, telemetry);
104
147
  return validator;
105
148
  }
106
149
  getValidatorAddresses() {
@@ -109,12 +152,8 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
109
152
  getBlockProposalHandler() {
110
153
  return this.blockProposalHandler;
111
154
  }
112
- // Proxy method for backwards compatibility with tests
113
- reExecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages) {
114
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
115
- }
116
- signWithAddress(addr, msg) {
117
- return this.keyStore.signTypedDataWithAddress(addr, msg);
155
+ signWithAddress(addr, msg, context) {
156
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
118
157
  }
119
158
  getCoinbaseForAttestor(attestor) {
120
159
  return this.keyStore.getCoinbaseAddress(attestor);
@@ -131,11 +170,17 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
131
170
  ...config
132
171
  };
133
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
+ }
134
178
  async start() {
135
179
  if (this.epochCacheUpdateLoop.isRunning()) {
136
180
  this.log.warn(`Validator client already started`);
137
181
  return;
138
182
  }
183
+ await this.keyStore.start();
139
184
  await this.registerHandlers();
140
185
  const myAddresses = this.getValidatorAddresses();
141
186
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
@@ -148,46 +193,75 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
148
193
  }
149
194
  async stop() {
150
195
  await this.epochCacheUpdateLoop.stop();
196
+ await this.keyStore.stop();
151
197
  }
152
198
  /** Register handlers on the p2p client */ async registerHandlers() {
153
199
  if (!this.hasRegisteredHandlers) {
154
200
  this.hasRegisteredHandlers = true;
155
201
  this.log.debug(`Registering validator handlers for p2p client`);
156
- const handler = (block, proposalSender)=>this.attestToProposal(block, proposalSender);
157
- this.p2pClient.registerBlockProposalHandler(handler);
202
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
203
+ const blockHandler = (block, proposalSender)=>this.validateBlockProposal(block, proposalSender);
204
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
205
+ // Checkpoint proposal handler - validates and creates attestations
206
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
207
+ // and processed separately via the block handler above.
208
+ const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
209
+ this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
210
+ // Duplicate proposal handler - triggers slashing for equivocation
211
+ this.p2pClient.registerDuplicateProposalCallback((info)=>{
212
+ this.handleDuplicateProposal(info);
213
+ });
214
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
215
+ this.p2pClient.registerDuplicateAttestationCallback((info)=>{
216
+ this.handleDuplicateAttestation(info);
217
+ });
158
218
  const myAddresses = this.getValidatorAddresses();
159
219
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
160
220
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
161
221
  }
162
222
  }
163
- async attestToProposal(proposal, proposalSender) {
223
+ /**
224
+ * Validate a block proposal from a peer.
225
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
226
+ * @returns true if the proposal is valid, false otherwise
227
+ */ async validateBlockProposal(proposal, proposalSender) {
164
228
  const slotNumber = proposal.slotNumber;
229
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
230
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
231
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
165
232
  const proposer = proposal.getSender();
166
233
  // Reject proposals with invalid signatures
167
234
  if (!proposer) {
168
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
169
- return undefined;
235
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
236
+ return false;
170
237
  }
171
- // Check that I have any address in current committee before attesting
238
+ // Ignore proposals from ourselves (may happen in HA setups)
239
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
240
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
241
+ proposer: proposer.toString(),
242
+ slotNumber
243
+ });
244
+ return false;
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
260
  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);
261
+ const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.blobClient.canUpload();
262
+ const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
189
263
  if (!validationResult.isValid) {
190
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
264
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
191
265
  const reason = validationResult.reason || 'unknown';
192
266
  // Classify failure reason: bad proposal vs node issue
193
267
  const badProposalReasons = [
@@ -200,30 +274,108 @@ 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 slotNumber = 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(slotNumber)) {
309
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
310
+ return undefined;
311
+ }
312
+ // Reject proposals with invalid signatures
313
+ if (!proposer) {
314
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
315
+ return undefined;
316
+ }
317
+ // Ignore proposals from ourselves (may happen in HA setups)
318
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
319
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
320
+ proposer: proposer.toString(),
321
+ slotNumber
322
+ });
323
+ return undefined;
324
+ }
325
+ // Validate fee asset price modifier is within allowed range
326
+ if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
327
+ this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${slotNumber}`);
211
328
  return undefined;
212
329
  }
213
330
  // Check that I have any address in current committee before attesting
331
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
332
+ const partOfCommittee = inCommittee.length > 0;
333
+ const proposalInfo = {
334
+ slotNumber,
335
+ archive: proposal.archive.toString(),
336
+ proposer: proposer.toString()
337
+ };
338
+ this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
339
+ ...proposalInfo,
340
+ fishermanMode: this.config.fishermanMode || false
341
+ });
342
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
343
+ if (this.config.skipCheckpointProposalValidation) {
344
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
345
+ } else {
346
+ const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
347
+ if (!validationResult.isValid) {
348
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
349
+ return undefined;
350
+ }
351
+ }
352
+ // Upload blobs to filestore if we can (fire and forget)
353
+ if (this.blobClient.canUpload()) {
354
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
355
+ }
356
+ // Check that I have any address in current committee before attesting
214
357
  // In fisherman mode, we still create attestations for validation even if not in committee
215
358
  if (!partOfCommittee && !this.config.fishermanMode) {
216
359
  this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
217
360
  return undefined;
218
361
  }
219
362
  // 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}`, {
363
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
221
364
  ...proposalInfo,
222
365
  inCommittee: partOfCommittee,
223
366
  fishermanMode: this.config.fishermanMode || false
224
367
  });
225
368
  this.metrics.incSuccessfulAttestations(inCommittee.length);
226
- // If the above function does not throw an error, then we can attest to the proposal
369
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
370
+ const proposalEpoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
371
+ for (const attester of inCommittee){
372
+ const key = attester.toString();
373
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
374
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
375
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
376
+ this.metrics.incAttestedEpochCount(attester);
377
+ }
378
+ }
227
379
  // Determine which validators should attest
228
380
  let attestors;
229
381
  if (partOfCommittee) {
@@ -240,13 +392,222 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
240
392
  }
241
393
  if (this.config.fishermanMode) {
242
394
  // 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}`, {
395
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
244
396
  ...proposalInfo,
245
397
  attestors: attestors.map((a)=>a.toString())
246
398
  });
247
399
  return undefined;
248
400
  }
249
- return this.createBlockAttestationsFromProposal(proposal, attestors);
401
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors);
402
+ }
403
+ /**
404
+ * Checks if we should attest to a slot based on equivocation prevention rules.
405
+ * @returns true if we should attest, false if we should skip
406
+ */ shouldAttestToSlot(slotNumber) {
407
+ // If attestToEquivocatedProposals is true, always allow
408
+ if (this.config.attestToEquivocatedProposals) {
409
+ return true;
410
+ }
411
+ // Check if incoming slot is strictly greater than last attested
412
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
413
+ this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
414
+ return false;
415
+ }
416
+ return true;
417
+ }
418
+ async createCheckpointAttestationsFromProposal(proposal, attestors = []) {
419
+ // Equivocation check: must happen right before signing to minimize the race window
420
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
421
+ return undefined;
422
+ }
423
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
424
+ // Track the proposal we attested to (to prevent equivocation)
425
+ this.lastAttestedProposal = proposal;
426
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
427
+ return attestations;
428
+ }
429
+ /**
430
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
431
+ * @returns Validation result with isValid flag and reason if invalid.
432
+ */ async validateCheckpointProposal(proposal, proposalInfo) {
433
+ const slot = proposal.slotNumber;
434
+ // Timeout block syncing at the start of the next slot
435
+ const config = this.checkpointsBuilder.getConfig();
436
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
437
+ const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
438
+ // Wait for last block to sync by archive
439
+ let lastBlockHeader;
440
+ try {
441
+ lastBlockHeader = await retryUntil(async ()=>{
442
+ await this.blockSource.syncImmediate();
443
+ return this.blockSource.getBlockHeaderByArchive(proposal.archive);
444
+ }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
445
+ } catch (err) {
446
+ if (err instanceof TimeoutError) {
447
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
448
+ return {
449
+ isValid: false,
450
+ reason: 'last_block_not_found'
451
+ };
452
+ }
453
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
454
+ return {
455
+ isValid: false,
456
+ reason: 'block_fetch_error'
457
+ };
458
+ }
459
+ if (!lastBlockHeader) {
460
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
461
+ return {
462
+ isValid: false,
463
+ reason: 'last_block_not_found'
464
+ };
465
+ }
466
+ // Get all full blocks for the slot and checkpoint
467
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
468
+ if (blocks.length === 0) {
469
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
470
+ return {
471
+ isValid: false,
472
+ reason: 'no_blocks_for_slot'
473
+ };
474
+ }
475
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
476
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
477
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
478
+ return {
479
+ isValid: false,
480
+ reason: 'last_block_archive_mismatch'
481
+ };
482
+ }
483
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
484
+ ...proposalInfo,
485
+ blockNumbers: blocks.map((b)=>b.number)
486
+ });
487
+ // Get checkpoint constants from first block
488
+ const firstBlock = blocks[0];
489
+ const constants = this.extractCheckpointConstants(firstBlock);
490
+ const checkpointNumber = firstBlock.checkpointNumber;
491
+ // Get L1-to-L2 messages for this checkpoint
492
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
493
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
494
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
495
+ const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
496
+ // Fork world state at the block before the first block
497
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
498
+ const fork = await this.worldState.fork(parentBlockNumber);
499
+ try {
500
+ // Create checkpoint builder with all existing blocks
501
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
502
+ // Complete the checkpoint to get computed values
503
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
504
+ // Compare checkpoint header with proposal
505
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
506
+ this.log.warn(`Checkpoint header mismatch`, {
507
+ ...proposalInfo,
508
+ computed: computedCheckpoint.header.toInspect(),
509
+ proposal: proposal.checkpointHeader.toInspect()
510
+ });
511
+ return {
512
+ isValid: false,
513
+ reason: 'checkpoint_header_mismatch'
514
+ };
515
+ }
516
+ // Compare archive root with proposal
517
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
518
+ this.log.warn(`Archive root mismatch`, {
519
+ ...proposalInfo,
520
+ computed: computedCheckpoint.archive.root.toString(),
521
+ proposal: proposal.archive.toString()
522
+ });
523
+ return {
524
+ isValid: false,
525
+ reason: 'archive_mismatch'
526
+ };
527
+ }
528
+ // Check that the accumulated epoch out hash matches the value in the proposal.
529
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
530
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
531
+ const computedEpochOutHash = accumulateCheckpointOutHashes([
532
+ ...previousCheckpointOutHashes,
533
+ checkpointOutHash
534
+ ]);
535
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
536
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
537
+ this.log.warn(`Epoch out hash mismatch`, {
538
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
539
+ computedEpochOutHash: computedEpochOutHash.toString(),
540
+ checkpointOutHash: checkpointOutHash.toString(),
541
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map((h)=>h.toString()),
542
+ ...proposalInfo
543
+ });
544
+ return {
545
+ isValid: false,
546
+ reason: 'out_hash_mismatch'
547
+ };
548
+ }
549
+ // Final round of validations on the checkpoint, just in case.
550
+ try {
551
+ validateCheckpoint(computedCheckpoint, {
552
+ rollupManaLimit: this.checkpointsBuilder.getConfig().rollupManaLimit,
553
+ maxDABlockGas: this.config.validateMaxDABlockGas,
554
+ maxL2BlockGas: this.config.validateMaxL2BlockGas,
555
+ maxTxsPerBlock: this.config.validateMaxTxsPerBlock,
556
+ maxTxsPerCheckpoint: this.config.validateMaxTxsPerCheckpoint
557
+ });
558
+ } catch (err) {
559
+ this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
560
+ return {
561
+ isValid: false,
562
+ reason: 'checkpoint_validation_failed'
563
+ };
564
+ }
565
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
566
+ return {
567
+ isValid: true
568
+ };
569
+ } finally{
570
+ await fork.close();
571
+ }
572
+ }
573
+ /**
574
+ * Extract checkpoint global variables from a block.
575
+ */ extractCheckpointConstants(block) {
576
+ const gv = block.header.globalVariables;
577
+ return {
578
+ chainId: gv.chainId,
579
+ version: gv.version,
580
+ slotNumber: gv.slotNumber,
581
+ timestamp: gv.timestamp,
582
+ coinbase: gv.coinbase,
583
+ feeRecipient: gv.feeRecipient,
584
+ gasFees: gv.gasFees
585
+ };
586
+ }
587
+ /**
588
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
589
+ */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
590
+ try {
591
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
592
+ if (!lastBlockHeader) {
593
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
594
+ return;
595
+ }
596
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
597
+ if (blocks.length === 0) {
598
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
599
+ return;
600
+ }
601
+ const blobFields = blocks.flatMap((b)=>b.toBlobFields());
602
+ const blobs = await getBlobsPerL1Block(blobFields);
603
+ await this.blobClient.sendBlobsToFilestore(blobs);
604
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
605
+ ...proposalInfo,
606
+ numBlobs: blobs.length
607
+ });
608
+ } catch (err) {
609
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
610
+ }
250
611
  }
251
612
  slashInvalidBlock(proposal) {
252
613
  const proposer = proposal.getSender();
@@ -270,42 +631,103 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
270
631
  }
271
632
  ]);
272
633
  }
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);
634
+ /**
635
+ * Handle detection of a duplicate proposal (equivocation).
636
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
637
+ */ handleDuplicateProposal(info) {
638
+ const { slot, proposer, type } = info;
639
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
640
+ proposer: proposer.toString(),
641
+ slot,
642
+ type
643
+ });
644
+ // Emit slash event
645
+ this.emit(WANT_TO_SLASH_EVENT, [
646
+ {
647
+ validator: proposer,
648
+ amount: this.config.slashDuplicateProposalPenalty,
649
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
650
+ epochOrSlot: BigInt(slot)
651
+ }
652
+ ]);
653
+ }
654
+ /**
655
+ * Handle detection of a duplicate attestation (equivocation).
656
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
657
+ */ handleDuplicateAttestation(info) {
658
+ const { slot, attester } = info;
659
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
660
+ attester: attester.toString(),
661
+ slot
662
+ });
663
+ this.emit(WANT_TO_SLASH_EVENT, [
664
+ {
665
+ validator: attester,
666
+ amount: this.config.slashDuplicateAttestationPenalty,
667
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
668
+ epochOrSlot: BigInt(slot)
669
+ }
670
+ ]);
671
+ }
672
+ async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
673
+ // Validate that we're not creating a proposal for an older or equal position
674
+ if (this.lastProposedBlock) {
675
+ const lastSlot = this.lastProposedBlock.slotNumber;
676
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
677
+ const newSlot = blockHeader.globalVariables.slotNumber;
678
+ if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
679
+ throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
680
+ }
277
681
  }
278
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
682
+ this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
683
+ const newProposal = await this.validationService.createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
279
684
  ...options,
280
685
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
281
686
  });
282
- this.previousProposal = newProposal;
687
+ this.lastProposedBlock = newProposal;
688
+ return newProposal;
689
+ }
690
+ async createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAddress, options = {}) {
691
+ // Validate that we're not creating a proposal for an older or equal slot
692
+ if (this.lastProposedCheckpoint) {
693
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
694
+ const newSlot = checkpointHeader.slotNumber;
695
+ if (newSlot <= lastSlot) {
696
+ throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
697
+ }
698
+ }
699
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
700
+ const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAddress, options);
701
+ this.lastProposedCheckpoint = newProposal;
283
702
  return newProposal;
284
703
  }
285
704
  async broadcastBlockProposal(proposal) {
286
705
  await this.p2pClient.broadcastProposal(proposal);
287
706
  }
288
- async signAttestationsAndSigners(attestationsAndSigners, proposer) {
289
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
707
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber) {
708
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
290
709
  }
291
710
  async collectOwnAttestations(proposal) {
292
- const slot = proposal.payload.header.slotNumber;
711
+ const slot = proposal.slotNumber;
293
712
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
294
713
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
295
714
  inCommittee
296
715
  });
297
- const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
716
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
717
+ if (!attestations) {
718
+ return [];
719
+ }
298
720
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
299
721
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
300
722
  // due to inactivity for missed attestations.
301
- void this.p2pClient.broadcastAttestations(attestations).catch((err)=>{
723
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch((err)=>{
302
724
  this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
303
725
  });
304
726
  return attestations;
305
727
  }
306
728
  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;
729
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
730
+ const slot = proposal.slotNumber;
309
731
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
310
732
  if (+deadline < this.dateProvider.now()) {
311
733
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
@@ -316,13 +738,13 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
316
738
  const myAddresses = this.getValidatorAddresses();
317
739
  let attestations = [];
318
740
  while(true){
319
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
741
+ // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
320
742
  // 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
743
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
744
+ if (!attestation.archive.equals(proposal.archive)) {
745
+ this.log.warn(`Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`, {
746
+ attestationArchive: attestation.archive.toString(),
747
+ proposalArchive: proposal.archive.toString()
326
748
  });
327
749
  return false;
328
750
  }
@@ -354,11 +776,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
354
776
  await sleep(this.config.attestationPollingIntervalMs);
355
777
  }
356
778
  }
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
779
  async handleAuthRequest(peer, msg) {
363
780
  const authRequest = AuthRequest.fromBuffer(msg);
364
781
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
@@ -373,7 +790,11 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
373
790
  return Buffer.alloc(0);
374
791
  }
375
792
  const payloadToSign = authRequest.getPayloadToSign();
376
- const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
793
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
794
+ const context = {
795
+ dutyType: DutyType.AUTH_REQUEST
796
+ };
797
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
377
798
  const authResponse = new AuthResponse(statusMessage, signature);
378
799
  return authResponse.toBuffer();
379
800
  }