@aztec/validator-client 4.0.0-nightly.20260112 → 4.0.0-nightly.20260114

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 (42) hide show
  1. package/README.md +256 -0
  2. package/dest/block_proposal_handler.d.ts +22 -10
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +347 -76
  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 +156 -0
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +10 -5
  11. package/dest/duties/validation_service.d.ts +26 -10
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +51 -21
  14. package/dest/factory.d.ts +10 -7
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +2 -2
  17. package/dest/index.d.ts +3 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +2 -0
  20. package/dest/tx_validator/index.d.ts +3 -0
  21. package/dest/tx_validator/index.d.ts.map +1 -0
  22. package/dest/tx_validator/index.js +2 -0
  23. package/dest/tx_validator/nullifier_cache.d.ts +14 -0
  24. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
  25. package/dest/tx_validator/nullifier_cache.js +24 -0
  26. package/dest/tx_validator/tx_validator_factory.d.ts +18 -0
  27. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  28. package/dest/tx_validator/tx_validator_factory.js +53 -0
  29. package/dest/validator.d.ts +39 -15
  30. package/dest/validator.d.ts.map +1 -1
  31. package/dest/validator.js +318 -449
  32. package/package.json +16 -12
  33. package/src/block_proposal_handler.ts +273 -43
  34. package/src/checkpoint_builder.ts +276 -0
  35. package/src/config.ts +10 -5
  36. package/src/duties/validation_service.ts +79 -25
  37. package/src/factory.ts +14 -8
  38. package/src/index.ts +2 -0
  39. package/src/tx_validator/index.ts +2 -0
  40. package/src/tx_validator/nullifier_cache.ts +30 -0
  41. package/src/tx_validator/tx_validator_factory.ts +133 -0
  42. package/src/validator.ts +424 -94
@@ -1,3 +1,68 @@
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
+ }
1
66
  import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
67
  import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
3
68
  import { Fr } from '@aztec/foundation/curves/bn254';
@@ -5,29 +70,31 @@ import { TimeoutError } from '@aztec/foundation/error';
5
70
  import { createLogger } from '@aztec/foundation/log';
6
71
  import { retryUntil } from '@aztec/foundation/retry';
7
72
  import { DateProvider, Timer } from '@aztec/foundation/timer';
8
- import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
9
- import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
10
- import { ConsensusPayload } from '@aztec/stdlib/p2p';
11
- import { GlobalVariables } from '@aztec/stdlib/tx';
73
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
74
+ import { computeCheckpointOutHash, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
12
75
  import { ReExFailedTxsError, ReExStateMismatchError, ReExTimeoutError, TransactionsNotAvailableError } from '@aztec/stdlib/validators';
13
76
  import { getTelemetryClient } from '@aztec/telemetry-client';
14
77
  export class BlockProposalHandler {
15
- blockBuilder;
78
+ checkpointsBuilder;
79
+ worldState;
16
80
  blockSource;
17
81
  l1ToL2MessageSource;
18
82
  txProvider;
19
83
  blockProposalValidator;
84
+ epochCache;
20
85
  config;
21
86
  metrics;
22
87
  dateProvider;
23
88
  log;
24
89
  tracer;
25
- constructor(blockBuilder, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, config, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:block-proposal-handler')){
26
- this.blockBuilder = blockBuilder;
90
+ constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:block-proposal-handler')){
91
+ this.checkpointsBuilder = checkpointsBuilder;
92
+ this.worldState = worldState;
27
93
  this.blockSource = blockSource;
28
94
  this.l1ToL2MessageSource = l1ToL2MessageSource;
29
95
  this.txProvider = txProvider;
30
96
  this.blockProposalValidator = blockProposalValidator;
97
+ this.epochCache = epochCache;
31
98
  this.config = config;
32
99
  this.metrics = metrics;
33
100
  this.dateProvider = dateProvider;
@@ -38,6 +105,8 @@ export class BlockProposalHandler {
38
105
  this.tracer = telemetry.getTracer('BlockProposalHandler');
39
106
  }
40
107
  registerForReexecution(p2pClient) {
108
+ // Non-validator handler that re-executes for monitoring but does not attest.
109
+ // Returns boolean indicating whether the proposal was valid.
41
110
  const handler = async (proposal, proposalSender)=>{
42
111
  try {
43
112
  const result = await this.handleBlockProposal(proposal, proposalSender, true);
@@ -48,16 +117,18 @@ export class BlockProposalHandler {
48
117
  totalManaUsed: result.reexecutionResult?.totalManaUsed,
49
118
  numTxs: result.reexecutionResult?.block?.body?.txEffects?.length ?? 0
50
119
  });
120
+ return true;
51
121
  } else {
52
122
  this.log.warn(`Non-validator reexecution failed for slot ${proposal.slotNumber}`, {
53
123
  blockNumber: result.blockNumber,
54
124
  reason: result.reason
55
125
  });
126
+ return false;
56
127
  }
57
128
  } catch (error) {
58
129
  this.log.error('Error processing block proposal in non-validator handler', error);
130
+ return false;
59
131
  }
60
- return undefined; // Non-validator nodes don't return attestations
61
132
  };
62
133
  p2pClient.registerBlockProposalHandler(handler);
63
134
  return this;
@@ -65,7 +136,7 @@ export class BlockProposalHandler {
65
136
  async handleBlockProposal(proposal, proposalSender, shouldReexecute) {
66
137
  const slotNumber = proposal.slotNumber;
67
138
  const proposer = proposal.getSender();
68
- const config = this.blockBuilder.getConfig();
139
+ const config = this.checkpointsBuilder.getConfig();
69
140
  // Reject proposals with invalid signatures
70
141
  if (!proposer) {
71
142
  this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
@@ -131,10 +202,20 @@ export class BlockProposalHandler {
131
202
  pinnedPeer: proposalSender,
132
203
  deadline: this.getReexecutionDeadline(slotNumber, config)
133
204
  });
205
+ // Compute the checkpoint number for this block and validate checkpoint consistency
206
+ const checkpointResult = await this.computeCheckpointNumber(proposal, parentBlockHeader, proposalInfo);
207
+ if (checkpointResult.reason) {
208
+ return {
209
+ isValid: false,
210
+ blockNumber,
211
+ reason: checkpointResult.reason
212
+ };
213
+ }
214
+ const checkpointNumber = checkpointResult.checkpointNumber;
134
215
  // Check that I have the same set of l1ToL2Messages as the proposal
135
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(CheckpointNumber.fromBlockNumber(blockNumber));
216
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
136
217
  const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
137
- const proposalInHash = proposal.payload.header.inHash;
218
+ const proposalInHash = proposal.inHash;
138
219
  if (!computedInHash.equals(proposalInHash)) {
139
220
  this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
140
221
  proposalInHash: proposalInHash.toString(),
@@ -162,9 +243,18 @@ export class BlockProposalHandler {
162
243
  // Try re-executing the transactions in the proposal if needed
163
244
  let reexecutionResult;
164
245
  if (shouldReexecute) {
246
+ // Compute the previous checkpoint out hashes for the epoch.
247
+ // TODO(mbps): This assumes one block per checkpoint, which is only true for now.
248
+ // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch all
249
+ // the blocks.
250
+ const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
251
+ const previousBlocks = (await this.blockSource.getBlocksForEpoch(epoch)).filter((b)=>b.number < blockNumber).sort((a, b)=>a.number - b.number);
252
+ const previousCheckpointOutHashes = previousBlocks.map((b)=>computeCheckpointOutHash([
253
+ b.body.txEffects.map((tx)=>tx.l2ToL1Msgs)
254
+ ]));
165
255
  try {
166
256
  this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
167
- reexecutionResult = await this.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
257
+ reexecutionResult = await this.reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes);
168
258
  } catch (error) {
169
259
  this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
170
260
  const reason = this.getReexecuteFailureReason(error);
@@ -176,7 +266,12 @@ export class BlockProposalHandler {
176
266
  };
177
267
  }
178
268
  }
179
- this.log.info(`Successfully processed proposal for slot ${slotNumber}`, proposalInfo);
269
+ // If we succeeded, push this block into the archiver (unless disabled)
270
+ // TODO(palla/mbps): Change default to false once block sync is stable.
271
+ if (reexecutionResult?.block && this.config.skipPushProposedBlocksToArchiver === false) {
272
+ await this.blockSource.addBlock(reexecutionResult?.block);
273
+ }
274
+ this.log.info(`Successfully processed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, proposalInfo);
180
275
  return {
181
276
  isValid: true,
182
277
  blockNumber,
@@ -184,9 +279,9 @@ export class BlockProposalHandler {
184
279
  };
185
280
  }
186
281
  async getParentBlock(proposal) {
187
- const parentArchive = proposal.payload.header.lastArchiveRoot;
282
+ const parentArchive = proposal.blockHeader.lastArchive.root;
188
283
  const slot = proposal.slotNumber;
189
- const config = this.blockBuilder.getConfig();
284
+ const config = this.checkpointsBuilder.getConfig();
190
285
  const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
191
286
  if (parentArchive.equals(genesisArchiveRoot)) {
192
287
  return 'genesis';
@@ -209,10 +304,163 @@ export class BlockProposalHandler {
209
304
  return undefined;
210
305
  }
211
306
  }
307
+ async computeCheckpointNumber(proposal, parentBlockHeader, proposalInfo) {
308
+ if (parentBlockHeader === 'genesis') {
309
+ // First block is in checkpoint 1
310
+ if (proposal.indexWithinCheckpoint !== 0) {
311
+ this.log.warn(`First block proposal has non-zero indexWithinCheckpoint`, proposalInfo);
312
+ return {
313
+ reason: 'invalid_proposal'
314
+ };
315
+ }
316
+ return {
317
+ checkpointNumber: CheckpointNumber.INITIAL
318
+ };
319
+ }
320
+ // Get the parent block to find its checkpoint number
321
+ // TODO(palla/mbps): The block header should include the checkpoint number to avoid this lookup,
322
+ // or at least the L2BlockSource should return a different struct that includes it.
323
+ const parentBlockNumber = parentBlockHeader.getBlockNumber();
324
+ const parentBlock = await this.blockSource.getL2BlockNew(parentBlockNumber);
325
+ if (!parentBlock) {
326
+ this.log.warn(`Parent block ${parentBlockNumber} not found in archiver`, proposalInfo);
327
+ return {
328
+ reason: 'invalid_proposal'
329
+ };
330
+ }
331
+ if (proposal.indexWithinCheckpoint === 0) {
332
+ // If this is the first block in a new checkpoint, increment the checkpoint number
333
+ if (!(proposal.blockHeader.getSlot() > parentBlockHeader.getSlot())) {
334
+ this.log.warn(`Slot should be greater than parent block slot for first block in checkpoint`, proposalInfo);
335
+ return {
336
+ reason: 'invalid_proposal'
337
+ };
338
+ }
339
+ return {
340
+ checkpointNumber: CheckpointNumber(parentBlock.checkpointNumber + 1)
341
+ };
342
+ }
343
+ // Otherwise it should follow the previous block in the same checkpoint
344
+ if (proposal.indexWithinCheckpoint !== parentBlock.indexWithinCheckpoint + 1) {
345
+ this.log.warn(`Non-sequential indexWithinCheckpoint`, proposalInfo);
346
+ return {
347
+ reason: 'invalid_proposal'
348
+ };
349
+ }
350
+ if (proposal.blockHeader.getSlot() !== parentBlockHeader.getSlot()) {
351
+ this.log.warn(`Slot should be equal to parent block slot for non-first block in checkpoint`, proposalInfo);
352
+ return {
353
+ reason: 'invalid_proposal'
354
+ };
355
+ }
356
+ // For non-first blocks in a checkpoint, validate global variables match parent (except blockNumber)
357
+ const validationResult = this.validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo);
358
+ if (validationResult) {
359
+ return validationResult;
360
+ }
361
+ return {
362
+ checkpointNumber: parentBlock.checkpointNumber
363
+ };
364
+ }
365
+ /**
366
+ * Validates that a non-first block in a checkpoint has consistent global variables with its parent.
367
+ * For blocks with indexWithinCheckpoint > 0, all global variables except blockNumber must match the parent.
368
+ * @returns A failure result if validation fails, undefined if validation passes
369
+ */ validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo) {
370
+ const proposalGlobals = proposal.blockHeader.globalVariables;
371
+ const parentGlobals = parentBlock.header.globalVariables;
372
+ // All global variables except blockNumber should match the parent
373
+ // blockNumber naturally increments between blocks
374
+ if (!proposalGlobals.chainId.equals(parentGlobals.chainId)) {
375
+ this.log.warn(`Non-first block in checkpoint has mismatched chainId`, {
376
+ ...proposalInfo,
377
+ proposalChainId: proposalGlobals.chainId.toString(),
378
+ parentChainId: parentGlobals.chainId.toString()
379
+ });
380
+ return {
381
+ reason: 'global_variables_mismatch'
382
+ };
383
+ }
384
+ if (!proposalGlobals.version.equals(parentGlobals.version)) {
385
+ this.log.warn(`Non-first block in checkpoint has mismatched version`, {
386
+ ...proposalInfo,
387
+ proposalVersion: proposalGlobals.version.toString(),
388
+ parentVersion: parentGlobals.version.toString()
389
+ });
390
+ return {
391
+ reason: 'global_variables_mismatch'
392
+ };
393
+ }
394
+ if (proposalGlobals.slotNumber !== parentGlobals.slotNumber) {
395
+ this.log.warn(`Non-first block in checkpoint has mismatched slotNumber`, {
396
+ ...proposalInfo,
397
+ proposalSlotNumber: proposalGlobals.slotNumber,
398
+ parentSlotNumber: parentGlobals.slotNumber
399
+ });
400
+ return {
401
+ reason: 'global_variables_mismatch'
402
+ };
403
+ }
404
+ if (proposalGlobals.timestamp !== parentGlobals.timestamp) {
405
+ this.log.warn(`Non-first block in checkpoint has mismatched timestamp`, {
406
+ ...proposalInfo,
407
+ proposalTimestamp: proposalGlobals.timestamp.toString(),
408
+ parentTimestamp: parentGlobals.timestamp.toString()
409
+ });
410
+ return {
411
+ reason: 'global_variables_mismatch'
412
+ };
413
+ }
414
+ if (!proposalGlobals.coinbase.equals(parentGlobals.coinbase)) {
415
+ this.log.warn(`Non-first block in checkpoint has mismatched coinbase`, {
416
+ ...proposalInfo,
417
+ proposalCoinbase: proposalGlobals.coinbase.toString(),
418
+ parentCoinbase: parentGlobals.coinbase.toString()
419
+ });
420
+ return {
421
+ reason: 'global_variables_mismatch'
422
+ };
423
+ }
424
+ if (!proposalGlobals.feeRecipient.equals(parentGlobals.feeRecipient)) {
425
+ this.log.warn(`Non-first block in checkpoint has mismatched feeRecipient`, {
426
+ ...proposalInfo,
427
+ proposalFeeRecipient: proposalGlobals.feeRecipient.toString(),
428
+ parentFeeRecipient: parentGlobals.feeRecipient.toString()
429
+ });
430
+ return {
431
+ reason: 'global_variables_mismatch'
432
+ };
433
+ }
434
+ if (!proposalGlobals.gasFees.equals(parentGlobals.gasFees)) {
435
+ this.log.warn(`Non-first block in checkpoint has mismatched gasFees`, {
436
+ ...proposalInfo,
437
+ proposalGasFees: proposalGlobals.gasFees.toInspect(),
438
+ parentGasFees: parentGlobals.gasFees.toInspect()
439
+ });
440
+ return {
441
+ reason: 'global_variables_mismatch'
442
+ };
443
+ }
444
+ return undefined;
445
+ }
212
446
  getReexecutionDeadline(slot, config) {
213
447
  const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
214
- const msNeededForPropagationAndPublishing = this.config.validatorReexecuteDeadlineMs;
215
- return new Date(nextSlotTimestampSeconds * 1000 - msNeededForPropagationAndPublishing);
448
+ return new Date(nextSlotTimestampSeconds * 1000);
449
+ }
450
+ /**
451
+ * Gets all prior blocks in the same checkpoint (same slot and checkpoint number) up to but not including upToBlockNumber.
452
+ */ async getBlocksInCheckpoint(slot, upToBlockNumber, checkpointNumber) {
453
+ const blocks = [];
454
+ let currentBlockNumber = BlockNumber(upToBlockNumber - 1);
455
+ while(currentBlockNumber >= INITIAL_L2_BLOCK_NUM){
456
+ const block = await this.blockSource.getL2BlockNew(currentBlockNumber);
457
+ if (!block || block.header.getSlot() !== slot || block.checkpointNumber !== checkpointNumber) {
458
+ break;
459
+ }
460
+ blocks.unshift(block);
461
+ currentBlockNumber = BlockNumber(currentBlockNumber - 1);
462
+ }
463
+ return blocks;
216
464
  }
217
465
  getReexecuteFailureReason(err) {
218
466
  if (err instanceof ReExStateMismatchError) {
@@ -225,66 +473,89 @@ export class BlockProposalHandler {
225
473
  return 'unknown_error';
226
474
  }
227
475
  }
228
- async reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages) {
229
- const { header } = proposal.payload;
230
- const { txHashes } = proposal;
231
- // If we do not have all of the transactions, then we should fail
232
- if (txs.length !== txHashes.length) {
233
- const foundTxHashes = txs.map((tx)=>tx.getTxHash());
234
- const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.includes(txHash));
235
- throw new TransactionsNotAvailableError(missingTxHashes);
236
- }
237
- // Use the sequencer's block building logic to re-execute the transactions
238
- const timer = new Timer();
239
- const config = this.blockBuilder.getConfig();
240
- // We source most global variables from the proposal
241
- const globalVariables = GlobalVariables.from({
242
- slotNumber: proposal.payload.header.slotNumber,
243
- coinbase: proposal.payload.header.coinbase,
244
- feeRecipient: proposal.payload.header.feeRecipient,
245
- gasFees: proposal.payload.header.gasFees,
246
- blockNumber,
247
- timestamp: header.timestamp,
248
- chainId: new Fr(config.l1ChainId),
249
- version: new Fr(config.rollupVersion)
250
- });
251
- const { block, failedTxs } = await this.blockBuilder.buildBlock(txs, l1ToL2Messages, globalVariables, {
252
- deadline: this.getReexecutionDeadline(proposal.payload.header.slotNumber, config)
253
- });
254
- const numFailedTxs = failedTxs.length;
255
- const slot = proposal.slotNumber;
256
- this.log.verbose(`Transaction re-execution complete for slot ${slot}`, {
257
- numFailedTxs,
258
- numProposalTxs: txHashes.length,
259
- numProcessedTxs: block.body.txEffects.length,
260
- slot
261
- });
262
- if (numFailedTxs > 0) {
263
- this.metrics?.recordFailedReexecution(proposal);
264
- throw new ReExFailedTxsError(numFailedTxs);
265
- }
266
- if (block.body.txEffects.length !== txHashes.length) {
267
- this.metrics?.recordFailedReexecution(proposal);
268
- throw new ReExTimeoutError();
269
- }
270
- // Throw a ReExStateMismatchError error if state updates do not match
271
- const blockPayload = ConsensusPayload.fromBlock(block);
272
- if (!blockPayload.equals(proposal.payload)) {
273
- this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
274
- expected: blockPayload.toInspect(),
275
- actual: proposal.payload.toInspect()
476
+ async reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes) {
477
+ const env = {
478
+ stack: [],
479
+ error: void 0,
480
+ hasError: false
481
+ };
482
+ try {
483
+ const { blockHeader, txHashes } = proposal;
484
+ // If we do not have all of the transactions, then we should fail
485
+ if (txs.length !== txHashes.length) {
486
+ const foundTxHashes = txs.map((tx)=>tx.getTxHash());
487
+ const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.includes(txHash));
488
+ throw new TransactionsNotAvailableError(missingTxHashes);
489
+ }
490
+ const timer = new Timer();
491
+ const slot = proposal.slotNumber;
492
+ const config = this.checkpointsBuilder.getConfig();
493
+ // Get prior blocks in this checkpoint (same slot and checkpoint number)
494
+ const priorBlocks = await this.getBlocksInCheckpoint(slot, blockNumber, checkpointNumber);
495
+ // Fork before the block to be built
496
+ const parentBlockNumber = BlockNumber(blockNumber - 1);
497
+ const fork = _ts_add_disposable_resource(env, await this.worldState.fork(parentBlockNumber), false);
498
+ // Build checkpoint constants from proposal (excludes blockNumber and timestamp which are per-block)
499
+ const constants = {
500
+ chainId: new Fr(config.l1ChainId),
501
+ version: new Fr(config.rollupVersion),
502
+ slotNumber: slot,
503
+ coinbase: blockHeader.globalVariables.coinbase,
504
+ feeRecipient: blockHeader.globalVariables.feeRecipient,
505
+ gasFees: blockHeader.globalVariables.gasFees
506
+ };
507
+ // Create checkpoint builder with prior blocks
508
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, l1ToL2Messages, previousCheckpointOutHashes, fork, priorBlocks);
509
+ // Build the new block
510
+ const deadline = this.getReexecutionDeadline(slot, config);
511
+ const result = await checkpointBuilder.buildBlock(txs, blockNumber, blockHeader.globalVariables.timestamp, {
512
+ deadline,
513
+ expectedEndState: blockHeader.state
276
514
  });
277
- this.metrics?.recordFailedReexecution(proposal);
278
- throw new ReExStateMismatchError(proposal.archive, block.archive.root);
515
+ const { block, failedTxs } = result;
516
+ const numFailedTxs = failedTxs.length;
517
+ this.log.verbose(`Transaction re-execution complete for slot ${slot}`, {
518
+ numFailedTxs,
519
+ numProposalTxs: txHashes.length,
520
+ numProcessedTxs: block.body.txEffects.length,
521
+ slot
522
+ });
523
+ if (numFailedTxs > 0) {
524
+ this.metrics?.recordFailedReexecution(proposal);
525
+ throw new ReExFailedTxsError(numFailedTxs);
526
+ }
527
+ if (block.body.txEffects.length !== txHashes.length) {
528
+ this.metrics?.recordFailedReexecution(proposal);
529
+ throw new ReExTimeoutError();
530
+ }
531
+ // Throw a ReExStateMismatchError error if state updates do not match
532
+ // Compare the full block structure (archive and header) from the built block with the proposal
533
+ const archiveMatches = proposal.archive.equals(block.archive.root);
534
+ const headerMatches = proposal.blockHeader.equals(block.header);
535
+ if (!archiveMatches || !headerMatches) {
536
+ this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
537
+ expectedArchive: block.archive.root.toString(),
538
+ actualArchive: proposal.archive.toString(),
539
+ expectedHeader: block.header.toInspect(),
540
+ actualHeader: proposal.blockHeader.toInspect()
541
+ });
542
+ this.metrics?.recordFailedReexecution(proposal);
543
+ throw new ReExStateMismatchError(proposal.archive, block.archive.root);
544
+ }
545
+ const reexecutionTimeMs = timer.ms();
546
+ const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
547
+ this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
548
+ return {
549
+ block,
550
+ failedTxs,
551
+ reexecutionTimeMs,
552
+ totalManaUsed
553
+ };
554
+ } catch (e) {
555
+ env.error = e;
556
+ env.hasError = true;
557
+ } finally{
558
+ _ts_dispose_resources(env);
279
559
  }
280
- const reexecutionTimeMs = timer.ms();
281
- const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
282
- this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
283
- return {
284
- block,
285
- failedTxs,
286
- reexecutionTimeMs,
287
- totalManaUsed
288
- };
289
560
  }
290
561
  }
@@ -0,0 +1,70 @@
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { DateProvider, Timer } from '@aztec/foundation/timer';
4
+ import { LightweightCheckpointBuilder } from '@aztec/prover-client/light';
5
+ import { PublicProcessor } from '@aztec/simulator/server';
6
+ import { L2BlockNew } from '@aztec/stdlib/block';
7
+ import { Checkpoint } from '@aztec/stdlib/checkpoint';
8
+ import type { ContractDataSource } from '@aztec/stdlib/contract';
9
+ import { Gas } from '@aztec/stdlib/gas';
10
+ import { type FullNodeBlockBuilderConfig, type MerkleTreeWriteOperations, type PublicProcessorLimits } from '@aztec/stdlib/interfaces/server';
11
+ import { type CheckpointGlobalVariables, type FailedTx, GlobalVariables, StateReference, Tx } from '@aztec/stdlib/tx';
12
+ import { type TelemetryClient } from '@aztec/telemetry-client';
13
+ export interface BuildBlockInCheckpointResult {
14
+ block: L2BlockNew;
15
+ publicGas: Gas;
16
+ publicProcessorDuration: number;
17
+ numTxs: number;
18
+ failedTxs: FailedTx[];
19
+ blockBuildingTimer: Timer;
20
+ usedTxs: Tx[];
21
+ }
22
+ /**
23
+ * Builder for a single checkpoint. Handles building blocks within the checkpoint
24
+ * and completing it.
25
+ */
26
+ export declare class CheckpointBuilder {
27
+ private checkpointBuilder;
28
+ private fork;
29
+ private config;
30
+ private contractDataSource;
31
+ private dateProvider;
32
+ private telemetryClient;
33
+ constructor(checkpointBuilder: LightweightCheckpointBuilder, fork: MerkleTreeWriteOperations, config: FullNodeBlockBuilderConfig, contractDataSource: ContractDataSource, dateProvider: DateProvider, telemetryClient: TelemetryClient);
34
+ getConstantData(): CheckpointGlobalVariables;
35
+ /**
36
+ * Builds a single block within this checkpoint.
37
+ */
38
+ buildBlock(pendingTxs: Iterable<Tx> | AsyncIterable<Tx>, blockNumber: BlockNumber, timestamp: bigint, opts: PublicProcessorLimits & {
39
+ expectedEndState?: StateReference;
40
+ }): Promise<BuildBlockInCheckpointResult>;
41
+ /** Completes the checkpoint and returns it. */
42
+ completeCheckpoint(): Promise<Checkpoint>;
43
+ /** Gets the checkpoint currently in progress. */
44
+ getCheckpoint(): Promise<Checkpoint>;
45
+ protected makeBlockBuilderDeps(globalVariables: GlobalVariables, fork: MerkleTreeWriteOperations): Promise<{
46
+ processor: PublicProcessor;
47
+ validator: import("@aztec/stdlib/interfaces/server").PublicProcessorValidator;
48
+ }>;
49
+ }
50
+ /**
51
+ * Factory for creating checkpoint builders.
52
+ */
53
+ export declare class FullNodeCheckpointsBuilder {
54
+ private config;
55
+ private contractDataSource;
56
+ private dateProvider;
57
+ private telemetryClient;
58
+ constructor(config: FullNodeBlockBuilderConfig, contractDataSource: ContractDataSource, dateProvider: DateProvider, telemetryClient?: TelemetryClient);
59
+ getConfig(): FullNodeBlockBuilderConfig;
60
+ updateConfig(config: Partial<FullNodeBlockBuilderConfig>): void;
61
+ /**
62
+ * Starts a new checkpoint and returns a CheckpointBuilder to build blocks within it.
63
+ */
64
+ startCheckpoint(checkpointNumber: CheckpointNumber, constants: CheckpointGlobalVariables, l1ToL2Messages: Fr[], previousCheckpointOutHashes: Fr[], fork: MerkleTreeWriteOperations): Promise<CheckpointBuilder>;
65
+ /**
66
+ * Opens a checkpoint, either starting fresh or resuming from existing blocks.
67
+ */
68
+ openCheckpoint(checkpointNumber: CheckpointNumber, constants: CheckpointGlobalVariables, l1ToL2Messages: Fr[], previousCheckpointOutHashes: Fr[], fork: MerkleTreeWriteOperations, existingBlocks?: L2BlockNew[]): Promise<CheckpointBuilder>;
69
+ }
70
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWx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