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