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

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