@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
package/package.json ADDED
@@ -0,0 +1,109 @@
1
+ {
2
+ "name": "@aztec-labs/simulator",
3
+ "version": "6.0.0-nightly.20260829",
4
+ "type": "module",
5
+ "exports": {
6
+ "./server": "./dest/server.js",
7
+ "./client": "./dest/client.js",
8
+ "./public/fixtures": "./dest/public/fixtures/index.js"
9
+ },
10
+ "typedocOptions": {
11
+ "entryPoints": [
12
+ "./src/index.ts"
13
+ ],
14
+ "name": "Simulator",
15
+ "tsconfig": "./tsconfig.json"
16
+ },
17
+ "scripts": {
18
+ "build": "yarn clean && ../scripts/tsc.sh",
19
+ "build:dev": "../scripts/tsc.sh --watch",
20
+ "clean": "rm -rf ./dest .tsbuildinfo",
21
+ "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}",
22
+ "build:fuzzer": "yarn clean && ../scripts/tsc.sh"
23
+ },
24
+ "inherits": [
25
+ "../package.common.json"
26
+ ],
27
+ "jest": {
28
+ "moduleNameMapper": {
29
+ "^(\\.{1,2}/.*)\\.[cm]?js$": "$1"
30
+ },
31
+ "testRegex": "./src/.*\\.test\\.(js|mjs|ts)$",
32
+ "rootDir": "./src",
33
+ "transform": {
34
+ "^.+\\.tsx?$": [
35
+ "@swc/jest",
36
+ {
37
+ "jsc": {
38
+ "parser": {
39
+ "syntax": "typescript",
40
+ "decorators": true
41
+ },
42
+ "transform": {
43
+ "decoratorVersion": "2022-03"
44
+ }
45
+ }
46
+ }
47
+ ]
48
+ },
49
+ "extensionsToTreatAsEsm": [
50
+ ".ts"
51
+ ],
52
+ "reporters": [
53
+ "default"
54
+ ],
55
+ "testTimeout": 120000,
56
+ "setupFiles": [
57
+ "../../foundation/src/jest/setup.mjs"
58
+ ],
59
+ "testEnvironment": "../../foundation/src/jest/env.mjs",
60
+ "setupFilesAfterEnv": [
61
+ "../../foundation/src/jest/setupAfterEnv.mjs"
62
+ ]
63
+ },
64
+ "dependencies": {
65
+ "@aztec-labs/constants": "6.0.0-nightly.20260829",
66
+ "@aztec-labs/foundation": "6.0.0-nightly.20260829",
67
+ "@aztec-labs/protocol-contracts": "6.0.0-nightly.20260829",
68
+ "@aztec-labs/standard-contracts": "6.0.0-nightly.20260829",
69
+ "@aztec-labs/stdlib": "6.0.0-nightly.20260829",
70
+ "@aztec-labs/telemetry-client": "6.0.0-nightly.20260829",
71
+ "@aztec-labs/world-state": "6.0.0-nightly.20260829",
72
+ "@aztec/bb-avm-sim": "6.0.0-nightly.20260826",
73
+ "@aztec/cdb": "6.0.0-nightly.20260826",
74
+ "@aztec/ipc-runtime": "6.0.0-nightly.20260826",
75
+ "@aztec/noir-acvm_js": "6.0.0-nightly.20260826",
76
+ "@aztec/noir-noirc_abi": "6.0.0-nightly.20260826",
77
+ "@aztec/noir-types": "6.0.0-nightly.20260826",
78
+ "lodash.clonedeep": "^4.5.0",
79
+ "lodash.merge": "^4.6.2",
80
+ "msgpackr": "^1.11.2",
81
+ "tslib": "^2.4.0"
82
+ },
83
+ "devDependencies": {
84
+ "@aztec-labs/noir-contracts.js": "6.0.0-nightly.20260829",
85
+ "@aztec-labs/noir-test-contracts.js": "6.0.0-nightly.20260829",
86
+ "@jest/globals": "^30.0.0",
87
+ "@types/jest": "^30.0.0",
88
+ "@types/lodash.clonedeep": "^4.5.7",
89
+ "@types/lodash.merge": "^4.6.9",
90
+ "@types/node": "^22.15.17",
91
+ "@typescript/native-preview": "7.0.0-dev.20260113.1",
92
+ "istanbul-lib-hook": "^3.0.0",
93
+ "istanbul-lib-instrument": "^6.0.3",
94
+ "jest": "^30.0.0",
95
+ "jest-mock-extended": "^4.0.0",
96
+ "ts-node": "^10.9.1",
97
+ "typescript": "^5.3.3",
98
+ "viem": "npm:@aztec/viem@2.38.2"
99
+ },
100
+ "files": [
101
+ "dest",
102
+ "src",
103
+ "!*.test.*"
104
+ ],
105
+ "types": "./dest/index.d.ts",
106
+ "engines": {
107
+ "node": ">=20.10"
108
+ }
109
+ }
package/src/client.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './private/acvm/index.js';
2
+ export { WASMSimulator } from './private/acvm_wasm.js';
3
+ export type { ACVMSuccess } from './private/acvm_native.js';
4
+ export { type CircuitSimulator, type DecodedError } from './private/circuit_simulator.js';
5
+ export * from './common/index.js';
@@ -0,0 +1,219 @@
1
+ import type { RawAssertionPayload } from '@aztec/noir-acvm_js';
2
+ import { abiDecodeError } from '@aztec/noir-noirc_abi';
3
+
4
+ import type { Fr } from '@aztec-labs/foundation/curves/bn254';
5
+ import { jsonStringify } from '@aztec-labs/foundation/json-rpc';
6
+ import type {
7
+ BrilligFunctionId,
8
+ DebugFileMap,
9
+ DebugInfo,
10
+ FunctionAbi,
11
+ LocationNodeDebugInfo,
12
+ OpcodeLocation,
13
+ } from '@aztec-labs/stdlib/abi';
14
+ import {
15
+ type FailingFunction,
16
+ type NoirCallStack,
17
+ SimulationError,
18
+ type SourceCodeLocation,
19
+ } from '@aztec-labs/stdlib/errors';
20
+
21
+ /**
22
+ * An error that occurred during the execution of a function.
23
+ * @param message - the error message
24
+ * @param failingFunction - the Aztec function that failed
25
+ * @param noirCallStack - the internal call stack of the function that failed (within the failing Aztec function)
26
+ * @param options - additional error options (an optional "cause" entry allows for a recursive error stack where
27
+ * an error's cause may be an ExecutionError itself)
28
+ */
29
+ export class ExecutionError extends Error {
30
+ constructor(
31
+ message: string,
32
+ /**
33
+ * The function that failed.
34
+ */
35
+ public failingFunction: FailingFunction,
36
+ /**
37
+ * The noir call stack of the function that failed.
38
+ */
39
+ public noirCallStack?: NoirCallStack,
40
+ options?: ErrorOptions,
41
+ ) {
42
+ super(message, options);
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Traverses the cause chain of an error.
48
+ * @param error - The error to start from.
49
+ * @param callback - A callback on every error, including the first one.
50
+ */
51
+ export function traverseCauseChain(error: Error, callback: (error: Error) => void) {
52
+ let currentError: Error | undefined = error;
53
+ while (currentError) {
54
+ callback(currentError);
55
+ if (currentError.cause && currentError.cause instanceof Error) {
56
+ currentError = currentError.cause;
57
+ } else {
58
+ currentError = undefined;
59
+ }
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Creates a simulation error from an error chain generated during the execution of a function.
65
+ * @param error - The error thrown during execution.
66
+ * @returns - A simulation error.
67
+ */
68
+ export function createSimulationError(error: Error, revertData?: Fr[]): SimulationError {
69
+ let rootCause = error;
70
+ let noirCallStack: NoirCallStack | undefined = undefined;
71
+ const aztecCallStack: FailingFunction[] = [];
72
+
73
+ traverseCauseChain(error, cause => {
74
+ rootCause = cause;
75
+ if (cause instanceof ExecutionError) {
76
+ aztecCallStack.push(cause.failingFunction);
77
+ if (cause.noirCallStack) {
78
+ noirCallStack = cause.noirCallStack;
79
+ }
80
+ }
81
+ });
82
+
83
+ return new SimulationError(rootCause.message, aztecCallStack, revertData, noirCallStack, { cause: rootCause });
84
+ }
85
+
86
+ /**
87
+ * Resolves the source code locations from an array of opcode locations
88
+ */
89
+ export function resolveOpcodeLocations(
90
+ opcodeLocations: OpcodeLocation[],
91
+ debug: DebugInfo,
92
+ files: DebugFileMap,
93
+ brilligFunctionId?: BrilligFunctionId,
94
+ ): SourceCodeLocation[] {
95
+ let locations = opcodeLocations.flatMap(opcodeLocation =>
96
+ getSourceCodeLocationsFromOpcodeLocation(opcodeLocation, debug, files, brilligFunctionId),
97
+ );
98
+
99
+ // Adds the acir call stack if the last location is a brillig opcode
100
+ if (locations.length > 0) {
101
+ const decomposedOpcodeLocation = opcodeLocations[opcodeLocations.length - 1].split('.');
102
+ if (decomposedOpcodeLocation.length === 2) {
103
+ const acirCallstackId = debug.acir_locations[decomposedOpcodeLocation[0]];
104
+ if (acirCallstackId !== undefined) {
105
+ const callStack = debug.location_tree.locations[acirCallstackId];
106
+ const acirCallstack = getCallStackFromLocationNode(callStack, debug.location_tree.locations, files);
107
+ locations = acirCallstack.concat(locations);
108
+ }
109
+ }
110
+ }
111
+ return locations;
112
+ }
113
+
114
+ function getCallStackFromLocationNode(
115
+ callStack: LocationNodeDebugInfo,
116
+ locationTree: LocationNodeDebugInfo[],
117
+ files: DebugFileMap,
118
+ ): SourceCodeLocation[] {
119
+ const result: SourceCodeLocation[] = [];
120
+
121
+ while (callStack.parent !== null) {
122
+ const { file: fileId, span } = callStack.value;
123
+
124
+ const { path, source } = files[fileId];
125
+
126
+ const locationText = source.substring(span.start, span.end);
127
+ const precedingText = source.substring(0, span.start);
128
+ const previousLines = precedingText.split('\n');
129
+ // Lines and columns in stacks are one indexed.
130
+ const line = previousLines.length;
131
+ const column = previousLines[previousLines.length - 1].length + 1;
132
+
133
+ // Unshift since we are exploring child nodes first
134
+ result.unshift({
135
+ filePath: path,
136
+ line,
137
+ column,
138
+ fileSource: source,
139
+ locationText,
140
+ });
141
+
142
+ callStack = locationTree[callStack.parent];
143
+ }
144
+
145
+ return result;
146
+ }
147
+ /**
148
+ * Extracts the call stack from the location of a failing opcode and the debug metadata.
149
+ * One opcode can point to multiple calls due to inlining.
150
+ */
151
+ function getSourceCodeLocationsFromOpcodeLocation(
152
+ opcodeLocation: string,
153
+ debug: DebugInfo,
154
+ files: DebugFileMap,
155
+ brilligFunctionId?: BrilligFunctionId,
156
+ ): SourceCodeLocation[] {
157
+ let callStackID = debug.acir_locations[opcodeLocation];
158
+ const brilligLocation = extractBrilligLocation(opcodeLocation);
159
+ if (brilligFunctionId !== undefined && brilligLocation !== undefined) {
160
+ callStackID = debug.brillig_locations[brilligFunctionId][brilligLocation];
161
+ if (callStackID === undefined) {
162
+ return [];
163
+ }
164
+ }
165
+
166
+ if (callStackID === undefined) {
167
+ return [];
168
+ }
169
+ const callStack = debug.location_tree.locations[callStackID];
170
+ return getCallStackFromLocationNode(callStack, debug.location_tree.locations, files);
171
+ }
172
+
173
+ /**
174
+ * Extracts a brillig location from an opcode location.
175
+ */
176
+ function extractBrilligLocation(opcodeLocation: string): string | undefined {
177
+ const splitted = opcodeLocation.split('.');
178
+ if (splitted.length === 2) {
179
+ return splitted[1];
180
+ }
181
+ return undefined;
182
+ }
183
+
184
+ export function resolveAssertionMessage(errorPayload: RawAssertionPayload, abi: FunctionAbi): string | undefined {
185
+ const decoded = abiDecodeError(
186
+ { parameters: [], error_types: abi.errorTypes, return_type: null }, // eslint-disable-line camelcase
187
+ errorPayload,
188
+ );
189
+
190
+ if (typeof decoded === 'string') {
191
+ return decoded;
192
+ } else {
193
+ return jsonStringify(decoded);
194
+ }
195
+ }
196
+
197
+ export function resolveAssertionMessageFromRevertData(revertData: Fr[], abi: FunctionAbi): string | undefined {
198
+ if (revertData.length == 0) {
199
+ return undefined;
200
+ }
201
+
202
+ const [errorSelector, ...errorData] = revertData;
203
+
204
+ return resolveAssertionMessage(
205
+ {
206
+ selector: errorSelector.toBigInt().toString(),
207
+ data: errorData.map(f => f.toString()),
208
+ },
209
+ abi,
210
+ );
211
+ }
212
+
213
+ export function resolveAssertionMessageFromError(err: Error, abi: FunctionAbi): string {
214
+ if (typeof err === 'object' && err !== null && 'rawAssertionPayload' in err && err.rawAssertionPayload) {
215
+ return `Assertion failed: ${resolveAssertionMessage(err.rawAssertionPayload as RawAssertionPayload, abi)}`;
216
+ } else {
217
+ return err.message;
218
+ }
219
+ }
@@ -0,0 +1,2 @@
1
+ export * from './errors.js';
2
+ export * from './stats/index.js';
@@ -0,0 +1 @@
1
+ export * from './stats.js';
@@ -0,0 +1,20 @@
1
+ import type { Logger } from '@aztec-labs/foundation/log';
2
+ import type { CircuitName, CircuitSimulationStats } from '@aztec-labs/stdlib/stats';
3
+
4
+ export function emitCircuitSimulationStats(
5
+ circuitName: CircuitName,
6
+ duration: number,
7
+ inputSize: number,
8
+ outputSize: number,
9
+ logger: Logger,
10
+ ) {
11
+ const stats: CircuitSimulationStats = {
12
+ eventName: 'circuit-simulation',
13
+ circuitName,
14
+ inputSize,
15
+ outputSize,
16
+ duration,
17
+ };
18
+
19
+ logger.debug('Circuit simulation stats', stats);
20
+ }
@@ -0,0 +1,114 @@
1
+ import {
2
+ type ExecutionError,
3
+ type ForeignCallInput,
4
+ type ForeignCallOutput,
5
+ executeCircuitWithReturnWitness,
6
+ } from '@aztec/noir-acvm_js';
7
+
8
+ import { type Logger, type LoggerBindings, resolveLogger } from '@aztec-labs/foundation/log';
9
+ import type { FunctionDebugMetadata } from '@aztec-labs/stdlib/abi';
10
+ import type { NoirCallStack } from '@aztec-labs/stdlib/errors';
11
+
12
+ import { resolveOpcodeLocations, traverseCauseChain } from '../../common/errors.js';
13
+ import type { ACVMWitness } from './acvm_types.js';
14
+
15
+ /**
16
+ * The callback interface for the ACIR.
17
+ */
18
+ export type ACIRCallback = Record<string, (...args: ForeignCallInput[]) => Promise<ForeignCallOutput[]>>;
19
+
20
+ export type ACIRCallbackStats = { times: number[] };
21
+
22
+ /**
23
+ * The result of executing an ACIR.
24
+ */
25
+ export interface ACIRExecutionResult {
26
+ /**
27
+ * An execution result contains two witnesses.
28
+ * 1. The partial witness of the execution.
29
+ * 2. The return witness which contains the given public return values within the full witness.
30
+ */
31
+ partialWitness: ACVMWitness;
32
+ returnWitness: ACVMWitness;
33
+ oracles?: Record<string, ACIRCallbackStats>;
34
+ }
35
+
36
+ /**
37
+ * The function call that executes an ACIR.
38
+ * @param acir - The ACIR circuit bytecode to execute.
39
+ * @param initialWitness - The initial witness map defining all of the inputs to `circuit`.
40
+ * @param callback - A callback to process any foreign calls from the circuit.
41
+ * @param logger - Optional logger for ACVM execution logs.
42
+ * @returns The solved witness calculated by executing the circuit on the provided inputs, as well as the return
43
+ * witness indices as specified by the circuit.
44
+ */
45
+ export async function acvm(
46
+ acir: Buffer,
47
+ initialWitness: ACVMWitness,
48
+ callback: ACIRCallback,
49
+ loggerOrBindings?: Logger | LoggerBindings,
50
+ ): Promise<ACIRExecutionResult> {
51
+ const logger = resolveLogger('simulator:acvm', loggerOrBindings);
52
+ const solvedAndReturnWitness = await executeCircuitWithReturnWitness(
53
+ acir,
54
+ initialWitness,
55
+ (name: string, args: ForeignCallInput[]) => {
56
+ try {
57
+ logger.debug(`Oracle callback ${name}`);
58
+ const oracleFunction = callback[name];
59
+ if (!oracleFunction) {
60
+ throw new Error(`Oracle callback ${name} not found`);
61
+ }
62
+
63
+ return oracleFunction.call(callback, ...args);
64
+ } catch (err) {
65
+ let typedError: Error;
66
+ if (err instanceof Error) {
67
+ typedError = err;
68
+ } else {
69
+ typedError = new Error(`Error in oracle callback ${err}`);
70
+ }
71
+ logger.error(`Error in oracle callback ${name}: ${typedError.message}`);
72
+ throw typedError;
73
+ }
74
+ },
75
+ ).catch((err: Error) => {
76
+ // Wasm callbacks act as a boundary for stack traces, so we capture it here and complete the error if it happens.
77
+ const stack = new Error().stack;
78
+
79
+ traverseCauseChain(err, cause => {
80
+ if (cause.stack) {
81
+ cause.stack += stack;
82
+ }
83
+ });
84
+
85
+ throw err;
86
+ });
87
+
88
+ return { partialWitness: solvedAndReturnWitness.solvedWitness, returnWitness: solvedAndReturnWitness.returnWitness };
89
+ }
90
+
91
+ /**
92
+ * Extracts the call stack from an thrown by the acvm.
93
+ * @param error - The error to extract from.
94
+ * @param debug - The debug metadata of the function called.
95
+ * @returns The call stack, if available.
96
+ */
97
+ export function extractCallStack(
98
+ error: Error | ExecutionError,
99
+ debug?: FunctionDebugMetadata,
100
+ ): NoirCallStack | undefined {
101
+ if (!('callStack' in error) || !error.callStack) {
102
+ return undefined;
103
+ }
104
+ const { callStack, brilligFunctionId } = error;
105
+ if (!debug) {
106
+ return callStack;
107
+ }
108
+
109
+ try {
110
+ return resolveOpcodeLocations(callStack, debug.debugSymbols, debug.files, brilligFunctionId);
111
+ } catch {
112
+ return callStack;
113
+ }
114
+ }
@@ -0,0 +1,11 @@
1
+ import type { WitnessMap } from '@aztec/noir-acvm_js';
2
+
3
+ /**
4
+ * ACVMField
5
+ */
6
+ export type ACVMField = string;
7
+
8
+ /**
9
+ * The format for witnesses of the ACVM.
10
+ */
11
+ export type ACVMWitness = WitnessMap;
@@ -0,0 +1,58 @@
1
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
2
+ import { hexToBuffer } from '@aztec-labs/foundation/string';
3
+
4
+ import type { ACVMField, ACVMWitness } from './acvm_types.js';
5
+
6
+ /**
7
+ * Converts a Noir BoundedVec of Fields into an Fr array. Note that BoundedVecs are structs, and therefore translated as
8
+ * two separate ACVMField values (an array and a single field).
9
+ *
10
+ * @param storage The array with the BoundedVec's storage (i.e. BoundedVec::storage())
11
+ * @param length The length of the BoundedVec (i.e. BoundedVec::len())
12
+ * @returns An array with the same content as the Noir version. Elements past the length are discarded.
13
+ */
14
+ export function fromBoundedVec(storage: ACVMField[], length: ACVMField): Fr[] {
15
+ return storage.slice(0, Fr.fromString(length).toNumber()).map(Fr.fromString);
16
+ }
17
+
18
+ /**
19
+ * Converts a Noir BoundedVec of unsigned integers into a Buffer. Note that BoundedVecs are structs, and therefore
20
+ * translated as two separate ACVMField values (an array and a single field).
21
+ *
22
+ * @param storage The array with the BoundedVec's storage (i.e. BoundedVec::storage())
23
+ * @param length The length of the BoundedVec (i.e. BoundedVec::len())
24
+ * @param uintBitSize If it's an array of Noir u8's, put `8`, etc.
25
+ * @returns A buffer containing the unsigned integers tightly packed
26
+ */
27
+ export function fromUintBoundedVec(storage: ACVMField[], length: ACVMField, uintBitSize: number): Buffer {
28
+ if (uintBitSize % 8 !== 0) {
29
+ throw new Error(`u${uintBitSize} is not a supported type in Noir`);
30
+ }
31
+ const uintByteSize = uintBitSize / 8;
32
+ const boundedStorage = storage.slice(0, Fr.fromString(length).toNumber());
33
+ return Buffer.concat(boundedStorage.map(str => hexToBuffer(str).subarray(-uintByteSize)));
34
+ }
35
+
36
+ /**
37
+ * Transforms a witness map to its field elements.
38
+ * @param witness - The witness to extract from.
39
+ * @returns The return values.
40
+ */
41
+ export function witnessMapToFields(witness: ACVMWitness): Fr[] {
42
+ const sortedKeys = [...witness.keys()].sort((a, b) => a - b);
43
+ return sortedKeys.map(key => witness.get(key)!).map(Fr.fromString);
44
+ }
45
+
46
+ /**
47
+ * Converts an array of Noir unsigned integers to a single tightly-packed buffer.
48
+ * @param uintBitSize If it's an array of Noir u8's, put `8`, etc.
49
+ * @returns A buffer where each byte is correctly represented as a single byte in the buffer.
50
+ * Copy of the function in txe/src/util/encoding.ts.
51
+ */
52
+ export function fromUintArray(obj: ACVMField[], uintBitSize: number): Buffer {
53
+ if (uintBitSize % 8 !== 0) {
54
+ throw new Error(`u${uintBitSize} is not a supported type in Noir`);
55
+ }
56
+ const uintByteSize = uintBitSize / 8;
57
+ return Buffer.concat(obj.map(str => hexToBuffer(str).slice(-uintByteSize)));
58
+ }
@@ -0,0 +1,4 @@
1
+ export { extractCallStack, type ACIRCallback, type ACIRCallbackStats, type ACIRExecutionResult } from './acvm.js';
2
+ export * from './acvm_types.js';
3
+ export * from './deserialize.js';
4
+ export * from './serialize.js';
@@ -0,0 +1,123 @@
1
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
2
+ import type { EthAddress } from '@aztec-labs/foundation/eth-address';
3
+ import type { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
4
+
5
+ import type { ACVMField } from './acvm_types.js';
6
+
7
+ /**
8
+ * Adapts the buffer to the field size.
9
+ * @param originalBuf - The buffer to adapt.
10
+ * @returns The adapted buffer.
11
+ */
12
+ function adaptBufferSize(originalBuf: Buffer) {
13
+ const buffer = Buffer.alloc(Fr.SIZE_IN_BYTES);
14
+ if (originalBuf.length > buffer.length) {
15
+ throw new Error('Buffer does not fit in field');
16
+ }
17
+ originalBuf.copy(buffer, buffer.length - originalBuf.length);
18
+ return buffer;
19
+ }
20
+
21
+ /**
22
+ * Converts a value to an ACVM field.
23
+ * @param value - The value to convert.
24
+ * @returns The ACVM field.
25
+ */
26
+ export function toACVMField(
27
+ value: AztecAddress | EthAddress | Fr | Buffer | boolean | number | bigint | ACVMField,
28
+ ): ACVMField {
29
+ let buffer;
30
+ if (Buffer.isBuffer(value)) {
31
+ buffer = value;
32
+ } else if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'bigint') {
33
+ buffer = new Fr(value).toBuffer();
34
+ } else if (typeof value === 'string') {
35
+ buffer = Fr.fromHexString(value).toBuffer();
36
+ } else {
37
+ buffer = value.toBuffer();
38
+ }
39
+ return `0x${adaptBufferSize(buffer).toString('hex')}`;
40
+ }
41
+
42
+ /**
43
+ * Converts a single value or an array of single values into the equivalent ACVM field representation.
44
+ */
45
+ export function toACVMFieldSingleOrArray(value: Fr | Fr[]) {
46
+ return Array.isArray(value) ? value.map(toACVMField) : toACVMField(value);
47
+ }
48
+
49
+ /**
50
+ * Inserts a list of ACVM fields to a witness.
51
+ * @param witnessStartIndex - The index where to start inserting the fields.
52
+ * @param fields - The fields to insert.
53
+ * @returns The witness.
54
+ */
55
+ export function toACVMWitness(witnessStartIndex: number, fields: Parameters<typeof toACVMField>[0][]) {
56
+ return fields.reduce((witness, field, index) => {
57
+ witness.set(index + witnessStartIndex, toACVMField(field));
58
+ return witness;
59
+ }, new Map<number, ACVMField>());
60
+ }
61
+
62
+ export function bufferToU8Array(buffer: Buffer): ACVMField[] {
63
+ return Array.from(buffer).map(byte => toACVMField(BigInt(byte)));
64
+ }
65
+
66
+ export function bufferToBoundedVec(buffer: Buffer, maxLen: number): [ACVMField[], ACVMField] {
67
+ const u8Array = bufferToU8Array(buffer);
68
+ return arrayToBoundedVec(u8Array, maxLen);
69
+ }
70
+
71
+ /**
72
+ * Converts a ForeignCallArray into a tuple which represents a nr BoundedVec.
73
+ * If the input array is shorter than the maxLen, it pads the result with zeros,
74
+ * so that nr can correctly coerce this result into a BoundedVec.
75
+ * @param bVecStorage - The array underlying the BoundedVec.
76
+ * @param maxLen - the max length of the BoundedVec.
77
+ * @returns a tuple representing a BoundedVec.
78
+ */
79
+ export function arrayToBoundedVec(bVecStorage: ACVMField[], maxLen: number): [ACVMField[], ACVMField] {
80
+ if (bVecStorage.length > maxLen) {
81
+ throw new Error(`Array of length ${bVecStorage.length} larger than maxLen ${maxLen}`);
82
+ }
83
+ const lengthDiff = maxLen - bVecStorage.length;
84
+ const zeroPaddingArray = Array(lengthDiff).fill(toACVMField(BigInt(0)));
85
+ const storage = bVecStorage.concat(zeroPaddingArray);
86
+ const len = toACVMField(BigInt(bVecStorage.length));
87
+ return [storage, len];
88
+ }
89
+
90
+ /**
91
+ * Converts an array of arrays representing Noir BoundedVec of nested arrays into its Noir serialized form.
92
+ * @param bVecStorage - The array underlying the BoundedVec.
93
+ * @param maxLen - The max length of the BoundedVec (max num of the nested arrays in the BoundedVec).
94
+ * @param nestedArrayLength - The length of the nested arrays (each nested array has to have the same length).
95
+ * @returns Serialized BoundedVec following Noir intrinsic serialization.
96
+ */
97
+ export function arrayOfArraysToBoundedVecOfArrays(
98
+ bVecStorage: ACVMField[][],
99
+ maxLen: number,
100
+ nestedArrayLength: number,
101
+ ): [ACVMField[], ACVMField] {
102
+ if (bVecStorage.length > maxLen) {
103
+ throw new Error(`Array of length ${bVecStorage.length} larger than maxLen ${maxLen}`);
104
+ }
105
+
106
+ // Check that all nested arrays have length nestedArrayLength
107
+ if (!bVecStorage.every(nestedArray => nestedArray.length === nestedArrayLength)) {
108
+ throw new Error(
109
+ `Nested array length passed in from Noir does not correspond to the length obtained in TS: ${nestedArrayLength} !== ${bVecStorage[0].length}`,
110
+ );
111
+ }
112
+
113
+ // Flatten the array of arrays
114
+ const flattenedStorage = bVecStorage.flat();
115
+
116
+ // Calculate and add padding
117
+ const numFieldsToPad = maxLen * nestedArrayLength - flattenedStorage.length;
118
+ const flattenedStorageWithPadding = flattenedStorage.concat(Array(numFieldsToPad).fill(toACVMField(BigInt(0))));
119
+
120
+ // Return flattened array with padding and length
121
+ const len = toACVMField(BigInt(bVecStorage.length));
122
+ return [flattenedStorageWithPadding, len];
123
+ }