@aztec/validator-client 0.0.1-commit.b655e406 → 0.0.1-commit.b8a057fa

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 (61) hide show
  1. package/README.md +327 -0
  2. package/dest/checkpoint_builder.d.ts +81 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +259 -0
  5. package/dest/config.d.ts +9 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +60 -13
  8. package/dest/duties/validation_service.d.ts +44 -16
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +104 -34
  11. package/dest/factory.d.ts +22 -11
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +19 -6
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -1
  17. package/dest/key_store/ha_key_store.d.ts +99 -0
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  19. package/dest/key_store/ha_key_store.js +208 -0
  20. package/dest/key_store/index.d.ts +2 -1
  21. package/dest/key_store/index.d.ts.map +1 -1
  22. package/dest/key_store/index.js +1 -0
  23. package/dest/key_store/interface.d.ts +36 -6
  24. package/dest/key_store/interface.d.ts.map +1 -1
  25. package/dest/key_store/local_key_store.d.ts +10 -5
  26. package/dest/key_store/local_key_store.d.ts.map +1 -1
  27. package/dest/key_store/local_key_store.js +9 -5
  28. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  29. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  30. package/dest/key_store/node_keystore_adapter.js +18 -4
  31. package/dest/key_store/web3signer_key_store.d.ts +13 -6
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +41 -46
  34. package/dest/metrics.d.ts +16 -3
  35. package/dest/metrics.d.ts.map +1 -1
  36. package/dest/metrics.js +58 -30
  37. package/dest/proposal_handler.d.ts +165 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +1207 -0
  40. package/dest/validator.d.ts +94 -25
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +534 -95
  43. package/package.json +24 -14
  44. package/src/checkpoint_builder.ts +426 -0
  45. package/src/config.ts +68 -14
  46. package/src/duties/validation_service.ts +170 -46
  47. package/src/factory.ts +46 -12
  48. package/src/index.ts +2 -1
  49. package/src/key_store/ha_key_store.ts +269 -0
  50. package/src/key_store/index.ts +1 -0
  51. package/src/key_store/interface.ts +44 -5
  52. package/src/key_store/local_key_store.ts +14 -5
  53. package/src/key_store/node_keystore_adapter.ts +28 -5
  54. package/src/key_store/web3signer_key_store.ts +61 -64
  55. package/src/metrics.ts +81 -33
  56. package/src/proposal_handler.ts +1314 -0
  57. package/src/validator.ts +762 -142
  58. package/dest/block_proposal_handler.d.ts +0 -52
  59. package/dest/block_proposal_handler.d.ts.map +0 -1
  60. package/dest/block_proposal_handler.js +0 -286
  61. package/src/block_proposal_handler.ts +0 -343
@@ -1,343 +0,0 @@
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
- }