@aztec-labs/simulator 6.0.0-nightly.20260829

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 (215) hide show
  1. package/README.md +57 -0
  2. package/dest/client.d.ts +6 -0
  3. package/dest/client.d.ts.map +1 -0
  4. package/dest/client.js +3 -0
  5. package/dest/common/errors.d.ts +51 -0
  6. package/dest/common/errors.d.ts.map +1 -0
  7. package/dest/common/errors.js +154 -0
  8. package/dest/common/index.d.ts +3 -0
  9. package/dest/common/index.d.ts.map +1 -0
  10. package/dest/common/index.js +2 -0
  11. package/dest/common/stats/index.d.ts +2 -0
  12. package/dest/common/stats/index.d.ts.map +1 -0
  13. package/dest/common/stats/index.js +1 -0
  14. package/dest/common/stats/stats.d.ts +4 -0
  15. package/dest/common/stats/stats.d.ts.map +1 -0
  16. package/dest/common/stats/stats.js +10 -0
  17. package/dest/private/acvm/acvm.d.ts +43 -0
  18. package/dest/private/acvm/acvm.d.ts.map +1 -0
  19. package/dest/private/acvm/acvm.js +65 -0
  20. package/dest/private/acvm/acvm_types.d.ts +10 -0
  21. package/dest/private/acvm/acvm_types.d.ts.map +1 -0
  22. package/dest/private/acvm/acvm_types.js +3 -0
  23. package/dest/private/acvm/deserialize.d.ts +35 -0
  24. package/dest/private/acvm/deserialize.d.ts.map +1 -0
  25. package/dest/private/acvm/deserialize.js +50 -0
  26. package/dest/private/acvm/index.d.ts +5 -0
  27. package/dest/private/acvm/index.d.ts.map +1 -0
  28. package/dest/private/acvm/index.js +4 -0
  29. package/dest/private/acvm/serialize.d.ts +41 -0
  30. package/dest/private/acvm/serialize.d.ts.map +1 -0
  31. package/dest/private/acvm/serialize.js +99 -0
  32. package/dest/private/acvm_native.d.ts +41 -0
  33. package/dest/private/acvm_native.d.ts.map +1 -0
  34. package/dest/private/acvm_native.js +147 -0
  35. package/dest/private/acvm_wasm.d.ts +16 -0
  36. package/dest/private/acvm_wasm.d.ts.map +1 -0
  37. package/dest/private/acvm_wasm.js +67 -0
  38. package/dest/private/acvm_wasm_with_blobs.d.ts +20 -0
  39. package/dest/private/acvm_wasm_with_blobs.d.ts.map +1 -0
  40. package/dest/private/acvm_wasm_with_blobs.js +35 -0
  41. package/dest/private/circuit_simulator.d.ts +35 -0
  42. package/dest/private/circuit_simulator.d.ts.map +1 -0
  43. package/dest/private/circuit_simulator.js +43 -0
  44. package/dest/private/factory.d.ts +12 -0
  45. package/dest/private/factory.d.ts.map +1 -0
  46. package/dest/private/factory.js +30 -0
  47. package/dest/public/avm/testing/account_proof_fetcher.d.ts +2 -0
  48. package/dest/public/avm/testing/account_proof_fetcher.d.ts.map +1 -0
  49. package/dest/public/avm/testing/account_proof_fetcher.js +152 -0
  50. package/dest/public/avm/testing/base_avm_simulation_tester.d.ts +39 -0
  51. package/dest/public/avm/testing/base_avm_simulation_tester.d.ts.map +1 -0
  52. package/dest/public/avm/testing/base_avm_simulation_tester.js +121 -0
  53. package/dest/public/avm/testing/utils.d.ts +32 -0
  54. package/dest/public/avm/testing/utils.d.ts.map +1 -0
  55. package/dest/public/avm/testing/utils.js +66 -0
  56. package/dest/public/avm_simulator.d.ts +28 -0
  57. package/dest/public/avm_simulator.d.ts.map +1 -0
  58. package/dest/public/avm_simulator.js +4 -0
  59. package/dest/public/avm_simulator_pool.d.ts +84 -0
  60. package/dest/public/avm_simulator_pool.d.ts.map +1 -0
  61. package/dest/public/avm_simulator_pool.js +311 -0
  62. package/dest/public/cdb_ipc_server.d.ts +40 -0
  63. package/dest/public/cdb_ipc_server.d.ts.map +1 -0
  64. package/dest/public/cdb_ipc_server.js +153 -0
  65. package/dest/public/contracts_db_checkpoint.d.ts +16 -0
  66. package/dest/public/contracts_db_checkpoint.d.ts.map +1 -0
  67. package/dest/public/contracts_db_checkpoint.js +30 -0
  68. package/dest/public/db_interfaces.d.ts +68 -0
  69. package/dest/public/db_interfaces.d.ts.map +1 -0
  70. package/dest/public/db_interfaces.js +3 -0
  71. package/dest/public/executor_metrics.d.ts +21 -0
  72. package/dest/public/executor_metrics.d.ts.map +1 -0
  73. package/dest/public/executor_metrics.js +64 -0
  74. package/dest/public/executor_metrics_interface.d.ts +10 -0
  75. package/dest/public/executor_metrics_interface.d.ts.map +1 -0
  76. package/dest/public/executor_metrics_interface.js +1 -0
  77. package/dest/public/fixtures/amm_test.d.ts +10 -0
  78. package/dest/public/fixtures/amm_test.d.ts.map +1 -0
  79. package/dest/public/fixtures/amm_test.js +213 -0
  80. package/dest/public/fixtures/bulk_test.d.ts +6 -0
  81. package/dest/public/fixtures/bulk_test.d.ts.map +1 -0
  82. package/dest/public/fixtures/bulk_test.js +289 -0
  83. package/dest/public/fixtures/custom_bytecode_tester.d.ts +34 -0
  84. package/dest/public/fixtures/custom_bytecode_tester.d.ts.map +1 -0
  85. package/dest/public/fixtures/custom_bytecode_tester.js +53 -0
  86. package/dest/public/fixtures/index.d.ts +10 -0
  87. package/dest/public/fixtures/index.d.ts.map +1 -0
  88. package/dest/public/fixtures/index.js +9 -0
  89. package/dest/public/fixtures/public_processor_test_env.d.ts +30 -0
  90. package/dest/public/fixtures/public_processor_test_env.d.ts.map +1 -0
  91. package/dest/public/fixtures/public_processor_test_env.js +73 -0
  92. package/dest/public/fixtures/public_tx_simulation_tester.d.ts +77 -0
  93. package/dest/public/fixtures/public_tx_simulation_tester.d.ts.map +1 -0
  94. package/dest/public/fixtures/public_tx_simulation_tester.js +176 -0
  95. package/dest/public/fixtures/simple_contract_data_source.d.ts +36 -0
  96. package/dest/public/fixtures/simple_contract_data_source.d.ts.map +1 -0
  97. package/dest/public/fixtures/simple_contract_data_source.js +95 -0
  98. package/dest/public/fixtures/token_test.d.ts +12 -0
  99. package/dest/public/fixtures/token_test.d.ts.map +1 -0
  100. package/dest/public/fixtures/token_test.js +96 -0
  101. package/dest/public/fixtures/utils.d.ts +26 -0
  102. package/dest/public/fixtures/utils.d.ts.map +1 -0
  103. package/dest/public/fixtures/utils.js +170 -0
  104. package/dest/public/fuzzing/avm_fuzzer_simulator.d.ts +65 -0
  105. package/dest/public/fuzzing/avm_fuzzer_simulator.d.ts.map +1 -0
  106. package/dest/public/fuzzing/avm_fuzzer_simulator.js +181 -0
  107. package/dest/public/fuzzing/avm_simulator_bin.d.ts +2 -0
  108. package/dest/public/fuzzing/avm_simulator_bin.d.ts.map +1 -0
  109. package/dest/public/fuzzing/avm_simulator_bin.js +108 -0
  110. package/dest/public/index.d.ts +10 -0
  111. package/dest/public/index.d.ts.map +1 -0
  112. package/dest/public/index.js +6 -0
  113. package/dest/public/public_db_sources.d.ts +83 -0
  114. package/dest/public/public_db_sources.d.ts.map +1 -0
  115. package/dest/public/public_db_sources.js +297 -0
  116. package/dest/public/public_errors.d.ts +12 -0
  117. package/dest/public/public_errors.d.ts.map +1 -0
  118. package/dest/public/public_errors.js +13 -0
  119. package/dest/public/public_processor/guarded_merkle_tree.d.ts +52 -0
  120. package/dest/public/public_processor/guarded_merkle_tree.d.ts.map +1 -0
  121. package/dest/public/public_processor/guarded_merkle_tree.js +116 -0
  122. package/dest/public/public_processor/public_processor.d.ts +71 -0
  123. package/dest/public/public_processor/public_processor.d.ts.map +1 -0
  124. package/dest/public/public_processor/public_processor.js +858 -0
  125. package/dest/public/public_processor/public_processor_metrics.d.ts +30 -0
  126. package/dest/public/public_processor/public_processor_metrics.d.ts.map +1 -0
  127. package/dest/public/public_processor/public_processor_metrics.js +116 -0
  128. package/dest/public/public_tx_simulator/dumping_public_tx_simulator.d.ts +17 -0
  129. package/dest/public/public_tx_simulator/dumping_public_tx_simulator.d.ts.map +1 -0
  130. package/dest/public/public_tx_simulator/dumping_public_tx_simulator.js +39 -0
  131. package/dest/public/public_tx_simulator/factories.d.ts +14 -0
  132. package/dest/public/public_tx_simulator/factories.d.ts.map +1 -0
  133. package/dest/public/public_tx_simulator/factories.js +28 -0
  134. package/dest/public/public_tx_simulator/index.d.ts +6 -0
  135. package/dest/public/public_tx_simulator/index.d.ts.map +1 -0
  136. package/dest/public/public_tx_simulator/index.js +3 -0
  137. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts +53 -0
  138. package/dest/public/public_tx_simulator/public_tx_simulator.d.ts.map +1 -0
  139. package/dest/public/public_tx_simulator/public_tx_simulator.js +127 -0
  140. package/dest/public/public_tx_simulator/public_tx_simulator_base.d.ts +24 -0
  141. package/dest/public/public_tx_simulator/public_tx_simulator_base.d.ts.map +1 -0
  142. package/dest/public/public_tx_simulator/public_tx_simulator_base.js +31 -0
  143. package/dest/public/public_tx_simulator/public_tx_simulator_interface.d.ts +32 -0
  144. package/dest/public/public_tx_simulator/public_tx_simulator_interface.d.ts.map +1 -0
  145. package/dest/public/public_tx_simulator/public_tx_simulator_interface.js +1 -0
  146. package/dest/public/side_effect_errors.d.ts +44 -0
  147. package/dest/public/side_effect_errors.d.ts.map +1 -0
  148. package/dest/public/side_effect_errors.js +75 -0
  149. package/dest/public/test_executor_metrics.d.ts +56 -0
  150. package/dest/public/test_executor_metrics.d.ts.map +1 -0
  151. package/dest/public/test_executor_metrics.js +305 -0
  152. package/dest/public/unique_class_ids.d.ts +37 -0
  153. package/dest/public/unique_class_ids.d.ts.map +1 -0
  154. package/dest/public/unique_class_ids.js +61 -0
  155. package/dest/public/utils.d.ts +3 -0
  156. package/dest/public/utils.d.ts.map +1 -0
  157. package/dest/public/utils.js +18 -0
  158. package/dest/server.d.ts +7 -0
  159. package/dest/server.d.ts.map +1 -0
  160. package/dest/server.js +5 -0
  161. package/package.json +109 -0
  162. package/src/client.ts +5 -0
  163. package/src/common/errors.ts +219 -0
  164. package/src/common/index.ts +2 -0
  165. package/src/common/stats/index.ts +1 -0
  166. package/src/common/stats/stats.ts +20 -0
  167. package/src/private/acvm/acvm.ts +114 -0
  168. package/src/private/acvm/acvm_types.ts +11 -0
  169. package/src/private/acvm/deserialize.ts +58 -0
  170. package/src/private/acvm/index.ts +4 -0
  171. package/src/private/acvm/serialize.ts +123 -0
  172. package/src/private/acvm_native.ts +200 -0
  173. package/src/private/acvm_wasm.ts +80 -0
  174. package/src/private/acvm_wasm_with_blobs.ts +55 -0
  175. package/src/private/circuit_simulator.ts +91 -0
  176. package/src/private/factory.ts +40 -0
  177. package/src/public/avm/testing/account_proof.json +553 -0
  178. package/src/public/avm/testing/account_proof_fetcher.ts +166 -0
  179. package/src/public/avm/testing/base_avm_simulation_tester.ts +162 -0
  180. package/src/public/avm/testing/utils.ts +114 -0
  181. package/src/public/avm_simulator.ts +29 -0
  182. package/src/public/avm_simulator_pool.ts +355 -0
  183. package/src/public/cdb_ipc_server.ts +198 -0
  184. package/src/public/contracts_db_checkpoint.ts +41 -0
  185. package/src/public/db_interfaces.ts +76 -0
  186. package/src/public/executor_metrics.ts +102 -0
  187. package/src/public/executor_metrics_interface.ts +20 -0
  188. package/src/public/fixtures/amm_test.ts +331 -0
  189. package/src/public/fixtures/bulk_test.ts +194 -0
  190. package/src/public/fixtures/custom_bytecode_tester.ts +83 -0
  191. package/src/public/fixtures/index.ts +13 -0
  192. package/src/public/fixtures/public_processor_test_env.ts +88 -0
  193. package/src/public/fixtures/public_tx_simulation_tester.ts +315 -0
  194. package/src/public/fixtures/simple_contract_data_source.ts +122 -0
  195. package/src/public/fixtures/token_test.ts +148 -0
  196. package/src/public/fixtures/utils.ts +269 -0
  197. package/src/public/fuzzing/avm_fuzzer_simulator.ts +302 -0
  198. package/src/public/fuzzing/avm_simulator_bin.ts +156 -0
  199. package/src/public/index.ts +16 -0
  200. package/src/public/public_db_sources.ts +405 -0
  201. package/src/public/public_errors.ts +14 -0
  202. package/src/public/public_processor/guarded_merkle_tree.ts +161 -0
  203. package/src/public/public_processor/public_processor.ts +657 -0
  204. package/src/public/public_processor/public_processor_metrics.ts +138 -0
  205. package/src/public/public_tx_simulator/dumping_public_tx_simulator.ts +66 -0
  206. package/src/public/public_tx_simulator/factories.ts +61 -0
  207. package/src/public/public_tx_simulator/index.ts +8 -0
  208. package/src/public/public_tx_simulator/public_tx_simulator.ts +190 -0
  209. package/src/public/public_tx_simulator/public_tx_simulator_base.ts +37 -0
  210. package/src/public/public_tx_simulator/public_tx_simulator_interface.ts +33 -0
  211. package/src/public/side_effect_errors.ts +96 -0
  212. package/src/public/test_executor_metrics.ts +399 -0
  213. package/src/public/unique_class_ids.ts +79 -0
  214. package/src/public/utils.ts +16 -0
  215. package/src/server.ts +6 -0
@@ -0,0 +1,200 @@
1
+ import type { ForeignCallHandler, WitnessMap } from '@aztec/noir-acvm_js';
2
+
3
+ import { runInDirectory } from '@aztec-labs/foundation/fs';
4
+ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec-labs/foundation/log';
5
+ import { Timer } from '@aztec-labs/foundation/timer';
6
+ import type { FunctionArtifactWithContractName } from '@aztec-labs/stdlib/abi';
7
+ import type { NoirCompiledCircuitWithName } from '@aztec-labs/stdlib/noir';
8
+ import * as proc from 'child_process';
9
+ import { promises as fs } from 'fs';
10
+
11
+ import type { ACIRCallback, ACIRExecutionResult } from './acvm/acvm.js';
12
+ import type { ACVMWitness } from './acvm/acvm_types.js';
13
+ import type { CircuitSimulator } from './circuit_simulator.js';
14
+
15
+ export enum ACVM_RESULT {
16
+ SUCCESS,
17
+ FAILURE,
18
+ }
19
+
20
+ export type ACVMSuccess = {
21
+ status: ACVM_RESULT.SUCCESS;
22
+ duration: number;
23
+ witness: Map<number, string>;
24
+ };
25
+
26
+ export type ACVMFailure = {
27
+ status: ACVM_RESULT.FAILURE;
28
+ reason: string;
29
+ };
30
+
31
+ export type ACVMResult = ACVMSuccess | ACVMFailure;
32
+
33
+ /**
34
+ * Parses a TOML format witness map string into a Map structure
35
+ * @param outputString - The witness map in TOML format
36
+ * @returns The parsed witness map
37
+ */
38
+ function parseIntoWitnessMap(outputString: string) {
39
+ const lines = outputString.split('\n');
40
+ return new Map<number, string>(
41
+ lines
42
+ .filter((line: string) => line.length)
43
+ .map((line: string) => {
44
+ const pair = line.replaceAll(' ', '').split('=');
45
+ return [Number(pair[0]), pair[1].replaceAll('"', '')];
46
+ }),
47
+ );
48
+ }
49
+
50
+ /**
51
+ *
52
+ * @param inputWitness - The circuit's input witness
53
+ * @param bytecode - The circuit bytecode
54
+ * @param workingDirectory - A directory to use for temporary files by the ACVM
55
+ * @param pathToAcvm - The path to the ACVM binary
56
+ * @param outputFilename - If specified, the output will be stored as a file, encoded using Bincode
57
+ * @returns The completed partial witness outputted from the circuit
58
+ */
59
+ export async function executeNativeCircuit(
60
+ inputWitness: WitnessMap,
61
+ bytecode: Buffer,
62
+ workingDirectory: string,
63
+ pathToAcvm: string,
64
+ outputFilename?: string,
65
+ loggerOrBindings?: Logger | LoggerBindings,
66
+ ): Promise<ACVMResult> {
67
+ const logger = resolveLogger('simulator:acvm-native', loggerOrBindings);
68
+ const bytecodeFilename = 'bytecode';
69
+ const witnessFilename = 'input_witness.toml';
70
+
71
+ // convert the witness map to TOML format
72
+ let witnessMap = '';
73
+ inputWitness.forEach((value: string, key: number) => {
74
+ witnessMap = witnessMap.concat(`${key} = '${value}'\n`);
75
+ });
76
+
77
+ try {
78
+ // Check that the directory exists
79
+ await fs.access(workingDirectory);
80
+ } catch {
81
+ return { status: ACVM_RESULT.FAILURE, reason: `Working directory ${workingDirectory} does not exist` };
82
+ }
83
+
84
+ try {
85
+ // Write the bytecode and input witness to the working directory
86
+ await fs.writeFile(`${workingDirectory}/${bytecodeFilename}`, bytecode);
87
+ await fs.writeFile(`${workingDirectory}/${witnessFilename}`, witnessMap);
88
+
89
+ // Execute the ACVM using the given args
90
+ const args = [
91
+ `execute`,
92
+ `--working-directory`,
93
+ `${workingDirectory}`,
94
+ `--bytecode`,
95
+ `${bytecodeFilename}`,
96
+ `--input-witness`,
97
+ `${witnessFilename}`,
98
+ '--print',
99
+ '--output-witness',
100
+ 'output-witness',
101
+ ];
102
+
103
+ logger.debug(`Calling ACVM with ${args.join(' ')}`);
104
+
105
+ const processPromise = new Promise<string>((resolve, reject) => {
106
+ const outChunks: Buffer[] = [];
107
+ const errChunks: Buffer[] = [];
108
+ let outLen = 0;
109
+ let errLen = 0;
110
+ const acvm = proc.spawn(pathToAcvm, args);
111
+ acvm.stdout.on('data', (data: Buffer) => {
112
+ outChunks.push(data);
113
+ outLen += data.length;
114
+ });
115
+ acvm.stderr.on('data', (data: Buffer) => {
116
+ errChunks.push(data);
117
+ errLen += data.length;
118
+ });
119
+ acvm.on('close', code => {
120
+ if (code === 0) {
121
+ resolve(Buffer.concat(outChunks, outLen).toString('utf-8'));
122
+ } else {
123
+ const stderr = Buffer.concat(errChunks, errLen);
124
+ logger.error(`From ACVM: ${stderr.toString('utf-8')}`);
125
+ reject(stderr.toString('utf-8'));
126
+ }
127
+ });
128
+ });
129
+
130
+ const timer = new Timer();
131
+ const output = await processPromise;
132
+ const duration = timer.ms();
133
+ if (outputFilename) {
134
+ const outputWitnessFileName = `${workingDirectory}/output-witness.gz`;
135
+ await fs.copyFile(outputWitnessFileName, outputFilename);
136
+ }
137
+ // TODO: We shouldn't be parsing the witness from stdout, it's not very performant, and we end up with two ways of fetching the witness.
138
+ // We probably should implement the WitnessStack type, run the ACVM with msgpack serialization mode (env variable), and ungzip and parse the witness from
139
+ // the outputted gz witness file.
140
+ const witness = parseIntoWitnessMap(output);
141
+ return { status: ACVM_RESULT.SUCCESS, witness, duration };
142
+ } catch (error) {
143
+ return { status: ACVM_RESULT.FAILURE, reason: `${error}` };
144
+ }
145
+ }
146
+
147
+ export class NativeACVMSimulator implements CircuitSimulator {
148
+ private logger: Logger;
149
+
150
+ constructor(
151
+ private workingDirectory: string,
152
+ private pathToAcvm: string,
153
+ private witnessFilename?: string,
154
+ loggerOrBindings?: Logger | LoggerBindings,
155
+ ) {
156
+ this.logger = resolveLogger('simulator:acvm-native', loggerOrBindings);
157
+ }
158
+
159
+ async executeProtocolCircuit(
160
+ input: ACVMWitness,
161
+ artifact: NoirCompiledCircuitWithName,
162
+ callback: ForeignCallHandler | undefined,
163
+ ): Promise<ACVMSuccess> {
164
+ // Execute the circuit on those initial witness values
165
+
166
+ if (callback) {
167
+ throw new Error('Native ACVM simulator does not support foreign calls. Ignoring callback.');
168
+ }
169
+
170
+ const operation = async (directory: string) => {
171
+ // Decode the bytecode from base64 since the acvm does not know about base64 encoding
172
+ const decodedBytecode = Buffer.from(artifact.bytecode, 'base64');
173
+ // Execute the circuit
174
+ const result = await executeNativeCircuit(
175
+ input,
176
+ decodedBytecode,
177
+ directory,
178
+ this.pathToAcvm,
179
+ this.witnessFilename,
180
+ this.logger,
181
+ );
182
+
183
+ if (result.status == ACVM_RESULT.FAILURE) {
184
+ throw new Error(`Failed to generate witness: ${result.reason}`);
185
+ }
186
+
187
+ return result;
188
+ };
189
+
190
+ return await runInDirectory(this.workingDirectory, operation, false, this.logger);
191
+ }
192
+
193
+ executeUserCircuit(
194
+ _input: ACVMWitness,
195
+ _artifact: FunctionArtifactWithContractName,
196
+ _callback: ACIRCallback,
197
+ ): Promise<ACIRExecutionResult> {
198
+ throw new Error('Not implemented');
199
+ }
200
+ }
@@ -0,0 +1,80 @@
1
+ import initACVM, { type ExecutionError, type ForeignCallHandler, executeCircuit } from '@aztec/noir-acvm_js';
2
+ import initAbi from '@aztec/noir-noirc_abi';
3
+
4
+ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec-labs/foundation/log';
5
+ import { Timer } from '@aztec-labs/foundation/timer';
6
+ import type { FunctionArtifactWithContractName } from '@aztec-labs/stdlib/abi';
7
+ import type { NoirCompiledCircuitWithName } from '@aztec-labs/stdlib/noir';
8
+
9
+ import { type ACIRCallback, type ACIRExecutionResult, acvm } from './acvm/acvm.js';
10
+ import type { ACVMWitness } from './acvm/acvm_types.js';
11
+ import type { ACVMSuccess } from './acvm_native.js';
12
+ import { type CircuitSimulator, enrichNoirError } from './circuit_simulator.js';
13
+
14
+ let wasmInitPromise: Promise<unknown> | undefined;
15
+
16
+ export class WASMSimulator implements CircuitSimulator {
17
+ protected log: Logger;
18
+
19
+ constructor(loggerOrBindings?: Logger | LoggerBindings) {
20
+ this.log = resolveLogger('wasm-simulator', loggerOrBindings);
21
+ }
22
+
23
+ async init(): Promise<void> {
24
+ // If these are available, then we are in the
25
+ // web environment. For the node environment, this
26
+ // is a no-op.
27
+ if (typeof initAbi === 'function') {
28
+ /** @ts-expect-error The node bundle doesn't include these default imports, so TS complains */
29
+ wasmInitPromise ??= Promise.all([initAbi(), initACVM()]);
30
+ await wasmInitPromise;
31
+ }
32
+ }
33
+
34
+ async executeProtocolCircuit(
35
+ input: ACVMWitness,
36
+ artifact: NoirCompiledCircuitWithName,
37
+ callback: ForeignCallHandler,
38
+ ): Promise<ACVMSuccess> {
39
+ this.log.debug('init', { hash: artifact.hash });
40
+ await this.init();
41
+
42
+ // Decode the bytecode from base64 since the acvm does not know about base64 encoding
43
+ const decodedBytecode = Buffer.from(artifact.bytecode, 'base64');
44
+ //
45
+ // Execute the circuit
46
+ try {
47
+ const timer = new Timer();
48
+ const result = await executeCircuit(
49
+ decodedBytecode,
50
+ input,
51
+ callback, // handle calls to debug_log
52
+ );
53
+ this.log.debug('execution successful', { hash: artifact.hash });
54
+ return { witness: result, duration: timer.ms() } as ACVMSuccess;
55
+ } catch (err) {
56
+ // Typescript types caught errors as unknown or any, so we need to narrow its type to check if it has raw
57
+ // assertion payload.
58
+ if (typeof err === 'object' && err !== null && 'rawAssertionPayload' in err) {
59
+ const parsed = enrichNoirError(artifact, err as ExecutionError);
60
+ this.log.debug('execution failed', {
61
+ hash: artifact.hash,
62
+ error: parsed,
63
+ message: parsed.message,
64
+ });
65
+ throw parsed;
66
+ }
67
+ this.log.debug('execution failed', { hash: artifact.hash, error: err });
68
+ throw new Error(`Circuit execution failed: ${err}`);
69
+ }
70
+ }
71
+
72
+ async executeUserCircuit(
73
+ input: ACVMWitness,
74
+ artifact: FunctionArtifactWithContractName,
75
+ callback: ACIRCallback,
76
+ ): Promise<ACIRExecutionResult> {
77
+ await this.init();
78
+ return acvm(artifact.bytecode, input, callback, this.log.createChild('acvm'));
79
+ }
80
+ }
@@ -0,0 +1,55 @@
1
+ import { type ExecutionError, type ForeignCallHandler, executeCircuit } from '@aztec/noir-acvm_js';
2
+ import type { WitnessMap } from '@aztec/noir-types';
3
+
4
+ import { Timer } from '@aztec-labs/foundation/timer';
5
+ import type { FunctionArtifactWithContractName } from '@aztec-labs/stdlib/abi';
6
+ import type { NoirCompiledCircuitWithName } from '@aztec-labs/stdlib/noir';
7
+
8
+ import type { ACIRCallback, ACIRExecutionResult } from './acvm/acvm.js';
9
+ import type { ACVMWitness } from './acvm/acvm_types.js';
10
+ import type { ACVMSuccess } from './acvm_native.js';
11
+ import { type CircuitSimulator, enrichNoirError } from './circuit_simulator.js';
12
+
13
+ /**
14
+ * A circuit simulator that uses the WASM simulator with the ability to handle blobs via the foreign call handler.
15
+ * This class is temporary while brillig cannot handle the blob math, and it is kept separate
16
+ * because the zkg commitment library used in the blob code is not browser compatible.
17
+ *
18
+ * It is only used in the context of server-side code executing simulated protocol circuits.
19
+ */
20
+ export class WASMSimulatorWithBlobs implements CircuitSimulator {
21
+ async executeProtocolCircuit(
22
+ input: WitnessMap,
23
+ artifact: NoirCompiledCircuitWithName,
24
+ callback: ForeignCallHandler,
25
+ ): Promise<ACVMSuccess> {
26
+ // Decode the bytecode from base64 since the acvm does not know about base64 encoding
27
+ const decodedBytecode = Buffer.from(artifact.bytecode, 'base64');
28
+ //
29
+ // Execute the circuit
30
+ try {
31
+ const timer = new Timer();
32
+ const _witnessMap = await executeCircuit(
33
+ decodedBytecode,
34
+ input,
35
+ callback, // handle calls to debug_log and evaluate_blobs mock
36
+ );
37
+ return { witness: _witnessMap, duration: timer.ms() } as ACVMSuccess;
38
+ } catch (err) {
39
+ // Typescript types caught errors as unknown or any, so we need to narrow its type to check if it has raw
40
+ // assertion payload.
41
+ if (typeof err === 'object' && err !== null && 'rawAssertionPayload' in err) {
42
+ throw enrichNoirError(artifact, err as ExecutionError);
43
+ }
44
+ throw new Error(`Circuit execution failed: ${err}`);
45
+ }
46
+ }
47
+
48
+ executeUserCircuit(
49
+ _input: ACVMWitness,
50
+ _artifact: FunctionArtifactWithContractName,
51
+ _callback: ACIRCallback,
52
+ ): Promise<ACIRExecutionResult> {
53
+ throw new Error('Not implemented');
54
+ }
55
+ }
@@ -0,0 +1,91 @@
1
+ import type { ExecutionError, ForeignCallHandler } from '@aztec/noir-acvm_js';
2
+ import { abiDecodeError } from '@aztec/noir-noirc_abi';
3
+
4
+ import { parseDebugSymbols } from '@aztec-labs/stdlib/abi';
5
+ import type { FunctionArtifactWithContractName } from '@aztec-labs/stdlib/abi';
6
+ import type { NoirCompiledCircuit, NoirCompiledCircuitWithName } from '@aztec-labs/stdlib/noir';
7
+
8
+ import { type ACIRCallback, type ACIRExecutionResult, extractCallStack } from './acvm/acvm.js';
9
+ import type { ACVMWitness } from './acvm/acvm_types.js';
10
+ import type { ACVMSuccess } from './acvm_native.js';
11
+
12
+ /**
13
+ * Low level simulation interface
14
+ */
15
+ export interface CircuitSimulator {
16
+ /**
17
+ * Execute a protocol circuit/generate a witness
18
+ * @param input - The initial witness map defining all of the inputs to `circuit`.
19
+ * @param artifact - ACIR circuit bytecode and its metadata.
20
+ * @param callback - A callback to process any foreign calls from the circuit. Can be undefined as for native
21
+ * ACVM simulator we don't process foreign calls.
22
+ * @returns The solved witness calculated by executing the circuit on the provided inputs.
23
+ */
24
+ executeProtocolCircuit(
25
+ input: ACVMWitness,
26
+ artifact: NoirCompiledCircuitWithName,
27
+ callback: ForeignCallHandler | undefined,
28
+ ): Promise<ACVMSuccess>;
29
+
30
+ /**
31
+ * Execute a user circuit (smart contract function)/generate a witness
32
+ * @param input - The initial witness map defining all of the inputs to `circuit`.
33
+ * @param artifact - Contract function ACIR circuit bytecode and its metadata.
34
+ * @param callback - A callback to process any foreign calls from the circuit.
35
+ * @returns The solved witness calculated by executing the circuit on the provided inputs, as well as the return
36
+ * witness indices as specified by the circuit.
37
+ */
38
+ executeUserCircuit(
39
+ input: ACVMWitness,
40
+ artifact: FunctionArtifactWithContractName,
41
+ callback: ACIRCallback,
42
+ ): Promise<ACIRExecutionResult>;
43
+ }
44
+
45
+ export type DecodedError = ExecutionError & { decodedAssertionPayload?: any; noirCallStack?: string[] };
46
+
47
+ // Payload parsing taken from noir/noir-repo/tooling/noir_js/src/witness_generation.ts.
48
+ // TODO: import this in isolation without having to import noir_js in its entirety.
49
+ export function enrichNoirError(artifact: NoirCompiledCircuit, originalError: ExecutionError): DecodedError {
50
+ const enrichedError = originalError as DecodedError;
51
+
52
+ if (originalError.rawAssertionPayload) {
53
+ try {
54
+ // Decode the payload
55
+ const decodedPayload = abiDecodeError(artifact.abi, originalError.rawAssertionPayload);
56
+
57
+ if (typeof decodedPayload === 'string') {
58
+ // If it's a string, just add it to the error message
59
+ enrichedError.message = `Circuit execution failed: ${decodedPayload}`;
60
+ } else {
61
+ // If not, attach the payload to the original error
62
+ enrichedError.decodedAssertionPayload = decodedPayload;
63
+ }
64
+ } catch {
65
+ // Ignore errors decoding the payload
66
+ }
67
+ }
68
+
69
+ try {
70
+ // Decode the callstack
71
+ const callStack = extractCallStack(originalError, {
72
+ // TODO(https://github.com/AztecProtocol/aztec-packages/issues/5813)
73
+ // We only support handling debug info for the circuit entry point.
74
+ // So for now we simply index into the first debug info.
75
+ debugSymbols: parseDebugSymbols(artifact.debug_symbols)[0],
76
+ files: artifact.file_map,
77
+ });
78
+
79
+ enrichedError.noirCallStack = callStack?.map(errorLocation => {
80
+ if (typeof errorLocation === 'string') {
81
+ return `at opcode ${errorLocation}`;
82
+ } else {
83
+ return `at ${errorLocation.locationText} (${errorLocation.filePath}:${errorLocation.line}:${errorLocation.column})`;
84
+ }
85
+ });
86
+ } catch {
87
+ // Ignore errors resolving the callstack
88
+ }
89
+
90
+ return enrichedError;
91
+ }
@@ -0,0 +1,40 @@
1
+ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec-labs/foundation/log';
2
+ import { promises as fs } from 'fs';
3
+
4
+ import { NativeACVMSimulator } from './acvm_native.js';
5
+ import { WASMSimulator } from './acvm_wasm.js';
6
+ import type { CircuitSimulator } from './circuit_simulator.js';
7
+
8
+ export type SimulatorConfig = {
9
+ acvmBinaryPath?: string;
10
+ acvmWorkingDirectory?: string;
11
+ };
12
+
13
+ export function getSimulatorConfigFromEnv() {
14
+ const { ACVM_BINARY_PATH, ACVM_WORKING_DIRECTORY } = process.env;
15
+ return {
16
+ acvmWorkingDirectory: ACVM_WORKING_DIRECTORY ? ACVM_WORKING_DIRECTORY : undefined,
17
+ acvmBinaryPath: ACVM_BINARY_PATH ? ACVM_BINARY_PATH : undefined,
18
+ };
19
+ }
20
+
21
+ export async function createSimulator(
22
+ config: SimulatorConfig,
23
+ loggerOrBindings?: Logger | LoggerBindings,
24
+ ): Promise<CircuitSimulator> {
25
+ const logger = resolveLogger('simulator', loggerOrBindings);
26
+ if (config.acvmBinaryPath && config.acvmWorkingDirectory) {
27
+ try {
28
+ await fs.access(config.acvmBinaryPath, fs.constants.R_OK);
29
+ await fs.mkdir(config.acvmWorkingDirectory, { recursive: true });
30
+ logger.info(`Using native ACVM at ${config.acvmBinaryPath} and working directory ${config.acvmWorkingDirectory}`);
31
+ const acvmLogger = logger.createChild('acvm-native');
32
+ return new NativeACVMSimulator(config.acvmWorkingDirectory, config.acvmBinaryPath, undefined, acvmLogger);
33
+ } catch {
34
+ logger.warn(`Failed to access ACVM at ${config.acvmBinaryPath}, falling back to WASM`);
35
+ }
36
+ }
37
+ logger.info('Using WASM ACVM simulation');
38
+ const wasmLogger = logger.createChild('wasm');
39
+ return new WASMSimulator(wasmLogger);
40
+ }