@aztec/validator-client 0.0.1-commit.03f7ef2 → 0.0.1-commit.04d373f

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 +325 -0
  2. package/dest/checkpoint_builder.d.ts +79 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +251 -0
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +48 -14
  8. package/dest/duties/validation_service.d.ts +43 -15
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +101 -30
  11. package/dest/factory.d.ts +22 -13
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +11 -5
  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 +8 -4
  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 +10 -5
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +8 -4
  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 +135 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +1111 -0
  40. package/dest/validator.d.ts +85 -26
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +475 -105
  43. package/package.json +21 -13
  44. package/src/checkpoint_builder.ts +417 -0
  45. package/src/config.ts +47 -12
  46. package/src/duties/validation_service.ts +167 -40
  47. package/src/factory.ts +37 -14
  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 +13 -4
  53. package/src/key_store/node_keystore_adapter.ts +27 -4
  54. package/src/key_store/web3signer_key_store.ts +17 -4
  55. package/src/metrics.ts +81 -33
  56. package/src/proposal_handler.ts +1207 -0
  57. package/src/validator.ts +692 -160
  58. package/dest/block_proposal_handler.d.ts +0 -53
  59. package/dest/block_proposal_handler.d.ts.map +0 -1
  60. package/dest/block_proposal_handler.js +0 -290
  61. package/src/block_proposal_handler.ts +0 -346
@@ -1,346 +0,0 @@
1
- import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
- import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
3
- import { Fr } from '@aztec/foundation/curves/bn254';
4
- import { TimeoutError } from '@aztec/foundation/error';
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: BlockNumber;
49
- reexecutionResult?: ReexecuteTransactionsResult;
50
- };
51
-
52
- export type BlockProposalValidationFailureResult = {
53
- isValid: false;
54
- reason: BlockProposalValidationFailureReason;
55
- blockNumber?: BlockNumber;
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 =
157
- parentBlockHeader === 'genesis'
158
- ? BlockNumber(INITIAL_L2_BLOCK_NUM)
159
- : BlockNumber(parentBlockHeader.getBlockNumber() + 1);
160
-
161
- // Check that this block number does not exist already
162
- const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
163
- if (existingBlock) {
164
- this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
165
- return { isValid: false, blockNumber, reason: 'block_number_already_exists' };
166
- }
167
-
168
- // Collect txs from the proposal. We start doing this as early as possible,
169
- // 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.
170
- const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
171
- pinnedPeer: proposalSender,
172
- deadline: this.getReexecutionDeadline(slotNumber, config),
173
- });
174
-
175
- // Check that I have the same set of l1ToL2Messages as the proposal
176
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(
177
- CheckpointNumber.fromBlockNumber(blockNumber),
178
- );
179
- const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
180
- const proposalInHash = proposal.payload.header.contentCommitment.inHash;
181
- if (!computedInHash.equals(proposalInHash)) {
182
- this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
183
- proposalInHash: proposalInHash.toString(),
184
- computedInHash: computedInHash.toString(),
185
- ...proposalInfo,
186
- });
187
- return { isValid: false, blockNumber, reason: 'in_hash_mismatch' };
188
- }
189
-
190
- // Check that all of the transactions in the proposal are available
191
- if (missingTxs.length > 0) {
192
- this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, { ...proposalInfo, missingTxs });
193
- return { isValid: false, blockNumber, reason: 'txs_not_available' };
194
- }
195
-
196
- // Try re-executing the transactions in the proposal if needed
197
- let reexecutionResult;
198
- if (shouldReexecute) {
199
- try {
200
- this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
201
- reexecutionResult = await this.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
202
- } catch (error) {
203
- this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
204
- const reason = this.getReexecuteFailureReason(error);
205
- return { isValid: false, blockNumber, reason, reexecutionResult };
206
- }
207
- }
208
-
209
- this.log.info(`Successfully processed proposal for slot ${slotNumber}`, proposalInfo);
210
- return { isValid: true, blockNumber, reexecutionResult };
211
- }
212
-
213
- private async getParentBlock(proposal: BlockProposal): Promise<'genesis' | BlockHeader | undefined> {
214
- const parentArchive = proposal.payload.header.lastArchiveRoot;
215
- const slot = proposal.slotNumber;
216
- const config = this.blockBuilder.getConfig();
217
- const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
218
-
219
- if (parentArchive.equals(genesisArchiveRoot)) {
220
- return 'genesis';
221
- }
222
-
223
- const deadline = this.getReexecutionDeadline(slot, config);
224
- const currentTime = this.dateProvider.now();
225
- const timeoutDurationMs = deadline.getTime() - currentTime;
226
-
227
- try {
228
- return (
229
- (await this.blockSource.getBlockHeaderByArchive(parentArchive)) ??
230
- (timeoutDurationMs <= 0
231
- ? undefined
232
- : await retryUntil(
233
- () =>
234
- this.blockSource.syncImmediate().then(() => this.blockSource.getBlockHeaderByArchive(parentArchive)),
235
- 'force archiver sync',
236
- timeoutDurationMs / 1000,
237
- 0.5,
238
- ))
239
- );
240
- } catch (err) {
241
- if (err instanceof TimeoutError) {
242
- this.log.debug(`Timed out getting parent block by archive root`, { parentArchive });
243
- } else {
244
- this.log.error('Error getting parent block by archive root', err, { parentArchive });
245
- }
246
- return undefined;
247
- }
248
- }
249
-
250
- private getReexecutionDeadline(slot: SlotNumber, config: { l1GenesisTime: bigint; slotDuration: number }): Date {
251
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
252
- const msNeededForPropagationAndPublishing = this.config.validatorReexecuteDeadlineMs;
253
- return new Date(nextSlotTimestampSeconds * 1000 - msNeededForPropagationAndPublishing);
254
- }
255
-
256
- private getReexecuteFailureReason(err: any) {
257
- if (err instanceof ReExStateMismatchError) {
258
- return 'state_mismatch';
259
- } else if (err instanceof ReExFailedTxsError) {
260
- return 'failed_txs';
261
- } else if (err instanceof ReExTimeoutError) {
262
- return 'timeout';
263
- } else {
264
- return 'unknown_error';
265
- }
266
- }
267
-
268
- async reexecuteTransactions(
269
- proposal: BlockProposal,
270
- blockNumber: BlockNumber,
271
- txs: Tx[],
272
- l1ToL2Messages: Fr[],
273
- ): Promise<ReexecuteTransactionsResult> {
274
- const { header } = proposal.payload;
275
- const { txHashes } = proposal;
276
-
277
- // If we do not have all of the transactions, then we should fail
278
- if (txs.length !== txHashes.length) {
279
- const foundTxHashes = txs.map(tx => tx.getTxHash());
280
- const missingTxHashes = txHashes.filter(txHash => !foundTxHashes.includes(txHash));
281
- throw new TransactionsNotAvailableError(missingTxHashes);
282
- }
283
-
284
- // Use the sequencer's block building logic to re-execute the transactions
285
- const timer = new Timer();
286
- const config = this.blockBuilder.getConfig();
287
-
288
- // We source most global variables from the proposal
289
- const globalVariables = GlobalVariables.from({
290
- slotNumber: proposal.payload.header.slotNumber, // checked in the block proposal validator
291
- coinbase: proposal.payload.header.coinbase, // set arbitrarily by the proposer
292
- feeRecipient: proposal.payload.header.feeRecipient, // set arbitrarily by the proposer
293
- gasFees: proposal.payload.header.gasFees, // validated by the rollup contract
294
- blockNumber, // computed from the parent block and checked it does not exist in archiver
295
- timestamp: header.timestamp, // checked in the rollup contract against the slot number
296
- chainId: new Fr(config.l1ChainId),
297
- version: new Fr(config.rollupVersion),
298
- });
299
-
300
- const { block, failedTxs } = await this.blockBuilder.buildBlock(txs, l1ToL2Messages, globalVariables, {
301
- deadline: this.getReexecutionDeadline(proposal.payload.header.slotNumber, config),
302
- });
303
-
304
- const numFailedTxs = failedTxs.length;
305
- const slot = proposal.slotNumber;
306
- this.log.verbose(`Transaction re-execution complete for slot ${slot}`, {
307
- numFailedTxs,
308
- numProposalTxs: txHashes.length,
309
- numProcessedTxs: block.body.txEffects.length,
310
- slot,
311
- });
312
-
313
- if (numFailedTxs > 0) {
314
- this.metrics?.recordFailedReexecution(proposal);
315
- throw new ReExFailedTxsError(numFailedTxs);
316
- }
317
-
318
- if (block.body.txEffects.length !== txHashes.length) {
319
- this.metrics?.recordFailedReexecution(proposal);
320
- throw new ReExTimeoutError();
321
- }
322
-
323
- // Throw a ReExStateMismatchError error if state updates do not match
324
- const blockPayload = ConsensusPayload.fromBlock(block);
325
- if (!blockPayload.equals(proposal.payload)) {
326
- this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
327
- expected: blockPayload.toInspect(),
328
- actual: proposal.payload.toInspect(),
329
- });
330
- this.metrics?.recordFailedReexecution(proposal);
331
- throw new ReExStateMismatchError(proposal.archive, block.archive.root);
332
- }
333
-
334
- const reexecutionTimeMs = timer.ms();
335
- const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
336
-
337
- this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
338
-
339
- return {
340
- block,
341
- failedTxs,
342
- reexecutionTimeMs,
343
- totalManaUsed,
344
- };
345
- }
346
- }