@aztec/simulator 0.0.1-commit.2f68f620 → 0.0.1-commit.321f6a9

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 (109) hide show
  1. package/dest/client.d.ts +1 -3
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +0 -2
  4. package/dest/private/circuit_recording/circuit_recorder.d.ts +36 -23
  5. package/dest/private/circuit_recording/circuit_recorder.d.ts.map +1 -1
  6. package/dest/private/circuit_recording/circuit_recorder.js +65 -69
  7. package/dest/private/circuit_recording/file_circuit_recorder.d.ts +7 -19
  8. package/dest/private/circuit_recording/file_circuit_recorder.d.ts.map +1 -1
  9. package/dest/private/circuit_recording/file_circuit_recorder.js +38 -42
  10. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts +1 -1
  11. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts.map +1 -1
  12. package/dest/private/circuit_recording/simulator_recorder_wrapper.js +11 -14
  13. package/dest/public/avm/testing/base_avm_simulation_tester.js +1 -1
  14. package/dest/public/avm/testing/utils.js +1 -1
  15. package/dest/public/avm_simulator.d.ts +28 -0
  16. package/dest/public/avm_simulator.d.ts.map +1 -0
  17. package/dest/public/avm_simulator.js +4 -0
  18. package/dest/public/avm_simulator_pool.d.ts +45 -0
  19. package/dest/public/avm_simulator_pool.d.ts.map +1 -0
  20. package/dest/public/avm_simulator_pool.js +197 -0
  21. package/dest/public/cdb/generated/api_types.d.ts +171 -0
  22. package/dest/public/cdb/generated/api_types.d.ts.map +1 -0
  23. package/dest/public/cdb/generated/api_types.js +314 -0
  24. package/dest/public/cdb/generated/server.d.ts +26 -0
  25. package/dest/public/cdb/generated/server.d.ts.map +1 -0
  26. package/dest/public/cdb/generated/server.js +135 -0
  27. package/dest/public/cdb_ipc_server.d.ts +33 -0
  28. package/dest/public/cdb_ipc_server.d.ts.map +1 -0
  29. package/dest/public/cdb_ipc_server.js +153 -0
  30. package/dest/public/fixtures/amm_test.js +2 -2
  31. package/dest/public/fixtures/bulk_test.js +2 -2
  32. package/dest/public/fixtures/custom_bytecode_tester.d.ts +1 -1
  33. package/dest/public/fixtures/custom_bytecode_tester.d.ts.map +1 -1
  34. package/dest/public/fixtures/custom_bytecode_tester.js +2 -2
  35. package/dest/public/fixtures/index.d.ts +2 -1
  36. package/dest/public/fixtures/index.d.ts.map +1 -1
  37. package/dest/public/fixtures/index.js +1 -0
  38. package/dest/public/fixtures/public_processor_test_env.d.ts +30 -0
  39. package/dest/public/fixtures/public_processor_test_env.d.ts.map +1 -0
  40. package/dest/public/fixtures/public_processor_test_env.js +73 -0
  41. package/dest/public/fixtures/public_tx_simulation_tester.d.ts +9 -5
  42. package/dest/public/fixtures/public_tx_simulation_tester.d.ts.map +1 -1
  43. package/dest/public/fixtures/public_tx_simulation_tester.js +29 -11
  44. package/dest/public/fixtures/token_test.js +3 -3
  45. package/dest/public/fixtures/utils.d.ts +1 -1
  46. package/dest/public/fixtures/utils.d.ts.map +1 -1
  47. package/dest/public/fixtures/utils.js +5 -3
  48. package/dest/public/fuzzing/avm_fuzzer_simulator.d.ts +7 -2
  49. package/dest/public/fuzzing/avm_fuzzer_simulator.d.ts.map +1 -1
  50. package/dest/public/fuzzing/avm_fuzzer_simulator.js +15 -6
  51. package/dest/public/index.d.ts +5 -2
  52. package/dest/public/index.d.ts.map +1 -1
  53. package/dest/public/index.js +2 -1
  54. package/dest/public/public_db_sources.d.ts +2 -2
  55. package/dest/public/public_db_sources.d.ts.map +1 -1
  56. package/dest/public/public_db_sources.js +1 -1
  57. package/dest/public/public_processor/public_processor.d.ts +8 -4
  58. package/dest/public/public_processor/public_processor.d.ts.map +1 -1
  59. package/dest/public/public_processor/public_processor.js +17 -13
  60. package/dest/public/public_tx_simulator/dumping_public_tx_simulator.d.ts +6 -12
  61. package/dest/public/public_tx_simulator/dumping_public_tx_simulator.d.ts.map +1 -1
  62. package/dest/public/public_tx_simulator/dumping_public_tx_simulator.js +8 -21
  63. package/dest/public/public_tx_simulator/factories.d.ts +5 -5
  64. package/dest/public/public_tx_simulator/factories.d.ts.map +1 -1
  65. package/dest/public/public_tx_simulator/factories.js +5 -5
  66. package/dest/public/public_tx_simulator/index.d.ts +3 -3
  67. package/dest/public/public_tx_simulator/index.d.ts.map +1 -1
  68. package/dest/public/public_tx_simulator/index.js +1 -1
  69. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts +16 -16
  70. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts.map +1 -1
  71. package/dest/public/public_tx_simulator/public_tx_simulator.js +59 -58
  72. package/dest/public/public_tx_simulator/public_tx_simulator_base.d.ts +10 -8
  73. package/dest/public/public_tx_simulator/public_tx_simulator_base.d.ts.map +1 -1
  74. package/dest/public/public_tx_simulator/public_tx_simulator_base.js +11 -8
  75. package/dest/public/public_tx_simulator/public_tx_simulator_interface.d.ts +5 -5
  76. package/package.json +21 -17
  77. package/src/client.ts +0 -2
  78. package/src/private/circuit_recording/circuit_recorder.ts +84 -78
  79. package/src/private/circuit_recording/file_circuit_recorder.ts +38 -48
  80. package/src/private/circuit_recording/simulator_recorder_wrapper.ts +9 -15
  81. package/src/public/avm/testing/base_avm_simulation_tester.ts +1 -1
  82. package/src/public/avm/testing/utils.ts +1 -1
  83. package/src/public/avm_simulator.ts +29 -0
  84. package/src/public/avm_simulator_pool.ts +226 -0
  85. package/src/public/cdb/generated/api_types.ts +457 -0
  86. package/src/public/cdb/generated/server.ts +109 -0
  87. package/src/public/cdb_ipc_server.ts +197 -0
  88. package/src/public/fixtures/amm_test.ts +2 -2
  89. package/src/public/fixtures/bulk_test.ts +2 -2
  90. package/src/public/fixtures/custom_bytecode_tester.ts +2 -2
  91. package/src/public/fixtures/index.ts +1 -0
  92. package/src/public/fixtures/public_processor_test_env.ts +88 -0
  93. package/src/public/fixtures/public_tx_simulation_tester.ts +37 -25
  94. package/src/public/fixtures/token_test.ts +3 -3
  95. package/src/public/fixtures/utils.ts +6 -11
  96. package/src/public/fuzzing/avm_fuzzer_simulator.ts +28 -10
  97. package/src/public/index.ts +4 -0
  98. package/src/public/public_db_sources.ts +1 -1
  99. package/src/public/public_processor/public_processor.ts +22 -15
  100. package/src/public/public_tx_simulator/dumping_public_tx_simulator.ts +13 -29
  101. package/src/public/public_tx_simulator/factories.ts +24 -7
  102. package/src/public/public_tx_simulator/index.ts +5 -2
  103. package/src/public/public_tx_simulator/public_tx_simulator.ts +70 -81
  104. package/src/public/public_tx_simulator/public_tx_simulator_base.ts +8 -6
  105. package/src/public/public_tx_simulator/public_tx_simulator_interface.ts +5 -5
  106. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts +0 -19
  107. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts.map +0 -1
  108. package/dest/public/public_tx_simulator/contract_provider_for_cpp.js +0 -99
  109. package/src/public/public_tx_simulator/contract_provider_for_cpp.ts +0 -125
@@ -1,107 +1,108 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
2
  import { sleep } from '@aztec/foundation/sleep';
3
- import { avmSimulate, cancelSimulation, createCancellationToken } from '@aztec/native';
4
- import { ProtocolContractsList } from '@aztec/protocol-contracts';
5
3
  import { AvmFastSimulationInputs, AvmTxHint, PublicTxResult, deserializeFromMessagePack } from '@aztec/stdlib/avm';
6
4
  import { SimulationError } from '@aztec/stdlib/errors';
5
+ import { WorldStateRevision } from '@aztec/stdlib/world-state';
7
6
  import { getTelemetryClient } from '@aztec/telemetry-client';
8
7
  import { ExecutorMetrics } from '../executor_metrics.js';
9
- import { ContractProviderForCpp } from './contract_provider_for_cpp.js';
10
8
  import { PublicTxSimulatorBase } from './public_tx_simulator_base.js';
11
9
  /**
12
- * Simulates a transaction's public portion using the C++ AVM simulator.
13
- * The C++ simulator accesses the world state directly/natively within C++.
14
- * For contract DB accesses, it makes callbacks through NAPI back to the TS PublicContractsDB cache.
10
+ * Simulates a transaction's public portion by running its public calls through an {@link AvmSimulator}.
11
+ * `forkId` selects the fork whose contract data the simulation reads.
15
12
  */ export class PublicTxSimulator extends PublicTxSimulatorBase {
16
13
  log;
17
- /** Current cancellation token for in-flight simulation. */ cancellationToken;
14
+ /** Aborts the in-flight simulation. */ abortController;
18
15
  /** Current simulation promise, used to wait for completion after cancellation. */ simulationPromise;
19
- constructor(merkleTree, contractsDB, globalVariables, config, bindings){
20
- super(merkleTree, contractsDB, globalVariables, config, undefined, bindings);
16
+ constructor(avmSimulator, globalVariables, contractsDB, forkId, config, bindings){
17
+ super(avmSimulator, globalVariables, contractsDB, forkId, config, undefined, bindings);
21
18
  this.log = createLogger(`simulator:public_tx_simulator`, bindings);
22
19
  }
23
20
  /**
24
- * Simulate a transaction's public portion using the C++ avvm simulator.
21
+ * Simulate a transaction's public portion.
25
22
  *
26
23
  * @param tx - The transaction to simulate.
27
24
  * @returns The result of the transaction's public execution.
28
25
  */ async simulate(tx) {
26
+ this.abortController = new AbortController();
27
+ this.simulationPromise = this.doSimulate(tx, this.abortController.signal);
28
+ try {
29
+ return await this.simulationPromise;
30
+ } finally{
31
+ this.abortController = undefined;
32
+ this.simulationPromise = undefined;
33
+ }
34
+ }
35
+ async doSimulate(tx, signal) {
29
36
  const txHash = this.computeTxHash(tx);
30
- this.log.debug(`C++ simulation of ${tx.publicFunctionCalldata.length} public calls for tx ${txHash}`, {
37
+ this.log.debug(`Simulating ${tx.publicFunctionCalldata.length} public calls for tx ${txHash}, forkId=${this.forkId}`, {
31
38
  txHash
32
39
  });
33
- const wsRevision = this.merkleTree.getRevision();
34
- const wsdbIpcPath = this.merkleTree.getIpcPath();
35
- this.log.trace(`Running C++ simulation with world state revision ${JSON.stringify(wsRevision)}`);
36
- // Create the fast simulation inputs
40
+ // Create the fast simulation inputs.
37
41
  const txHint = AvmTxHint.fromTx(tx, this.globalVariables.gasFees);
38
- const protocolContracts = ProtocolContractsList;
39
- const fastSimInputs = new AvmFastSimulationInputs(wsRevision, this.config, txHint, this.globalVariables, protocolContracts);
40
- // Create contract provider for callbacks to TypeScript PublicContractsDB from C++
41
- const contractProvider = new ContractProviderForCpp(this.contractsDB, this.globalVariables, this.bindings);
42
- // Serialize to msgpack and call the C++ simulator
42
+ const fastSimInputs = new AvmFastSimulationInputs(// blockNumber: WorldStateRevision.LATEST sentinel so the WSDB walks the fork's current
43
+ // uncommitted state. Using 0 here makes WSDB treat this as a historical query against
44
+ // the empty genesis tree and miss any in-fork uncommitted leaves (deployed contracts,
45
+ // etc.) from earlier txs in the same block.
46
+ {
47
+ forkId: this.forkId,
48
+ blockNumber: WorldStateRevision.LATEST,
49
+ includeUncommitted: true
50
+ }, this.config, txHint, this.globalVariables, this.protocolContracts);
43
51
  this.log.trace(`Serializing fast simulation inputs to msgpack...`);
44
52
  const inputBuffer = fastSimInputs.serializeWithMessagePack();
45
- // Create cancellation token for this simulation
46
- this.cancellationToken = createCancellationToken();
47
- // Store the promise so cancel() can wait for it
48
- this.log.debug(`Calling C++ simulator for tx ${txHash}`);
49
- this.simulationPromise = avmSimulate(inputBuffer, contractProvider, wsdbIpcPath, this.log.level, undefined, this.cancellationToken);
53
+ this.log.debug(`Running AVM simulation for tx ${txHash}`);
54
+ const context = {
55
+ contractsDB: this.contractsDB,
56
+ forkId: this.forkId,
57
+ timestamp: this.globalVariables.timestamp
58
+ };
50
59
  let resultBuffer;
51
60
  try {
52
- resultBuffer = await this.simulationPromise;
61
+ resultBuffer = await this.avmSimulator.simulate(inputBuffer, context, signal);
53
62
  } catch (error) {
54
- // Check if this was a cancellation
55
- if (error.message?.includes('Simulation cancelled')) {
56
- throw new SimulationError(`C++ simulation cancelled`, []);
63
+ if (error.message?.includes('cancelled')) {
64
+ throw new SimulationError(`AVM simulation cancelled`, []);
57
65
  }
58
- throw new SimulationError(`C++ simulation failed: ${error.message}`, []);
59
- } finally{
60
- this.cancellationToken = undefined;
61
- this.simulationPromise = undefined;
66
+ throw new SimulationError(`AVM simulation failed: ${error.message}`, []);
62
67
  }
63
- // If we've reached this point, C++ succeeded during simulation,
64
- // Deserialize the msgpack result
65
- this.log.trace(`Deserializing C++ from buffer (size: ${resultBuffer.length})...`);
66
- const cppResultJSON = deserializeFromMessagePack(resultBuffer);
67
- this.log.trace(`Deserializing C++ result to PublicTxResult...`);
68
- const cppResult = PublicTxResult.fromPlainObject(cppResultJSON);
69
- this.log.trace(`C++ simulation completed for tx ${txHash}`, {
68
+ this.log.trace(`Deserializing simulation result from buffer (size: ${resultBuffer.length})...`);
69
+ const resultJSON = deserializeFromMessagePack(Buffer.from(resultBuffer));
70
+ const result = PublicTxResult.fromPlainObject(resultJSON);
71
+ this.log.trace(`AVM simulation completed for tx ${txHash}`, {
70
72
  txHash,
71
- reverted: !cppResult.revertCode.isOK(),
72
- cppGasUsed: cppResult.gasUsed.totalGas.l2Gas
73
+ reverted: !result.revertCode.isOK(),
74
+ l2GasUsed: result.gasUsed.totalGas.l2Gas
73
75
  });
74
- return cppResult;
76
+ return result;
75
77
  }
76
78
  /**
77
79
  * Cancel the current simulation if one is in progress.
78
- * This signals the C++ simulator to stop at the next opcode or before the next WorldState write.
79
- * Safe to call even if no simulation is in progress.
80
+ * This signals the underlying simulator to stop at the next safe point (between opcodes, before a
81
+ * world-state write). Safe to call even if no simulation is in progress.
80
82
  *
81
83
  * @param waitTimeoutMs - If provided, wait up to this many ms for the simulation to actually stop.
82
- * This is important because C++ might be in the middle of a slow operation
83
- * (e.g., pad_trees) and won't check the cancellation flag until it completes.
84
+ * Cancellation is cooperative: the simulator may be mid slow-operation and
85
+ * won't observe the cancellation until it completes.
84
86
  * Default timeout of 100ms after cancellation.
85
87
  */ async cancel(waitTimeoutMs = 100) {
86
- if (this.cancellationToken) {
87
- this.log.debug('Cancelling C++ simulation');
88
- cancelSimulation(this.cancellationToken);
88
+ if (this.abortController) {
89
+ this.log.debug('Cancelling AVM simulation');
90
+ this.abortController.abort();
89
91
  }
90
- // Wait for the simulation to actually complete if not already done
91
92
  if (this.simulationPromise) {
92
- this.log.debug(`Waiting up to ${waitTimeoutMs}ms for C++ simulation to stop`);
93
+ this.log.debug(`Waiting up to ${waitTimeoutMs}ms for AVM simulation to stop`);
93
94
  await Promise.race([
94
95
  this.simulationPromise.catch(()=>{}),
95
96
  sleep(waitTimeoutMs)
96
97
  ]);
97
- this.log.debug('C++ simulation stopped or wait timed out');
98
+ this.log.debug('AVM simulation stopped or wait timed out');
98
99
  }
99
100
  }
100
101
  }
101
102
  export class MeasuredPublicTxSimulator extends PublicTxSimulator {
102
103
  metrics;
103
- constructor(merkleTree, contractsDB, globalVariables, metrics, config, bindings){
104
- super(merkleTree, contractsDB, globalVariables, config, bindings), this.metrics = metrics;
104
+ constructor(avmSimulator, globalVariables, contractsDB, forkId, metrics, config, bindings){
105
+ super(avmSimulator, globalVariables, contractsDB, forkId, config, bindings), this.metrics = metrics;
105
106
  }
106
107
  async simulate(tx, txLabel = 'unlabeledTx') {
107
108
  this.metrics.startRecordingTxSimulation(txLabel);
@@ -115,12 +116,12 @@ export class MeasuredPublicTxSimulator extends PublicTxSimulator {
115
116
  }
116
117
  }
117
118
  /**
118
- * A C++ public tx simulator that tracks runtime/production metrics with telemetry.
119
+ * A public tx simulator that tracks runtime/production metrics with telemetry.
119
120
  */ export class TelemetryPublicTxSimulator extends MeasuredPublicTxSimulator {
120
121
  /* tracer needed by trackSpans */ tracer;
121
- constructor(merkleTree, contractsDB, globalVariables, telemetryClient = getTelemetryClient(), config, bindings){
122
+ constructor(avmSimulator, globalVariables, contractsDB, forkId, telemetryClient = getTelemetryClient(), config, bindings){
122
123
  const metrics = new ExecutorMetrics(telemetryClient, 'PublicTxSimulator');
123
- super(merkleTree, contractsDB, globalVariables, metrics, config, bindings);
124
+ super(avmSimulator, globalVariables, contractsDB, forkId, metrics, config, bindings);
124
125
  this.tracer = metrics.tracer;
125
126
  }
126
127
  }
@@ -1,22 +1,24 @@
1
1
  import { type Logger, type LoggerBindings } from '@aztec/foundation/log';
2
2
  import { PublicSimulatorConfig } from '@aztec/stdlib/avm';
3
- import type { MerkleTreeWriteOperations } from '@aztec/stdlib/trees';
4
3
  import type { GlobalVariables, ProtocolContracts, Tx } from '@aztec/stdlib/tx';
4
+ import type { AvmSimulator } from '../avm_simulator.js';
5
5
  import type { PublicContractsDB } from '../public_db_sources.js';
6
6
  /**
7
- * Shared base for public tx simulators. Holds the common configuration, world-state and contract DB
8
- * handles, logger, and the tx-hash helper. Concrete simulators (e.g. the C++ simulator) extend this
9
- * and implement `simulate`.
7
+ * Shared base for public tx simulators: holds the common configuration, the {@link AvmSimulator} used
8
+ * to run the transaction's public calls, the contracts DB and fork id that scope the simulation's
9
+ * contract-data lookups, the logger, and the tx-hash helper. Concrete simulators extend this and
10
+ * implement `simulate`.
10
11
  */
11
12
  export declare abstract class PublicTxSimulatorBase {
12
- protected merkleTree: MerkleTreeWriteOperations;
13
- protected contractsDB: PublicContractsDB;
13
+ protected avmSimulator: AvmSimulator;
14
14
  protected globalVariables: GlobalVariables;
15
+ protected contractsDB: PublicContractsDB;
16
+ protected forkId: number;
15
17
  protected protocolContracts: ProtocolContracts;
16
18
  protected log: Logger;
17
19
  protected readonly config: PublicSimulatorConfig;
18
20
  protected readonly bindings?: LoggerBindings;
19
- constructor(merkleTree: MerkleTreeWriteOperations, contractsDB: PublicContractsDB, globalVariables: GlobalVariables, config?: Partial<PublicSimulatorConfig>, protocolContracts?: ProtocolContracts, bindings?: LoggerBindings);
21
+ constructor(avmSimulator: AvmSimulator, globalVariables: GlobalVariables, contractsDB: PublicContractsDB, forkId: number, config?: Partial<PublicSimulatorConfig>, protocolContracts?: ProtocolContracts, bindings?: LoggerBindings);
20
22
  protected computeTxHash(tx: Tx): import("@aztec/stdlib/tx").TxHash;
21
23
  }
22
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX3R4X3NpbXVsYXRvcl9iYXNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvcHVibGljL3B1YmxpY190eF9zaW11bGF0b3IvcHVibG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AAY,EAC1B,eAAe,EAAE,eAAe,EAChC,WAAW,EAAE,iBAAiB,EAC9B,MAAM,EAAE,MAAM,EACxB,MAAM,CAAC,EAAE,OAAO,CAAC,qBAAqB,CAAC,EAC7B,iBAAiB,GAAE,iBAAyC,EACtE,QAAQ,CAAC,EAAE,cAAc,EAK1B;IAED,SAAS,CAAC,aAAa,CAAC,EAAE,EAAE,EAAE,qCAE7B;CACF"}
@@ -2,21 +2,24 @@ import { createLogger } from '@aztec/foundation/log';
2
2
  import { ProtocolContractsList } from '@aztec/protocol-contracts';
3
3
  import { PublicSimulatorConfig } from '@aztec/stdlib/avm';
4
4
  /**
5
- * Shared base for public tx simulators. Holds the common configuration, world-state and contract DB
6
- * handles, logger, and the tx-hash helper. Concrete simulators (e.g. the C++ simulator) extend this
7
- * and implement `simulate`.
5
+ * Shared base for public tx simulators: holds the common configuration, the {@link AvmSimulator} used
6
+ * to run the transaction's public calls, the contracts DB and fork id that scope the simulation's
7
+ * contract-data lookups, the logger, and the tx-hash helper. Concrete simulators extend this and
8
+ * implement `simulate`.
8
9
  */ export class PublicTxSimulatorBase {
9
- merkleTree;
10
- contractsDB;
10
+ avmSimulator;
11
11
  globalVariables;
12
+ contractsDB;
13
+ forkId;
12
14
  protocolContracts;
13
15
  log;
14
16
  config;
15
17
  bindings;
16
- constructor(merkleTree, contractsDB, globalVariables, config, protocolContracts = ProtocolContractsList, bindings){
17
- this.merkleTree = merkleTree;
18
- this.contractsDB = contractsDB;
18
+ constructor(avmSimulator, globalVariables, contractsDB, forkId, config, protocolContracts = ProtocolContractsList, bindings){
19
+ this.avmSimulator = avmSimulator;
19
20
  this.globalVariables = globalVariables;
21
+ this.contractsDB = contractsDB;
22
+ this.forkId = forkId;
20
23
  this.protocolContracts = protocolContracts;
21
24
  this.config = PublicSimulatorConfig.from(config ?? {});
22
25
  this.bindings = bindings;
@@ -4,14 +4,14 @@ export interface PublicTxSimulatorInterface {
4
4
  simulate(tx: Tx): Promise<PublicTxResult>;
5
5
  /**
6
6
  * Cancel the current simulation if one is in progress.
7
- * This signals the underlying simulator (e.g., C++) to stop at the next safe point.
7
+ * This signals the underlying simulator to stop at the next safe point.
8
8
  * Safe to call even if no simulation is in progress.
9
9
  * Optional - not all implementations support cancellation.
10
10
  *
11
11
  * @param waitTimeoutMs - If provided, wait up to this many ms for the simulation to actually stop.
12
- * This is important because signaling cancellation doesn't immediately stop C++ -
13
- * it only sets a flag that C++ checks at certain points. If C++ is in the middle
14
- * of a slow operation (e.g., pad_trees), it won't stop until that completes.
12
+ * Cancellation is cooperative: signaling it only sets a flag the simulator
13
+ * checks at certain points, so if it's mid slow-operation it won't stop until
14
+ * that completes.
15
15
  * @returns Promise that resolves when cancellation is signaled (and optionally when simulation stops)
16
16
  */
17
17
  cancel?(waitTimeoutMs?: number): Promise<void>;
@@ -20,7 +20,7 @@ export interface MeasuredPublicTxSimulatorInterface {
20
20
  simulate(tx: Tx, txLabel: string): Promise<PublicTxResult>;
21
21
  /**
22
22
  * Cancel the current simulation if one is in progress.
23
- * This signals the underlying simulator (e.g., C++) to stop at the next safe point.
23
+ * This signals the underlying simulator to stop at the next safe point.
24
24
  * Safe to call even if no simulation is in progress.
25
25
  * Optional - not all implementations support cancellation.
26
26
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/simulator",
3
- "version": "0.0.1-commit.2f68f620",
3
+ "version": "0.0.1-commit.321f6a9",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  "./server": "./dest/server.js",
@@ -19,8 +19,9 @@
19
19
  "build": "yarn clean && ../scripts/tsc.sh",
20
20
  "build:dev": "../scripts/tsc.sh --watch",
21
21
  "clean": "rm -rf ./dest .tsbuildinfo",
22
+ "generate": "node --experimental-strip-types --experimental-transform-types --no-warnings ../../ipc-codegen/src/generate.ts --schema ../../barretenberg/cpp/src/barretenberg/cdb/cdb_schema.json --lang ts --server --out src/public/cdb/generated",
22
23
  "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}",
23
- "build:fuzzer": "yarn clean && ../scripts/tsc.sh"
24
+ "build:fuzzer": "yarn clean && yarn generate && ../scripts/tsc.sh"
24
25
  },
25
26
  "inherits": [
26
27
  "../package.common.json"
@@ -63,26 +64,29 @@
63
64
  ]
64
65
  },
65
66
  "dependencies": {
66
- "@aztec/constants": "0.0.1-commit.2f68f620",
67
- "@aztec/foundation": "0.0.1-commit.2f68f620",
68
- "@aztec/native": "0.0.1-commit.2f68f620",
69
- "@aztec/noir-acvm_js": "0.0.1-commit.2f68f620",
70
- "@aztec/noir-noirc_abi": "0.0.1-commit.2f68f620",
71
- "@aztec/noir-protocol-circuits-types": "0.0.1-commit.2f68f620",
72
- "@aztec/noir-types": "0.0.1-commit.2f68f620",
73
- "@aztec/protocol-contracts": "0.0.1-commit.2f68f620",
74
- "@aztec/standard-contracts": "0.0.1-commit.2f68f620",
75
- "@aztec/stdlib": "0.0.1-commit.2f68f620",
76
- "@aztec/telemetry-client": "0.0.1-commit.2f68f620",
77
- "@aztec/world-state": "0.0.1-commit.2f68f620",
67
+ "@aztec/bb-avm-sim": "0.0.1-commit.321f6a9",
68
+ "@aztec/constants": "0.0.1-commit.321f6a9",
69
+ "@aztec/foundation": "0.0.1-commit.321f6a9",
70
+ "@aztec/ipc-runtime": "0.0.1-commit.321f6a9",
71
+ "@aztec/native": "0.0.1-commit.321f6a9",
72
+ "@aztec/noir-acvm_js": "0.0.1-commit.321f6a9",
73
+ "@aztec/noir-noirc_abi": "0.0.1-commit.321f6a9",
74
+ "@aztec/noir-protocol-circuits-types": "0.0.1-commit.321f6a9",
75
+ "@aztec/noir-types": "0.0.1-commit.321f6a9",
76
+ "@aztec/protocol-contracts": "0.0.1-commit.321f6a9",
77
+ "@aztec/standard-contracts": "0.0.1-commit.321f6a9",
78
+ "@aztec/stdlib": "0.0.1-commit.321f6a9",
79
+ "@aztec/telemetry-client": "0.0.1-commit.321f6a9",
80
+ "@aztec/world-state": "0.0.1-commit.321f6a9",
78
81
  "lodash.clonedeep": "^4.5.0",
79
82
  "lodash.merge": "^4.6.2",
83
+ "msgpackr": "^1.11.2",
80
84
  "tslib": "^2.4.0"
81
85
  },
82
86
  "devDependencies": {
83
- "@aztec/kv-store": "0.0.1-commit.2f68f620",
84
- "@aztec/noir-contracts.js": "0.0.1-commit.2f68f620",
85
- "@aztec/noir-test-contracts.js": "0.0.1-commit.2f68f620",
87
+ "@aztec/kv-store": "0.0.1-commit.321f6a9",
88
+ "@aztec/noir-contracts.js": "0.0.1-commit.321f6a9",
89
+ "@aztec/noir-test-contracts.js": "0.0.1-commit.321f6a9",
86
90
  "@jest/globals": "^30.0.0",
87
91
  "@types/jest": "^30.0.0",
88
92
  "@types/lodash.clonedeep": "^4.5.7",
package/src/client.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  export * from './private/acvm/index.js';
2
2
  export { WASMSimulator } from './private/acvm_wasm.js';
3
- export { SimulatorRecorderWrapper } from './private/circuit_recording/simulator_recorder_wrapper.js';
4
- export { MemoryCircuitRecorder } from './private/circuit_recording/memory_circuit_recorder.js';
5
3
  export { type CircuitSimulator, type DecodedError } from './private/circuit_simulator.js';
6
4
  export * from './common/index.js';
@@ -3,6 +3,8 @@ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec/foundati
3
3
  import { Timer } from '@aztec/foundation/timer';
4
4
  import type { ForeignCallHandler, ForeignCallInput, ForeignCallOutput } from '@aztec/noir-acvm_js';
5
5
 
6
+ import { AsyncLocalStorage } from 'node:async_hooks';
7
+
6
8
  import type { ACIRCallback } from '../acvm/acvm.js';
7
9
  import type { ACVMWitness } from '../acvm/acvm_types.js';
8
10
 
@@ -43,10 +45,23 @@ export class CircuitRecording {
43
45
  }
44
46
  }
45
47
 
48
+ /** Inputs needed to open a recording for a single circuit execution. */
49
+ export type RecordingMetadata = {
50
+ input: ACVMWitness;
51
+ bytecode: Buffer;
52
+ circuitName: string;
53
+ functionName: string;
54
+ };
55
+
46
56
  /**
47
57
  * Class responsible for recording circuit inputs necessary to replay the circuit. These inputs are the initial witness
48
58
  * map and the oracle calls made during the circuit execution/witness generation.
49
59
  *
60
+ * The active recording for an execution lives in `AsyncLocalStorage`, so each (possibly nested) circuit execution owns
61
+ * its own recording and concurrent or re-entrant executions cannot corrupt one another's state. Nested executions
62
+ * (`aztec_prv_callPrivateFunction`, utility calls) re-enter {@link record}, which links the child to the recording
63
+ * active in the enclosing async context and lets ALS restore the parent automatically when the child completes.
64
+ *
50
65
  * Example recording object:
51
66
  * ```json
52
67
  * {
@@ -91,37 +106,44 @@ export class CircuitRecording {
91
106
  export class CircuitRecorder {
92
107
  protected readonly logger: Logger;
93
108
 
94
- protected recording?: CircuitRecording;
95
-
96
- private stackDepth: number = 0;
97
- private newCircuit: boolean = true;
109
+ readonly #recordings = new AsyncLocalStorage<CircuitRecording>();
98
110
 
99
111
  protected constructor(loggerOrBindings?: Logger | LoggerBindings) {
100
112
  this.logger = resolveLogger('simulator:acvm:recording', loggerOrBindings);
101
113
  }
102
114
 
103
115
  /**
104
- * Initializes a new circuit recording session.
105
- * @param recordDir - Directory to store the recording
106
- * @param input - Circuit input witness
107
- * @param circuitBytecode - Compiled circuit bytecode
108
- * @param circuitName - Name of the circuit
109
- * @param functionName - Name of the circuit function (defaults to 'main'). This is meaningful only for
110
- * contracts as protocol circuits artifacts always contain a single entrypoint function called 'main'.
116
+ * Records a single circuit execution. Opens a recording for the circuit (linked as a child of the recording active
117
+ * in the current async context, if any), runs `fn` within that recording's context, and finalizes it. The recording
118
+ * is returned alongside the result so callers can derive per-circuit stats (e.g. oracle timings).
119
+ *
120
+ * Recorder bookkeeping never alters execution: if `fn` throws, the error is attached to the recording and re-thrown
121
+ * unchanged.
122
+ * @param metadata - Identifies the circuit and its initial witness.
123
+ * @param fn - Runs the circuit execution; its oracle calls are recorded into this recording.
111
124
  */
112
- start(input: ACVMWitness, circuitBytecode: Buffer, circuitName: string, functionName: string): Promise<void> {
113
- if (this.newCircuit) {
114
- const parentRef = this.recording;
115
- this.recording = new CircuitRecording(
116
- circuitName,
117
- functionName,
118
- sha512(circuitBytecode).toString('hex'),
119
- Object.fromEntries(input),
120
- );
121
- this.recording.setParent(parentRef);
122
- }
125
+ record<T>(metadata: RecordingMetadata, fn: () => Promise<T>): Promise<{ result: T; recording: CircuitRecording }> {
126
+ const parent = this.#recordings.getStore();
127
+ const recording = new CircuitRecording(
128
+ metadata.circuitName,
129
+ metadata.functionName,
130
+ sha512(metadata.bytecode).toString('hex'),
131
+ Object.fromEntries(metadata.input),
132
+ );
133
+ recording.setParent(parent);
123
134
 
124
- return Promise.resolve();
135
+ return this.#recordings.run(recording, async () => {
136
+ await this.onStart(recording);
137
+ try {
138
+ const result = await fn();
139
+ await this.onFinish(recording);
140
+ return { result, recording };
141
+ } catch (error) {
142
+ recording.error = JSON.stringify(error);
143
+ await this.onError(recording, error);
144
+ throw error;
145
+ }
146
+ });
125
147
  }
126
148
 
127
149
  /**
@@ -147,7 +169,9 @@ export class CircuitRecorder {
147
169
  }
148
170
 
149
171
  /**
150
- * Wraps a user circuit callback to record all oracle calls.
172
+ * Wraps a user circuit callback to record all oracle calls. A nested circuit entered via an oracle (e.g.
173
+ * `aztec_prv_callPrivateFunction`) re-enters {@link record}, so its own oracle calls land on the child recording and
174
+ * this circuit's calls (including the entering oracle call itself) land on this recording once the child completes.
151
175
  * @param callback - The original circuit callback.
152
176
  * @returns A wrapped callback that records all oracle interactions which is to be provided to the ACVM.
153
177
  */
@@ -161,38 +185,16 @@ export class CircuitRecorder {
161
185
  throw new Error(`Oracle method ${name} not found when setting up recording callback`);
162
186
  }
163
187
 
164
- const isExternalCall = (name as keyof ACIRCallback) === 'aztec_prv_callPrivateFunction';
165
-
166
188
  recordingCallback[name as keyof ACIRCallback] = (...args: ForeignCallInput[]): ReturnType<typeof fn> => {
167
189
  const timer = new Timer();
168
- // If we're entering another circuit via `aztec_prv_callPrivateFunction`, we increase the stack depth and set the
169
- // newCircuit variable to ensure we are creating a new recording object.
170
- if (isExternalCall) {
171
- this.stackDepth++;
172
- this.newCircuit = true;
173
- }
174
190
  const result = fn.call(callback, ...args);
175
191
  if (result instanceof Promise) {
176
192
  return result.then(async r => {
177
- // Once we leave the nested circuit, we decrease the stack depth and set newCircuit to false
178
- // so that the parent circuit continues with its existing recording
179
- // Note: recording restoration is handled by finish()
180
- if (isExternalCall) {
181
- this.stackDepth--;
182
- this.newCircuit = false;
183
- }
184
- await this.recordCall(name, args, r, timer.ms(), this.stackDepth);
193
+ await this.recordCall(name, args, r, timer.ms());
185
194
  return r;
186
195
  }) as ReturnType<typeof fn>;
187
196
  }
188
- // Once we leave the nested circuit, we decrease the stack depth and set newCircuit to false
189
- // so that the parent circuit continues with its existing recording
190
- // Note: recording restoration is handled by finish()
191
- if (isExternalCall) {
192
- this.stackDepth--;
193
- this.newCircuit = false;
194
- }
195
- void this.recordCall(name, args, result, timer.ms(), this.stackDepth);
197
+ void this.recordCall(name, args, result, timer.ms());
196
198
  return result;
197
199
  };
198
200
  }
@@ -209,55 +211,59 @@ export class CircuitRecorder {
209
211
  return async (name: string, inputs: ForeignCallInput[]): Promise<ForeignCallOutput[]> => {
210
212
  const timer = new Timer();
211
213
  const result = await callback(name, inputs);
212
- await this.recordCall(name, inputs, result, timer.ms(), 0);
214
+ await this.recordCall(name, inputs, result, timer.ms());
213
215
  return result;
214
216
  };
215
217
  }
216
218
 
217
219
  /**
218
- * Records a single oracle/foreign call with its inputs and outputs.
220
+ * Records a single oracle/foreign call with its inputs and outputs against the recording active in the current
221
+ * async context.
219
222
  * @param name - Name of the call
220
223
  * @param inputs - Input arguments
221
224
  * @param outputs - Output results
222
225
  */
223
- recordCall(name: string, inputs: unknown[], outputs: unknown, time: number, stackDepth: number): Promise<OracleCall> {
226
+ recordCall(name: string, inputs: unknown[], outputs: unknown, time: number): Promise<OracleCall> {
227
+ const recording = this.#recordings.getStore();
224
228
  const entry = {
225
229
  name,
226
230
  inputs,
227
231
  outputs,
228
232
  time,
229
- stackDepth,
233
+ stackDepth: depthOf(recording),
230
234
  };
231
- this.recording!.oracleCalls.push(entry);
235
+ // Outside any active recording context (e.g. a stray call after the scope closed, or a direct unit-test call)
236
+ // there is nowhere to record; return the entry without throwing into the execution path.
237
+ recording?.oracleCalls.push(entry);
232
238
  return Promise.resolve(entry);
233
239
  }
234
240
 
235
- /**
236
- * Finalizes the recording by resetting the state and returning the recording object.
237
- */
238
- finish(): Promise<CircuitRecording> {
239
- const result = this.recording;
240
- // If this is the top-level circuit recording, we reset the state for the next simulator call
241
- if (!result!.parent) {
242
- this.newCircuit = true;
243
- this.recording = undefined;
244
- } else {
245
- // For nested circuits (utility calls, nested contract calls), restore to parent recording
246
- // Note: we don't set newCircuit=false here because:
247
- // - For privateCallPrivateFunction, the callback wrapper will set it to false
248
- // - For utility calls, we want newCircuit to remain true so the next circuit creates its own recording
249
- this.recording = result!.parent;
250
- }
251
- return Promise.resolve(result!);
241
+ /** The recording active in the current async context, if any. */
242
+ protected currentRecording(): CircuitRecording | undefined {
243
+ return this.#recordings.getStore();
252
244
  }
253
245
 
254
- /**
255
- * Finalizes the recording by resetting the state and returning the recording object with an attached error.
256
- * @param error - The error that occurred during circuit execution
257
- */
258
- async finishWithError(error: unknown): Promise<CircuitRecording> {
259
- const result = await this.finish();
260
- result.error = JSON.stringify(error);
261
- return result;
246
+ /** Hook invoked when a recording opens, within the recording's context. Overridden to persist recordings. */
247
+ protected onStart(_recording: CircuitRecording): Promise<void> {
248
+ return Promise.resolve();
249
+ }
250
+
251
+ /** Hook invoked when a recording completes successfully, within the recording's context. */
252
+ protected onFinish(_recording: CircuitRecording): Promise<void> {
253
+ return Promise.resolve();
254
+ }
255
+
256
+ /** Hook invoked when a recording's execution throws, within the recording's context. */
257
+ protected onError(_recording: CircuitRecording, _error: unknown): Promise<void> {
258
+ return Promise.resolve();
259
+ }
260
+ }
261
+
262
+ /** Depth of a recording in the call tree: 0 for a top-level circuit, incremented per nested circuit. */
263
+ function depthOf(recording: CircuitRecording | undefined): number {
264
+ let depth = 0;
265
+ for (let ancestor = recording?.parent; ancestor; ancestor = ancestor.parent) {
266
+ depth++;
262
267
  }
268
+ return depth;
263
269
  }