@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
@@ -0,0 +1,341 @@
1
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
+ import { SlotNumber } from '@aztec/foundation/branded-types';
3
+ import { TimeoutError } from '@aztec/foundation/error';
4
+ import { Fr } from '@aztec/foundation/fields';
5
+ import { createLogger } from '@aztec/foundation/log';
6
+ import { retryUntil } from '@aztec/foundation/retry';
7
+ import { DateProvider, Timer } from '@aztec/foundation/timer';
8
+ import type { P2P, PeerId } from '@aztec/p2p';
9
+ import { TxProvider } from '@aztec/p2p';
10
+ import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
11
+ import type { L2Block, L2BlockSource } from '@aztec/stdlib/block';
12
+ import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
13
+ import type { IFullNodeBlockBuilder, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
14
+ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
15
+ import { type BlockProposal, ConsensusPayload } from '@aztec/stdlib/p2p';
16
+ import { BlockHeader, type FailedTx, GlobalVariables, type Tx } from '@aztec/stdlib/tx';
17
+ import {
18
+ ReExFailedTxsError,
19
+ ReExStateMismatchError,
20
+ ReExTimeoutError,
21
+ TransactionsNotAvailableError,
22
+ } from '@aztec/stdlib/validators';
23
+ import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
24
+
25
+ import type { ValidatorMetrics } from './metrics.js';
26
+
27
+ export type BlockProposalValidationFailureReason =
28
+ | 'invalid_proposal'
29
+ | 'parent_block_not_found'
30
+ | 'parent_block_wrong_slot'
31
+ | 'in_hash_mismatch'
32
+ | 'block_number_already_exists'
33
+ | 'txs_not_available'
34
+ | 'state_mismatch'
35
+ | 'failed_txs'
36
+ | 'timeout'
37
+ | 'unknown_error';
38
+
39
+ type ReexecuteTransactionsResult = {
40
+ block: L2Block;
41
+ failedTxs: FailedTx[];
42
+ reexecutionTimeMs: number;
43
+ totalManaUsed: number;
44
+ };
45
+
46
+ export type BlockProposalValidationSuccessResult = {
47
+ isValid: true;
48
+ blockNumber: number;
49
+ reexecutionResult?: ReexecuteTransactionsResult;
50
+ };
51
+
52
+ export type BlockProposalValidationFailureResult = {
53
+ isValid: false;
54
+ reason: BlockProposalValidationFailureReason;
55
+ blockNumber?: number;
56
+ reexecutionResult?: ReexecuteTransactionsResult;
57
+ };
58
+
59
+ export type BlockProposalValidationResult = BlockProposalValidationSuccessResult | BlockProposalValidationFailureResult;
60
+
61
+ export class BlockProposalHandler {
62
+ public readonly tracer: Tracer;
63
+
64
+ constructor(
65
+ private blockBuilder: IFullNodeBlockBuilder,
66
+ private blockSource: L2BlockSource,
67
+ private l1ToL2MessageSource: L1ToL2MessageSource,
68
+ private txProvider: TxProvider,
69
+ private blockProposalValidator: BlockProposalValidator,
70
+ private config: ValidatorClientFullConfig,
71
+ private metrics?: ValidatorMetrics,
72
+ private dateProvider: DateProvider = new DateProvider(),
73
+ telemetry: TelemetryClient = getTelemetryClient(),
74
+ private log = createLogger('validator:block-proposal-handler'),
75
+ ) {
76
+ if (config.fishermanMode) {
77
+ this.log = this.log.createChild('[FISHERMAN]');
78
+ }
79
+ this.tracer = telemetry.getTracer('BlockProposalHandler');
80
+ }
81
+
82
+ registerForReexecution(p2pClient: P2P): BlockProposalHandler {
83
+ const handler = async (proposal: BlockProposal, proposalSender: PeerId) => {
84
+ try {
85
+ const result = await this.handleBlockProposal(proposal, proposalSender, true);
86
+ if (result.isValid) {
87
+ this.log.info(`Non-validator reexecution completed for slot ${proposal.slotNumber}`, {
88
+ blockNumber: result.blockNumber,
89
+ reexecutionTimeMs: result.reexecutionResult?.reexecutionTimeMs,
90
+ totalManaUsed: result.reexecutionResult?.totalManaUsed,
91
+ numTxs: result.reexecutionResult?.block?.body?.txEffects?.length ?? 0,
92
+ });
93
+ } else {
94
+ this.log.warn(`Non-validator reexecution failed for slot ${proposal.slotNumber}`, {
95
+ blockNumber: result.blockNumber,
96
+ reason: result.reason,
97
+ });
98
+ }
99
+ } catch (error) {
100
+ this.log.error('Error processing block proposal in non-validator handler', error);
101
+ }
102
+ return undefined; // Non-validator nodes don't return attestations
103
+ };
104
+
105
+ p2pClient.registerBlockProposalHandler(handler);
106
+ return this;
107
+ }
108
+
109
+ async handleBlockProposal(
110
+ proposal: BlockProposal,
111
+ proposalSender: PeerId,
112
+ shouldReexecute: boolean,
113
+ ): Promise<BlockProposalValidationResult> {
114
+ const slotNumber = proposal.slotNumber;
115
+ const proposer = proposal.getSender();
116
+ const config = this.blockBuilder.getConfig();
117
+
118
+ // Reject proposals with invalid signatures
119
+ if (!proposer) {
120
+ this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
121
+ return { isValid: false, reason: 'invalid_proposal' };
122
+ }
123
+
124
+ const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
125
+ this.log.info(`Processing proposal for slot ${slotNumber}`, {
126
+ ...proposalInfo,
127
+ txHashes: proposal.txHashes.map(t => t.toString()),
128
+ });
129
+
130
+ // Check that the proposal is from the current proposer, or the next proposer
131
+ // This should have been handled by the p2p layer, but we double check here out of caution
132
+ const invalidProposal = await this.blockProposalValidator.validate(proposal);
133
+ if (invalidProposal) {
134
+ this.log.warn(`Proposal is not valid, skipping processing`, proposalInfo);
135
+ return { isValid: false, reason: 'invalid_proposal' };
136
+ }
137
+
138
+ // Check that the parent proposal is a block we know, otherwise reexecution would fail
139
+ const parentBlockHeader = await this.getParentBlock(proposal);
140
+ if (parentBlockHeader === undefined) {
141
+ this.log.warn(`Parent block for proposal not found, skipping processing`, proposalInfo);
142
+ return { isValid: false, reason: 'parent_block_not_found' };
143
+ }
144
+
145
+ // Check that the parent block's slot is less than the proposal's slot (should not happen, but we check anyway)
146
+ if (parentBlockHeader !== 'genesis' && parentBlockHeader.getSlot() >= slotNumber) {
147
+ this.log.warn(`Parent block slot is greater than or equal to proposal slot, skipping processing`, {
148
+ parentBlockSlot: parentBlockHeader.getSlot().toString(),
149
+ proposalSlot: slotNumber.toString(),
150
+ ...proposalInfo,
151
+ });
152
+ return { isValid: false, reason: 'parent_block_wrong_slot' };
153
+ }
154
+
155
+ // Compute the block number based on the parent block
156
+ const blockNumber = parentBlockHeader === 'genesis' ? INITIAL_L2_BLOCK_NUM : parentBlockHeader.getBlockNumber() + 1;
157
+
158
+ // Check that this block number does not exist already
159
+ const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
160
+ if (existingBlock) {
161
+ this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
162
+ return { isValid: false, blockNumber, reason: 'block_number_already_exists' };
163
+ }
164
+
165
+ // Collect txs from the proposal. We start doing this as early as possible,
166
+ // and we do it even if we don't plan to re-execute the txs, so that we have them if another node needs them.
167
+ const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
168
+ pinnedPeer: proposalSender,
169
+ deadline: this.getReexecutionDeadline(slotNumber, config),
170
+ });
171
+
172
+ // Check that I have the same set of l1ToL2Messages as the proposal
173
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(blockNumber);
174
+ const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
175
+ const proposalInHash = proposal.payload.header.contentCommitment.inHash;
176
+ if (!computedInHash.equals(proposalInHash)) {
177
+ this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
178
+ proposalInHash: proposalInHash.toString(),
179
+ computedInHash: computedInHash.toString(),
180
+ ...proposalInfo,
181
+ });
182
+ return { isValid: false, blockNumber, reason: 'in_hash_mismatch' };
183
+ }
184
+
185
+ // Check that all of the transactions in the proposal are available
186
+ if (missingTxs.length > 0) {
187
+ this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, { ...proposalInfo, missingTxs });
188
+ return { isValid: false, blockNumber, reason: 'txs_not_available' };
189
+ }
190
+
191
+ // Try re-executing the transactions in the proposal if needed
192
+ let reexecutionResult;
193
+ if (shouldReexecute) {
194
+ try {
195
+ this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
196
+ reexecutionResult = await this.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
197
+ } catch (error) {
198
+ this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
199
+ const reason = this.getReexecuteFailureReason(error);
200
+ return { isValid: false, blockNumber, reason, reexecutionResult };
201
+ }
202
+ }
203
+
204
+ this.log.info(`Successfully processed proposal for slot ${slotNumber}`, proposalInfo);
205
+ return { isValid: true, blockNumber, reexecutionResult };
206
+ }
207
+
208
+ private async getParentBlock(proposal: BlockProposal): Promise<'genesis' | BlockHeader | undefined> {
209
+ const parentArchive = proposal.payload.header.lastArchiveRoot;
210
+ const slot = proposal.slotNumber;
211
+ const config = this.blockBuilder.getConfig();
212
+ const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
213
+
214
+ if (parentArchive.equals(genesisArchiveRoot)) {
215
+ return 'genesis';
216
+ }
217
+
218
+ const deadline = this.getReexecutionDeadline(slot, config);
219
+ const currentTime = this.dateProvider.now();
220
+ const timeoutDurationMs = deadline.getTime() - currentTime;
221
+
222
+ try {
223
+ return (
224
+ (await this.blockSource.getBlockHeaderByArchive(parentArchive)) ??
225
+ (timeoutDurationMs <= 0
226
+ ? undefined
227
+ : await retryUntil(
228
+ () =>
229
+ this.blockSource.syncImmediate().then(() => this.blockSource.getBlockHeaderByArchive(parentArchive)),
230
+ 'force archiver sync',
231
+ timeoutDurationMs / 1000,
232
+ 0.5,
233
+ ))
234
+ );
235
+ } catch (err) {
236
+ if (err instanceof TimeoutError) {
237
+ this.log.debug(`Timed out getting parent block by archive root`, { parentArchive });
238
+ } else {
239
+ this.log.error('Error getting parent block by archive root', err, { parentArchive });
240
+ }
241
+ return undefined;
242
+ }
243
+ }
244
+
245
+ private getReexecutionDeadline(slot: SlotNumber, config: { l1GenesisTime: bigint; slotDuration: number }): Date {
246
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
247
+ const msNeededForPropagationAndPublishing = this.config.validatorReexecuteDeadlineMs;
248
+ return new Date(nextSlotTimestampSeconds * 1000 - msNeededForPropagationAndPublishing);
249
+ }
250
+
251
+ private getReexecuteFailureReason(err: any) {
252
+ if (err instanceof ReExStateMismatchError) {
253
+ return 'state_mismatch';
254
+ } else if (err instanceof ReExFailedTxsError) {
255
+ return 'failed_txs';
256
+ } else if (err instanceof ReExTimeoutError) {
257
+ return 'timeout';
258
+ } else {
259
+ return 'unknown_error';
260
+ }
261
+ }
262
+
263
+ async reexecuteTransactions(
264
+ proposal: BlockProposal,
265
+ blockNumber: number,
266
+ txs: Tx[],
267
+ l1ToL2Messages: Fr[],
268
+ ): Promise<ReexecuteTransactionsResult> {
269
+ const { header } = proposal.payload;
270
+ const { txHashes } = proposal;
271
+
272
+ // If we do not have all of the transactions, then we should fail
273
+ if (txs.length !== txHashes.length) {
274
+ const foundTxHashes = txs.map(tx => tx.getTxHash());
275
+ const missingTxHashes = txHashes.filter(txHash => !foundTxHashes.includes(txHash));
276
+ throw new TransactionsNotAvailableError(missingTxHashes);
277
+ }
278
+
279
+ // Use the sequencer's block building logic to re-execute the transactions
280
+ const timer = new Timer();
281
+ const config = this.blockBuilder.getConfig();
282
+
283
+ // We source most global variables from the proposal
284
+ const globalVariables = GlobalVariables.from({
285
+ slotNumber: proposal.payload.header.slotNumber, // checked in the block proposal validator
286
+ coinbase: proposal.payload.header.coinbase, // set arbitrarily by the proposer
287
+ feeRecipient: proposal.payload.header.feeRecipient, // set arbitrarily by the proposer
288
+ gasFees: proposal.payload.header.gasFees, // validated by the rollup contract
289
+ blockNumber, // computed from the parent block and checked it does not exist in archiver
290
+ timestamp: header.timestamp, // checked in the rollup contract against the slot number
291
+ chainId: new Fr(config.l1ChainId),
292
+ version: new Fr(config.rollupVersion),
293
+ });
294
+
295
+ const { block, failedTxs } = await this.blockBuilder.buildBlock(txs, l1ToL2Messages, globalVariables, {
296
+ deadline: this.getReexecutionDeadline(proposal.payload.header.slotNumber, config),
297
+ });
298
+
299
+ const numFailedTxs = failedTxs.length;
300
+ const slot = proposal.slotNumber;
301
+ this.log.verbose(`Transaction re-execution complete for slot ${slot}`, {
302
+ numFailedTxs,
303
+ numProposalTxs: txHashes.length,
304
+ numProcessedTxs: block.body.txEffects.length,
305
+ slot,
306
+ });
307
+
308
+ if (numFailedTxs > 0) {
309
+ this.metrics?.recordFailedReexecution(proposal);
310
+ throw new ReExFailedTxsError(numFailedTxs);
311
+ }
312
+
313
+ if (block.body.txEffects.length !== txHashes.length) {
314
+ this.metrics?.recordFailedReexecution(proposal);
315
+ throw new ReExTimeoutError();
316
+ }
317
+
318
+ // Throw a ReExStateMismatchError error if state updates do not match
319
+ const blockPayload = ConsensusPayload.fromBlock(block);
320
+ if (!blockPayload.equals(proposal.payload)) {
321
+ this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
322
+ expected: blockPayload.toInspect(),
323
+ actual: proposal.payload.toInspect(),
324
+ });
325
+ this.metrics?.recordFailedReexecution(proposal);
326
+ throw new ReExStateMismatchError(proposal.archive, block.archive.root);
327
+ }
328
+
329
+ const reexecutionTimeMs = timer.ms();
330
+ const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
331
+
332
+ this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
333
+
334
+ return {
335
+ block,
336
+ failedTxs,
337
+ reexecutionTimeMs,
338
+ totalManaUsed,
339
+ };
340
+ }
341
+ }
package/src/config.ts CHANGED
@@ -1,38 +1,47 @@
1
- import { NULL_KEY } from '@aztec/ethereum';
2
1
  import {
3
2
  type ConfigMappingsType,
4
3
  booleanConfigHelper,
5
4
  getConfigFromMappings,
6
5
  numberConfigHelper,
6
+ secretValueConfigHelper,
7
7
  } from '@aztec/foundation/config';
8
+ import { EthAddress } from '@aztec/foundation/eth-address';
9
+ import type { ValidatorClientConfig } from '@aztec/stdlib/interfaces/server';
8
10
 
9
- /**
10
- * The Validator Configuration
11
- */
12
- export interface ValidatorClientConfig {
13
- /** The private key of the validator participating in attestation duties */
14
- validatorPrivateKey?: string;
15
-
16
- /** Do not run the validator */
17
- disableValidator: boolean;
18
-
19
- /** Interval between polling for new attestations from peers */
20
- attestationPollingIntervalMs: number;
21
-
22
- /** Re-execute transactions before attesting */
23
- validatorReexecute: boolean;
24
- }
11
+ export type { ValidatorClientConfig };
25
12
 
26
13
  export const validatorClientConfigMappings: ConfigMappingsType<ValidatorClientConfig> = {
27
- validatorPrivateKey: {
28
- env: 'VALIDATOR_PRIVATE_KEY',
29
- parseEnv: (val: string) => (val ? `0x${val.replace('0x', '')}` : NULL_KEY),
30
- description: 'The private key of the validator participating in attestation duties',
14
+ validatorPrivateKeys: {
15
+ env: 'VALIDATOR_PRIVATE_KEYS',
16
+ description: 'List of private keys of the validators participating in attestation duties',
17
+ ...secretValueConfigHelper<`0x${string}`[]>(val =>
18
+ val ? val.split(',').map<`0x${string}`>(key => `0x${key.replace('0x', '')}`) : [],
19
+ ),
20
+ fallback: ['VALIDATOR_PRIVATE_KEY'],
21
+ },
22
+ validatorAddresses: {
23
+ env: 'VALIDATOR_ADDRESSES',
24
+ description: 'List of addresses of the validators to use with remote signers',
25
+ parseEnv: (val: string) =>
26
+ val
27
+ .split(',')
28
+ .filter(address => address && address.trim().length > 0)
29
+ .map(address => EthAddress.fromString(address.trim())),
30
+ defaultValue: [],
31
31
  },
32
32
  disableValidator: {
33
33
  env: 'VALIDATOR_DISABLED',
34
34
  description: 'Do not run the validator',
35
- ...booleanConfigHelper(),
35
+ ...booleanConfigHelper(false),
36
+ },
37
+ disabledValidators: {
38
+ description: 'Temporarily disable these specific validator addresses',
39
+ parseEnv: (val: string) =>
40
+ val
41
+ .split(',')
42
+ .filter(address => address && address.trim().length > 0)
43
+ .map(address => EthAddress.fromString(address.trim())),
44
+ defaultValue: [],
36
45
  },
37
46
  attestationPollingIntervalMs: {
38
47
  env: 'VALIDATOR_ATTESTATIONS_POLLING_INTERVAL_MS',
@@ -44,6 +53,23 @@ export const validatorClientConfigMappings: ConfigMappingsType<ValidatorClientCo
44
53
  description: 'Re-execute transactions before attesting',
45
54
  ...booleanConfigHelper(true),
46
55
  },
56
+ validatorReexecuteDeadlineMs: {
57
+ env: 'VALIDATOR_REEXECUTE_DEADLINE_MS',
58
+ description: 'Will re-execute until this many milliseconds are left in the slot',
59
+ ...numberConfigHelper(6000),
60
+ },
61
+ alwaysReexecuteBlockProposals: {
62
+ env: 'ALWAYS_REEXECUTE_BLOCK_PROPOSALS',
63
+ description:
64
+ 'Whether to always reexecute block proposals, even for non-validator nodes (useful for monitoring network status).',
65
+ ...booleanConfigHelper(false),
66
+ },
67
+ fishermanMode: {
68
+ env: 'FISHERMAN_MODE',
69
+ description:
70
+ 'Whether to run in fisherman mode: validates all proposals and attestations but does not broadcast attestations or participate in consensus.',
71
+ ...booleanConfigHelper(false),
72
+ },
47
73
  };
48
74
 
49
75
  /**
@@ -1,13 +1,27 @@
1
1
  import { Buffer32 } from '@aztec/foundation/buffer';
2
2
  import { keccak256 } from '@aztec/foundation/crypto';
3
- import type { Fr } from '@aztec/foundation/fields';
4
- import { BlockAttestation, BlockProposal, ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
5
- import type { BlockHeader, TxHash } from '@aztec/stdlib/tx';
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 { createLogger } from '@aztec/foundation/log';
7
+ import type { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
8
+ import {
9
+ BlockAttestation,
10
+ BlockProposal,
11
+ type BlockProposalOptions,
12
+ ConsensusPayload,
13
+ SignatureDomainSeparator,
14
+ } from '@aztec/stdlib/p2p';
15
+ import type { CheckpointHeader } from '@aztec/stdlib/rollup';
16
+ import type { Tx } from '@aztec/stdlib/tx';
6
17
 
7
18
  import type { ValidatorKeyStore } from '../key_store/interface.js';
8
19
 
9
20
  export class ValidationService {
10
- constructor(private keyStore: ValidatorKeyStore) {}
21
+ constructor(
22
+ private keyStore: ValidatorKeyStore,
23
+ private log = createLogger('validator:validation-service'),
24
+ ) {}
11
25
 
12
26
  /**
13
27
  * Create a block proposal with the given header, archive, and transactions
@@ -15,31 +29,69 @@ export class ValidationService {
15
29
  * @param header - The block header
16
30
  * @param archive - The archive of the current block
17
31
  * @param txs - TxHash[] ordered list of transactions
32
+ * @param options - Block proposal options (including broadcastInvalidBlockProposal for testing)
18
33
  *
19
34
  * @returns A block proposal signing the above information (not the current implementation!!!)
20
35
  */
21
- createBlockProposal(header: BlockHeader, archive: Fr, txs: TxHash[]): Promise<BlockProposal> {
22
- const payloadSigner = (payload: Buffer32) => this.keyStore.signMessage(payload);
36
+ async createBlockProposal(
37
+ header: CheckpointHeader,
38
+ archive: Fr,
39
+ txs: Tx[],
40
+ proposerAttesterAddress: EthAddress | undefined,
41
+ options: BlockProposalOptions,
42
+ ): Promise<BlockProposal> {
43
+ let payloadSigner: (payload: Buffer32) => Promise<Signature>;
44
+ if (proposerAttesterAddress !== undefined) {
45
+ payloadSigner = (payload: Buffer32) => this.keyStore.signMessageWithAddress(proposerAttesterAddress, payload);
46
+ } else {
47
+ // if there is no proposer attester address, just use the first signer
48
+ const signer = this.keyStore.getAddress(0);
49
+ payloadSigner = (payload: Buffer32) => this.keyStore.signMessageWithAddress(signer, payload);
50
+ }
51
+ // TODO: check if this is calculated earlier / can not be recomputed
52
+ const txHashes = await Promise.all(txs.map(tx => tx.getTxHash()));
23
53
 
24
- return BlockProposal.createProposalFromSigner(new ConsensusPayload(header, archive, txs), payloadSigner);
54
+ // For testing: change the new archive to trigger state_mismatch validation failure
55
+ if (options.broadcastInvalidBlockProposal) {
56
+ archive = Fr.random();
57
+ this.log.warn(`Creating INVALID block proposal for slot ${header.slotNumber}`);
58
+ }
59
+
60
+ return BlockProposal.createProposalFromSigner(
61
+ new ConsensusPayload(header, archive),
62
+ txHashes,
63
+ options.publishFullTxs ? txs : undefined,
64
+ payloadSigner,
65
+ );
25
66
  }
26
67
 
27
68
  /**
28
- * Attest to the given block proposal constructed by the current sequencer
69
+ * Attest with selection of validators to the given block proposal, constructed by the current sequencer
29
70
  *
30
71
  * NOTE: This is just a blind signing.
31
72
  * We assume that the proposal is valid and DA guarantees have been checked previously.
32
73
  *
33
74
  * @param proposal - The proposal to attest to
34
- * @returns attestation
75
+ * @param attestors - The validators to attest with
76
+ * @returns attestations
35
77
  */
36
- async attestToProposal(proposal: BlockProposal): Promise<BlockAttestation> {
37
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/7961): check that the current validator is correct
78
+ async attestToProposal(proposal: BlockProposal, attestors: EthAddress[]): Promise<BlockAttestation[]> {
79
+ const buf = Buffer32.fromBuffer(
80
+ keccak256(proposal.payload.getPayloadToSign(SignatureDomainSeparator.blockAttestation)),
81
+ );
82
+ const signatures = await Promise.all(
83
+ attestors.map(attestor => this.keyStore.signMessageWithAddress(attestor, buf)),
84
+ );
85
+ return signatures.map(sig => new BlockAttestation(proposal.payload, sig, proposal.signature));
86
+ }
38
87
 
88
+ async signAttestationsAndSigners(
89
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
90
+ proposer: EthAddress,
91
+ ): Promise<Signature> {
39
92
  const buf = Buffer32.fromBuffer(
40
- keccak256(await proposal.payload.getPayloadToSign(SignatureDomainSeparator.blockAttestation)),
93
+ keccak256(attestationsAndSigners.getPayloadToSign(SignatureDomainSeparator.attestationsAndSigners)),
41
94
  );
42
- const sig = await this.keyStore.signMessage(buf);
43
- return new BlockAttestation(proposal.payload, sig);
95
+ return await this.keyStore.signMessageWithAddress(proposer, buf);
44
96
  }
45
97
  }
package/src/factory.ts CHANGED
@@ -1,28 +1,73 @@
1
1
  import type { EpochCache } from '@aztec/epoch-cache';
2
2
  import type { DateProvider } from '@aztec/foundation/timer';
3
- import type { P2P } from '@aztec/p2p';
3
+ import type { KeystoreManager } from '@aztec/node-keystore';
4
+ import { BlockProposalValidator, type P2PClient } from '@aztec/p2p';
5
+ import type { L2BlockSource } from '@aztec/stdlib/block';
6
+ import type { IFullNodeBlockBuilder, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
7
+ import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
4
8
  import type { TelemetryClient } from '@aztec/telemetry-client';
5
9
 
6
- import { generatePrivateKey } from 'viem/accounts';
7
-
8
- import type { ValidatorClientConfig } from './config.js';
10
+ import { BlockProposalHandler } from './block_proposal_handler.js';
11
+ import { ValidatorMetrics } from './metrics.js';
9
12
  import { ValidatorClient } from './validator.js';
10
13
 
14
+ export function createBlockProposalHandler(
15
+ config: ValidatorClientFullConfig,
16
+ deps: {
17
+ blockBuilder: IFullNodeBlockBuilder;
18
+ blockSource: L2BlockSource;
19
+ l1ToL2MessageSource: L1ToL2MessageSource;
20
+ p2pClient: P2PClient;
21
+ epochCache: EpochCache;
22
+ dateProvider: DateProvider;
23
+ telemetry: TelemetryClient;
24
+ },
25
+ ) {
26
+ const metrics = new ValidatorMetrics(deps.telemetry);
27
+ const blockProposalValidator = new BlockProposalValidator(deps.epochCache, {
28
+ txsPermitted: !config.disableTransactions,
29
+ });
30
+ return new BlockProposalHandler(
31
+ deps.blockBuilder,
32
+ deps.blockSource,
33
+ deps.l1ToL2MessageSource,
34
+ deps.p2pClient.getTxProvider(),
35
+ blockProposalValidator,
36
+ config,
37
+ metrics,
38
+ deps.dateProvider,
39
+ deps.telemetry,
40
+ );
41
+ }
42
+
11
43
  export function createValidatorClient(
12
- config: ValidatorClientConfig,
44
+ config: ValidatorClientFullConfig,
13
45
  deps: {
14
- p2pClient: P2P;
46
+ blockBuilder: IFullNodeBlockBuilder;
47
+ p2pClient: P2PClient;
48
+ blockSource: L2BlockSource;
49
+ l1ToL2MessageSource: L1ToL2MessageSource;
15
50
  telemetry: TelemetryClient;
16
51
  dateProvider: DateProvider;
17
52
  epochCache: EpochCache;
53
+ keyStoreManager: KeystoreManager | undefined;
18
54
  },
19
55
  ) {
20
- if (config.disableValidator) {
56
+ if (config.disableValidator || !deps.keyStoreManager) {
21
57
  return undefined;
22
58
  }
23
- if (config.validatorPrivateKey === undefined || config.validatorPrivateKey === '') {
24
- config.validatorPrivateKey = generatePrivateKey();
25
- }
26
59
 
27
- return ValidatorClient.new(config, deps.epochCache, deps.p2pClient, deps.dateProvider, deps.telemetry);
60
+ const txProvider = deps.p2pClient.getTxProvider();
61
+ return ValidatorClient.new(
62
+ config,
63
+ deps.blockBuilder,
64
+ deps.epochCache,
65
+ deps.p2pClient,
66
+ deps.blockSource,
67
+ deps.l1ToL2MessageSource,
68
+ txProvider,
69
+ deps.keyStoreManager,
70
+ deps.dateProvider,
71
+ deps.telemetry,
72
+ );
28
73
  }
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export * from './block_proposal_handler.js';
1
2
  export * from './config.js';
2
- export * from './validator.js';
3
3
  export * from './factory.js';
4
+ export * from './validator.js';
5
+ export * from './key_store/index.js';
@@ -1,2 +1,4 @@
1
1
  export * from './interface.js';
2
2
  export * from './local_key_store.js';
3
+ export * from './node_keystore_adapter.js';
4
+ export * from './web3signer_key_store.js';