@aztec/validator-client 0.0.0-test.1 → 0.0.1-commit.5476d83

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 +52 -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 +34 -11
  10. package/dest/factory.d.ts +22 -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 +63 -16
  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 +50 -63
  35. package/dest/validator.d.ts.map +1 -1
  36. package/dest/validator.js +306 -172
  37. package/package.json +27 -21
  38. package/src/block_proposal_handler.ts +341 -0
  39. package/src/config.ts +48 -22
  40. package/src/duties/validation_service.ts +66 -14
  41. package/src/factory.ts +56 -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 +67 -17
  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 +416 -230
  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/src/validator.ts CHANGED
@@ -1,151 +1,240 @@
1
1
  import type { EpochCache } from '@aztec/epoch-cache';
2
- import { Buffer32 } from '@aztec/foundation/buffer';
3
- import type { Fr } from '@aztec/foundation/fields';
4
- import { createLogger } from '@aztec/foundation/log';
2
+ import { EpochNumber } from '@aztec/foundation/branded-types';
3
+ import type { EthAddress } from '@aztec/foundation/eth-address';
4
+ import type { Signature } from '@aztec/foundation/eth-signature';
5
+ import { Fr } from '@aztec/foundation/fields';
6
+ import { type Logger, createLogger } from '@aztec/foundation/log';
5
7
  import { RunningPromise } from '@aztec/foundation/running-promise';
6
8
  import { sleep } from '@aztec/foundation/sleep';
7
- import { DateProvider, type Timer } from '@aztec/foundation/timer';
8
- import type { P2P } from '@aztec/p2p';
9
- import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
10
- import type { L2Block } from '@aztec/stdlib/block';
11
- import type { BlockAttestation, BlockProposal } from '@aztec/stdlib/p2p';
12
- import type { BlockHeader, GlobalVariables, Tx, TxHash } from '@aztec/stdlib/tx';
13
- import { type TelemetryClient, WithTracer, getTelemetryClient } from '@aztec/telemetry-client';
14
-
15
- import type { ValidatorClientConfig } from './config.js';
9
+ import { DateProvider } from '@aztec/foundation/timer';
10
+ import type { KeystoreManager } from '@aztec/node-keystore';
11
+ import type { P2P, PeerId, TxProvider } from '@aztec/p2p';
12
+ import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
13
+ import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
14
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
15
+ import type { CommitteeAttestationsAndSigners, L2BlockSource } from '@aztec/stdlib/block';
16
+ import type { IFullNodeBlockBuilder, Validator, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
17
+ import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
18
+ import type { BlockAttestation, BlockProposal, BlockProposalOptions } from '@aztec/stdlib/p2p';
19
+ import type { CheckpointHeader } from '@aztec/stdlib/rollup';
20
+ import type { Tx } from '@aztec/stdlib/tx';
21
+ import { AttestationTimeoutError } from '@aztec/stdlib/validators';
22
+ import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
23
+
24
+ import { EventEmitter } from 'events';
25
+ import type { TypedDataDefinition } from 'viem';
26
+
27
+ import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
16
28
  import { ValidationService } from './duties/validation_service.js';
17
- import {
18
- AttestationTimeoutError,
19
- BlockBuilderNotProvidedError,
20
- InvalidValidatorPrivateKeyError,
21
- ReExFailedTxsError,
22
- ReExStateMismatchError,
23
- ReExTimeoutError,
24
- TransactionsNotAvailableError,
25
- } from './errors/validator.error.js';
26
- import type { ValidatorKeyStore } from './key_store/interface.js';
27
- import { LocalKeyStore } from './key_store/local_key_store.js';
29
+ import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
28
30
  import { ValidatorMetrics } from './metrics.js';
29
31
 
30
- /**
31
- * Callback function for building a block
32
- *
33
- * We reuse the sequencer's block building functionality for re-execution
34
- */
35
- type BlockBuilderCallback = (
36
- txs: Iterable<Tx> | AsyncIterableIterator<Tx>,
37
- globalVariables: GlobalVariables,
38
- opts?: { validateOnly?: boolean },
39
- ) => Promise<{
40
- block: L2Block;
41
- publicProcessorDuration: number;
42
- numTxs: number;
43
- numFailedTxs: number;
44
- blockBuildingTimer: Timer;
45
- }>;
46
-
47
- export interface Validator {
48
- start(): Promise<void>;
49
- registerBlockProposalHandler(): void;
50
- registerBlockBuilder(blockBuilder: BlockBuilderCallback): void;
51
-
52
- // Block validation responsibilities
53
- createBlockProposal(header: BlockHeader, archive: Fr, txs: TxHash[]): Promise<BlockProposal | undefined>;
54
- attestToProposal(proposal: BlockProposal): void;
55
-
56
- broadcastBlockProposal(proposal: BlockProposal): void;
57
- collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]>;
58
- }
32
+ // We maintain a set of proposers who have proposed invalid blocks.
33
+ // Just cap the set to avoid unbounded growth.
34
+ const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
35
+
36
+ // What errors from the block proposal handler result in slashing
37
+ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT: BlockProposalValidationFailureReason[] = [
38
+ 'state_mismatch',
39
+ 'failed_txs',
40
+ ];
59
41
 
60
42
  /**
61
43
  * Validator Client
62
44
  */
63
- export class ValidatorClient extends WithTracer implements Validator {
45
+ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter) implements Validator, Watcher {
46
+ public readonly tracer: Tracer;
64
47
  private validationService: ValidationService;
65
48
  private metrics: ValidatorMetrics;
49
+ private log: Logger;
50
+
51
+ // Whether it has already registered handlers on the p2p client
52
+ private hasRegisteredHandlers = false;
66
53
 
67
54
  // Used to check if we are sending the same proposal twice
68
55
  private previousProposal?: BlockProposal;
69
56
 
70
- // Callback registered to: sequencer.buildBlock
71
- private blockBuilder?: BlockBuilderCallback = undefined;
72
-
57
+ private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
73
58
  private epochCacheUpdateLoop: RunningPromise;
74
59
 
75
- private blockProposalValidator: BlockProposalValidator;
60
+ private proposersOfInvalidBlocks: Set<string> = new Set();
76
61
 
77
- constructor(
78
- private keyStore: ValidatorKeyStore,
62
+ protected constructor(
63
+ private keyStore: NodeKeystoreAdapter,
79
64
  private epochCache: EpochCache,
80
65
  private p2pClient: P2P,
81
- private config: ValidatorClientConfig,
66
+ private blockProposalHandler: BlockProposalHandler,
67
+ private config: ValidatorClientFullConfig,
82
68
  private dateProvider: DateProvider = new DateProvider(),
83
69
  telemetry: TelemetryClient = getTelemetryClient(),
84
- private log = createLogger('validator'),
70
+ log = createLogger('validator'),
85
71
  ) {
86
- // Instantiate tracer
87
- super(telemetry, 'Validator');
72
+ super();
73
+
74
+ // Create child logger with fisherman prefix if in fisherman mode
75
+ this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
76
+
77
+ this.tracer = telemetry.getTracer('Validator');
88
78
  this.metrics = new ValidatorMetrics(telemetry);
89
79
 
90
- this.validationService = new ValidationService(keyStore);
80
+ this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
91
81
 
92
- this.blockProposalValidator = new BlockProposalValidator(epochCache);
82
+ // Refresh epoch cache every second to trigger alert if participation in committee changes
83
+ this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
93
84
 
94
- // Refresh epoch cache every second to trigger commiteeChanged event
95
- this.epochCacheUpdateLoop = new RunningPromise(
96
- () =>
97
- this.epochCache
98
- .getCommittee()
99
- .then(() => {})
100
- .catch(err => log.error('Error updating validator committee', err)),
101
- log,
102
- 1000,
103
- );
85
+ const myAddresses = this.getValidatorAddresses();
86
+ this.log.verbose(`Initialized validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
87
+ }
104
88
 
105
- // Listen to commiteeChanged event to alert operator when their validator has entered the committee
106
- this.epochCache.on('committeeChanged', (newCommittee, epochNumber) => {
107
- const me = this.keyStore.getAddress();
108
- if (newCommittee.some(addr => addr.equals(me))) {
109
- this.log.info(`Validator ${me.toString()} is on the validator committee for epoch ${epochNumber}`);
110
- } else {
111
- this.log.verbose(`Validator ${me.toString()} not on the validator committee for epoch ${epochNumber}`);
89
+ public static validateKeyStoreConfiguration(keyStoreManager: KeystoreManager, logger?: Logger) {
90
+ const validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
91
+ const validatorAddresses = validatorKeyStore.getAddresses();
92
+ // Verify that we can retrieve all required data from the key store
93
+ for (const address of validatorAddresses) {
94
+ // Functions throw if required data is not available
95
+ let coinbase: EthAddress;
96
+ let feeRecipient: AztecAddress;
97
+ try {
98
+ coinbase = validatorKeyStore.getCoinbaseAddress(address);
99
+ feeRecipient = validatorKeyStore.getFeeRecipient(address);
100
+ } catch (error) {
101
+ throw new Error(`Failed to retrieve required data for validator address ${address}, error: ${error}`);
112
102
  }
113
- });
114
103
 
115
- this.log.verbose(`Initialized validator with address ${this.keyStore.getAddress().toString()}`);
104
+ const publisherAddresses = validatorKeyStore.getPublisherAddresses(address);
105
+ if (!publisherAddresses.length) {
106
+ throw new Error(`No publisher addresses found for validator address ${address}`);
107
+ }
108
+ logger?.debug(
109
+ `Validator ${address.toString()} configured with coinbase ${coinbase.toString()}, feeRecipient ${feeRecipient.toString()} and publishers ${publisherAddresses.map(x => x.toString()).join()}`,
110
+ );
111
+ }
112
+ }
113
+
114
+ private async handleEpochCommitteeUpdate() {
115
+ try {
116
+ const { committee, epoch } = await this.epochCache.getCommittee('next');
117
+ if (!committee) {
118
+ this.log.trace(`No committee found for slot`);
119
+ return;
120
+ }
121
+ if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
122
+ const me = this.getValidatorAddresses();
123
+ const committeeSet = new Set(committee.map(v => v.toString()));
124
+ const inCommittee = me.filter(a => committeeSet.has(a.toString()));
125
+ if (inCommittee.length > 0) {
126
+ this.log.info(
127
+ `Validators ${inCommittee.map(a => a.toString()).join(',')} are on the validator committee for epoch ${epoch}`,
128
+ );
129
+ } else {
130
+ this.log.verbose(
131
+ `Validators ${me.map(a => a.toString()).join(', ')} are not on the validator committee for epoch ${epoch}`,
132
+ );
133
+ }
134
+ this.lastEpochForCommitteeUpdateLoop = epoch;
135
+ }
136
+ } catch (err) {
137
+ this.log.error(`Error updating epoch committee`, err);
138
+ }
116
139
  }
117
140
 
118
141
  static new(
119
- config: ValidatorClientConfig,
142
+ config: ValidatorClientFullConfig,
143
+ blockBuilder: IFullNodeBlockBuilder,
120
144
  epochCache: EpochCache,
121
145
  p2pClient: P2P,
146
+ blockSource: L2BlockSource,
147
+ l1ToL2MessageSource: L1ToL2MessageSource,
148
+ txProvider: TxProvider,
149
+ keyStoreManager: KeystoreManager,
122
150
  dateProvider: DateProvider = new DateProvider(),
123
151
  telemetry: TelemetryClient = getTelemetryClient(),
124
152
  ) {
125
- if (!config.validatorPrivateKey) {
126
- throw new InvalidValidatorPrivateKeyError();
127
- }
153
+ const metrics = new ValidatorMetrics(telemetry);
154
+ const blockProposalValidator = new BlockProposalValidator(epochCache, {
155
+ txsPermitted: !config.disableTransactions,
156
+ });
157
+ const blockProposalHandler = new BlockProposalHandler(
158
+ blockBuilder,
159
+ blockSource,
160
+ l1ToL2MessageSource,
161
+ txProvider,
162
+ blockProposalValidator,
163
+ config,
164
+ metrics,
165
+ dateProvider,
166
+ telemetry,
167
+ );
128
168
 
129
- const privateKey = validatePrivateKey(config.validatorPrivateKey);
130
- const localKeyStore = new LocalKeyStore(privateKey);
169
+ const validator = new ValidatorClient(
170
+ NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager),
171
+ epochCache,
172
+ p2pClient,
173
+ blockProposalHandler,
174
+ config,
175
+ dateProvider,
176
+ telemetry,
177
+ );
131
178
 
132
- const validator = new ValidatorClient(localKeyStore, epochCache, p2pClient, config, dateProvider, telemetry);
133
- validator.registerBlockProposalHandler();
134
179
  return validator;
135
180
  }
136
181
 
182
+ public getValidatorAddresses() {
183
+ return this.keyStore
184
+ .getAddresses()
185
+ .filter(addr => !this.config.disabledValidators.some(disabled => disabled.equals(addr)));
186
+ }
187
+
188
+ public getBlockProposalHandler() {
189
+ return this.blockProposalHandler;
190
+ }
191
+
192
+ // Proxy method for backwards compatibility with tests
193
+ public reExecuteTransactions(
194
+ proposal: BlockProposal,
195
+ blockNumber: number,
196
+ txs: any[],
197
+ l1ToL2Messages: Fr[],
198
+ ): Promise<any> {
199
+ return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
200
+ }
201
+
202
+ public signWithAddress(addr: EthAddress, msg: TypedDataDefinition) {
203
+ return this.keyStore.signTypedDataWithAddress(addr, msg);
204
+ }
205
+
206
+ public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
207
+ return this.keyStore.getCoinbaseAddress(attestor);
208
+ }
209
+
210
+ public getFeeRecipientForAttestor(attestor: EthAddress): AztecAddress {
211
+ return this.keyStore.getFeeRecipient(attestor);
212
+ }
213
+
214
+ public getConfig(): ValidatorClientFullConfig {
215
+ return this.config;
216
+ }
217
+
218
+ public updateConfig(config: Partial<ValidatorClientFullConfig>) {
219
+ this.config = { ...this.config, ...config };
220
+ }
221
+
137
222
  public async start() {
138
- // Sync the committee from the smart contract
139
- // https://github.com/AztecProtocol/aztec-packages/issues/7962
223
+ if (this.epochCacheUpdateLoop.isRunning()) {
224
+ this.log.warn(`Validator client already started`);
225
+ return;
226
+ }
140
227
 
141
- const me = this.keyStore.getAddress();
142
- const inCommittee = await this.epochCache.isInCommittee(me);
143
- if (inCommittee) {
144
- this.log.info(`Started validator with address ${me.toString()} in current validator committee`);
145
- } else {
146
- this.log.info(`Started validator with address ${me.toString()}`);
228
+ await this.registerHandlers();
229
+
230
+ const myAddresses = this.getValidatorAddresses();
231
+ const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
232
+ this.log.info(`Started validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
233
+ if (inCommittee.length > 0) {
234
+ this.log.info(`Addresses in current validator committee: ${inCommittee.map(a => a.toString()).join(', ')}`);
147
235
  }
148
236
  this.epochCacheUpdateLoop.start();
237
+
149
238
  return Promise.resolve();
150
239
  }
151
240
 
@@ -153,185 +242,258 @@ export class ValidatorClient extends WithTracer implements Validator {
153
242
  await this.epochCacheUpdateLoop.stop();
154
243
  }
155
244
 
156
- public registerBlockProposalHandler() {
157
- const handler = (block: BlockProposal): Promise<BlockAttestation | undefined> => {
158
- return this.attestToProposal(block);
159
- };
160
- this.p2pClient.registerBlockProposalHandler(handler);
161
- }
245
+ /** Register handlers on the p2p client */
246
+ public async registerHandlers() {
247
+ if (!this.hasRegisteredHandlers) {
248
+ this.hasRegisteredHandlers = true;
249
+ this.log.debug(`Registering validator handlers for p2p client`);
162
250
 
163
- /**
164
- * Register a callback function for building a block
165
- *
166
- * We reuse the sequencer's block building functionality for re-execution
167
- */
168
- public registerBlockBuilder(blockBuilder: BlockBuilderCallback) {
169
- this.blockBuilder = blockBuilder;
170
- }
251
+ const handler = (block: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> =>
252
+ this.attestToProposal(block, proposalSender);
253
+ this.p2pClient.registerBlockProposalHandler(handler);
171
254
 
172
- async attestToProposal(proposal: BlockProposal): Promise<BlockAttestation | undefined> {
173
- const slotNumber = proposal.slotNumber.toNumber();
174
- const proposalInfo = {
175
- slotNumber,
176
- blockNumber: proposal.payload.header.globalVariables.blockNumber.toNumber(),
177
- archive: proposal.payload.archive.toString(),
178
- txCount: proposal.payload.txHashes.length,
179
- txHashes: proposal.payload.txHashes.map(txHash => txHash.toString()),
180
- };
181
- this.log.verbose(`Received request to attest for slot ${slotNumber}`);
182
-
183
- // Check that I am in the committee
184
- if (!(await this.epochCache.isInCommittee(this.keyStore.getAddress()))) {
185
- this.log.verbose(`Not in the committee, skipping attestation`);
186
- return undefined;
187
- }
255
+ const myAddresses = this.getValidatorAddresses();
256
+ this.p2pClient.registerThisValidatorAddresses(myAddresses);
188
257
 
189
- // Check that the proposal is from the current proposer, or the next proposer.
190
- const invalidProposal = await this.blockProposalValidator.validate(proposal);
191
- if (invalidProposal) {
192
- this.log.verbose(`Proposal is not valid, skipping attestation`);
193
- return undefined;
258
+ await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
194
259
  }
260
+ }
195
261
 
196
- // Check that all of the transactions in the proposal are available in the tx pool before attesting
197
- this.log.verbose(`Processing attestation for slot ${slotNumber}`, proposalInfo);
198
- try {
199
- await this.ensureTransactionsAreAvailable(proposal);
262
+ async attestToProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> {
263
+ const slotNumber = proposal.slotNumber;
264
+ const proposer = proposal.getSender();
200
265
 
201
- if (this.config.validatorReexecute) {
202
- this.log.verbose(`Re-executing transactions in the proposal before attesting`);
203
- await this.reExecuteTransactions(proposal);
204
- }
205
- } catch (error: any) {
206
- // If the transactions are not available, then we should not attempt to attest
207
- if (error instanceof TransactionsNotAvailableError) {
208
- this.log.error(`Transactions not available, skipping attestation`, error, proposalInfo);
209
- } else {
210
- // This branch most commonly be hit if the transactions are available, but the re-execution fails
211
- // Catch all error handler
212
- this.log.error(`Failed to attest to proposal`, error, proposalInfo);
213
- }
266
+ // Reject proposals with invalid signatures
267
+ if (!proposer) {
268
+ this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
214
269
  return undefined;
215
270
  }
216
271
 
217
- // Provided all of the above checks pass, we can attest to the proposal
218
- this.log.info(`Attesting to proposal for slot ${slotNumber}`, proposalInfo);
272
+ // Check that I have any address in current committee before attesting
273
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
274
+ const partOfCommittee = inCommittee.length > 0;
219
275
 
220
- // If the above function does not throw an error, then we can attest to the proposal
221
- return this.validationService.attestToProposal(proposal);
222
- }
276
+ const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
277
+ this.log.info(`Received proposal for slot ${slotNumber}`, {
278
+ ...proposalInfo,
279
+ txHashes: proposal.txHashes.map(t => t.toString()),
280
+ fishermanMode: this.config.fishermanMode || false,
281
+ });
223
282
 
224
- /**
225
- * Re-execute the transactions in the proposal and check that the state updates match the header state
226
- * @param proposal - The proposal to re-execute
227
- */
228
- async reExecuteTransactions(proposal: BlockProposal) {
229
- const { header, txHashes } = proposal.payload;
283
+ // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
284
+ // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
285
+ // In fisherman mode, we always reexecute to validate proposals.
286
+ const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
287
+ this.config;
288
+ const shouldReexecute =
289
+ fishermanMode ||
290
+ (slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
291
+ (partOfCommittee && validatorReexecute) ||
292
+ alwaysReexecuteBlockProposals;
293
+
294
+ const validationResult = await this.blockProposalHandler.handleBlockProposal(
295
+ proposal,
296
+ proposalSender,
297
+ !!shouldReexecute,
298
+ );
230
299
 
231
- const txs = (await Promise.all(txHashes.map(tx => this.p2pClient.getTxByHash(tx)))).filter(
232
- tx => tx !== undefined,
233
- ) as Tx[];
300
+ if (!validationResult.isValid) {
301
+ this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
302
+
303
+ const reason = validationResult.reason || 'unknown';
304
+ // Classify failure reason: bad proposal vs node issue
305
+ const badProposalReasons: BlockProposalValidationFailureReason[] = [
306
+ 'invalid_proposal',
307
+ 'state_mismatch',
308
+ 'failed_txs',
309
+ 'in_hash_mismatch',
310
+ 'parent_block_wrong_slot',
311
+ ];
312
+
313
+ if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
314
+ this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
315
+ } else {
316
+ // Node issues so we can't attest
317
+ this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
318
+ }
234
319
 
235
- // If we cannot request all of the transactions, then we should fail
236
- if (txs.length !== txHashes.length) {
237
- throw new TransactionsNotAvailableError(txHashes);
320
+ // Slash invalid block proposals (can happen even when not in committee)
321
+ if (
322
+ validationResult.reason &&
323
+ SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) &&
324
+ slashBroadcastedInvalidBlockPenalty > 0n
325
+ ) {
326
+ this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
327
+ this.slashInvalidBlock(proposal);
328
+ }
329
+ return undefined;
238
330
  }
239
331
 
240
- // Assertion: This check will fail if re-execution is not enabled
241
- if (this.blockBuilder === undefined) {
242
- throw new BlockBuilderNotProvidedError();
332
+ // Check that I have any address in current committee before attesting
333
+ // In fisherman mode, we still create attestations for validation even if not in committee
334
+ if (!partOfCommittee && !this.config.fishermanMode) {
335
+ this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
336
+ return undefined;
243
337
  }
244
338
 
245
- // Use the sequencer's block building logic to re-execute the transactions
246
- const stopTimer = this.metrics.reExecutionTimer();
247
- const { block, numFailedTxs } = await this.blockBuilder(txs, header.globalVariables, {
248
- validateOnly: true,
339
+ // Provided all of the above checks pass, we can attest to the proposal
340
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} proposal for slot ${slotNumber}`, {
341
+ ...proposalInfo,
342
+ inCommittee: partOfCommittee,
343
+ fishermanMode: this.config.fishermanMode || false,
249
344
  });
250
- stopTimer();
251
345
 
252
- this.log.verbose(`Transaction re-execution complete`);
346
+ this.metrics.incSuccessfulAttestations(inCommittee.length);
253
347
 
254
- if (numFailedTxs > 0) {
255
- await this.metrics.recordFailedReexecution(proposal);
256
- throw new ReExFailedTxsError(numFailedTxs);
348
+ // If the above function does not throw an error, then we can attest to the proposal
349
+ // Determine which validators should attest
350
+ let attestors: EthAddress[];
351
+ if (partOfCommittee) {
352
+ attestors = inCommittee;
353
+ } else if (this.config.fishermanMode) {
354
+ // In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
355
+ attestors = this.getValidatorAddresses();
356
+ } else {
357
+ attestors = [];
257
358
  }
258
359
 
259
- if (block.body.txEffects.length !== txHashes.length) {
260
- await this.metrics.recordFailedReexecution(proposal);
261
- throw new ReExTimeoutError();
360
+ // Only create attestations if we have attestors
361
+ if (attestors.length === 0) {
362
+ return undefined;
262
363
  }
263
364
 
264
- // This function will throw an error if state updates do not match
265
- if (!block.archive.root.equals(proposal.archive)) {
266
- await this.metrics.recordFailedReexecution(proposal);
267
- throw new ReExStateMismatchError();
365
+ if (this.config.fishermanMode) {
366
+ // bail out early and don't save attestations to the pool in fisherman mode
367
+ this.log.info(`Creating attestations for proposal for slot ${slotNumber}`, {
368
+ ...proposalInfo,
369
+ attestors: attestors.map(a => a.toString()),
370
+ });
371
+ return undefined;
268
372
  }
373
+ return this.createBlockAttestationsFromProposal(proposal, attestors);
269
374
  }
270
375
 
271
- /**
272
- * Ensure that all of the transactions in the proposal are available in the tx pool before attesting
273
- *
274
- * 1. Check if the local tx pool contains all of the transactions in the proposal
275
- * 2. If any transactions are not in the local tx pool, request them from the network
276
- * 3. If we cannot retrieve them from the network, throw an error
277
- * @param proposal - The proposal to attest to
278
- */
279
- async ensureTransactionsAreAvailable(proposal: BlockProposal) {
280
- const txHashes: TxHash[] = proposal.payload.txHashes;
281
- const transactionStatuses = await Promise.all(txHashes.map(txHash => this.p2pClient.getTxStatus(txHash)));
282
-
283
- const missingTxs = txHashes.filter((_, index) => !['pending', 'mined'].includes(transactionStatuses[index] ?? ''));
284
-
285
- if (missingTxs.length === 0) {
286
- return; // All transactions are available
287
- }
376
+ private slashInvalidBlock(proposal: BlockProposal) {
377
+ const proposer = proposal.getSender();
288
378
 
289
- this.log.verbose(`Missing ${missingTxs.length} transactions in the tx pool, requesting from the network`);
379
+ // Skip if signature is invalid (shouldn't happen since we validate earlier)
380
+ if (!proposer) {
381
+ this.log.warn(`Cannot slash proposal with invalid signature`);
382
+ return;
383
+ }
290
384
 
291
- const requestedTxs = await this.p2pClient.requestTxs(missingTxs);
292
- if (requestedTxs.some(tx => tx === undefined)) {
293
- throw new TransactionsNotAvailableError(missingTxs);
385
+ // Trim the set if it's too big.
386
+ if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
387
+ // remove oldest proposer. `values` is guaranteed to be in insertion order.
388
+ this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value!);
294
389
  }
390
+
391
+ this.proposersOfInvalidBlocks.add(proposer.toString());
392
+
393
+ this.emit(WANT_TO_SLASH_EVENT, [
394
+ {
395
+ validator: proposer,
396
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
397
+ offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
398
+ epochOrSlot: BigInt(proposal.slotNumber),
399
+ },
400
+ ]);
295
401
  }
296
402
 
297
- async createBlockProposal(header: BlockHeader, archive: Fr, txs: TxHash[]): Promise<BlockProposal | undefined> {
298
- if (this.previousProposal?.slotNumber.equals(header.globalVariables.slotNumber)) {
403
+ async createBlockProposal(
404
+ blockNumber: number,
405
+ header: CheckpointHeader,
406
+ archive: Fr,
407
+ txs: Tx[],
408
+ proposerAddress: EthAddress | undefined,
409
+ options: BlockProposalOptions,
410
+ ): Promise<BlockProposal | undefined> {
411
+ if (this.previousProposal?.slotNumber === header.slotNumber) {
299
412
  this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
300
413
  return Promise.resolve(undefined);
301
414
  }
302
415
 
303
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs);
416
+ const newProposal = await this.validationService.createBlockProposal(header, archive, txs, proposerAddress, {
417
+ ...options,
418
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
419
+ });
304
420
  this.previousProposal = newProposal;
305
421
  return newProposal;
306
422
  }
307
423
 
308
- broadcastBlockProposal(proposal: BlockProposal): void {
309
- this.p2pClient.broadcastProposal(proposal);
424
+ async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
425
+ await this.p2pClient.broadcastProposal(proposal);
426
+ }
427
+
428
+ async signAttestationsAndSigners(
429
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
430
+ proposer: EthAddress,
431
+ ): Promise<Signature> {
432
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
433
+ }
434
+
435
+ async collectOwnAttestations(proposal: BlockProposal): Promise<BlockAttestation[]> {
436
+ const slot = proposal.payload.header.slotNumber;
437
+ const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
438
+ this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
439
+ const attestations = await this.createBlockAttestationsFromProposal(proposal, inCommittee);
440
+
441
+ // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
442
+ // other nodes can see that our validators did attest to this block proposal, and do not slash us
443
+ // due to inactivity for missed attestations.
444
+ void this.p2pClient.broadcastAttestations(attestations).catch(err => {
445
+ this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
446
+ });
447
+ return attestations;
310
448
  }
311
449
 
312
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/7962)
313
450
  async collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]> {
314
451
  // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
315
- const slot = proposal.payload.header.globalVariables.slotNumber.toBigInt();
452
+ const slot = proposal.payload.header.slotNumber;
316
453
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
317
454
 
318
455
  if (+deadline < this.dateProvider.now()) {
319
456
  this.log.error(
320
457
  `Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`,
321
458
  );
322
- throw new AttestationTimeoutError(required, slot);
459
+ throw new AttestationTimeoutError(0, required, slot);
323
460
  }
324
461
 
462
+ await this.collectOwnAttestations(proposal);
463
+
325
464
  const proposalId = proposal.archive.toString();
326
- const myAttestation = await this.validationService.attestToProposal(proposal);
465
+ const myAddresses = this.getValidatorAddresses();
327
466
 
328
467
  let attestations: BlockAttestation[] = [];
329
468
  while (true) {
330
- const collectedAttestations = [myAttestation, ...(await this.p2pClient.getAttestationsForSlot(slot, proposalId))];
331
- const oldSenders = await Promise.all(attestations.map(attestation => attestation.getSender()));
469
+ // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
470
+ // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
471
+ const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter(
472
+ attestation => {
473
+ if (!attestation.payload.equals(proposal.payload)) {
474
+ this.log.warn(
475
+ `Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`,
476
+ { attestationPayload: attestation.payload, proposalPayload: proposal.payload },
477
+ );
478
+ return false;
479
+ }
480
+ return true;
481
+ },
482
+ );
483
+
484
+ // Log new attestations we collected
485
+ const oldSenders = attestations.map(attestation => attestation.getSender());
332
486
  for (const collected of collectedAttestations) {
333
- const collectedSender = await collected.getSender();
334
- if (!oldSenders.some(sender => sender.equals(collectedSender))) {
487
+ const collectedSender = collected.getSender();
488
+ // Skip attestations with invalid signatures
489
+ if (!collectedSender) {
490
+ this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
491
+ continue;
492
+ }
493
+ if (
494
+ !myAddresses.some(address => address.equals(collectedSender)) &&
495
+ !oldSenders.some(sender => sender?.equals(collectedSender))
496
+ ) {
335
497
  this.log.debug(`Received attestation for slot ${slot} from ${collectedSender.toString()}`);
336
498
  }
337
499
  }
@@ -344,19 +506,43 @@ export class ValidatorClient extends WithTracer implements Validator {
344
506
 
345
507
  if (+deadline < this.dateProvider.now()) {
346
508
  this.log.error(`Timeout ${deadline.toISOString()} waiting for ${required} attestations for slot ${slot}`);
347
- throw new AttestationTimeoutError(required, slot);
509
+ throw new AttestationTimeoutError(attestations.length, required, slot);
348
510
  }
349
511
 
350
- this.log.debug(`Collected ${attestations.length} attestations so far`);
512
+ this.log.debug(`Collected ${attestations.length} of ${required} attestations so far`);
351
513
  await sleep(this.config.attestationPollingIntervalMs);
352
514
  }
353
515
  }
354
- }
355
516
 
356
- function validatePrivateKey(privateKey: string): Buffer32 {
357
- try {
358
- return Buffer32.fromString(privateKey);
359
- } catch (error) {
360
- throw new InvalidValidatorPrivateKeyError();
517
+ private async createBlockAttestationsFromProposal(
518
+ proposal: BlockProposal,
519
+ attestors: EthAddress[] = [],
520
+ ): Promise<BlockAttestation[]> {
521
+ const attestations = await this.validationService.attestToProposal(proposal, attestors);
522
+ await this.p2pClient.addAttestations(attestations);
523
+ return attestations;
524
+ }
525
+
526
+ private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
527
+ const authRequest = AuthRequest.fromBuffer(msg);
528
+ const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);
529
+ if (statusMessage === undefined) {
530
+ return Buffer.alloc(0);
531
+ }
532
+
533
+ // Find a validator address that is in the set
534
+ const allRegisteredValidators = await this.epochCache.getRegisteredValidators();
535
+ const addressToUse = this.getValidatorAddresses().find(
536
+ address => allRegisteredValidators.find(v => v.equals(address)) !== undefined,
537
+ );
538
+ if (addressToUse === undefined) {
539
+ // We don't have a registered address
540
+ return Buffer.alloc(0);
541
+ }
542
+
543
+ const payloadToSign = authRequest.getPayloadToSign();
544
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
545
+ const authResponse = new AuthResponse(statusMessage, signature);
546
+ return authResponse.toBuffer();
361
547
  }
362
548
  }