@aztec/simulator 0.0.1-commit.2ed92850 → 0.0.1-commit.3100065

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 (179) hide show
  1. package/README.md +4 -4
  2. package/dest/client.d.ts +1 -3
  3. package/dest/client.d.ts.map +1 -1
  4. package/dest/client.js +0 -2
  5. package/dest/private/acvm/acvm.d.ts +4 -2
  6. package/dest/private/acvm/acvm.d.ts.map +1 -1
  7. package/dest/private/acvm/acvm.js +4 -3
  8. package/dest/private/acvm_native.d.ts +5 -3
  9. package/dest/private/acvm_native.d.ts.map +1 -1
  10. package/dest/private/acvm_native.js +8 -6
  11. package/dest/private/acvm_wasm.d.ts +4 -3
  12. package/dest/private/acvm_wasm.d.ts.map +1 -1
  13. package/dest/private/acvm_wasm.js +7 -5
  14. package/dest/private/circuit_recording/circuit_recorder.d.ts +39 -25
  15. package/dest/private/circuit_recording/circuit_recorder.d.ts.map +1 -1
  16. package/dest/private/circuit_recording/circuit_recorder.js +70 -72
  17. package/dest/private/circuit_recording/file_circuit_recorder.d.ts +9 -20
  18. package/dest/private/circuit_recording/file_circuit_recorder.d.ts.map +1 -1
  19. package/dest/private/circuit_recording/file_circuit_recorder.js +39 -43
  20. package/dest/private/circuit_recording/memory_circuit_recorder.d.ts +7 -2
  21. package/dest/private/circuit_recording/memory_circuit_recorder.d.ts.map +1 -1
  22. package/dest/private/circuit_recording/memory_circuit_recorder.js +4 -4
  23. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts +1 -1
  24. package/dest/private/circuit_recording/simulator_recorder_wrapper.d.ts.map +1 -1
  25. package/dest/private/circuit_recording/simulator_recorder_wrapper.js +11 -14
  26. package/dest/private/factory.d.ts +3 -3
  27. package/dest/private/factory.d.ts.map +1 -1
  28. package/dest/private/factory.js +7 -4
  29. package/dest/public/avm/avm_gas.js +3 -3
  30. package/dest/public/avm/avm_simulator.js +1 -1
  31. package/dest/public/avm/calldata.d.ts +1 -1
  32. package/dest/public/avm/calldata.d.ts.map +1 -1
  33. package/dest/public/avm/calldata.js +3 -2
  34. package/dest/public/avm/fixtures/account_proof_fetcher.d.ts +2 -0
  35. package/dest/public/avm/fixtures/account_proof_fetcher.d.ts.map +1 -0
  36. package/dest/public/avm/fixtures/account_proof_fetcher.js +152 -0
  37. package/dest/public/avm/fixtures/base_avm_simulation_tester.d.ts +2 -1
  38. package/dest/public/avm/fixtures/base_avm_simulation_tester.d.ts.map +1 -1
  39. package/dest/public/avm/fixtures/base_avm_simulation_tester.js +18 -3
  40. package/dest/public/avm/fixtures/utils.d.ts +1 -1
  41. package/dest/public/avm/fixtures/utils.d.ts.map +1 -1
  42. package/dest/public/avm/fixtures/utils.js +4 -1
  43. package/dest/public/avm/opcodes/accrued_substate.d.ts +4 -5
  44. package/dest/public/avm/opcodes/accrued_substate.d.ts.map +1 -1
  45. package/dest/public/avm/opcodes/accrued_substate.js +11 -16
  46. package/dest/public/avm/opcodes/contract.d.ts +3 -2
  47. package/dest/public/avm/opcodes/contract.d.ts.map +1 -1
  48. package/dest/public/avm/opcodes/contract.js +5 -1
  49. package/dest/public/avm/opcodes/ec_add.d.ts +2 -4
  50. package/dest/public/avm/opcodes/ec_add.d.ts.map +1 -1
  51. package/dest/public/avm/opcodes/ec_add.js +13 -27
  52. package/dest/public/avm/serialization/bytecode_serialization.js +3 -3
  53. package/dest/public/avm/serialization/instruction_serialization.d.ts +2 -2
  54. package/dest/public/avm/serialization/instruction_serialization.d.ts.map +1 -1
  55. package/dest/public/avm/serialization/instruction_serialization.js +1 -1
  56. package/dest/public/contracts_db_checkpoint.d.ts +2 -2
  57. package/dest/public/contracts_db_checkpoint.d.ts.map +1 -1
  58. package/dest/public/contracts_db_checkpoint.js +1 -1
  59. package/dest/public/executor_metrics.d.ts +1 -1
  60. package/dest/public/executor_metrics.d.ts.map +1 -1
  61. package/dest/public/executor_metrics.js +7 -2
  62. package/dest/public/fixtures/amm_test.js +4 -4
  63. package/dest/public/fixtures/bulk_test.d.ts +1 -1
  64. package/dest/public/fixtures/bulk_test.d.ts.map +1 -1
  65. package/dest/public/fixtures/bulk_test.js +33 -6
  66. package/dest/public/fixtures/custom_bytecode_tester.d.ts +1 -1
  67. package/dest/public/fixtures/custom_bytecode_tester.d.ts.map +1 -1
  68. package/dest/public/fixtures/custom_bytecode_tester.js +2 -2
  69. package/dest/public/fixtures/custom_bytecode_tests.d.ts +8 -1
  70. package/dest/public/fixtures/custom_bytecode_tests.d.ts.map +1 -1
  71. package/dest/public/fixtures/custom_bytecode_tests.js +91 -2
  72. package/dest/public/fixtures/opcode_spammer.d.ts +3 -4
  73. package/dest/public/fixtures/opcode_spammer.d.ts.map +1 -1
  74. package/dest/public/fixtures/opcode_spammer.js +18 -66
  75. package/dest/public/fixtures/public_tx_simulation_tester.d.ts +6 -5
  76. package/dest/public/fixtures/public_tx_simulation_tester.d.ts.map +1 -1
  77. package/dest/public/fixtures/public_tx_simulation_tester.js +38 -9
  78. package/dest/public/fixtures/token_test.js +3 -3
  79. package/dest/public/fixtures/utils.d.ts +2 -2
  80. package/dest/public/fixtures/utils.d.ts.map +1 -1
  81. package/dest/public/fixtures/utils.js +21 -20
  82. package/dest/public/hinting_db_sources.d.ts +5 -5
  83. package/dest/public/hinting_db_sources.d.ts.map +1 -1
  84. package/dest/public/hinting_db_sources.js +8 -7
  85. package/dest/public/public_db_sources.d.ts +9 -5
  86. package/dest/public/public_db_sources.d.ts.map +1 -1
  87. package/dest/public/public_db_sources.js +20 -14
  88. package/dest/public/public_processor/guarded_merkle_tree.d.ts +5 -5
  89. package/dest/public/public_processor/guarded_merkle_tree.d.ts.map +1 -1
  90. package/dest/public/public_processor/guarded_merkle_tree.js +5 -5
  91. package/dest/public/public_processor/public_processor.d.ts +11 -6
  92. package/dest/public/public_processor/public_processor.d.ts.map +1 -1
  93. package/dest/public/public_processor/public_processor.js +125 -68
  94. package/dest/public/public_processor/public_processor_metrics.d.ts +5 -2
  95. package/dest/public/public_processor/public_processor_metrics.d.ts.map +1 -1
  96. package/dest/public/public_processor/public_processor_metrics.js +28 -4
  97. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts +3 -2
  98. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts.map +1 -1
  99. package/dest/public/public_tx_simulator/contract_provider_for_cpp.js +7 -6
  100. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.d.ts +5 -5
  101. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.d.ts.map +1 -1
  102. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.js +10 -11
  103. package/dest/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.d.ts +4 -4
  104. package/dest/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.d.ts.map +1 -1
  105. package/dest/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.js +7 -7
  106. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts +4 -4
  107. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts.map +1 -1
  108. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.js +6 -6
  109. package/dest/public/public_tx_simulator/dumping_cpp_public_tx_simulator.d.ts +3 -2
  110. package/dest/public/public_tx_simulator/dumping_cpp_public_tx_simulator.d.ts.map +1 -1
  111. package/dest/public/public_tx_simulator/dumping_cpp_public_tx_simulator.js +2 -2
  112. package/dest/public/public_tx_simulator/factories.d.ts +3 -2
  113. package/dest/public/public_tx_simulator/factories.d.ts.map +1 -1
  114. package/dest/public/public_tx_simulator/factories.js +4 -4
  115. package/dest/public/public_tx_simulator/public_tx_context.d.ts +10 -5
  116. package/dest/public/public_tx_simulator/public_tx_context.d.ts.map +1 -1
  117. package/dest/public/public_tx_simulator/public_tx_context.js +16 -18
  118. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts +9 -4
  119. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts.map +1 -1
  120. package/dest/public/public_tx_simulator/public_tx_simulator.js +19 -12
  121. package/dest/public/side_effect_trace.d.ts +4 -4
  122. package/dest/public/side_effect_trace.d.ts.map +1 -1
  123. package/dest/public/side_effect_trace.js +3 -3
  124. package/dest/public/state_manager/state_manager.d.ts +10 -4
  125. package/dest/public/state_manager/state_manager.d.ts.map +1 -1
  126. package/dest/public/state_manager/state_manager.js +13 -6
  127. package/dest/public/test_executor_metrics.d.ts +8 -2
  128. package/dest/public/test_executor_metrics.d.ts.map +1 -1
  129. package/dest/public/test_executor_metrics.js +24 -2
  130. package/package.json +16 -16
  131. package/src/client.ts +0 -2
  132. package/src/private/acvm/acvm.ts +4 -3
  133. package/src/private/acvm_native.ts +11 -5
  134. package/src/private/acvm_wasm.ts +11 -4
  135. package/src/private/circuit_recording/circuit_recorder.ts +89 -81
  136. package/src/private/circuit_recording/file_circuit_recorder.ts +45 -50
  137. package/src/private/circuit_recording/memory_circuit_recorder.ts +6 -4
  138. package/src/private/circuit_recording/simulator_recorder_wrapper.ts +9 -15
  139. package/src/private/factory.ts +7 -4
  140. package/src/public/avm/avm_gas.ts +2 -2
  141. package/src/public/avm/avm_simulator.ts +1 -1
  142. package/src/public/avm/calldata.ts +3 -2
  143. package/src/public/avm/fixtures/account_proof.json +553 -0
  144. package/src/public/avm/fixtures/account_proof_fetcher.ts +166 -0
  145. package/src/public/avm/fixtures/base_avm_simulation_tester.ts +23 -3
  146. package/src/public/avm/fixtures/utils.ts +4 -1
  147. package/src/public/avm/opcodes/accrued_substate.ts +10 -19
  148. package/src/public/avm/opcodes/contract.ts +5 -1
  149. package/src/public/avm/opcodes/ec_add.ts +12 -31
  150. package/src/public/avm/opcodes/external_calls.ts +1 -1
  151. package/src/public/avm/serialization/bytecode_serialization.ts +2 -2
  152. package/src/public/avm/serialization/instruction_serialization.ts +1 -1
  153. package/src/public/contracts_db_checkpoint.ts +1 -1
  154. package/src/public/executor_metrics.ts +4 -1
  155. package/src/public/fixtures/amm_test.ts +4 -4
  156. package/src/public/fixtures/bulk_test.ts +31 -6
  157. package/src/public/fixtures/custom_bytecode_tester.ts +2 -2
  158. package/src/public/fixtures/custom_bytecode_tests.ts +209 -2
  159. package/src/public/fixtures/opcode_spammer.ts +22 -63
  160. package/src/public/fixtures/public_tx_simulation_tester.ts +45 -5
  161. package/src/public/fixtures/token_test.ts +3 -3
  162. package/src/public/fixtures/utils.ts +23 -24
  163. package/src/public/fuzzing/avm_fuzzer_simulator.ts +1 -1
  164. package/src/public/hinting_db_sources.ts +10 -7
  165. package/src/public/public_db_sources.ts +36 -19
  166. package/src/public/public_processor/guarded_merkle_tree.ts +6 -6
  167. package/src/public/public_processor/public_processor.ts +173 -90
  168. package/src/public/public_processor/public_processor_metrics.ts +22 -4
  169. package/src/public/public_tx_simulator/contract_provider_for_cpp.ts +11 -7
  170. package/src/public/public_tx_simulator/cpp_public_tx_simulator.ts +10 -8
  171. package/src/public/public_tx_simulator/cpp_public_tx_simulator_with_hinted_dbs.ts +7 -5
  172. package/src/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.ts +7 -5
  173. package/src/public/public_tx_simulator/dumping_cpp_public_tx_simulator.ts +3 -1
  174. package/src/public/public_tx_simulator/factories.ts +6 -3
  175. package/src/public/public_tx_simulator/public_tx_context.ts +21 -16
  176. package/src/public/public_tx_simulator/public_tx_simulator.ts +20 -12
  177. package/src/public/side_effect_trace.ts +5 -2
  178. package/src/public/state_manager/state_manager.ts +28 -5
  179. package/src/public/test_executor_metrics.ts +27 -3
@@ -1,5 +1,5 @@
1
1
  import { runInDirectory } from '@aztec/foundation/fs';
2
- import { createLogger } from '@aztec/foundation/log';
2
+ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec/foundation/log';
3
3
  import { Timer } from '@aztec/foundation/timer';
4
4
  import type { ForeignCallHandler, WitnessMap } from '@aztec/noir-acvm_js';
5
5
  import type { FunctionArtifactWithContractName } from '@aztec/stdlib/abi';
@@ -12,8 +12,6 @@ import type { ACIRCallback, ACIRExecutionResult } from './acvm/acvm.js';
12
12
  import type { ACVMWitness } from './acvm/acvm_types.js';
13
13
  import type { CircuitSimulator } from './circuit_simulator.js';
14
14
 
15
- const logger = createLogger('simulator:acvm-native');
16
-
17
15
  export enum ACVM_RESULT {
18
16
  SUCCESS,
19
17
  FAILURE,
@@ -64,7 +62,9 @@ export async function executeNativeCircuit(
64
62
  workingDirectory: string,
65
63
  pathToAcvm: string,
66
64
  outputFilename?: string,
65
+ loggerOrBindings?: Logger | LoggerBindings,
67
66
  ): Promise<ACVMResult> {
67
+ const logger = resolveLogger('simulator:acvm-native', loggerOrBindings);
68
68
  const bytecodeFilename = 'bytecode';
69
69
  const witnessFilename = 'input_witness.toml';
70
70
 
@@ -145,11 +145,16 @@ export async function executeNativeCircuit(
145
145
  }
146
146
 
147
147
  export class NativeACVMSimulator implements CircuitSimulator {
148
+ private logger: Logger;
149
+
148
150
  constructor(
149
151
  private workingDirectory: string,
150
152
  private pathToAcvm: string,
151
153
  private witnessFilename?: string,
152
- ) {}
154
+ loggerOrBindings?: Logger | LoggerBindings,
155
+ ) {
156
+ this.logger = resolveLogger('simulator:acvm-native', loggerOrBindings);
157
+ }
153
158
 
154
159
  async executeProtocolCircuit(
155
160
  input: ACVMWitness,
@@ -172,6 +177,7 @@ export class NativeACVMSimulator implements CircuitSimulator {
172
177
  directory,
173
178
  this.pathToAcvm,
174
179
  this.witnessFilename,
180
+ this.logger,
175
181
  );
176
182
 
177
183
  if (result.status == ACVM_RESULT.FAILURE) {
@@ -181,7 +187,7 @@ export class NativeACVMSimulator implements CircuitSimulator {
181
187
  return result;
182
188
  };
183
189
 
184
- return await runInDirectory(this.workingDirectory, operation, false, logger);
190
+ return await runInDirectory(this.workingDirectory, operation, false, this.logger);
185
191
  }
186
192
 
187
193
  executeUserCircuit(
@@ -1,4 +1,4 @@
1
- import { createLogger } from '@aztec/foundation/log';
1
+ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec/foundation/log';
2
2
  import { Timer } from '@aztec/foundation/timer';
3
3
  import initACVM, { type ExecutionError, type ForeignCallHandler, executeCircuit } from '@aztec/noir-acvm_js';
4
4
  import initAbi from '@aztec/noir-noirc_abi';
@@ -10,8 +10,14 @@ import type { ACVMWitness } from './acvm/acvm_types.js';
10
10
  import type { ACVMSuccess } from './acvm_native.js';
11
11
  import { type CircuitSimulator, enrichNoirError } from './circuit_simulator.js';
12
12
 
13
+ let wasmInitPromise: Promise<unknown> | undefined;
14
+
13
15
  export class WASMSimulator implements CircuitSimulator {
14
- constructor(protected log = createLogger('wasm-simulator')) {}
16
+ protected log: Logger;
17
+
18
+ constructor(loggerOrBindings?: Logger | LoggerBindings) {
19
+ this.log = resolveLogger('wasm-simulator', loggerOrBindings);
20
+ }
15
21
 
16
22
  async init(): Promise<void> {
17
23
  // If these are available, then we are in the
@@ -19,7 +25,8 @@ export class WASMSimulator implements CircuitSimulator {
19
25
  // is a no-op.
20
26
  if (typeof initAbi === 'function') {
21
27
  /** @ts-expect-error The node bundle doesn't include these default imports, so TS complains */
22
- await Promise.all([initAbi(), initACVM()]);
28
+ wasmInitPromise ??= Promise.all([initAbi(), initACVM()]);
29
+ await wasmInitPromise;
23
30
  }
24
31
  }
25
32
 
@@ -67,6 +74,6 @@ export class WASMSimulator implements CircuitSimulator {
67
74
  callback: ACIRCallback,
68
75
  ): Promise<ACIRExecutionResult> {
69
76
  await this.init();
70
- return acvm(artifact.bytecode, input, callback);
77
+ return acvm(artifact.bytecode, input, callback, this.log.createChild('acvm'));
71
78
  }
72
79
  }
@@ -1,8 +1,10 @@
1
1
  import { sha512 } from '@aztec/foundation/crypto/sha512';
2
- import { createLogger } from '@aztec/foundation/log';
2
+ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec/foundation/log';
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
  * {
@@ -89,37 +104,46 @@ export class CircuitRecording {
89
104
  * ```
90
105
  */
91
106
  export class CircuitRecorder {
92
- protected readonly logger = createLogger('simulator:acvm:recording');
107
+ protected readonly logger: Logger;
93
108
 
94
- protected recording?: CircuitRecording;
109
+ readonly #recordings = new AsyncLocalStorage<CircuitRecording>();
95
110
 
96
- private stackDepth: number = 0;
97
- private newCircuit: boolean = true;
98
-
99
- protected constructor() {}
111
+ protected constructor(loggerOrBindings?: Logger | LoggerBindings) {
112
+ this.logger = resolveLogger('simulator:acvm:recording', loggerOrBindings);
113
+ }
100
114
 
101
115
  /**
102
- * Initializes a new circuit recording session.
103
- * @param recordDir - Directory to store the recording
104
- * @param input - Circuit input witness
105
- * @param circuitBytecode - Compiled circuit bytecode
106
- * @param circuitName - Name of the circuit
107
- * @param functionName - Name of the circuit function (defaults to 'main'). This is meaningful only for
108
- * 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.
109
124
  */
110
- start(input: ACVMWitness, circuitBytecode: Buffer, circuitName: string, functionName: string): Promise<void> {
111
- if (this.newCircuit) {
112
- const parentRef = this.recording;
113
- this.recording = new CircuitRecording(
114
- circuitName,
115
- functionName,
116
- sha512(circuitBytecode).toString('hex'),
117
- Object.fromEntries(input),
118
- );
119
- this.recording.setParent(parentRef);
120
- }
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);
121
134
 
122
- 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
+ });
123
147
  }
124
148
 
125
149
  /**
@@ -145,7 +169,9 @@ export class CircuitRecorder {
145
169
  }
146
170
 
147
171
  /**
148
- * 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.
149
175
  * @param callback - The original circuit callback.
150
176
  * @returns A wrapped callback that records all oracle interactions which is to be provided to the ACVM.
151
177
  */
@@ -159,38 +185,16 @@ export class CircuitRecorder {
159
185
  throw new Error(`Oracle method ${name} not found when setting up recording callback`);
160
186
  }
161
187
 
162
- const isExternalCall = (name as keyof ACIRCallback) === 'privateCallPrivateFunction';
163
-
164
188
  recordingCallback[name as keyof ACIRCallback] = (...args: ForeignCallInput[]): ReturnType<typeof fn> => {
165
189
  const timer = new Timer();
166
- // If we're entering another circuit via `privateCallPrivateFunction`, we increase the stack depth and set the
167
- // newCircuit variable to ensure we are creating a new recording object.
168
- if (isExternalCall) {
169
- this.stackDepth++;
170
- this.newCircuit = true;
171
- }
172
190
  const result = fn.call(callback, ...args);
173
191
  if (result instanceof Promise) {
174
192
  return result.then(async r => {
175
- // Once we leave the nested circuit, we decrease the stack depth and set newCircuit to false
176
- // so that the parent circuit continues with its existing recording
177
- // Note: recording restoration is handled by finish()
178
- if (isExternalCall) {
179
- this.stackDepth--;
180
- this.newCircuit = false;
181
- }
182
- await this.recordCall(name, args, r, timer.ms(), this.stackDepth);
193
+ await this.recordCall(name, args, r, timer.ms());
183
194
  return r;
184
195
  }) as ReturnType<typeof fn>;
185
196
  }
186
- // Once we leave the nested circuit, we decrease the stack depth and set newCircuit to false
187
- // so that the parent circuit continues with its existing recording
188
- // Note: recording restoration is handled by finish()
189
- if (isExternalCall) {
190
- this.stackDepth--;
191
- this.newCircuit = false;
192
- }
193
- void this.recordCall(name, args, result, timer.ms(), this.stackDepth);
197
+ void this.recordCall(name, args, result, timer.ms());
194
198
  return result;
195
199
  };
196
200
  }
@@ -207,55 +211,59 @@ export class CircuitRecorder {
207
211
  return async (name: string, inputs: ForeignCallInput[]): Promise<ForeignCallOutput[]> => {
208
212
  const timer = new Timer();
209
213
  const result = await callback(name, inputs);
210
- await this.recordCall(name, inputs, result, timer.ms(), 0);
214
+ await this.recordCall(name, inputs, result, timer.ms());
211
215
  return result;
212
216
  };
213
217
  }
214
218
 
215
219
  /**
216
- * 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.
217
222
  * @param name - Name of the call
218
223
  * @param inputs - Input arguments
219
224
  * @param outputs - Output results
220
225
  */
221
- 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();
222
228
  const entry = {
223
229
  name,
224
230
  inputs,
225
231
  outputs,
226
232
  time,
227
- stackDepth,
233
+ stackDepth: depthOf(recording),
228
234
  };
229
- 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);
230
238
  return Promise.resolve(entry);
231
239
  }
232
240
 
233
- /**
234
- * Finalizes the recording by resetting the state and returning the recording object.
235
- */
236
- finish(): Promise<CircuitRecording> {
237
- const result = this.recording;
238
- // If this is the top-level circuit recording, we reset the state for the next simulator call
239
- if (!result!.parent) {
240
- this.newCircuit = true;
241
- this.recording = undefined;
242
- } else {
243
- // For nested circuits (utility calls, nested contract calls), restore to parent recording
244
- // Note: we don't set newCircuit=false here because:
245
- // - For privateCallPrivateFunction, the callback wrapper will set it to false
246
- // - For utility calls, we want newCircuit to remain true so the next circuit creates its own recording
247
- this.recording = result!.parent;
248
- }
249
- 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();
250
244
  }
251
245
 
252
- /**
253
- * Finalizes the recording by resetting the state and returning the recording object with an attached error.
254
- * @param error - The error that occurred during circuit execution
255
- */
256
- async finishWithError(error: unknown): Promise<CircuitRecording> {
257
- const result = await this.finish();
258
- result.error = JSON.stringify(error);
259
- 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++;
260
267
  }
268
+ return depth;
261
269
  }
@@ -1,26 +1,26 @@
1
+ import type { Logger } from '@aztec/foundation/log';
2
+
1
3
  import fs from 'fs/promises';
2
4
  import path from 'path';
3
5
 
4
- import type { ACVMWitness } from '../acvm/acvm_types.js';
5
6
  import { CircuitRecorder, type CircuitRecording } from './circuit_recorder.js';
6
7
 
7
- export class FileCircuitRecorder extends CircuitRecorder {
8
- declare recording?: CircuitRecording & { filePath: string; isFirstCall: boolean };
8
+ /** Per-recording file state, keyed by recording so concurrent/nested executions don't share it. */
9
+ type RecordingFileState = { filePath: string; isFirstCall: boolean };
9
10
 
10
- constructor(private readonly recordDir: string) {
11
- super();
12
- }
11
+ export class FileCircuitRecorder extends CircuitRecorder {
12
+ readonly #fileState = new WeakMap<CircuitRecording, RecordingFileState>();
13
13
 
14
- override async start(
15
- input: ACVMWitness,
16
- circuitBytecode: Buffer,
17
- circuitName: string,
18
- functionName: string = 'main',
14
+ constructor(
15
+ private readonly recordDir: string,
16
+ logger?: Logger,
19
17
  ) {
20
- await super.start(input, circuitBytecode, circuitName, functionName);
18
+ super(logger);
19
+ }
21
20
 
21
+ protected override async onStart(recording: CircuitRecording): Promise<void> {
22
22
  const recordingStringWithoutClosingBracket = JSON.stringify(
23
- { ...this.recording, isFirstCall: undefined, parent: undefined, oracleCalls: undefined, filePath: undefined },
23
+ { ...recording, parent: undefined, oracleCalls: undefined },
24
24
  null,
25
25
  2,
26
26
  ).slice(0, -2);
@@ -40,13 +40,13 @@ export class FileCircuitRecorder extends CircuitRecorder {
40
40
  }
41
41
  }
42
42
 
43
- this.recording!.isFirstCall = true;
44
- this.recording!.filePath = await FileCircuitRecorder.#computeFilePathAndStoreInitialRecording(
43
+ const filePath = await FileCircuitRecorder.#computeFilePathAndStoreInitialRecording(
45
44
  this.recordDir,
46
- this.recording!.circuitName,
47
- this.recording!.functionName,
45
+ recording.circuitName,
46
+ recording.functionName,
48
47
  recordingStringWithoutClosingBracket,
49
48
  );
49
+ this.#fileState.set(recording, { filePath, isFirstCall: true });
50
50
  }
51
51
 
52
52
  /**
@@ -90,53 +90,48 @@ export class FileCircuitRecorder extends CircuitRecorder {
90
90
  * @param inputs - Input arguments
91
91
  * @param outputs - Output results
92
92
  */
93
- override async recordCall(name: string, inputs: unknown[], outputs: unknown, time: number, stackDepth: number) {
94
- const entry = await super.recordCall(name, inputs, outputs, time, stackDepth);
95
- try {
96
- const prefix = this.recording!.isFirstCall ? ' ' : ' ,';
97
- this.recording!.isFirstCall = false;
98
- await fs.appendFile(this.recording!.filePath, prefix + JSON.stringify(entry) + '\n');
99
- } catch (err) {
100
- this.logger.error('Failed to log circuit call', { error: err });
93
+ override async recordCall(name: string, inputs: unknown[], outputs: unknown, time: number) {
94
+ const entry = await super.recordCall(name, inputs, outputs, time);
95
+ const recording = this.currentRecording();
96
+ const state = recording && this.#fileState.get(recording);
97
+ if (state) {
98
+ try {
99
+ const prefix = state.isFirstCall ? ' ' : ' ,';
100
+ state.isFirstCall = false;
101
+ await fs.appendFile(state.filePath, prefix + JSON.stringify(entry) + '\n');
102
+ } catch (err) {
103
+ this.logger.error('Failed to log circuit call', { error: err });
104
+ }
101
105
  }
102
106
  return entry;
103
107
  }
104
108
 
105
- /**
106
- * Finalizes the recording file by adding closing brackets. Without calling this method, the recording file is
107
- * incomplete and it fails to parse.
108
- */
109
- override async finish(): Promise<CircuitRecording> {
110
- // Finish sets the recording to undefined if we are at the topmost circuit,
111
- // so we save the current file path before that
112
- const filePath = this.recording!.filePath;
113
- const result = await super.finish();
109
+ /** Closes the recording file with the trailing brackets so the JSON parses. */
110
+ protected override async onFinish(recording: CircuitRecording): Promise<void> {
111
+ const state = this.#fileState.get(recording);
112
+ if (!state) {
113
+ return;
114
+ }
114
115
  try {
115
- await fs.appendFile(filePath, ' ]\n}\n');
116
+ await fs.appendFile(state.filePath, ' ]\n}\n');
116
117
  } catch (err) {
117
118
  this.logger.error('Failed to finalize recording file', { error: err });
118
119
  }
119
- return result!;
120
120
  }
121
121
 
122
- /**
123
- * Finalizes the recording file by adding the error and closing brackets. Without calling this method or `finish`,
124
- * the recording file is incomplete and it fails to parse.
125
- * @param error - The error that occurred during circuit execution
126
- */
127
- override async finishWithError(error: unknown): Promise<CircuitRecording> {
128
- // Finish sets the recording to undefined if we are at the topmost circuit,
129
- // so we save the current file path before that
130
- const filePath = this.recording!.filePath;
131
- const result = await super.finishWithError(error);
122
+ /** Closes the recording file with the execution error and trailing brackets so the JSON parses. */
123
+ protected override async onError(recording: CircuitRecording, error: unknown): Promise<void> {
124
+ const state = this.#fileState.get(recording);
125
+ if (!state) {
126
+ return;
127
+ }
132
128
  try {
133
- await fs.appendFile(filePath, ' ],\n');
134
- await fs.appendFile(filePath, ` "error": ${JSON.stringify(error)}\n`);
135
- await fs.appendFile(filePath, '}\n');
129
+ await fs.appendFile(state.filePath, ' ],\n');
130
+ await fs.appendFile(state.filePath, ` "error": ${JSON.stringify(error)}\n`);
131
+ await fs.appendFile(state.filePath, '}\n');
136
132
  } catch (err) {
137
133
  this.logger.error('Failed to finalize recording file with error', { error: err });
138
134
  }
139
- return result!;
140
135
  }
141
136
  }
142
137
 
@@ -1,11 +1,13 @@
1
+ import type { Logger } from '@aztec/foundation/log';
2
+
1
3
  import { CircuitRecorder } from './circuit_recorder.js';
2
4
 
3
- /*
5
+ /**
4
6
  * In memory circuit recorder uses the default implementation. This is kept
5
- * while we decide the fate of the FileCircuitRecorder
7
+ * while we decide the fate of the FileCircuitRecorder.
6
8
  */
7
9
  export class MemoryCircuitRecorder extends CircuitRecorder {
8
- constructor() {
9
- super();
10
+ constructor(logger?: Logger) {
11
+ super(logger);
10
12
  }
11
13
  }
@@ -58,24 +58,18 @@ export class SimulatorRecorderWrapper implements CircuitSimulator {
58
58
  functionName: string,
59
59
  callback: C,
60
60
  ): Promise<T> {
61
- // Start recording circuit execution
62
- await this.recorder.start(input, bytecode, contractName, functionName);
63
-
64
- // If callback was provided, we wrap it in a circuit recorder callback wrapper
61
+ // If a callback was provided, we wrap it so that its oracle calls are recorded. The wrapped callback reads the
62
+ // active recording lazily, so it picks up the recording opened by record() below.
65
63
  const wrappedCallback = this.recorder.wrapCallback(callback);
66
- let result: T;
67
- try {
68
- result = await simulateFn(wrappedCallback as C);
69
- } catch (error) {
70
- // If an error occurs, we finalize the recording file with the error
71
- await this.recorder.finishWithError(error);
72
- throw error;
73
- }
74
64
 
75
- // Witness generation is complete so we finish the circuit recorder
76
- const recording = await this.recorder.finish();
65
+ // record() opens a recording for this circuit, runs the simulation within it, and finalizes it. A simulation
66
+ // failure is re-thrown unchanged, so recorder bookkeeping never masks the underlying error.
67
+ const { result, recording } = await this.recorder.record(
68
+ { input, bytecode, circuitName: contractName, functionName },
69
+ () => simulateFn(wrappedCallback as C),
70
+ );
77
71
 
78
- (result as ACIRExecutionResult).oracles = recording.oracleCalls?.reduce(
72
+ (result as ACIRExecutionResult).oracles = recording.oracleCalls.reduce(
79
73
  (acc, { time, name }) => {
80
74
  if (!acc[name]) {
81
75
  acc[name] = { times: [] };
@@ -1,4 +1,4 @@
1
- import { type Logger, createLogger } from '@aztec/foundation/log';
1
+ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec/foundation/log';
2
2
 
3
3
  import { promises as fs } from 'fs';
4
4
 
@@ -21,18 +21,21 @@ export function getSimulatorConfigFromEnv() {
21
21
 
22
22
  export async function createSimulator(
23
23
  config: SimulatorConfig,
24
- logger: Logger = createLogger('simulator'),
24
+ loggerOrBindings?: Logger | LoggerBindings,
25
25
  ): Promise<CircuitSimulator> {
26
+ const logger = resolveLogger('simulator', loggerOrBindings);
26
27
  if (config.acvmBinaryPath && config.acvmWorkingDirectory) {
27
28
  try {
28
29
  await fs.access(config.acvmBinaryPath, fs.constants.R_OK);
29
30
  await fs.mkdir(config.acvmWorkingDirectory, { recursive: true });
30
31
  logger.info(`Using native ACVM at ${config.acvmBinaryPath} and working directory ${config.acvmWorkingDirectory}`);
31
- return new NativeACVMSimulator(config.acvmWorkingDirectory, config.acvmBinaryPath);
32
+ const acvmLogger = logger.createChild('acvm-native');
33
+ return new NativeACVMSimulator(config.acvmWorkingDirectory, config.acvmBinaryPath, undefined, acvmLogger);
32
34
  } catch {
33
35
  logger.warn(`Failed to access ACVM at ${config.acvmBinaryPath}, falling back to WASM`);
34
36
  }
35
37
  }
36
38
  logger.info('Using WASM ACVM simulation');
37
- return new WASMSimulator();
39
+ const wasmLogger = logger.createChild('wasm');
40
+ return new WASMSimulator(wasmLogger);
38
41
  }
@@ -110,7 +110,7 @@ const BASE_GAS_COSTS: Record<Opcode, Gas> = {
110
110
  [Opcode.NULLIFIEREXISTS]: makeCost(c.AVM_NULLIFIEREXISTS_BASE_L2_GAS, 0),
111
111
  [Opcode.EMITNULLIFIER]: makeCost(c.AVM_EMITNULLIFIER_BASE_L2_GAS, c.AVM_EMITNULLIFIER_BASE_DA_GAS),
112
112
  [Opcode.L1TOL2MSGEXISTS]: makeCost(c.AVM_L1TOL2MSGEXISTS_BASE_L2_GAS, 0),
113
- [Opcode.EMITUNENCRYPTEDLOG]: makeCost(c.AVM_EMITUNENCRYPTEDLOG_BASE_L2_GAS, c.AVM_EMITUNENCRYPTEDLOG_BASE_DA_GAS),
113
+ [Opcode.EMITPUBLICLOG]: makeCost(c.AVM_EMITPUBLICLOG_BASE_L2_GAS, c.AVM_EMITPUBLICLOG_BASE_DA_GAS),
114
114
  [Opcode.SENDL2TOL1MSG]: makeCost(c.AVM_SENDL2TOL1MSG_BASE_L2_GAS, c.AVM_SENDL2TOL1MSG_BASE_DA_GAS),
115
115
  [Opcode.GETCONTRACTINSTANCE]: makeCost(c.AVM_GETCONTRACTINSTANCE_BASE_L2_GAS, 0),
116
116
  [Opcode.CALL]: makeCost(c.AVM_CALL_BASE_L2_GAS, 0),
@@ -130,7 +130,7 @@ const DYNAMIC_GAS_COSTS = new Map<Opcode, Gas>([
130
130
  [Opcode.CALLDATACOPY, makeCost(c.AVM_CALLDATACOPY_DYN_L2_GAS, 0)],
131
131
  [Opcode.RETURNDATACOPY, makeCost(c.AVM_RETURNDATACOPY_DYN_L2_GAS, 0)],
132
132
  // TODO: Call and static call based on bytecode length
133
- [Opcode.EMITUNENCRYPTEDLOG, makeCost(c.AVM_EMITUNENCRYPTEDLOG_DYN_L2_GAS, c.AVM_EMITUNENCRYPTEDLOG_DYN_DA_GAS)],
133
+ [Opcode.EMITPUBLICLOG, makeCost(c.AVM_EMITPUBLICLOG_DYN_L2_GAS, c.AVM_EMITPUBLICLOG_DYN_DA_GAS)],
134
134
  [Opcode.TORADIXBE, makeCost(c.AVM_TORADIXBE_DYN_L2_GAS, 0)],
135
135
  [Opcode.AND_8, makeCost(c.AVM_BITWISE_DYN_L2_GAS, 0)],
136
136
  [Opcode.AND_16, makeCost(c.AVM_BITWISE_DYN_L2_GAS, 0)],
@@ -63,7 +63,7 @@ export class AvmSimulator implements AvmSimulatorInterface {
63
63
  public static async build(context: AvmContext): Promise<AvmSimulator> {
64
64
  const simulator = new AvmSimulator(context);
65
65
  const fnName = await context.persistableState.getPublicFunctionDebugName(context.environment);
66
- simulator.log = createLogger(`simulator:avm(f:${fnName})`);
66
+ simulator.log = createLogger(`simulator:avm(f:${fnName.slice(0, 128)})`);
67
67
 
68
68
  return simulator;
69
69
  }
@@ -33,13 +33,14 @@ export class LazyReaderMemory implements LazyReader {
33
33
  }
34
34
 
35
35
  public slice(start: number, end: number): Fr[] {
36
- const clampedEnd = Math.min(end, this.size);
36
+ const clampedEnd = Math.min(end, this.size, TaggedMemory.MAX_MEMORY_SIZE - this.offset);
37
37
  const length = Math.max(0, clampedEnd - start);
38
38
  return this.memory.getSlice(this.offset + start, length).map(word => word.toFr());
39
39
  }
40
40
 
41
41
  public readAll(): Fr[] {
42
- return this.memory.getSlice(this.offset, this.size).map(word => word.toFr());
42
+ const size = Math.min(this.size, TaggedMemory.MAX_MEMORY_SIZE - this.offset);
43
+ return this.memory.getSlice(this.offset, size).map(word => word.toFr());
43
44
  }
44
45
 
45
46
  public length(): number {