@aztec/validator-client 2.0.3 → 2.1.0-rc.2

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.
@@ -0,0 +1,314 @@
1
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
+ import { Fr } from '@aztec/foundation/fields';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import { retryUntil } from '@aztec/foundation/retry';
5
+ import { DateProvider, Timer } from '@aztec/foundation/timer';
6
+ import type { P2P, PeerId } from '@aztec/p2p';
7
+ import { TxProvider } from '@aztec/p2p';
8
+ import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
9
+ import { computeInHashFromL1ToL2Messages } from '@aztec/prover-client/helpers';
10
+ import type { L2BlockSource } from '@aztec/stdlib/block';
11
+ import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
12
+ import type { IFullNodeBlockBuilder, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
13
+ import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
14
+ import { type BlockProposal, ConsensusPayload } from '@aztec/stdlib/p2p';
15
+ import { type FailedTx, GlobalVariables, type Tx } from '@aztec/stdlib/tx';
16
+ import {
17
+ ReExFailedTxsError,
18
+ ReExStateMismatchError,
19
+ ReExTimeoutError,
20
+ TransactionsNotAvailableError,
21
+ } from '@aztec/stdlib/validators';
22
+ import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
23
+
24
+ import type { ValidatorMetrics } from './metrics.js';
25
+
26
+ export type BlockProposalValidationFailureReason =
27
+ | 'invalid_proposal'
28
+ | 'parent_block_not_found'
29
+ | 'parent_block_does_not_match'
30
+ | 'in_hash_mismatch'
31
+ | 'block_number_already_exists'
32
+ | 'txs_not_available'
33
+ | 'state_mismatch'
34
+ | 'failed_txs'
35
+ | 'timeout'
36
+ | 'unknown_error';
37
+
38
+ export interface BlockProposalValidationResult {
39
+ isValid: boolean;
40
+ reason?: BlockProposalValidationFailureReason;
41
+ reexecutionResult?: {
42
+ block: any;
43
+ failedTxs: FailedTx[];
44
+ reexecutionTimeMs: number;
45
+ totalManaUsed: number;
46
+ };
47
+ }
48
+
49
+ export class BlockProposalHandler {
50
+ public readonly tracer: Tracer;
51
+
52
+ constructor(
53
+ private blockBuilder: IFullNodeBlockBuilder,
54
+ private blockSource: L2BlockSource,
55
+ private l1ToL2MessageSource: L1ToL2MessageSource,
56
+ private txProvider: TxProvider,
57
+ private blockProposalValidator: BlockProposalValidator,
58
+ private config: ValidatorClientFullConfig,
59
+ private metrics?: ValidatorMetrics,
60
+ private dateProvider: DateProvider = new DateProvider(),
61
+ telemetry: TelemetryClient = getTelemetryClient(),
62
+ private log = createLogger('validator:block-proposal-handler'),
63
+ ) {
64
+ this.tracer = telemetry.getTracer('BlockProposalHandler');
65
+ }
66
+
67
+ registerForReexecution(p2pClient: P2P): BlockProposalHandler {
68
+ const handler = async (proposal: BlockProposal, proposalSender: PeerId) => {
69
+ try {
70
+ const result = await this.handleBlockProposal(proposal, proposalSender, true);
71
+ if (result.isValid && result.reexecutionResult) {
72
+ this.log.info(`Non-validator reexecution completed for slot ${proposal.slotNumber.toBigInt()}`, {
73
+ blockNumber: proposal.blockNumber,
74
+ reexecutionTimeMs: result.reexecutionResult.reexecutionTimeMs,
75
+ totalManaUsed: result.reexecutionResult.totalManaUsed,
76
+ numTxs: result.reexecutionResult.block?.body?.txEffects?.length ?? 0,
77
+ });
78
+ } else {
79
+ this.log.warn(`Non-validator reexecution failed for slot ${proposal.slotNumber.toBigInt()}`, {
80
+ blockNumber: proposal.blockNumber,
81
+ reason: result.reason,
82
+ });
83
+ }
84
+ } catch (error) {
85
+ this.log.error('Error processing block proposal in non-validator handler', error);
86
+ }
87
+ return undefined; // Non-validator nodes don't return attestations
88
+ };
89
+
90
+ p2pClient.registerBlockProposalHandler(handler);
91
+ return this;
92
+ }
93
+
94
+ async handleBlockProposal(
95
+ proposal: BlockProposal,
96
+ proposalSender: PeerId,
97
+ shouldReexecute: boolean,
98
+ ): Promise<BlockProposalValidationResult> {
99
+ const slotNumber = proposal.slotNumber.toBigInt();
100
+ const blockNumber = proposal.blockNumber;
101
+ const proposer = proposal.getSender();
102
+
103
+ const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
104
+ this.log.info(`Processing proposal for slot ${slotNumber}`, {
105
+ ...proposalInfo,
106
+ txHashes: proposal.txHashes.map(t => t.toString()),
107
+ });
108
+
109
+ // Check that the proposal is from the current proposer, or the next proposer
110
+ // This should have been handled by the p2p layer, but we double check here out of caution
111
+ const invalidProposal = await this.blockProposalValidator.validate(proposal);
112
+ if (invalidProposal) {
113
+ this.log.warn(`Proposal is not valid, skipping processing`, proposalInfo);
114
+ return { isValid: false, reason: 'invalid_proposal' };
115
+ }
116
+
117
+ // Collect txs from the proposal. We start doing this as early as possible,
118
+ // and we do it even if we don't plan to re-execute the txs, so that we have them
119
+ // if another node needs them.
120
+ const config = this.blockBuilder.getConfig();
121
+ const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, {
122
+ pinnedPeer: proposalSender,
123
+ deadline: this.getReexecutionDeadline(proposal, config),
124
+ });
125
+
126
+ // Check that the parent proposal is a block we know, otherwise reexecution would fail
127
+ if (blockNumber > INITIAL_L2_BLOCK_NUM) {
128
+ const deadline = this.getReexecutionDeadline(proposal, config);
129
+ const currentTime = this.dateProvider.now();
130
+ const timeoutDurationMs = deadline.getTime() - currentTime;
131
+ const parentBlock =
132
+ timeoutDurationMs <= 0
133
+ ? undefined
134
+ : await retryUntil(
135
+ async () => {
136
+ const block = await this.blockSource.getBlock(blockNumber - 1);
137
+ if (block) {
138
+ return block;
139
+ }
140
+ await this.blockSource.syncImmediate();
141
+ return await this.blockSource.getBlock(blockNumber - 1);
142
+ },
143
+ 'Force Archiver Sync',
144
+ timeoutDurationMs / 1000,
145
+ 0.5,
146
+ );
147
+
148
+ if (parentBlock === undefined) {
149
+ this.log.warn(`Parent block for ${blockNumber} not found, skipping processing`, proposalInfo);
150
+ return { isValid: false, reason: 'parent_block_not_found' };
151
+ }
152
+
153
+ if (!proposal.payload.header.lastArchiveRoot.equals(parentBlock.archive.root)) {
154
+ this.log.warn(`Parent block archive root for proposal does not match, skipping processing`, {
155
+ proposalLastArchiveRoot: proposal.payload.header.lastArchiveRoot.toString(),
156
+ parentBlockArchiveRoot: parentBlock.archive.root.toString(),
157
+ ...proposalInfo,
158
+ });
159
+ return { isValid: false, reason: 'parent_block_does_not_match' };
160
+ }
161
+ }
162
+
163
+ // Check that I have the same set of l1ToL2Messages as the proposal
164
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(blockNumber);
165
+ const computedInHash = await computeInHashFromL1ToL2Messages(l1ToL2Messages);
166
+ const proposalInHash = proposal.payload.header.contentCommitment.inHash;
167
+ if (!computedInHash.equals(proposalInHash)) {
168
+ this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
169
+ proposalInHash: proposalInHash.toString(),
170
+ computedInHash: computedInHash.toString(),
171
+ ...proposalInfo,
172
+ });
173
+ return { isValid: false, reason: 'in_hash_mismatch' };
174
+ }
175
+
176
+ // Check that this block number does not exist already
177
+ const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
178
+ if (existingBlock) {
179
+ this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
180
+ return { isValid: false, reason: 'block_number_already_exists' };
181
+ }
182
+
183
+ // Check that all of the transactions in the proposal are available
184
+ if (missingTxs.length > 0) {
185
+ this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, { ...proposalInfo, missingTxs });
186
+ return { isValid: false, reason: 'txs_not_available' };
187
+ }
188
+
189
+ // Try re-executing the transactions in the proposal if needed
190
+ let reexecutionResult;
191
+ if (shouldReexecute) {
192
+ try {
193
+ this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
194
+ reexecutionResult = await this.reexecuteTransactions(proposal, txs, l1ToL2Messages);
195
+ } catch (error) {
196
+ this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
197
+ const reason = this.getReexecuteFailureReason(error);
198
+ return { isValid: false, reason, reexecutionResult };
199
+ }
200
+ }
201
+
202
+ this.log.info(`Successfully processed proposal for slot ${slotNumber}`, proposalInfo);
203
+ return { isValid: true, reexecutionResult };
204
+ }
205
+
206
+ private getReexecutionDeadline(
207
+ proposal: BlockProposal,
208
+ config: { l1GenesisTime: bigint; slotDuration: number },
209
+ ): Date {
210
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(proposal.slotNumber.toBigInt() + 1n, config));
211
+ const msNeededForPropagationAndPublishing = this.config.validatorReexecuteDeadlineMs;
212
+ return new Date(nextSlotTimestampSeconds * 1000 - msNeededForPropagationAndPublishing);
213
+ }
214
+
215
+ private getReexecuteFailureReason(err: any) {
216
+ if (err instanceof ReExStateMismatchError) {
217
+ return 'state_mismatch';
218
+ } else if (err instanceof ReExFailedTxsError) {
219
+ return 'failed_txs';
220
+ } else if (err instanceof ReExTimeoutError) {
221
+ return 'timeout';
222
+ } else if (err instanceof Error) {
223
+ return 'unknown_error';
224
+ }
225
+ }
226
+
227
+ async reexecuteTransactions(
228
+ proposal: BlockProposal,
229
+ txs: Tx[],
230
+ l1ToL2Messages: Fr[],
231
+ ): Promise<{
232
+ block: any;
233
+ failedTxs: FailedTx[];
234
+ reexecutionTimeMs: number;
235
+ totalManaUsed: number;
236
+ }> {
237
+ const { header } = proposal.payload;
238
+ const { txHashes } = proposal;
239
+
240
+ // If we do not have all of the transactions, then we should fail
241
+ if (txs.length !== txHashes.length) {
242
+ const foundTxHashes = txs.map(tx => tx.getTxHash());
243
+ const missingTxHashes = txHashes.filter(txHash => !foundTxHashes.includes(txHash));
244
+ throw new TransactionsNotAvailableError(missingTxHashes);
245
+ }
246
+
247
+ // Use the sequencer's block building logic to re-execute the transactions
248
+ const timer = new Timer();
249
+ const config = this.blockBuilder.getConfig();
250
+
251
+ // We source most global variables from the proposal
252
+ const globalVariables = GlobalVariables.from({
253
+ slotNumber: proposal.payload.header.slotNumber, // checked in the block proposal validator
254
+ coinbase: proposal.payload.header.coinbase, // set arbitrarily by the proposer
255
+ feeRecipient: proposal.payload.header.feeRecipient, // set arbitrarily by the proposer
256
+ gasFees: proposal.payload.header.gasFees, // validated by the rollup contract
257
+ blockNumber: proposal.blockNumber, // checked blockNumber-1 exists in archiver but blockNumber doesnt
258
+ timestamp: header.timestamp, // checked in the rollup contract against the slot number
259
+ chainId: new Fr(config.l1ChainId),
260
+ version: new Fr(config.rollupVersion),
261
+ });
262
+
263
+ const { block, failedTxs } = await this.blockBuilder.buildBlock(txs, l1ToL2Messages, globalVariables, {
264
+ deadline: this.getReexecutionDeadline(proposal, config),
265
+ });
266
+
267
+ const numFailedTxs = failedTxs.length;
268
+ const slot = proposal.slotNumber.toBigInt();
269
+ this.log.verbose(`Transaction re-execution complete for slot ${slot}`, {
270
+ numFailedTxs,
271
+ numProposalTxs: txHashes.length,
272
+ numProcessedTxs: block.body.txEffects.length,
273
+ slot,
274
+ });
275
+
276
+ if (numFailedTxs > 0) {
277
+ this.metrics?.recordFailedReexecution(proposal);
278
+ throw new ReExFailedTxsError(numFailedTxs);
279
+ }
280
+
281
+ if (block.body.txEffects.length !== txHashes.length) {
282
+ this.metrics?.recordFailedReexecution(proposal);
283
+ throw new ReExTimeoutError();
284
+ }
285
+
286
+ // Throw a ReExStateMismatchError error if state updates do not match
287
+ const blockPayload = ConsensusPayload.fromBlock(block);
288
+ if (!blockPayload.equals(proposal.payload)) {
289
+ this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
290
+ expected: blockPayload.toInspect(),
291
+ actual: proposal.payload.toInspect(),
292
+ });
293
+ this.metrics?.recordFailedReexecution(proposal);
294
+ throw new ReExStateMismatchError(
295
+ proposal.archive,
296
+ block.archive.root,
297
+ proposal.payload.stateReference,
298
+ block.header.state,
299
+ );
300
+ }
301
+
302
+ const reexecutionTimeMs = timer.ms();
303
+ const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
304
+
305
+ this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
306
+
307
+ return {
308
+ block,
309
+ failedTxs,
310
+ reexecutionTimeMs,
311
+ totalManaUsed,
312
+ };
313
+ }
314
+ }
package/src/config.ts CHANGED
@@ -58,6 +58,12 @@ export const validatorClientConfigMappings: ConfigMappingsType<ValidatorClientCo
58
58
  description: 'Will re-execute until this many milliseconds are left in the slot',
59
59
  ...numberConfigHelper(6000),
60
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
+ },
61
67
  };
62
68
 
63
69
  /**
@@ -1,8 +1,9 @@
1
1
  import { Buffer32 } from '@aztec/foundation/buffer';
2
2
  import { keccak256 } from '@aztec/foundation/crypto';
3
3
  import type { EthAddress } from '@aztec/foundation/eth-address';
4
- import type { Signature } from '@aztec/foundation/eth-signature';
4
+ import { Signature } from '@aztec/foundation/eth-signature';
5
5
  import type { Fr } from '@aztec/foundation/fields';
6
+ import type { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
6
7
  import {
7
8
  BlockAttestation,
8
9
  BlockProposal,
@@ -76,4 +77,18 @@ export class ValidationService {
76
77
  //await this.keyStore.signMessage(buf);
77
78
  return signatures.map(sig => new BlockAttestation(proposal.blockNumber, proposal.payload, sig));
78
79
  }
80
+
81
+ async signAttestationsAndSigners(
82
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
83
+ proposer: EthAddress | undefined,
84
+ ): Promise<Signature> {
85
+ if (proposer === undefined) {
86
+ return Signature.empty();
87
+ }
88
+
89
+ const buf = Buffer32.fromBuffer(
90
+ keccak256(attestationsAndSigners.getPayloadToSign(SignatureDomainSeparator.attestationsAndSigners)),
91
+ );
92
+ return await this.keyStore.signMessageWithAddress(proposer, buf);
93
+ }
79
94
  }
package/src/factory.ts CHANGED
@@ -1,17 +1,45 @@
1
1
  import type { EpochCache } from '@aztec/epoch-cache';
2
2
  import type { DateProvider } from '@aztec/foundation/timer';
3
3
  import type { KeystoreManager } from '@aztec/node-keystore';
4
- import type { P2PClient } from '@aztec/p2p';
4
+ import { BlockProposalValidator, type P2PClient } from '@aztec/p2p';
5
5
  import type { L2BlockSource } from '@aztec/stdlib/block';
6
- import type { IFullNodeBlockBuilder, SlasherConfig } from '@aztec/stdlib/interfaces/server';
6
+ import type { IFullNodeBlockBuilder, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
7
7
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
8
8
  import type { TelemetryClient } from '@aztec/telemetry-client';
9
9
 
10
- import type { ValidatorClientConfig } from './config.js';
10
+ import { BlockProposalHandler } from './block_proposal_handler.js';
11
+ import { ValidatorMetrics } from './metrics.js';
11
12
  import { ValidatorClient } from './validator.js';
12
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
+ return new BlockProposalHandler(
29
+ deps.blockBuilder,
30
+ deps.blockSource,
31
+ deps.l1ToL2MessageSource,
32
+ deps.p2pClient.getTxProvider(),
33
+ blockProposalValidator,
34
+ config,
35
+ metrics,
36
+ deps.dateProvider,
37
+ deps.telemetry,
38
+ );
39
+ }
40
+
13
41
  export function createValidatorClient(
14
- config: ValidatorClientConfig & Pick<SlasherConfig, 'slashBroadcastedInvalidBlockPenalty'>,
42
+ config: ValidatorClientFullConfig,
15
43
  deps: {
16
44
  blockBuilder: IFullNodeBlockBuilder;
17
45
  p2pClient: P2PClient;
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './block_proposal_handler.js';
1
2
  export * from './config.js';
2
3
  export * from './factory.js';
3
4
  export * from './validator.js';
package/src/metrics.ts CHANGED
@@ -72,9 +72,10 @@ export class ValidatorMetrics {
72
72
  this.attestationsCount.add(num);
73
73
  }
74
74
 
75
- public incFailedAttestations(num: number, reason: string) {
75
+ public incFailedAttestations(num: number, reason: string, inCommittee: boolean) {
76
76
  this.failedAttestationsCount.add(num, {
77
77
  [Attributes.ERROR_TYPE]: reason,
78
+ [Attributes.VALIDATOR_STATUS]: inCommittee ? 'in-committee' : 'none',
78
79
  });
79
80
  }
80
81
  }