@aztec/validator-client 0.0.0-test.1 → 0.0.1-commit.03f7ef2

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/dest/block_proposal_handler.d.ts +53 -0
  2. package/dest/block_proposal_handler.d.ts.map +1 -0
  3. package/dest/block_proposal_handler.js +290 -0
  4. package/dest/config.d.ts +3 -14
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +36 -7
  7. package/dest/duties/validation_service.d.ts +17 -9
  8. package/dest/duties/validation_service.d.ts.map +1 -1
  9. package/dest/duties/validation_service.js +35 -12
  10. package/dest/factory.d.ts +24 -5
  11. package/dest/factory.d.ts.map +1 -1
  12. package/dest/factory.js +13 -6
  13. package/dest/index.d.ts +4 -2
  14. package/dest/index.d.ts.map +1 -1
  15. package/dest/index.js +3 -1
  16. package/dest/key_store/index.d.ts +3 -1
  17. package/dest/key_store/index.d.ts.map +1 -1
  18. package/dest/key_store/index.js +2 -0
  19. package/dest/key_store/interface.d.ts +55 -6
  20. package/dest/key_store/interface.d.ts.map +1 -1
  21. package/dest/key_store/interface.js +3 -3
  22. package/dest/key_store/local_key_store.d.ts +41 -11
  23. package/dest/key_store/local_key_store.d.ts.map +1 -1
  24. package/dest/key_store/local_key_store.js +64 -17
  25. package/dest/key_store/node_keystore_adapter.d.ts +138 -0
  26. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
  27. package/dest/key_store/node_keystore_adapter.js +316 -0
  28. package/dest/key_store/web3signer_key_store.d.ts +61 -0
  29. package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
  30. package/dest/key_store/web3signer_key_store.js +152 -0
  31. package/dest/metrics.d.ts +12 -5
  32. package/dest/metrics.d.ts.map +1 -1
  33. package/dest/metrics.js +52 -15
  34. package/dest/validator.d.ts +54 -63
  35. package/dest/validator.d.ts.map +1 -1
  36. package/dest/validator.js +331 -174
  37. package/package.json +29 -21
  38. package/src/block_proposal_handler.ts +346 -0
  39. package/src/config.ts +48 -22
  40. package/src/duties/validation_service.ts +67 -15
  41. package/src/factory.ts +59 -11
  42. package/src/index.ts +3 -1
  43. package/src/key_store/index.ts +2 -0
  44. package/src/key_store/interface.ts +61 -5
  45. package/src/key_store/local_key_store.ts +68 -18
  46. package/src/key_store/node_keystore_adapter.ts +375 -0
  47. package/src/key_store/web3signer_key_store.ts +192 -0
  48. package/src/metrics.ts +68 -17
  49. package/src/validator.ts +455 -234
  50. package/dest/errors/index.d.ts +0 -2
  51. package/dest/errors/index.d.ts.map +0 -1
  52. package/dest/errors/index.js +0 -1
  53. package/dest/errors/validator.error.d.ts +0 -29
  54. package/dest/errors/validator.error.d.ts.map +0 -1
  55. package/dest/errors/validator.error.js +0 -45
  56. package/src/errors/index.ts +0 -1
  57. package/src/errors/validator.error.ts +0 -55
package/dest/validator.js CHANGED
@@ -1,69 +1,149 @@
1
- import { Buffer32 } from '@aztec/foundation/buffer';
1
+ import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
2
  import { createLogger } from '@aztec/foundation/log';
3
3
  import { RunningPromise } from '@aztec/foundation/running-promise';
4
4
  import { sleep } from '@aztec/foundation/sleep';
5
5
  import { DateProvider } from '@aztec/foundation/timer';
6
- import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
7
- import { WithTracer, getTelemetryClient } from '@aztec/telemetry-client';
6
+ import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
7
+ import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
8
+ import { AttestationTimeoutError } from '@aztec/stdlib/validators';
9
+ import { getTelemetryClient } from '@aztec/telemetry-client';
10
+ import { EventEmitter } from 'events';
11
+ import { BlockProposalHandler } from './block_proposal_handler.js';
8
12
  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';
13
+ import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
11
14
  import { ValidatorMetrics } from './metrics.js';
15
+ // We maintain a set of proposers who have proposed invalid blocks.
16
+ // Just cap the set to avoid unbounded growth.
17
+ const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
18
+ // What errors from the block proposal handler result in slashing
19
+ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
20
+ 'state_mismatch',
21
+ 'failed_txs'
22
+ ];
12
23
  /**
13
24
  * Validator Client
14
- */ export class ValidatorClient extends WithTracer {
25
+ */ export class ValidatorClient extends EventEmitter {
15
26
  keyStore;
16
27
  epochCache;
17
28
  p2pClient;
29
+ blockProposalHandler;
18
30
  config;
31
+ fileStoreBlobUploadClient;
19
32
  dateProvider;
20
- log;
33
+ tracer;
21
34
  validationService;
22
35
  metrics;
36
+ log;
37
+ // Whether it has already registered handlers on the p2p client
38
+ hasRegisteredHandlers;
23
39
  // Used to check if we are sending the same proposal twice
24
40
  previousProposal;
25
- // Callback registered to: sequencer.buildBlock
26
- blockBuilder;
41
+ lastEpochForCommitteeUpdateLoop;
27
42
  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;
43
+ proposersOfInvalidBlocks;
44
+ constructor(keyStore, epochCache, p2pClient, blockProposalHandler, config, fileStoreBlobUploadClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
45
+ super(), this.keyStore = keyStore, this.epochCache = epochCache, this.p2pClient = p2pClient, this.blockProposalHandler = blockProposalHandler, this.config = config, this.fileStoreBlobUploadClient = fileStoreBlobUploadClient, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.proposersOfInvalidBlocks = new Set();
46
+ // Create child logger with fisherman prefix if in fisherman mode
47
+ this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
48
+ this.tracer = telemetry.getTracer('Validator');
32
49
  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}`);
50
+ this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
51
+ // Refresh epoch cache every second to trigger alert if participation in committee changes
52
+ this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
53
+ const myAddresses = this.getValidatorAddresses();
54
+ this.log.verbose(`Initialized validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
55
+ }
56
+ static validateKeyStoreConfiguration(keyStoreManager, logger) {
57
+ const validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
58
+ const validatorAddresses = validatorKeyStore.getAddresses();
59
+ // Verify that we can retrieve all required data from the key store
60
+ for (const address of validatorAddresses){
61
+ // Functions throw if required data is not available
62
+ let coinbase;
63
+ let feeRecipient;
64
+ try {
65
+ coinbase = validatorKeyStore.getCoinbaseAddress(address);
66
+ feeRecipient = validatorKeyStore.getFeeRecipient(address);
67
+ } catch (error) {
68
+ throw new Error(`Failed to retrieve required data for validator address ${address}, error: ${error}`);
44
69
  }
45
- });
46
- this.log.verbose(`Initialized validator with address ${this.keyStore.getAddress().toString()}`);
70
+ const publisherAddresses = validatorKeyStore.getPublisherAddresses(address);
71
+ if (!publisherAddresses.length) {
72
+ throw new Error(`No publisher addresses found for validator address ${address}`);
73
+ }
74
+ logger?.debug(`Validator ${address.toString()} configured with coinbase ${coinbase.toString()}, feeRecipient ${feeRecipient.toString()} and publishers ${publisherAddresses.map((x)=>x.toString()).join()}`);
75
+ }
47
76
  }
48
- static new(config, epochCache, p2pClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
49
- if (!config.validatorPrivateKey) {
50
- throw new InvalidValidatorPrivateKeyError();
77
+ async handleEpochCommitteeUpdate() {
78
+ try {
79
+ const { committee, epoch } = await this.epochCache.getCommittee('next');
80
+ if (!committee) {
81
+ this.log.trace(`No committee found for slot`);
82
+ return;
83
+ }
84
+ if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
85
+ const me = this.getValidatorAddresses();
86
+ const committeeSet = new Set(committee.map((v)=>v.toString()));
87
+ const inCommittee = me.filter((a)=>committeeSet.has(a.toString()));
88
+ if (inCommittee.length > 0) {
89
+ this.log.info(`Validators ${inCommittee.map((a)=>a.toString()).join(',')} are on the validator committee for epoch ${epoch}`);
90
+ } else {
91
+ this.log.verbose(`Validators ${me.map((a)=>a.toString()).join(', ')} are not on the validator committee for epoch ${epoch}`);
92
+ }
93
+ this.lastEpochForCommitteeUpdateLoop = epoch;
94
+ }
95
+ } catch (err) {
96
+ this.log.error(`Error updating epoch committee`, err);
51
97
  }
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();
98
+ }
99
+ static new(config, blockBuilder, epochCache, p2pClient, blockSource, l1ToL2MessageSource, txProvider, keyStoreManager, fileStoreBlobUploadClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient()) {
100
+ const metrics = new ValidatorMetrics(telemetry);
101
+ const blockProposalValidator = new BlockProposalValidator(epochCache, {
102
+ txsPermitted: !config.disableTransactions
103
+ });
104
+ const blockProposalHandler = new BlockProposalHandler(blockBuilder, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, config, metrics, dateProvider, telemetry);
105
+ const validator = new ValidatorClient(NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager), epochCache, p2pClient, blockProposalHandler, config, fileStoreBlobUploadClient, dateProvider, telemetry);
56
106
  return validator;
57
107
  }
108
+ getValidatorAddresses() {
109
+ return this.keyStore.getAddresses().filter((addr)=>!this.config.disabledValidators.some((disabled)=>disabled.equals(addr)));
110
+ }
111
+ getBlockProposalHandler() {
112
+ return this.blockProposalHandler;
113
+ }
114
+ // Proxy method for backwards compatibility with tests
115
+ reExecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages) {
116
+ return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
117
+ }
118
+ signWithAddress(addr, msg) {
119
+ return this.keyStore.signTypedDataWithAddress(addr, msg);
120
+ }
121
+ getCoinbaseForAttestor(attestor) {
122
+ return this.keyStore.getCoinbaseAddress(attestor);
123
+ }
124
+ getFeeRecipientForAttestor(attestor) {
125
+ return this.keyStore.getFeeRecipient(attestor);
126
+ }
127
+ getConfig() {
128
+ return this.config;
129
+ }
130
+ updateConfig(config) {
131
+ this.config = {
132
+ ...this.config,
133
+ ...config
134
+ };
135
+ }
58
136
  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()}`);
137
+ if (this.epochCacheUpdateLoop.isRunning()) {
138
+ this.log.warn(`Validator client already started`);
139
+ return;
140
+ }
141
+ await this.registerHandlers();
142
+ const myAddresses = this.getValidatorAddresses();
143
+ const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
144
+ this.log.info(`Started validator with addresses: ${myAddresses.map((a)=>a.toString()).join(', ')}`);
145
+ if (inCommittee.length > 0) {
146
+ this.log.info(`Addresses in current validator committee: ${inCommittee.map((a)=>a.toString()).join(', ')}`);
67
147
  }
68
148
  this.epochCacheUpdateLoop.start();
69
149
  return Promise.resolve();
@@ -71,155 +151,216 @@ import { ValidatorMetrics } from './metrics.js';
71
151
  async stop() {
72
152
  await this.epochCacheUpdateLoop.stop();
73
153
  }
74
- registerBlockProposalHandler() {
75
- const handler = (block)=>{
76
- return this.attestToProposal(block);
77
- };
78
- this.p2pClient.registerBlockProposalHandler(handler);
79
- }
80
- /**
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();
89
- 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())
95
- };
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`);
100
- return undefined;
154
+ /** Register handlers on the p2p client */ async registerHandlers() {
155
+ if (!this.hasRegisteredHandlers) {
156
+ this.hasRegisteredHandlers = true;
157
+ this.log.debug(`Registering validator handlers for p2p client`);
158
+ const handler = (block, proposalSender)=>this.attestToProposal(block, proposalSender);
159
+ this.p2pClient.registerBlockProposalHandler(handler);
160
+ const myAddresses = this.getValidatorAddresses();
161
+ this.p2pClient.registerThisValidatorAddresses(myAddresses);
162
+ await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
101
163
  }
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`);
164
+ }
165
+ async attestToProposal(proposal, proposalSender) {
166
+ const slotNumber = proposal.slotNumber;
167
+ const proposer = proposal.getSender();
168
+ // Reject proposals with invalid signatures
169
+ if (!proposer) {
170
+ this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
106
171
  return undefined;
107
172
  }
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);
173
+ // Check that I have any address in current committee before attesting
174
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
175
+ const partOfCommittee = inCommittee.length > 0;
176
+ const proposalInfo = {
177
+ ...proposal.toBlockInfo(),
178
+ proposer: proposer.toString()
179
+ };
180
+ this.log.info(`Received proposal for slot ${slotNumber}`, {
181
+ ...proposalInfo,
182
+ txHashes: proposal.txHashes.map((t)=>t.toString()),
183
+ fishermanMode: this.config.fishermanMode || false
184
+ });
185
+ // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
186
+ // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
187
+ // In fisherman mode, we always reexecute to validate proposals.
188
+ const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } = this.config;
189
+ const shouldReexecute = fishermanMode || slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute || partOfCommittee && validatorReexecute || alwaysReexecuteBlockProposals || this.fileStoreBlobUploadClient;
190
+ const validationResult = await this.blockProposalHandler.handleBlockProposal(proposal, proposalSender, !!shouldReexecute);
191
+ if (!validationResult.isValid) {
192
+ this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
193
+ const reason = validationResult.reason || 'unknown';
194
+ // Classify failure reason: bad proposal vs node issue
195
+ const badProposalReasons = [
196
+ 'invalid_proposal',
197
+ 'state_mismatch',
198
+ 'failed_txs',
199
+ 'in_hash_mismatch',
200
+ 'parent_block_wrong_slot'
201
+ ];
202
+ if (badProposalReasons.includes(reason)) {
203
+ this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
120
204
  } 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);
205
+ // Node issues so we can't attest
206
+ this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
207
+ }
208
+ // Slash invalid block proposals (can happen even when not in committee)
209
+ if (validationResult.reason && SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) && slashBroadcastedInvalidBlockPenalty > 0n) {
210
+ this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
211
+ this.slashInvalidBlock(proposal);
124
212
  }
125
213
  return undefined;
126
214
  }
215
+ // Check that I have any address in current committee before attesting
216
+ // In fisherman mode, we still create attestations for validation even if not in committee
217
+ if (!partOfCommittee && !this.config.fishermanMode) {
218
+ this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
219
+ return undefined;
220
+ }
127
221
  // Provided all of the above checks pass, we can attest to the proposal
128
- this.log.info(`Attesting to proposal for slot ${slotNumber}`, proposalInfo);
222
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} proposal for slot ${slotNumber}`, {
223
+ ...proposalInfo,
224
+ inCommittee: partOfCommittee,
225
+ fishermanMode: this.config.fishermanMode || false
226
+ });
227
+ this.metrics.incSuccessfulAttestations(inCommittee.length);
228
+ // Upload blobs to filestore after successful re-execution (fire-and-forget)
229
+ if (validationResult.reexecutionResult?.block && this.fileStoreBlobUploadClient) {
230
+ void Promise.resolve().then(async ()=>{
231
+ try {
232
+ const blobFields = validationResult.reexecutionResult.block.getCheckpointBlobFields();
233
+ const blobs = getBlobsPerL1Block(blobFields);
234
+ await this.fileStoreBlobUploadClient.saveBlobs(blobs, true);
235
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore from re-execution`, proposalInfo);
236
+ } catch (err) {
237
+ this.log.warn(`Failed to upload blobs from re-execution`, err);
238
+ }
239
+ });
240
+ }
129
241
  // If the above function does not throw an error, then we can attest to the proposal
130
- return this.validationService.attestToProposal(proposal);
131
- }
132
- /**
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
242
+ // Determine which validators should attest
243
+ let attestors;
244
+ if (partOfCommittee) {
245
+ attestors = inCommittee;
246
+ } else if (this.config.fishermanMode) {
247
+ // In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
248
+ attestors = this.getValidatorAddresses();
249
+ } else {
250
+ attestors = [];
251
+ }
252
+ // Only create attestations if we have attestors
253
+ if (attestors.length === 0) {
254
+ return undefined;
255
+ }
256
+ if (this.config.fishermanMode) {
257
+ // bail out early and don't save attestations to the pool in fisherman mode
258
+ this.log.info(`Creating attestations for proposal for slot ${slotNumber}`, {
259
+ ...proposalInfo,
260
+ attestors: attestors.map((a)=>a.toString())
261
+ });
262
+ return undefined;
263
+ }
264
+ return this.createBlockAttestationsFromProposal(proposal, attestors);
265
+ }
266
+ slashInvalidBlock(proposal) {
267
+ const proposer = proposal.getSender();
268
+ // Skip if signature is invalid (shouldn't happen since we validate earlier)
269
+ if (!proposer) {
270
+ this.log.warn(`Cannot slash proposal with invalid signature`);
271
+ return;
272
+ }
273
+ // Trim the set if it's too big.
274
+ if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
275
+ // remove oldest proposer. `values` is guaranteed to be in insertion order.
276
+ this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value);
277
+ }
278
+ this.proposersOfInvalidBlocks.add(proposer.toString());
279
+ this.emit(WANT_TO_SLASH_EVENT, [
280
+ {
281
+ validator: proposer,
282
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
283
+ offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
284
+ epochOrSlot: BigInt(proposal.slotNumber)
285
+ }
286
+ ]);
287
+ }
288
+ // TODO(palla/mbps): Block proposal should not require a checkpoint proposal
289
+ async createBlockProposal(blockNumber, header, archive, txs, proposerAddress, options) {
290
+ // TODO(palla/mbps): Prevent double proposals properly
291
+ // if (this.previousProposal?.slotNumber === header.slotNumber) {
292
+ // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
293
+ // return Promise.resolve(undefined);
294
+ // }
295
+ this.log.info(`Assembling block proposal for block ${blockNumber} slot ${header.slotNumber}`);
296
+ const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
297
+ ...options,
298
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
150
299
  });
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);
156
- }
157
- if (block.body.txEffects.length !== txHashes.length) {
158
- await this.metrics.recordFailedReexecution(proposal);
159
- throw new ReExTimeoutError();
160
- }
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();
165
- }
166
- }
167
- /**
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);
196
300
  this.previousProposal = newProposal;
197
301
  return newProposal;
198
302
  }
199
- broadcastBlockProposal(proposal) {
200
- this.p2pClient.broadcastProposal(proposal);
303
+ // TODO(palla/mbps): Effectively create a checkpoint proposal different from a block proposal
304
+ createCheckpointProposal(header, archive, txs, proposerAddress, options) {
305
+ this.log.info(`Assembling checkpoint proposal for slot ${header.slotNumber}`);
306
+ return this.createBlockProposal(0, header, archive, txs, proposerAddress, options);
307
+ }
308
+ async broadcastBlockProposal(proposal) {
309
+ await this.p2pClient.broadcastProposal(proposal);
310
+ }
311
+ async signAttestationsAndSigners(attestationsAndSigners, proposer) {
312
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
313
+ }
314
+ async collectOwnAttestations(proposal) {
315
+ const slot = proposal.payload.header.slotNumber;
316
+ const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
317
+ this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, {
318
+ inCommittee
319
+ });
320
+ const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
321
+ // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
322
+ // other nodes can see that our validators did attest to this block proposal, and do not slash us
323
+ // due to inactivity for missed attestations.
324
+ void this.p2pClient.broadcastAttestations(attestations).catch((err)=>{
325
+ this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
326
+ });
327
+ return attestations;
201
328
  }
202
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/7962)
203
329
  async collectAttestations(proposal, required, deadline) {
204
330
  // 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();
331
+ const slot = proposal.payload.header.slotNumber;
206
332
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
207
333
  if (+deadline < this.dateProvider.now()) {
208
334
  this.log.error(`Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`);
209
- throw new AttestationTimeoutError(required, slot);
335
+ throw new AttestationTimeoutError(0, required, slot);
210
336
  }
337
+ await this.collectOwnAttestations(proposal);
211
338
  const proposalId = proposal.archive.toString();
212
- const myAttestation = await this.validationService.attestToProposal(proposal);
339
+ const myAddresses = this.getValidatorAddresses();
213
340
  let attestations = [];
214
341
  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()));
342
+ // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
343
+ // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
344
+ const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter((attestation)=>{
345
+ if (!attestation.payload.equals(proposal.payload)) {
346
+ this.log.warn(`Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`, {
347
+ attestationPayload: attestation.payload,
348
+ proposalPayload: proposal.payload
349
+ });
350
+ return false;
351
+ }
352
+ return true;
353
+ });
354
+ // Log new attestations we collected
355
+ const oldSenders = attestations.map((attestation)=>attestation.getSender());
220
356
  for (const collected of collectedAttestations){
221
- const collectedSender = await collected.getSender();
222
- if (!oldSenders.some((sender)=>sender.equals(collectedSender))) {
357
+ const collectedSender = collected.getSender();
358
+ // Skip attestations with invalid signatures
359
+ if (!collectedSender) {
360
+ this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
361
+ continue;
362
+ }
363
+ if (!myAddresses.some((address)=>address.equals(collectedSender)) && !oldSenders.some((sender)=>sender?.equals(collectedSender))) {
223
364
  this.log.debug(`Received attestation for slot ${slot} from ${collectedSender.toString()}`);
224
365
  }
225
366
  }
@@ -230,17 +371,33 @@ import { ValidatorMetrics } from './metrics.js';
230
371
  }
231
372
  if (+deadline < this.dateProvider.now()) {
232
373
  this.log.error(`Timeout ${deadline.toISOString()} waiting for ${required} attestations for slot ${slot}`);
233
- throw new AttestationTimeoutError(required, slot);
374
+ throw new AttestationTimeoutError(attestations.length, required, slot);
234
375
  }
235
- this.log.debug(`Collected ${attestations.length} attestations so far`);
376
+ this.log.debug(`Collected ${attestations.length} of ${required} attestations so far`);
236
377
  await sleep(this.config.attestationPollingIntervalMs);
237
378
  }
238
379
  }
239
- }
240
- function validatePrivateKey(privateKey) {
241
- try {
242
- return Buffer32.fromString(privateKey);
243
- } catch (error) {
244
- throw new InvalidValidatorPrivateKeyError();
380
+ async createBlockAttestationsFromProposal(proposal, attestors = []) {
381
+ const attestations = await this.validationService.attestToProposal(proposal, attestors);
382
+ await this.p2pClient.addAttestations(attestations);
383
+ return attestations;
384
+ }
385
+ async handleAuthRequest(peer, msg) {
386
+ const authRequest = AuthRequest.fromBuffer(msg);
387
+ const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch((_)=>undefined);
388
+ if (statusMessage === undefined) {
389
+ return Buffer.alloc(0);
390
+ }
391
+ // Find a validator address that is in the set
392
+ const allRegisteredValidators = await this.epochCache.getRegisteredValidators();
393
+ const addressToUse = this.getValidatorAddresses().find((address)=>allRegisteredValidators.find((v)=>v.equals(address)) !== undefined);
394
+ if (addressToUse === undefined) {
395
+ // We don't have a registered address
396
+ return Buffer.alloc(0);
397
+ }
398
+ const payloadToSign = authRequest.getPayloadToSign();
399
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
400
+ const authResponse = new AuthResponse(statusMessage, signature);
401
+ return authResponse.toBuffer();
245
402
  }
246
403
  }