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

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