@aztec/validator-client 0.0.0-test.0 → 0.0.1-commit.023c3e5

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 (78) hide show
  1. package/README.md +282 -0
  2. package/dest/block_proposal_handler.d.ts +63 -0
  3. package/dest/block_proposal_handler.d.ts.map +1 -0
  4. package/dest/block_proposal_handler.js +546 -0
  5. package/dest/checkpoint_builder.d.ts +66 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +173 -0
  8. package/dest/config.d.ts +3 -14
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +41 -8
  11. package/dest/duties/validation_service.d.ts +50 -13
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +123 -17
  14. package/dest/factory.d.ts +28 -6
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +13 -6
  17. package/dest/index.d.ts +6 -2
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +5 -1
  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 +4 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +3 -0
  26. package/dest/key_store/interface.d.ts +85 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/interface.js +3 -3
  29. package/dest/key_store/local_key_store.d.ts +46 -11
  30. package/dest/key_store/local_key_store.d.ts.map +1 -1
  31. package/dest/key_store/local_key_store.js +68 -17
  32. package/dest/key_store/node_keystore_adapter.d.ts +151 -0
  33. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
  34. package/dest/key_store/node_keystore_adapter.js +330 -0
  35. package/dest/key_store/web3signer_key_store.d.ts +66 -0
  36. package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
  37. package/dest/key_store/web3signer_key_store.js +156 -0
  38. package/dest/metrics.d.ts +13 -5
  39. package/dest/metrics.d.ts.map +1 -1
  40. package/dest/metrics.js +63 -22
  41. package/dest/tx_validator/index.d.ts +3 -0
  42. package/dest/tx_validator/index.d.ts.map +1 -0
  43. package/dest/tx_validator/index.js +2 -0
  44. package/dest/tx_validator/nullifier_cache.d.ts +14 -0
  45. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
  46. package/dest/tx_validator/nullifier_cache.js +24 -0
  47. package/dest/tx_validator/tx_validator_factory.d.ts +19 -0
  48. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  49. package/dest/tx_validator/tx_validator_factory.js +54 -0
  50. package/dest/validator.d.ts +73 -58
  51. package/dest/validator.d.ts.map +1 -1
  52. package/dest/validator.js +559 -166
  53. package/package.json +37 -21
  54. package/src/block_proposal_handler.ts +555 -0
  55. package/src/checkpoint_builder.ts +314 -0
  56. package/src/config.ts +52 -22
  57. package/src/duties/validation_service.ts +193 -19
  58. package/src/factory.ts +65 -11
  59. package/src/index.ts +5 -1
  60. package/src/key_store/ha_key_store.ts +269 -0
  61. package/src/key_store/index.ts +3 -0
  62. package/src/key_store/interface.ts +100 -5
  63. package/src/key_store/local_key_store.ts +77 -18
  64. package/src/key_store/node_keystore_adapter.ts +398 -0
  65. package/src/key_store/web3signer_key_store.ts +205 -0
  66. package/src/metrics.ts +86 -23
  67. package/src/tx_validator/index.ts +2 -0
  68. package/src/tx_validator/nullifier_cache.ts +30 -0
  69. package/src/tx_validator/tx_validator_factory.ts +154 -0
  70. package/src/validator.ts +757 -221
  71. package/dest/errors/index.d.ts +0 -2
  72. package/dest/errors/index.d.ts.map +0 -1
  73. package/dest/errors/index.js +0 -1
  74. package/dest/errors/validator.error.d.ts +0 -29
  75. package/dest/errors/validator.error.d.ts.map +0 -1
  76. package/dest/errors/validator.error.js +0 -45
  77. package/src/errors/index.ts +0 -1
  78. package/src/errors/validator.error.ts +0 -55
package/dest/validator.js CHANGED
@@ -1,225 +1,603 @@
1
- import { Buffer32 } from '@aztec/foundation/buffer';
1
+ import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
+ import { BlockNumber } from '@aztec/foundation/branded-types';
3
+ import { TimeoutError } from '@aztec/foundation/error';
2
4
  import { createLogger } from '@aztec/foundation/log';
5
+ import { retryUntil } from '@aztec/foundation/retry';
3
6
  import { RunningPromise } from '@aztec/foundation/running-promise';
4
7
  import { sleep } from '@aztec/foundation/sleep';
5
8
  import { DateProvider } from '@aztec/foundation/timer';
6
- import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
7
- import { WithTracer, getTelemetryClient } from '@aztec/telemetry-client';
9
+ import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
10
+ import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
11
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
12
+ import { accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
13
+ import { AttestationTimeoutError } from '@aztec/stdlib/validators';
14
+ import { getTelemetryClient } from '@aztec/telemetry-client';
15
+ import { createHASigner } from '@aztec/validator-ha-signer/factory';
16
+ import { DutyType } from '@aztec/validator-ha-signer/types';
17
+ import { EventEmitter } from 'events';
18
+ import { BlockProposalHandler } from './block_proposal_handler.js';
8
19
  import { ValidationService } from './duties/validation_service.js';
9
- import { AttestationTimeoutError, BlockBuilderNotProvidedError, InvalidValidatorPrivateKeyError, ReExFailedTxsError, ReExStateMismatchError, ReExTimeoutError, TransactionsNotAvailableError } from './errors/validator.error.js';
10
- import { LocalKeyStore } from './key_store/local_key_store.js';
20
+ import { HAKeyStore } from './key_store/ha_key_store.js';
21
+ import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
11
22
  import { ValidatorMetrics } from './metrics.js';
23
+ // We maintain a set of proposers who have proposed invalid blocks.
24
+ // Just cap the set to avoid unbounded growth.
25
+ const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
26
+ // What errors from the block proposal handler result in slashing
27
+ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
28
+ 'state_mismatch',
29
+ 'failed_txs'
30
+ ];
12
31
  /**
13
32
  * Validator Client
14
- */ export class ValidatorClient extends WithTracer {
33
+ */ export class ValidatorClient extends EventEmitter {
15
34
  keyStore;
16
35
  epochCache;
17
36
  p2pClient;
37
+ blockProposalHandler;
38
+ blockSource;
39
+ checkpointsBuilder;
40
+ worldState;
41
+ l1ToL2MessageSource;
18
42
  config;
43
+ blobClient;
19
44
  dateProvider;
20
- log;
45
+ tracer;
21
46
  validationService;
22
47
  metrics;
48
+ log;
49
+ // Whether it has already registered handlers on the p2p client
50
+ hasRegisteredHandlers;
23
51
  // Used to check if we are sending the same proposal twice
24
52
  previousProposal;
25
- // Callback registered to: sequencer.buildBlock
26
- blockBuilder;
53
+ lastEpochForCommitteeUpdateLoop;
27
54
  epochCacheUpdateLoop;
28
- blockProposalValidator;
29
- constructor(keyStore, epochCache, p2pClient, config, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
30
- // Instantiate tracer
31
- super(telemetry, 'Validator'), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.config = config, this.dateProvider = dateProvider, this.log = log, this.blockBuilder = undefined;
55
+ 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();
58
+ // Create child logger with fisherman prefix if in fisherman mode
59
+ this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
60
+ this.tracer = telemetry.getTracer('Validator');
32
61
  this.metrics = new ValidatorMetrics(telemetry);
33
- this.validationService = new ValidationService(keyStore);
34
- this.blockProposalValidator = new BlockProposalValidator(epochCache);
35
- // Refresh epoch cache every second to trigger commiteeChanged event
36
- this.epochCacheUpdateLoop = new RunningPromise(()=>this.epochCache.getCommittee().then(()=>{}).catch((err)=>log.error('Error updating validator committee', err)), log, 1000);
37
- // Listen to commiteeChanged event to alert operator when their validator has entered the committee
38
- this.epochCache.on('committeeChanged', (newCommittee, epochNumber)=>{
39
- const me = this.keyStore.getAddress();
40
- if (newCommittee.some((addr)=>addr.equals(me))) {
41
- this.log.info(`Validator ${me.toString()} is on the validator committee for epoch ${epochNumber}`);
42
- } else {
43
- this.log.verbose(`Validator ${me.toString()} not on the validator committee for epoch ${epochNumber}`);
62
+ this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
63
+ // Refresh epoch cache every second to trigger alert if participation in committee changes
64
+ this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
65
+ const myAddresses = this.getValidatorAddresses();
66
+ this.log.verbose(`Initialized validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
67
+ }
68
+ static validateKeyStoreConfiguration(keyStoreManager, logger) {
69
+ const validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
70
+ const validatorAddresses = validatorKeyStore.getAddresses();
71
+ // Verify that we can retrieve all required data from the key store
72
+ for (const address of validatorAddresses){
73
+ // Functions throw if required data is not available
74
+ let coinbase;
75
+ let feeRecipient;
76
+ try {
77
+ coinbase = validatorKeyStore.getCoinbaseAddress(address);
78
+ feeRecipient = validatorKeyStore.getFeeRecipient(address);
79
+ } catch (error) {
80
+ throw new Error(`Failed to retrieve required data for validator address ${address}, error: ${error}`);
44
81
  }
45
- });
46
- this.log.verbose(`Initialized validator with address ${this.keyStore.getAddress().toString()}`);
82
+ const publisherAddresses = validatorKeyStore.getPublisherAddresses(address);
83
+ if (!publisherAddresses.length) {
84
+ throw new Error(`No publisher addresses found for validator address ${address}`);
85
+ }
86
+ logger?.debug(`Validator ${address.toString()} configured with coinbase ${coinbase.toString()}, feeRecipient ${feeRecipient.toString()} and publishers ${publisherAddresses.map((x)=>x.toString()).join()}`);
87
+ }
47
88
  }
48
- static new(config, epochCache, p2pClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
49
- if (!config.validatorPrivateKey) {
50
- throw new InvalidValidatorPrivateKeyError();
89
+ async handleEpochCommitteeUpdate() {
90
+ try {
91
+ const { committee, epoch } = await this.epochCache.getCommittee('next');
92
+ if (!committee) {
93
+ this.log.trace(`No committee found for slot`);
94
+ return;
95
+ }
96
+ if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
97
+ const me = this.getValidatorAddresses();
98
+ const committeeSet = new Set(committee.map((v)=>v.toString()));
99
+ const inCommittee = me.filter((a)=>committeeSet.has(a.toString()));
100
+ if (inCommittee.length > 0) {
101
+ this.log.info(`Validators ${inCommittee.map((a)=>a.toString()).join(',')} are on the validator committee for epoch ${epoch}`);
102
+ } else {
103
+ this.log.verbose(`Validators ${me.map((a)=>a.toString()).join(', ')} are not on the validator committee for epoch ${epoch}`);
104
+ }
105
+ this.lastEpochForCommitteeUpdateLoop = epoch;
106
+ }
107
+ } catch (err) {
108
+ this.log.error(`Error updating epoch committee`, err);
51
109
  }
52
- const privateKey = validatePrivateKey(config.validatorPrivateKey);
53
- const localKeyStore = new LocalKeyStore(privateKey);
54
- const validator = new ValidatorClient(localKeyStore, epochCache, p2pClient, config, dateProvider, telemetry);
55
- validator.registerBlockProposalHandler();
110
+ }
111
+ static async new(config, checkpointsBuilder, worldState, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
112
+ const metrics = new ValidatorMetrics(telemetry);
113
+ const blockProposalValidator = new BlockProposalValidator(epochCache, {
114
+ txsPermitted: !config.disableTransactions
115
+ });
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) {
119
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
120
+ const haConfig = {
121
+ ...config,
122
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
123
+ };
124
+ const { signer } = await createHASigner(haConfig);
125
+ validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
126
+ }
127
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider, telemetry);
56
128
  return validator;
57
129
  }
130
+ getValidatorAddresses() {
131
+ return this.keyStore.getAddresses().filter((addr)=>!this.config.disabledValidators.some((disabled)=>disabled.equals(addr)));
132
+ }
133
+ getBlockProposalHandler() {
134
+ return this.blockProposalHandler;
135
+ }
136
+ signWithAddress(addr, msg, context) {
137
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
138
+ }
139
+ getCoinbaseForAttestor(attestor) {
140
+ return this.keyStore.getCoinbaseAddress(attestor);
141
+ }
142
+ getFeeRecipientForAttestor(attestor) {
143
+ return this.keyStore.getFeeRecipient(attestor);
144
+ }
145
+ getConfig() {
146
+ return this.config;
147
+ }
148
+ updateConfig(config) {
149
+ this.config = {
150
+ ...this.config,
151
+ ...config
152
+ };
153
+ }
58
154
  async start() {
59
- // Sync the committee from the smart contract
60
- // https://github.com/AztecProtocol/aztec-packages/issues/7962
61
- const me = this.keyStore.getAddress();
62
- const inCommittee = await this.epochCache.isInCommittee(me);
63
- if (inCommittee) {
64
- this.log.info(`Started validator with address ${me.toString()} in current validator committee`);
65
- } else {
66
- this.log.info(`Started validator with address ${me.toString()}`);
155
+ if (this.epochCacheUpdateLoop.isRunning()) {
156
+ this.log.warn(`Validator client already started`);
157
+ return;
158
+ }
159
+ await this.keyStore.start();
160
+ await this.registerHandlers();
161
+ const myAddresses = this.getValidatorAddresses();
162
+ const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
163
+ this.log.info(`Started validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
164
+ if (inCommittee.length > 0) {
165
+ this.log.info(`Addresses in current validator committee: ${inCommittee.map((a)=>a.toString()).join(', ')}`);
67
166
  }
68
167
  this.epochCacheUpdateLoop.start();
69
168
  return Promise.resolve();
70
169
  }
71
170
  async stop() {
72
171
  await this.epochCacheUpdateLoop.stop();
172
+ await this.keyStore.stop();
73
173
  }
74
- registerBlockProposalHandler() {
75
- const handler = (block)=>{
76
- return this.attestToProposal(block);
77
- };
78
- this.p2pClient.registerBlockProposalHandler(handler);
174
+ /** Register handlers on the p2p client */ async registerHandlers() {
175
+ if (!this.hasRegisteredHandlers) {
176
+ this.hasRegisteredHandlers = true;
177
+ this.log.debug(`Registering validator handlers for p2p client`);
178
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
179
+ const blockHandler = (block, proposalSender)=>this.validateBlockProposal(block, proposalSender);
180
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
181
+ // Checkpoint proposal handler - validates and creates attestations
182
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
183
+ // and processed separately via the block handler above.
184
+ const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
185
+ this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
186
+ const myAddresses = this.getValidatorAddresses();
187
+ this.p2pClient.registerThisValidatorAddresses(myAddresses);
188
+ await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
189
+ }
79
190
  }
80
191
  /**
81
- * Register a callback function for building a block
82
- *
83
- * We reuse the sequencer's block building functionality for re-execution
84
- */ registerBlockBuilder(blockBuilder) {
85
- this.blockBuilder = blockBuilder;
86
- }
87
- async attestToProposal(proposal) {
88
- const slotNumber = proposal.slotNumber.toNumber();
192
+ * Validate a block proposal from a peer.
193
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
194
+ * @returns true if the proposal is valid, false otherwise
195
+ */ async validateBlockProposal(proposal, proposalSender) {
196
+ const slotNumber = proposal.slotNumber;
197
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
198
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
199
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
200
+ const proposer = proposal.getSender();
201
+ // Reject proposals with invalid signatures
202
+ if (!proposer) {
203
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
204
+ return false;
205
+ }
206
+ // Check if we're in the committee (for metrics purposes)
207
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
208
+ const partOfCommittee = inCommittee.length > 0;
89
209
  const proposalInfo = {
90
- slotNumber,
91
- blockNumber: proposal.payload.header.globalVariables.blockNumber.toNumber(),
92
- archive: proposal.payload.archive.toString(),
93
- txCount: proposal.payload.txHashes.length,
94
- txHashes: proposal.payload.txHashes.map((txHash)=>txHash.toString())
210
+ ...proposal.toBlockInfo(),
211
+ proposer: proposer.toString()
95
212
  };
96
- this.log.verbose(`Received request to attest for slot ${slotNumber}`);
97
- // Check that I am in the committee
98
- if (!await this.epochCache.isInCommittee(this.keyStore.getAddress())) {
99
- this.log.verbose(`Not in the committee, skipping attestation`);
213
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
214
+ ...proposalInfo,
215
+ txHashes: proposal.txHashes.map((t)=>t.toString()),
216
+ fishermanMode: this.config.fishermanMode || false
217
+ });
218
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
219
+ // In fisherman mode, we always reexecute to validate proposals.
220
+ const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
221
+ const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.blobClient.canUpload();
222
+ const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute && !escapeHatchOpen);
223
+ if (!validationResult.isValid) {
224
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
225
+ const reason = validationResult.reason || 'unknown';
226
+ // Classify failure reason: bad proposal vs node issue
227
+ const badProposalReasons = [
228
+ 'invalid_proposal',
229
+ 'state_mismatch',
230
+ 'failed_txs',
231
+ 'in_hash_mismatch',
232
+ 'parent_block_wrong_slot'
233
+ ];
234
+ if (badProposalReasons.includes(reason)) {
235
+ this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
236
+ } else {
237
+ // Node issues so we can't validate
238
+ this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
239
+ }
240
+ // Slash invalid block proposals (can happen even when not in committee)
241
+ if (!escapeHatchOpen && validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
242
+ this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
243
+ this.slashInvalidBlock(proposal);
244
+ }
245
+ return false;
246
+ }
247
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
248
+ ...proposalInfo,
249
+ inCommittee: partOfCommittee,
250
+ fishermanMode: this.config.fishermanMode || false,
251
+ escapeHatchOpen
252
+ });
253
+ if (escapeHatchOpen) {
254
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
255
+ return false;
256
+ }
257
+ return true;
258
+ }
259
+ /**
260
+ * Validate and attest to a checkpoint proposal from a peer.
261
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
262
+ * the lastBlock is extracted and processed separately via the block handler.
263
+ * @returns Checkpoint attestations if valid, undefined otherwise
264
+ */ async attestToCheckpointProposal(proposal, _proposalSender) {
265
+ const slotNumber = proposal.slotNumber;
266
+ const proposer = proposal.getSender();
267
+ // If escape hatch is open for this slot's epoch, do not attest.
268
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
269
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
100
270
  return undefined;
101
271
  }
102
- // Check that the proposal is from the current proposer, or the next proposer.
103
- const invalidProposal = await this.blockProposalValidator.validate(proposal);
104
- if (invalidProposal) {
105
- this.log.verbose(`Proposal is not valid, skipping attestation`);
272
+ // Reject proposals with invalid signatures
273
+ if (!proposer) {
274
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
106
275
  return undefined;
107
276
  }
108
- // Check that all of the transactions in the proposal are available in the tx pool before attesting
109
- this.log.verbose(`Processing attestation for slot ${slotNumber}`, proposalInfo);
110
- try {
111
- await this.ensureTransactionsAreAvailable(proposal);
112
- if (this.config.validatorReexecute) {
113
- this.log.verbose(`Re-executing transactions in the proposal before attesting`);
114
- await this.reExecuteTransactions(proposal);
115
- }
116
- } catch (error) {
117
- // If the transactions are not available, then we should not attempt to attest
118
- if (error instanceof TransactionsNotAvailableError) {
119
- this.log.error(`Transactions not available, skipping attestation`, error, proposalInfo);
120
- } else {
121
- // This branch most commonly be hit if the transactions are available, but the re-execution fails
122
- // Catch all error handler
123
- this.log.error(`Failed to attest to proposal`, error, proposalInfo);
277
+ // Check that I have any address in current committee before attesting
278
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
279
+ const partOfCommittee = inCommittee.length > 0;
280
+ const proposalInfo = {
281
+ slotNumber,
282
+ archive: proposal.archive.toString(),
283
+ proposer: proposer.toString(),
284
+ txCount: proposal.txHashes.length
285
+ };
286
+ this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
287
+ ...proposalInfo,
288
+ txHashes: proposal.txHashes.map((t)=>t.toString()),
289
+ fishermanMode: this.config.fishermanMode || false
290
+ });
291
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
292
+ if (this.config.skipCheckpointProposalValidation) {
293
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
294
+ } else {
295
+ const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
296
+ if (!validationResult.isValid) {
297
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
298
+ return undefined;
124
299
  }
300
+ }
301
+ // Upload blobs to filestore if we can (fire and forget)
302
+ if (this.blobClient.canUpload()) {
303
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
304
+ }
305
+ // Check that I have any address in current committee before attesting
306
+ // In fisherman mode, we still create attestations for validation even if not in committee
307
+ if (!partOfCommittee && !this.config.fishermanMode) {
308
+ this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
125
309
  return undefined;
126
310
  }
127
311
  // Provided all of the above checks pass, we can attest to the proposal
128
- this.log.info(`Attesting to proposal for slot ${slotNumber}`, proposalInfo);
129
- // If the above function does not throw an error, then we can attest to the proposal
130
- return this.validationService.attestToProposal(proposal);
312
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
313
+ ...proposalInfo,
314
+ inCommittee: partOfCommittee,
315
+ fishermanMode: this.config.fishermanMode || false
316
+ });
317
+ this.metrics.incSuccessfulAttestations(inCommittee.length);
318
+ // Determine which validators should attest
319
+ let attestors;
320
+ if (partOfCommittee) {
321
+ attestors = inCommittee;
322
+ } else if (this.config.fishermanMode) {
323
+ // In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
324
+ attestors = this.getValidatorAddresses();
325
+ } else {
326
+ attestors = [];
327
+ }
328
+ // Only create attestations if we have attestors
329
+ if (attestors.length === 0) {
330
+ return undefined;
331
+ }
332
+ if (this.config.fishermanMode) {
333
+ // bail out early and don't save attestations to the pool in fisherman mode
334
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
335
+ ...proposalInfo,
336
+ attestors: attestors.map((a)=>a.toString())
337
+ });
338
+ return undefined;
339
+ }
340
+ return this.createCheckpointAttestationsFromProposal(proposal, attestors);
341
+ }
342
+ async createCheckpointAttestationsFromProposal(proposal, attestors = []) {
343
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
344
+ await this.p2pClient.addCheckpointAttestations(attestations);
345
+ return attestations;
131
346
  }
132
347
  /**
133
- * Re-execute the transactions in the proposal and check that the state updates match the header state
134
- * @param proposal - The proposal to re-execute
135
- */ async reExecuteTransactions(proposal) {
136
- const { header, txHashes } = proposal.payload;
137
- const txs = (await Promise.all(txHashes.map((tx)=>this.p2pClient.getTxByHash(tx)))).filter((tx)=>tx !== undefined);
138
- // If we cannot request all of the transactions, then we should fail
139
- if (txs.length !== txHashes.length) {
140
- throw new TransactionsNotAvailableError(txHashes);
141
- }
142
- // Assertion: This check will fail if re-execution is not enabled
143
- if (this.blockBuilder === undefined) {
144
- throw new BlockBuilderNotProvidedError();
145
- }
146
- // Use the sequencer's block building logic to re-execute the transactions
147
- const stopTimer = this.metrics.reExecutionTimer();
148
- const { block, numFailedTxs } = await this.blockBuilder(txs, header.globalVariables, {
149
- validateOnly: true
150
- });
151
- stopTimer();
152
- this.log.verbose(`Transaction re-execution complete`);
153
- if (numFailedTxs > 0) {
154
- await this.metrics.recordFailedReexecution(proposal);
155
- throw new ReExFailedTxsError(numFailedTxs);
348
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
349
+ * @returns Validation result with isValid flag and reason if invalid.
350
+ */ async validateCheckpointProposal(proposal, proposalInfo) {
351
+ const slot = proposal.slotNumber;
352
+ const timeoutSeconds = 10; // TODO(palla/mbps): This should map to the timetable settings
353
+ // Wait for last block to sync by archive
354
+ let lastBlockHeader;
355
+ try {
356
+ lastBlockHeader = await retryUntil(async ()=>{
357
+ await this.blockSource.syncImmediate();
358
+ return this.blockSource.getBlockHeaderByArchive(proposal.archive);
359
+ }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
360
+ } catch (err) {
361
+ if (err instanceof TimeoutError) {
362
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
363
+ return {
364
+ isValid: false,
365
+ reason: 'last_block_not_found'
366
+ };
367
+ }
368
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
369
+ return {
370
+ isValid: false,
371
+ reason: 'block_fetch_error'
372
+ };
156
373
  }
157
- if (block.body.txEffects.length !== txHashes.length) {
158
- await this.metrics.recordFailedReexecution(proposal);
159
- throw new ReExTimeoutError();
374
+ if (!lastBlockHeader) {
375
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
376
+ return {
377
+ isValid: false,
378
+ reason: 'last_block_not_found'
379
+ };
160
380
  }
161
- // This function will throw an error if state updates do not match
162
- if (!block.archive.root.equals(proposal.archive)) {
163
- await this.metrics.recordFailedReexecution(proposal);
164
- throw new ReExStateMismatchError();
381
+ // Get all full blocks for the slot and checkpoint
382
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
383
+ if (blocks.length === 0) {
384
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
385
+ return {
386
+ isValid: false,
387
+ reason: 'no_blocks_for_slot'
388
+ };
165
389
  }
390
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
391
+ ...proposalInfo,
392
+ blockNumbers: blocks.map((b)=>b.number)
393
+ });
394
+ // Get checkpoint constants from first block
395
+ const firstBlock = blocks[0];
396
+ const constants = this.extractCheckpointConstants(firstBlock);
397
+ const checkpointNumber = firstBlock.checkpointNumber;
398
+ // Get L1-to-L2 messages for this checkpoint
399
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
400
+ // Compute the previous checkpoint out hashes for the epoch.
401
+ // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch the
402
+ // actual checkpoints and the blocks/txs in them.
403
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
404
+ const previousCheckpoints = (await this.blockSource.getCheckpointsForEpoch(epoch)).filter((b)=>b.number < checkpointNumber).sort((a, b)=>a.number - b.number);
405
+ const previousCheckpointOutHashes = previousCheckpoints.map((c)=>c.getCheckpointOutHash());
406
+ // Fork world state at the block before the first block
407
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
408
+ const fork = await this.worldState.fork(parentBlockNumber);
409
+ try {
410
+ // Create checkpoint builder with all existing blocks
411
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
412
+ // Complete the checkpoint to get computed values
413
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
414
+ // Compare checkpoint header with proposal
415
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
416
+ this.log.warn(`Checkpoint header mismatch`, {
417
+ ...proposalInfo,
418
+ computed: computedCheckpoint.header.toInspect(),
419
+ proposal: proposal.checkpointHeader.toInspect()
420
+ });
421
+ return {
422
+ isValid: false,
423
+ reason: 'checkpoint_header_mismatch'
424
+ };
425
+ }
426
+ // Compare archive root with proposal
427
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
428
+ this.log.warn(`Archive root mismatch`, {
429
+ ...proposalInfo,
430
+ computed: computedCheckpoint.archive.root.toString(),
431
+ proposal: proposal.archive.toString()
432
+ });
433
+ return {
434
+ isValid: false,
435
+ reason: 'archive_mismatch'
436
+ };
437
+ }
438
+ // Check that the accumulated epoch out hash matches the value in the proposal.
439
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
440
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
441
+ const computedEpochOutHash = accumulateCheckpointOutHashes([
442
+ ...previousCheckpointOutHashes,
443
+ checkpointOutHash
444
+ ]);
445
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
446
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
447
+ this.log.warn(`Epoch out hash mismatch`, {
448
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
449
+ computedEpochOutHash: computedEpochOutHash.toString(),
450
+ checkpointOutHash: checkpointOutHash.toString(),
451
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map((h)=>h.toString()),
452
+ ...proposalInfo
453
+ });
454
+ return {
455
+ isValid: false,
456
+ reason: 'out_hash_mismatch'
457
+ };
458
+ }
459
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
460
+ return {
461
+ isValid: true
462
+ };
463
+ } finally{
464
+ await fork.close();
465
+ }
466
+ }
467
+ /**
468
+ * Extract checkpoint global variables from a block.
469
+ */ extractCheckpointConstants(block) {
470
+ const gv = block.header.globalVariables;
471
+ return {
472
+ chainId: gv.chainId,
473
+ version: gv.version,
474
+ slotNumber: gv.slotNumber,
475
+ coinbase: gv.coinbase,
476
+ feeRecipient: gv.feeRecipient,
477
+ gasFees: gv.gasFees
478
+ };
166
479
  }
167
480
  /**
168
- * Ensure that all of the transactions in the proposal are available in the tx pool before attesting
169
- *
170
- * 1. Check if the local tx pool contains all of the transactions in the proposal
171
- * 2. If any transactions are not in the local tx pool, request them from the network
172
- * 3. If we cannot retrieve them from the network, throw an error
173
- * @param proposal - The proposal to attest to
174
- */ async ensureTransactionsAreAvailable(proposal) {
175
- const txHashes = proposal.payload.txHashes;
176
- const transactionStatuses = await Promise.all(txHashes.map((txHash)=>this.p2pClient.getTxStatus(txHash)));
177
- const missingTxs = txHashes.filter((_, index)=>![
178
- 'pending',
179
- 'mined'
180
- ].includes(transactionStatuses[index] ?? ''));
181
- if (missingTxs.length === 0) {
182
- return; // All transactions are available
183
- }
184
- this.log.verbose(`Missing ${missingTxs.length} transactions in the tx pool, requesting from the network`);
185
- const requestedTxs = await this.p2pClient.requestTxs(missingTxs);
186
- if (requestedTxs.some((tx)=>tx === undefined)) {
187
- throw new TransactionsNotAvailableError(missingTxs);
188
- }
189
- }
190
- async createBlockProposal(header, archive, txs) {
191
- if (this.previousProposal?.slotNumber.equals(header.globalVariables.slotNumber)) {
192
- this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
193
- return Promise.resolve(undefined);
194
- }
195
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs);
481
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
482
+ */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
483
+ try {
484
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
485
+ if (!lastBlockHeader) {
486
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
487
+ return;
488
+ }
489
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
490
+ if (blocks.length === 0) {
491
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
492
+ return;
493
+ }
494
+ const blobFields = blocks.flatMap((b)=>b.toBlobFields());
495
+ const blobs = getBlobsPerL1Block(blobFields);
496
+ await this.blobClient.sendBlobsToFilestore(blobs);
497
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
498
+ ...proposalInfo,
499
+ numBlobs: blobs.length
500
+ });
501
+ } catch (err) {
502
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
503
+ }
504
+ }
505
+ slashInvalidBlock(proposal) {
506
+ const proposer = proposal.getSender();
507
+ // Skip if signature is invalid (shouldn't happen since we validate earlier)
508
+ if (!proposer) {
509
+ this.log.warn(`Cannot slash proposal with invalid signature`);
510
+ return;
511
+ }
512
+ // Trim the set if it's too big.
513
+ if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
514
+ // remove oldest proposer. `values` is guaranteed to be in insertion order.
515
+ this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value);
516
+ }
517
+ this.proposersOfInvalidBlocks.add(proposer.toString());
518
+ this.emit(WANT_TO_SLASH_EVENT, [
519
+ {
520
+ validator: proposer,
521
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
522
+ offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
523
+ epochOrSlot: BigInt(proposal.slotNumber)
524
+ }
525
+ ]);
526
+ }
527
+ async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
528
+ // TODO(palla/mbps): Prevent double proposals properly
529
+ // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
530
+ // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
531
+ // return Promise.resolve(undefined);
532
+ // }
533
+ this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
534
+ const newProposal = await this.validationService.createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
535
+ ...options,
536
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
537
+ });
196
538
  this.previousProposal = newProposal;
197
539
  return newProposal;
198
540
  }
199
- broadcastBlockProposal(proposal) {
200
- this.p2pClient.broadcastProposal(proposal);
541
+ async createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options = {}) {
542
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
543
+ return await this.validationService.createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options);
544
+ }
545
+ async broadcastBlockProposal(proposal) {
546
+ await this.p2pClient.broadcastProposal(proposal);
547
+ }
548
+ async signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber) {
549
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
550
+ }
551
+ async collectOwnAttestations(proposal) {
552
+ const slot = proposal.slotNumber;
553
+ const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
554
+ this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
555
+ inCommittee
556
+ });
557
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
558
+ // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
559
+ // other nodes can see that our validators did attest to this block proposal, and do not slash us
560
+ // due to inactivity for missed attestations.
561
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch((err)=>{
562
+ this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
563
+ });
564
+ return attestations;
201
565
  }
202
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/7962)
203
566
  async collectAttestations(proposal, required, deadline) {
204
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
205
- const slot = proposal.payload.header.globalVariables.slotNumber.toBigInt();
567
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
568
+ const slot = proposal.slotNumber;
206
569
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
207
570
  if (+deadline < this.dateProvider.now()) {
208
571
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
209
- throw new AttestationTimeoutError(required, slot);
572
+ throw new AttestationTimeoutError(0, required, slot);
210
573
  }
574
+ await this.collectOwnAttestations(proposal);
211
575
  const proposalId = proposal.archive.toString();
212
- const myAttestation = await this.validationService.attestToProposal(proposal);
576
+ const myAddresses = this.getValidatorAddresses();
213
577
  let attestations = [];
214
578
  while(true){
215
- const collectedAttestations = [
216
- myAttestation,
217
- ...await this.p2pClient.getAttestationsForSlot(slot, proposalId)
218
- ];
219
- const oldSenders = await Promise.all(attestations.map((attestation)=>attestation.getSender()));
579
+ // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
580
+ // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
581
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
582
+ if (!attestation.archive.equals(proposal.archive)) {
583
+ this.log.warn(`Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`, {
584
+ attestationArchive: attestation.archive.toString(),
585
+ proposalArchive: proposal.archive.toString()
586
+ });
587
+ return false;
588
+ }
589
+ return true;
590
+ });
591
+ // Log new attestations we collected
592
+ const oldSenders = attestations.map((attestation)=>attestation.getSender());
220
593
  for (const collected of collectedAttestations){
221
- const collectedSender = await collected.getSender();
222
- if (!oldSenders.some((sender)=>sender.equals(collectedSender))) {
594
+ const collectedSender = collected.getSender();
595
+ // Skip attestations with invalid signatures
596
+ if (!collectedSender) {
597
+ this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
598
+ continue;
599
+ }
600
+ if (!myAddresses.some((address)=>address.equals(collectedSender)) && !oldSenders.some((sender)=>sender?.equals(collectedSender))) {
223
601
  this.log.debug(`Received attestation for slot ${slot} from ${collectedSender.toString()}`);
224
602
  }
225
603
  }
@@ -230,17 +608,32 @@ import { ValidatorMetrics } from './metrics.js';
230
608
  }
231
609
  if (+deadline < this.dateProvider.now()) {
232
610
  this.log.error(`Timeout ${deadline.toISOString()} waiting for ${required} attestations for slot ${slot}`);
233
- throw new AttestationTimeoutError(required, slot);
611
+ throw new AttestationTimeoutError(attestations.length, required, slot);
234
612
  }
235
- this.log.debug(`Collected ${attestations.length} attestations so far`);
613
+ this.log.debug(`Collected ${attestations.length} of ${required} attestations so far`);
236
614
  await sleep(this.config.attestationPollingIntervalMs);
237
615
  }
238
616
  }
239
- }
240
- function validatePrivateKey(privateKey) {
241
- try {
242
- return Buffer32.fromString(privateKey);
243
- } catch (error) {
244
- throw new InvalidValidatorPrivateKeyError();
617
+ async handleAuthRequest(peer, msg) {
618
+ const authRequest = AuthRequest.fromBuffer(msg);
619
+ const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
620
+ if (statusMessage === undefined) {
621
+ return Buffer.alloc(0);
622
+ }
623
+ // Find a validator address that is in the set
624
+ const allRegisteredValidators = await this.epochCache.getRegisteredValidators();
625
+ const addressToUse = this.getValidatorAddresses().find((address)=>allRegisteredValidators.find((v)=>v.equals(address)) !== undefined);
626
+ if (addressToUse === undefined) {
627
+ // We don't have a registered address
628
+ return Buffer.alloc(0);
629
+ }
630
+ const payloadToSign = authRequest.getPayloadToSign();
631
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
632
+ const context = {
633
+ dutyType: DutyType.AUTH_REQUEST
634
+ };
635
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
636
+ const authResponse = new AuthResponse(statusMessage, signature);
637
+ return authResponse.toBuffer();
245
638
  }
246
639
  }