@aztec/validator-client 0.0.1-commit.f504929 → 0.0.1-commit.f5d02921e

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 (39) hide show
  1. package/README.md +41 -2
  2. package/dest/checkpoint_builder.d.ts +14 -4
  3. package/dest/checkpoint_builder.d.ts.map +1 -1
  4. package/dest/checkpoint_builder.js +97 -29
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +22 -6
  8. package/dest/duties/validation_service.d.ts +1 -1
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +3 -9
  11. package/dest/factory.d.ts +7 -4
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +5 -5
  14. package/dest/index.d.ts +2 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -1
  17. package/dest/key_store/ha_key_store.js +1 -1
  18. package/dest/metrics.d.ts +2 -2
  19. package/dest/metrics.d.ts.map +1 -1
  20. package/dest/proposal_handler.d.ts +107 -0
  21. package/dest/proposal_handler.d.ts.map +1 -0
  22. package/dest/proposal_handler.js +963 -0
  23. package/dest/validator.d.ts +9 -14
  24. package/dest/validator.d.ts.map +1 -1
  25. package/dest/validator.js +58 -218
  26. package/package.json +19 -19
  27. package/src/checkpoint_builder.ts +120 -34
  28. package/src/config.ts +22 -6
  29. package/src/duties/validation_service.ts +3 -9
  30. package/src/factory.ts +9 -4
  31. package/src/index.ts +1 -1
  32. package/src/key_store/ha_key_store.ts +1 -1
  33. package/src/metrics.ts +1 -1
  34. package/src/proposal_handler.ts +1027 -0
  35. package/src/validator.ts +78 -246
  36. package/dest/block_proposal_handler.d.ts +0 -63
  37. package/dest/block_proposal_handler.d.ts.map +0 -1
  38. package/dest/block_proposal_handler.js +0 -532
  39. package/src/block_proposal_handler.ts +0 -535
@@ -1,535 +0,0 @@
1
- import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
- import type { EpochCache } from '@aztec/epoch-cache';
3
- import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
- import { Fr } from '@aztec/foundation/curves/bn254';
5
- import { TimeoutError } from '@aztec/foundation/error';
6
- import { createLogger } from '@aztec/foundation/log';
7
- import { retryUntil } from '@aztec/foundation/retry';
8
- import { DateProvider, Timer } from '@aztec/foundation/timer';
9
- import type { P2P, PeerId } from '@aztec/p2p';
10
- import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
11
- import type { BlockData, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
12
- import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
13
- import type { ITxProvider, ValidatorClientFullConfig, WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
14
- import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
15
- import type { BlockProposal } from '@aztec/stdlib/p2p';
16
- import type { CheckpointGlobalVariables, FailedTx, 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 { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
26
- import type { ValidatorMetrics } from './metrics.js';
27
-
28
- export type BlockProposalValidationFailureReason =
29
- | 'invalid_proposal'
30
- | 'parent_block_not_found'
31
- | 'parent_block_wrong_slot'
32
- | 'in_hash_mismatch'
33
- | 'global_variables_mismatch'
34
- | 'block_number_already_exists'
35
- | 'txs_not_available'
36
- | 'state_mismatch'
37
- | 'failed_txs'
38
- | 'timeout'
39
- | 'unknown_error';
40
-
41
- type ReexecuteTransactionsResult = {
42
- block: L2Block;
43
- failedTxs: FailedTx[];
44
- reexecutionTimeMs: number;
45
- totalManaUsed: number;
46
- };
47
-
48
- export type BlockProposalValidationSuccessResult = {
49
- isValid: true;
50
- blockNumber: BlockNumber;
51
- reexecutionResult?: ReexecuteTransactionsResult;
52
- };
53
-
54
- export type BlockProposalValidationFailureResult = {
55
- isValid: false;
56
- reason: BlockProposalValidationFailureReason;
57
- blockNumber?: BlockNumber;
58
- reexecutionResult?: ReexecuteTransactionsResult;
59
- };
60
-
61
- export type BlockProposalValidationResult = BlockProposalValidationSuccessResult | BlockProposalValidationFailureResult;
62
-
63
- type CheckpointComputationResult =
64
- | { checkpointNumber: CheckpointNumber; reason?: undefined }
65
- | { checkpointNumber?: undefined; reason: 'invalid_proposal' | 'global_variables_mismatch' };
66
-
67
- export class BlockProposalHandler {
68
- public readonly tracer: Tracer;
69
-
70
- constructor(
71
- private checkpointsBuilder: FullNodeCheckpointsBuilder,
72
- private worldState: WorldStateSynchronizer,
73
- private blockSource: L2BlockSource & L2BlockSink,
74
- private l1ToL2MessageSource: L1ToL2MessageSource,
75
- private txProvider: ITxProvider,
76
- private blockProposalValidator: BlockProposalValidator,
77
- private epochCache: EpochCache,
78
- private config: ValidatorClientFullConfig,
79
- private metrics?: ValidatorMetrics,
80
- private dateProvider: DateProvider = new DateProvider(),
81
- telemetry: TelemetryClient = getTelemetryClient(),
82
- private log = createLogger('validator:block-proposal-handler'),
83
- ) {
84
- if (config.fishermanMode) {
85
- this.log = this.log.createChild('[FISHERMAN]');
86
- }
87
- this.tracer = telemetry.getTracer('BlockProposalHandler');
88
- }
89
-
90
- registerForReexecution(p2pClient: P2P): BlockProposalHandler {
91
- // Non-validator handler that re-executes for monitoring but does not attest.
92
- // Returns boolean indicating whether the proposal was valid.
93
- const handler = async (proposal: BlockProposal, proposalSender: PeerId): Promise<boolean> => {
94
- try {
95
- const result = await this.handleBlockProposal(proposal, proposalSender, true);
96
- if (result.isValid) {
97
- this.log.info(`Non-validator reexecution completed for slot ${proposal.slotNumber}`, {
98
- blockNumber: result.blockNumber,
99
- reexecutionTimeMs: result.reexecutionResult?.reexecutionTimeMs,
100
- totalManaUsed: result.reexecutionResult?.totalManaUsed,
101
- numTxs: result.reexecutionResult?.block?.body?.txEffects?.length ?? 0,
102
- });
103
- return true;
104
- } else {
105
- this.log.warn(`Non-validator reexecution failed for slot ${proposal.slotNumber}`, {
106
- blockNumber: result.blockNumber,
107
- reason: result.reason,
108
- });
109
- return false;
110
- }
111
- } catch (error) {
112
- this.log.error('Error processing block proposal in non-validator handler', error);
113
- return false;
114
- }
115
- };
116
-
117
- p2pClient.registerBlockProposalHandler(handler);
118
- return this;
119
- }
120
-
121
- async handleBlockProposal(
122
- proposal: BlockProposal,
123
- proposalSender: PeerId,
124
- shouldReexecute: boolean,
125
- ): Promise<BlockProposalValidationResult> {
126
- const slotNumber = proposal.slotNumber;
127
- const proposer = proposal.getSender();
128
- const config = this.checkpointsBuilder.getConfig();
129
-
130
- // Reject proposals with invalid signatures
131
- if (!proposer) {
132
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
133
- return { isValid: false, reason: 'invalid_proposal' };
134
- }
135
-
136
- const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
137
- this.log.info(`Processing proposal for slot ${slotNumber}`, {
138
- ...proposalInfo,
139
- txHashes: proposal.txHashes.map(t => t.toString()),
140
- });
141
-
142
- // Check that the proposal is from the current proposer, or the next proposer
143
- // This should have been handled by the p2p layer, but we double check here out of caution
144
- const validationResult = await this.blockProposalValidator.validate(proposal);
145
- if (validationResult.result !== 'accept') {
146
- this.log.warn(`Proposal is not valid, skipping processing`, proposalInfo);
147
- return { isValid: false, reason: 'invalid_proposal' };
148
- }
149
-
150
- // Check that the parent proposal is a block we know, otherwise reexecution would fail
151
- const parentBlock = await this.getParentBlock(proposal);
152
- if (parentBlock === undefined) {
153
- this.log.warn(`Parent block for proposal not found, skipping processing`, proposalInfo);
154
- return { isValid: false, reason: 'parent_block_not_found' };
155
- }
156
-
157
- // Check that the parent block's slot is not greater than the proposal's slot.
158
- if (parentBlock !== 'genesis' && parentBlock.header.getSlot() > slotNumber) {
159
- this.log.warn(`Parent block slot is greater than proposal slot, skipping processing`, {
160
- parentBlockSlot: parentBlock.header.getSlot().toString(),
161
- proposalSlot: slotNumber.toString(),
162
- ...proposalInfo,
163
- });
164
- return { isValid: false, reason: 'parent_block_wrong_slot' };
165
- }
166
-
167
- // Compute the block number based on the parent block
168
- const blockNumber =
169
- parentBlock === 'genesis'
170
- ? BlockNumber(INITIAL_L2_BLOCK_NUM)
171
- : BlockNumber(parentBlock.header.getBlockNumber() + 1);
172
-
173
- // Check that this block number does not exist already
174
- const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
175
- if (existingBlock) {
176
- this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
177
- return { isValid: false, blockNumber, reason: 'block_number_already_exists' };
178
- }
179
-
180
- // Collect txs from the proposal. We start doing this as early as possible,
181
- // 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.
182
- const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
183
- pinnedPeer: proposalSender,
184
- deadline: this.getReexecutionDeadline(slotNumber, config),
185
- });
186
-
187
- // Compute the checkpoint number for this block and validate checkpoint consistency
188
- const checkpointResult = this.computeCheckpointNumber(proposal, parentBlock, proposalInfo);
189
- if (checkpointResult.reason) {
190
- return { isValid: false, blockNumber, reason: checkpointResult.reason };
191
- }
192
- const checkpointNumber = checkpointResult.checkpointNumber;
193
-
194
- // Check that I have the same set of l1ToL2Messages as the proposal
195
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
196
- const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
197
- const proposalInHash = proposal.inHash;
198
- if (!computedInHash.equals(proposalInHash)) {
199
- this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
200
- proposalInHash: proposalInHash.toString(),
201
- computedInHash: computedInHash.toString(),
202
- ...proposalInfo,
203
- });
204
- return { isValid: false, blockNumber, reason: 'in_hash_mismatch' };
205
- }
206
-
207
- // Check that all of the transactions in the proposal are available
208
- if (missingTxs.length > 0) {
209
- this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, { ...proposalInfo, missingTxs });
210
- return { isValid: false, blockNumber, reason: 'txs_not_available' };
211
- }
212
-
213
- // Try re-executing the transactions in the proposal if needed
214
- let reexecutionResult;
215
- if (shouldReexecute) {
216
- // Collect the out hashes of all the checkpoints before this one in the same epoch
217
- const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
218
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch))
219
- .filter(c => c.checkpointNumber < checkpointNumber)
220
- .map(c => c.checkpointOutHash);
221
-
222
- try {
223
- this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
224
- reexecutionResult = await this.reexecuteTransactions(
225
- proposal,
226
- blockNumber,
227
- checkpointNumber,
228
- txs,
229
- l1ToL2Messages,
230
- previousCheckpointOutHashes,
231
- );
232
- } catch (error) {
233
- this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
234
- const reason = this.getReexecuteFailureReason(error);
235
- return { isValid: false, blockNumber, reason, reexecutionResult };
236
- }
237
- }
238
-
239
- // If we succeeded, push this block into the archiver (unless disabled)
240
- if (reexecutionResult?.block && this.config.skipPushProposedBlocksToArchiver === false) {
241
- await this.blockSource.addBlock(reexecutionResult?.block);
242
- }
243
-
244
- this.log.info(
245
- `Successfully processed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`,
246
- proposalInfo,
247
- );
248
-
249
- return { isValid: true, blockNumber, reexecutionResult };
250
- }
251
-
252
- private async getParentBlock(proposal: BlockProposal): Promise<'genesis' | BlockData | undefined> {
253
- const parentArchive = proposal.blockHeader.lastArchive.root;
254
- const slot = proposal.slotNumber;
255
- const config = this.checkpointsBuilder.getConfig();
256
- const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
257
-
258
- if (parentArchive.equals(genesisArchiveRoot)) {
259
- return 'genesis';
260
- }
261
-
262
- const deadline = this.getReexecutionDeadline(slot, config);
263
- const currentTime = this.dateProvider.now();
264
- const timeoutDurationMs = deadline.getTime() - currentTime;
265
-
266
- try {
267
- return (
268
- (await this.blockSource.getBlockDataByArchive(parentArchive)) ??
269
- (timeoutDurationMs <= 0
270
- ? undefined
271
- : await retryUntil(
272
- () => this.blockSource.syncImmediate().then(() => this.blockSource.getBlockDataByArchive(parentArchive)),
273
- 'force archiver sync',
274
- timeoutDurationMs / 1000,
275
- 0.5,
276
- ))
277
- );
278
- } catch (err) {
279
- if (err instanceof TimeoutError) {
280
- this.log.debug(`Timed out getting parent block by archive root`, { parentArchive });
281
- } else {
282
- this.log.error('Error getting parent block by archive root', err, { parentArchive });
283
- }
284
- return undefined;
285
- }
286
- }
287
-
288
- private computeCheckpointNumber(
289
- proposal: BlockProposal,
290
- parentBlock: 'genesis' | BlockData,
291
- proposalInfo: object,
292
- ): CheckpointComputationResult {
293
- if (parentBlock === 'genesis') {
294
- // First block is in checkpoint 1
295
- if (proposal.indexWithinCheckpoint !== 0) {
296
- this.log.warn(`First block proposal has non-zero indexWithinCheckpoint`, proposalInfo);
297
- return { reason: 'invalid_proposal' };
298
- }
299
- return { checkpointNumber: CheckpointNumber.INITIAL };
300
- }
301
-
302
- if (proposal.indexWithinCheckpoint === 0) {
303
- // If this is the first block in a new checkpoint, increment the checkpoint number
304
- if (!(proposal.blockHeader.getSlot() > parentBlock.header.getSlot())) {
305
- this.log.warn(`Slot should be greater than parent block slot for first block in checkpoint`, proposalInfo);
306
- return { reason: 'invalid_proposal' };
307
- }
308
- return { checkpointNumber: CheckpointNumber(parentBlock.checkpointNumber + 1) };
309
- }
310
-
311
- // Otherwise it should follow the previous block in the same checkpoint
312
- if (proposal.indexWithinCheckpoint !== parentBlock.indexWithinCheckpoint + 1) {
313
- this.log.warn(`Non-sequential indexWithinCheckpoint`, proposalInfo);
314
- return { reason: 'invalid_proposal' };
315
- }
316
- if (proposal.blockHeader.getSlot() !== parentBlock.header.getSlot()) {
317
- this.log.warn(`Slot should be equal to parent block slot for non-first block in checkpoint`, proposalInfo);
318
- return { reason: 'invalid_proposal' };
319
- }
320
-
321
- // For non-first blocks in a checkpoint, validate global variables match parent (except blockNumber)
322
- const validationResult = this.validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo);
323
- if (validationResult) {
324
- return validationResult;
325
- }
326
-
327
- return { checkpointNumber: parentBlock.checkpointNumber };
328
- }
329
-
330
- /**
331
- * Validates that a non-first block in a checkpoint has consistent global variables with its parent.
332
- * For blocks with indexWithinCheckpoint > 0, all global variables except blockNumber must match the parent.
333
- * @returns A failure result if validation fails, undefined if validation passes
334
- */
335
- private validateNonFirstBlockInCheckpoint(
336
- proposal: BlockProposal,
337
- parentBlock: BlockData,
338
- proposalInfo: object,
339
- ): CheckpointComputationResult | undefined {
340
- const proposalGlobals = proposal.blockHeader.globalVariables;
341
- const parentGlobals = parentBlock.header.globalVariables;
342
-
343
- // All global variables except blockNumber should match the parent
344
- // blockNumber naturally increments between blocks
345
- if (!proposalGlobals.chainId.equals(parentGlobals.chainId)) {
346
- this.log.warn(`Non-first block in checkpoint has mismatched chainId`, {
347
- ...proposalInfo,
348
- proposalChainId: proposalGlobals.chainId.toString(),
349
- parentChainId: parentGlobals.chainId.toString(),
350
- });
351
- return { reason: 'global_variables_mismatch' };
352
- }
353
-
354
- if (!proposalGlobals.version.equals(parentGlobals.version)) {
355
- this.log.warn(`Non-first block in checkpoint has mismatched version`, {
356
- ...proposalInfo,
357
- proposalVersion: proposalGlobals.version.toString(),
358
- parentVersion: parentGlobals.version.toString(),
359
- });
360
- return { reason: 'global_variables_mismatch' };
361
- }
362
-
363
- if (proposalGlobals.slotNumber !== parentGlobals.slotNumber) {
364
- this.log.warn(`Non-first block in checkpoint has mismatched slotNumber`, {
365
- ...proposalInfo,
366
- proposalSlotNumber: proposalGlobals.slotNumber,
367
- parentSlotNumber: parentGlobals.slotNumber,
368
- });
369
- return { reason: 'global_variables_mismatch' };
370
- }
371
-
372
- if (proposalGlobals.timestamp !== parentGlobals.timestamp) {
373
- this.log.warn(`Non-first block in checkpoint has mismatched timestamp`, {
374
- ...proposalInfo,
375
- proposalTimestamp: proposalGlobals.timestamp.toString(),
376
- parentTimestamp: parentGlobals.timestamp.toString(),
377
- });
378
- return { reason: 'global_variables_mismatch' };
379
- }
380
-
381
- if (!proposalGlobals.coinbase.equals(parentGlobals.coinbase)) {
382
- this.log.warn(`Non-first block in checkpoint has mismatched coinbase`, {
383
- ...proposalInfo,
384
- proposalCoinbase: proposalGlobals.coinbase.toString(),
385
- parentCoinbase: parentGlobals.coinbase.toString(),
386
- });
387
- return { reason: 'global_variables_mismatch' };
388
- }
389
-
390
- if (!proposalGlobals.feeRecipient.equals(parentGlobals.feeRecipient)) {
391
- this.log.warn(`Non-first block in checkpoint has mismatched feeRecipient`, {
392
- ...proposalInfo,
393
- proposalFeeRecipient: proposalGlobals.feeRecipient.toString(),
394
- parentFeeRecipient: parentGlobals.feeRecipient.toString(),
395
- });
396
- return { reason: 'global_variables_mismatch' };
397
- }
398
-
399
- if (!proposalGlobals.gasFees.equals(parentGlobals.gasFees)) {
400
- this.log.warn(`Non-first block in checkpoint has mismatched gasFees`, {
401
- ...proposalInfo,
402
- proposalGasFees: proposalGlobals.gasFees.toInspect(),
403
- parentGasFees: parentGlobals.gasFees.toInspect(),
404
- });
405
- return { reason: 'global_variables_mismatch' };
406
- }
407
-
408
- return undefined;
409
- }
410
-
411
- private getReexecutionDeadline(slot: SlotNumber, config: { l1GenesisTime: bigint; slotDuration: number }): Date {
412
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
413
- return new Date(nextSlotTimestampSeconds * 1000);
414
- }
415
-
416
- private getReexecuteFailureReason(err: any) {
417
- if (err instanceof ReExStateMismatchError) {
418
- return 'state_mismatch';
419
- } else if (err instanceof ReExFailedTxsError) {
420
- return 'failed_txs';
421
- } else if (err instanceof ReExTimeoutError) {
422
- return 'timeout';
423
- } else {
424
- return 'unknown_error';
425
- }
426
- }
427
-
428
- async reexecuteTransactions(
429
- proposal: BlockProposal,
430
- blockNumber: BlockNumber,
431
- checkpointNumber: CheckpointNumber,
432
- txs: Tx[],
433
- l1ToL2Messages: Fr[],
434
- previousCheckpointOutHashes: Fr[],
435
- ): Promise<ReexecuteTransactionsResult> {
436
- const { blockHeader, txHashes } = proposal;
437
-
438
- // If we do not have all of the transactions, then we should fail
439
- if (txs.length !== txHashes.length) {
440
- const foundTxHashes = txs.map(tx => tx.getTxHash());
441
- const missingTxHashes = txHashes.filter(txHash => !foundTxHashes.includes(txHash));
442
- throw new TransactionsNotAvailableError(missingTxHashes);
443
- }
444
-
445
- const timer = new Timer();
446
- const slot = proposal.slotNumber;
447
- const config = this.checkpointsBuilder.getConfig();
448
-
449
- // Get prior blocks in this checkpoint (same slot before current block)
450
- const allBlocksInSlot = await this.blockSource.getBlocksForSlot(slot);
451
- const priorBlocks = allBlocksInSlot.filter(b => b.number < blockNumber && b.header.getSlot() === slot);
452
-
453
- // Fork before the block to be built
454
- const parentBlockNumber = BlockNumber(blockNumber - 1);
455
- await this.worldState.syncImmediate(parentBlockNumber);
456
- await using fork = await this.worldState.fork(parentBlockNumber);
457
-
458
- // Build checkpoint constants from proposal (excludes blockNumber which is per-block)
459
- const constants: CheckpointGlobalVariables = {
460
- chainId: new Fr(config.l1ChainId),
461
- version: new Fr(config.rollupVersion),
462
- slotNumber: slot,
463
- timestamp: blockHeader.globalVariables.timestamp,
464
- coinbase: blockHeader.globalVariables.coinbase,
465
- feeRecipient: blockHeader.globalVariables.feeRecipient,
466
- gasFees: blockHeader.globalVariables.gasFees,
467
- };
468
-
469
- // Create checkpoint builder with prior blocks
470
- const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
471
- checkpointNumber,
472
- constants,
473
- 0n, // only takes effect in the following checkpoint.
474
- l1ToL2Messages,
475
- previousCheckpointOutHashes,
476
- fork,
477
- priorBlocks,
478
- this.log.getBindings(),
479
- );
480
-
481
- // Build the new block
482
- const deadline = this.getReexecutionDeadline(slot, config);
483
- const result = await checkpointBuilder.buildBlock(txs, blockNumber, blockHeader.globalVariables.timestamp, {
484
- deadline,
485
- expectedEndState: blockHeader.state,
486
- });
487
-
488
- const { block, failedTxs } = result;
489
- const numFailedTxs = failedTxs.length;
490
-
491
- this.log.verbose(`Transaction re-execution complete for slot ${slot}`, {
492
- numFailedTxs,
493
- numProposalTxs: txHashes.length,
494
- numProcessedTxs: block.body.txEffects.length,
495
- slot,
496
- });
497
-
498
- if (numFailedTxs > 0) {
499
- this.metrics?.recordFailedReexecution(proposal);
500
- throw new ReExFailedTxsError(numFailedTxs);
501
- }
502
-
503
- if (block.body.txEffects.length !== txHashes.length) {
504
- this.metrics?.recordFailedReexecution(proposal);
505
- throw new ReExTimeoutError();
506
- }
507
-
508
- // Throw a ReExStateMismatchError error if state updates do not match
509
- // Compare the full block structure (archive and header) from the built block with the proposal
510
- const archiveMatches = proposal.archive.equals(block.archive.root);
511
- const headerMatches = proposal.blockHeader.equals(block.header);
512
- if (!archiveMatches || !headerMatches) {
513
- this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
514
- expectedArchive: block.archive.root.toString(),
515
- actualArchive: proposal.archive.toString(),
516
- expectedHeader: block.header.toInspect(),
517
- actualHeader: proposal.blockHeader.toInspect(),
518
- });
519
- this.metrics?.recordFailedReexecution(proposal);
520
- throw new ReExStateMismatchError(proposal.archive, block.archive.root);
521
- }
522
-
523
- const reexecutionTimeMs = timer.ms();
524
- const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
525
-
526
- this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
527
-
528
- return {
529
- block,
530
- failedTxs,
531
- reexecutionTimeMs,
532
- totalManaUsed,
533
- };
534
- }
535
- }