├── index.js ├── test ├── Multiplier2 │ ├── Multiplier2.circom │ └── multiplier2.js ├── Arrays_autogen_main │ ├── Arrays.circom │ └── arrays_autogen_main.js └── Arrays │ ├── Arrays.circom │ └── arrays.js ├── .github └── workflows │ ├── npm-publish.yml │ └── main.yml ├── package.json ├── wasm ├── tester.js ├── utils.js └── witness_calculator.js ├── .gitignore ├── README.md ├── c └── tester.js └── common └── tester.js /index.js: -------------------------------------------------------------------------------- 1 | exports.wasm = require("./wasm/tester"); 2 | exports.c = require("./c/tester"); 3 | -------------------------------------------------------------------------------- /test/Multiplier2/Multiplier2.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.0.0; 2 | 3 | template Multiplier2() { 4 | signal input a; 5 | signal input b; 6 | signal output c; 7 | c <== a*b; 8 | } 9 | 10 | component main = Multiplier2(); 11 | -------------------------------------------------------------------------------- /test/Arrays_autogen_main/Arrays.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.1; 2 | 3 | include "../../node_modules/circomlib/circuits/poseidon.circom"; 4 | 5 | template Arrays(N, M) { 6 | signal input a[N][M]; 7 | signal input commitment; 8 | 9 | signal tmp[N]; 10 | 11 | for (var i = 0; i < N; i++) { 12 | tmp[i] <== Poseidon(M)(a[i]); 13 | } 14 | 15 | signal hash <== Poseidon(N)(tmp); 16 | commitment === hash; 17 | } 18 | -------------------------------------------------------------------------------- /test/Arrays/Arrays.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.1; 2 | 3 | include "../../node_modules/circomlib/circuits/poseidon.circom"; 4 | 5 | template Arrays(N, M) { 6 | signal input a[N][M]; 7 | signal input commitment; 8 | 9 | signal tmp[N]; 10 | 11 | for (var i = 0; i < N; i++) { 12 | tmp[i] <== Poseidon(M)(a[i]); 13 | } 14 | 15 | signal hash <== Poseidon(N)(tmp); 16 | commitment === hash; 17 | } 18 | 19 | component main = Arrays(2, 2); 20 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish package to NPM 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | publish-npm: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - uses: actions/setup-node@v4 13 | with: 14 | node-version: '20.x' 15 | registry-url: https://registry.npmjs.org/ 16 | cache: 'npm' 17 | - run: npm ci 18 | - run: npm publish 19 | env: 20 | NODE_AUTH_TOKEN: ${{secrets.IDEN3_CIRCOM_NPM_PUBLISH_TOKEN}} 21 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: 3 | pull_request: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | test: 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | node: [ 22 ] 12 | name: Node ${{ matrix.node }} 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Setup node 17 | uses: actions/setup-node@v3 18 | with: 19 | node-version: ${{ matrix.node }} 20 | 21 | - name: Setup other deps 22 | run: sudo apt-get update && sudo apt-get install -y wget nlohmann-json3-dev libgmp-dev nasm g++ build-essential 23 | 24 | - name: Setup Circom 25 | run: wget https://github.com/iden3/circom/releases/latest/download/circom-linux-amd64 && sudo mv ./circom-linux-amd64 /usr/bin/circom && sudo chmod +x /usr/bin/circom 26 | 27 | - run: npm ci 28 | 29 | - run: npm run test 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "circom_tester", 3 | "version": "0.0.24", 4 | "description": "Tools for testing circom circuits.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "./node_modules/.bin/mocha -p 'test/*/*.js'" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/iden3/circom_tester.git" 12 | }, 13 | "keywords": [ 14 | "circom", 15 | "test", 16 | "snarkjs", 17 | "iden3" 18 | ], 19 | "author": "Albert Rubio", 20 | "license": "GPL-3.0", 21 | "bugs": { 22 | "url": "https://github.com/iden3/circom_tester/issues" 23 | }, 24 | "homepage": "https://github.com/iden3/circom_tester#readme", 25 | "dependencies": { 26 | "chai": "^4.3.6", 27 | "ffjavascript": "^0.3.1", 28 | "fnv-plus": "^1.3.1", 29 | "r1csfile": "^0.0.48", 30 | "tmp-promise": "^3.0.3", 31 | "util": "^0.12.5", 32 | "snarkjs": "^0.7.5" 33 | }, 34 | "devDependencies": { 35 | "@types/chai": "^4.3.6", 36 | "@types/mocha": "^10.0.1", 37 | "mocha": "^10.1.0", 38 | "circomlib": "^2.0.5" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /wasm/tester.js: -------------------------------------------------------------------------------- 1 | const { BaseTester, parseOptionsAndCompile} = require("../common/tester"); 2 | 3 | const fs = require("fs"); 4 | const path = require("path"); 5 | 6 | module.exports = wasm_tester; 7 | 8 | async function wasm_tester(circomInput, _options) { 9 | let options = Object.assign({}, _options); 10 | options.wasm = true; 11 | options = await parseOptionsAndCompile(circomInput, options); 12 | 13 | const baseName = options.baseName; 14 | 15 | const WitnessCalculator = require("./witness_calculator"); 16 | const wasm = await fs.promises.readFile(path.join(options.output, baseName + "_js/" + baseName + ".wasm")); 17 | const wc = await WitnessCalculator(wasm); 18 | 19 | return new WasmTester(options.output, baseName, wc); 20 | } 21 | 22 | class WasmTester extends BaseTester { 23 | constructor(dir, baseName, witnessCalculator) { 24 | super(dir, baseName); 25 | this.witnessCalculator = witnessCalculator; 26 | } 27 | 28 | async calculateWitness(input, sanityCheck) { 29 | return await this.witnessCalculator.calculateWitness(input, sanityCheck); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | tmp 64 | 65 | .DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # circom tester 2 | ## Setup 3 | 1. Create new node js project. 4 | 2. Install `circom_tester` and `chai` packges. 5 | 3. Install `mocha` packge to run the tests. 6 | 7 | 8 | ## Creating & Running a test file 9 | 10 | Create a js file contain the following code or use the src provided in the following section. 11 |
Execue `mocha -p -r ts-node/register 'multiplier2.js'` to run the test file. 12 | 13 | multiplier2.js ([src](test/multiplier2.js)) 14 | ``` multiplier2.js 15 | const chai = require("chai"); 16 | const path = require("path"); 17 | const wasm_tester = require("./../index").wasm; 18 | const c_tester = require("./../index").c; 19 | 20 | const F1Field = require("ffjavascript").F1Field; 21 | const Scalar = require("ffjavascript").Scalar; 22 | exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); 23 | const Fr = new F1Field(exports.p); 24 | 25 | const assert = chai.assert; 26 | 27 | describe("Simple test", function () { 28 | this.timeout(100000); 29 | 30 | it("Checking the compilation of a simple circuit generating wasm", async function () { 31 | const circuit = await wasm_tester(path.join(__dirname, "Multiplier2circom")); 32 | const w = await circuit.calculateWitness({a: 2, b: 4}); 33 | await circuit.checkConstraints(w); 34 | }); 35 | }); 36 | ``` 37 | -------------------------------------------------------------------------------- /wasm/utils.js: -------------------------------------------------------------------------------- 1 | const fnv = require("fnv-plus"); 2 | 3 | module.exports.fnvHash = fnvHash; 4 | module.exports.toArray32 = toArray32; 5 | module.exports.fromArray32 = fromArray32; 6 | module.exports.flatArray = flatArray; 7 | module.exports.normalize = normalize; 8 | 9 | function toArray32(rem, size) { 10 | const res = []; //new Uint32Array(size); //has no unshift 11 | const radix = BigInt(0x100000000); 12 | while (rem) { 13 | res.unshift(Number(rem % radix)); 14 | rem = rem / radix; 15 | } 16 | if (size) { 17 | var i = size - res.length; 18 | while (i > 0) { 19 | res.unshift(0); 20 | i--; 21 | } 22 | } 23 | return res; 24 | } 25 | 26 | function fromArray32(arr) { //returns a BigInt 27 | var res = BigInt(0); 28 | const radix = BigInt(0x100000000); 29 | for (let i = 0; i < arr.length; i++) { 30 | res = res * radix + BigInt(arr[i]); 31 | } 32 | return res; 33 | } 34 | 35 | function flatArray(a) { 36 | var res = []; 37 | fillArray(res, a); 38 | return res; 39 | 40 | function fillArray(res, a) { 41 | if (Array.isArray(a)) { 42 | for (let i = 0; i < a.length; i++) { 43 | fillArray(res, a[i]); 44 | } 45 | } else { 46 | res.push(a); 47 | } 48 | } 49 | } 50 | 51 | function normalize(n, prime) { 52 | let res = BigInt(n) % prime 53 | if (res < 0) res += prime 54 | return res 55 | } 56 | 57 | function fnvHash(str) { 58 | return fnv.hash(str, 64).hex(); 59 | } 60 | -------------------------------------------------------------------------------- /c/tester.js: -------------------------------------------------------------------------------- 1 | const { BaseTester, parseOptionsAndCompile} = require("../common/tester"); 2 | 3 | const fs = require("fs"); 4 | const path = require("path"); 5 | 6 | const util = require("util"); 7 | const exec = util.promisify(require("child_process").exec); 8 | 9 | const readWtns = require("snarkjs").wtns.exportJson; 10 | 11 | module.exports = c_tester; 12 | 13 | BigInt.prototype.toJSON = function () { 14 | return this.toString() 15 | } 16 | 17 | async function c_tester(circomInput, _options) { 18 | let options = Object.assign({}, _options); 19 | options.c = true; 20 | options = await parseOptionsAndCompile(circomInput, options); 21 | return new CTester(options.output, options.baseName); 22 | } 23 | 24 | class CTester extends BaseTester { 25 | constructor(dir, baseName) { 26 | super(dir, baseName); 27 | } 28 | 29 | async calculateWitness(input) { 30 | const inputjson = JSON.stringify(input); 31 | const inputFile = path.join(this.dir, this.baseName + "_cpp/" + this.baseName + ".json"); 32 | const wtnsFile = path.join(this.dir, this.baseName + "_cpp/" + this.baseName + ".wtns"); 33 | const runc = path.join(this.dir, this.baseName + "_cpp/" + this.baseName); 34 | fs.writeFile(inputFile, inputjson, function (err) { 35 | if (err) throw err; 36 | }); 37 | await exec("cd " + path.join(this.dir, this.baseName + "_cpp/")); 38 | let proc = await exec(runc + " " + inputFile + " " + wtnsFile); 39 | if (proc.stdout !== "") { 40 | console.log(proc.stdout); 41 | } 42 | if (proc.stderr !== "") { 43 | console.error(proc.stderr); 44 | } 45 | return await readBinWitnessFile(wtnsFile); 46 | } 47 | } 48 | 49 | async function readBinWitnessFile(fileName) { 50 | return readWtns(fileName); 51 | } 52 | -------------------------------------------------------------------------------- /test/Arrays/arrays.js: -------------------------------------------------------------------------------- 1 | const chai = require("chai"); 2 | const path = require("path"); 3 | const wasm_tester = require("./../../index").wasm; 4 | const c_tester = require("./../../index").c; 5 | 6 | const F1Field = require("ffjavascript").F1Field; 7 | const Scalar = require("ffjavascript").Scalar; 8 | exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); 9 | const Fr = new F1Field(exports.p); 10 | 11 | const assert = chai.assert; 12 | 13 | const testInput = { 14 | a: [["1", "2"], ["3", "4"]], 15 | commitment: "3330844108758711782672220159612173083623710937399719017074673646455206473965" 16 | }; 17 | 18 | describe("Arrays", function () { 19 | this.timeout(100000); 20 | 21 | it("Checking the compilation of a simple circuit generating wasm", async function () { 22 | 23 | const circuit = await wasm_tester( 24 | path.join(__dirname, "Arrays.circom") 25 | ); 26 | const w = await circuit.calculateWitness(testInput); 27 | 28 | const outputs = await circuit.getOutput(w, {"a": [2, 2], "commitment": 1}); 29 | await circuit.checkConstraints(w); 30 | console.log(outputs); 31 | }); 32 | 33 | it("Checking the compilation of a simple circuit generating wasm in a given folder", async function () { 34 | const circuit = await wasm_tester( 35 | path.join(__dirname, "Arrays.circom"), 36 | { 37 | output: path.join(__dirname, "tmp"), 38 | } 39 | ); 40 | const w = await circuit.calculateWitness(testInput); 41 | await circuit.checkConstraints(w); 42 | }); 43 | 44 | it("Checking the compilation of a simple circuit generating wasm in a given folder without recompiling", async function () { 45 | const circuit = await wasm_tester( 46 | path.join(__dirname, "Arrays.circom"), 47 | { 48 | output: path.join(__dirname, "tmp"), 49 | recompile: false, 50 | } 51 | ); 52 | const w = await circuit.calculateWitness(testInput); 53 | await circuit.checkConstraints(w); 54 | 55 | }); 56 | 57 | it("Checking the compilation of a simple circuit generating C", async function () { 58 | const circuit = await c_tester( 59 | path.join(__dirname, "Arrays.circom") 60 | ); 61 | try { 62 | const w = await circuit.calculateWitness(testInput); 63 | await circuit.checkConstraints(w); 64 | } catch (e) { 65 | if (e.message.includes("Illegal instruction")) { 66 | // GitHub Actions may run on older hardware that doesn't support ADX 67 | // instructions used in cpp witness calculator 68 | // If such a case, skip this test 69 | this.skip(); 70 | } else { 71 | throw e; 72 | } 73 | } 74 | }); 75 | 76 | it("Checking the compilation of a simple circuit generating C in a given folder", async function () { 77 | const circuit = await c_tester( 78 | path.join(__dirname, "Arrays.circom"), 79 | { 80 | output: path.join(__dirname, "tmp"), 81 | } 82 | ); 83 | try { 84 | const w = await circuit.calculateWitness(testInput); 85 | await circuit.checkConstraints(w); 86 | } catch (e) { 87 | if (e.message.includes("Illegal instruction")) { 88 | this.skip(); 89 | } else { 90 | throw e; 91 | } 92 | } 93 | }); 94 | 95 | it("Checking the compilation of a simple circuit generating C in a given folder without recompiling", async function () { 96 | const circuit = await c_tester( 97 | path.join(__dirname, "Arrays.circom"), 98 | { 99 | output: path.join(__dirname, "tmp"), 100 | recompile: false, 101 | } 102 | ); 103 | try { 104 | const w = await circuit.calculateWitness(testInput); 105 | await circuit.checkConstraints(w); 106 | } catch (e) { 107 | if (e.message.includes("Illegal instruction")) { 108 | this.skip(); 109 | } else { 110 | throw e; 111 | } 112 | } 113 | }); 114 | 115 | }); 116 | -------------------------------------------------------------------------------- /test/Multiplier2/multiplier2.js: -------------------------------------------------------------------------------- 1 | const chai = require("chai"); 2 | const path = require("path"); 3 | const wasm_tester = require("./../../index").wasm; 4 | const c_tester = require("./../../index").c; 5 | 6 | const F1Field = require("ffjavascript").F1Field; 7 | const Scalar = require("ffjavascript").Scalar; 8 | exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); 9 | const Fr = new F1Field(exports.p); 10 | 11 | const assert = chai.assert; 12 | 13 | describe("Multiplier2", function () { 14 | this.timeout(100000); 15 | 16 | it("Checking the compilation of a simple circuit generating wasm", async function () { 17 | 18 | const circuit = await wasm_tester( 19 | path.join(__dirname, "Multiplier2.circom") 20 | ); 21 | const w = await circuit.calculateWitness({ 22 | a: "18557398763080563439574185585645102004924653463016315326623530540120602021652", 23 | b: "6905411550336032894518809912132382781376814349417260111983470984156998288047" 24 | }); 25 | await circuit.checkConstraints(w); 26 | const outputs = await circuit.getOutput(w, {"a": 1, "b": 1, "c": 1}); 27 | console.log(outputs); 28 | assert.equal(outputs.c, "17557711783593955402415343928078493368246126305786338715665102716827650933") 29 | }); 30 | 31 | it("Checking the compilation of a simple circuit generating wasm in a given folder", async function () { 32 | const circuit = await wasm_tester( 33 | path.join(__dirname, "Multiplier2.circom"), 34 | { 35 | output: path.join(__dirname, "tmp"), 36 | } 37 | ); 38 | const w = await circuit.calculateWitness({a: 2, b: 4}); 39 | await circuit.checkConstraints(w); 40 | }); 41 | 42 | it("Checking the compilation of a simple circuit generating wasm in a given folder without recompiling", async function () { 43 | const circuit = await wasm_tester( 44 | path.join(__dirname, "Multiplier2.circom"), 45 | { 46 | output: path.join(__dirname, "tmp"), 47 | recompile: false, 48 | } 49 | ); 50 | const w = await circuit.calculateWitness({a: 6, b: 3}); 51 | await circuit.checkConstraints(w); 52 | 53 | }); 54 | 55 | it("Checking the compilation of a simple circuit generating C", async function () { 56 | const circuit = await c_tester( 57 | path.join(__dirname, "Multiplier2.circom") 58 | ); 59 | try { 60 | const w = await circuit.calculateWitness({a: 2, b: 4}); 61 | await circuit.checkConstraints(w); 62 | } catch (e) { 63 | if (e.message.includes("Illegal instruction")) { 64 | // GitHub Actions may run on older hardware that doesn't support ADX 65 | // instructions used in cpp witness calculator 66 | // If such a case, skip this test 67 | this.skip(); 68 | } else { 69 | throw e; 70 | } 71 | } 72 | }); 73 | 74 | it("Checking the compilation of a simple circuit generating C in a given folder", async function () { 75 | const circuit = await c_tester( 76 | path.join(__dirname, "Multiplier2.circom"), 77 | { 78 | output: path.join(__dirname, "tmp"), 79 | } 80 | ); 81 | try { 82 | const w = await circuit.calculateWitness({a: 2, b: 4}); 83 | await circuit.checkConstraints(w); 84 | } catch (e) { 85 | if (e.message.includes("Illegal instruction")) { 86 | this.skip(); 87 | } else { 88 | throw e; 89 | } 90 | } 91 | }); 92 | 93 | it("Checking the compilation of a simple circuit generating C in a given folder without recompiling", async function () { 94 | const circuit = await c_tester( 95 | path.join(__dirname, "Multiplier2.circom"), 96 | { 97 | output: path.join(__dirname, "tmp"), 98 | recompile: false, 99 | } 100 | ); 101 | try { 102 | const w = await circuit.calculateWitness({a: 6, b: 3}); 103 | await circuit.checkConstraints(w); 104 | } catch (e) { 105 | if (e.message.includes("Illegal instruction")) { 106 | this.skip(); 107 | } else { 108 | throw e; 109 | } 110 | } 111 | }); 112 | 113 | }); 114 | -------------------------------------------------------------------------------- /test/Arrays_autogen_main/arrays_autogen_main.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const wasm_tester = require("./../../index").wasm; 3 | const c_tester = require("./../../index").c; 4 | 5 | const testInput = { 6 | a: [["1", "2"], ["3", "4"]], 7 | commitment: "3330844108758711782672220159612173083623710937399719017074673646455206473965" 8 | }; 9 | 10 | describe("Arrays (autogenerated main component)", function () { 11 | this.timeout(100000); 12 | 13 | it("wasm: gen main with template name, params", async function () { 14 | 15 | const circuit = await wasm_tester( 16 | path.join(__dirname, "Arrays.circom"), 17 | { 18 | templateName: "Arrays", 19 | templateParams: [2, 2n], 20 | } 21 | ); 22 | const w = await circuit.calculateWitness(testInput); 23 | 24 | const outputs = await circuit.getOutput(w, {"a": [2, 2], "commitment": 1}); 25 | await circuit.checkConstraints(w); 26 | console.log(outputs); 27 | }); 28 | 29 | it("wasm: gen main with template name, params & public signals", async function () { 30 | 31 | const circuit = await wasm_tester( 32 | path.join(__dirname, "Arrays.circom"), 33 | { 34 | templateName: "Arrays", 35 | templateParams: [2, 2n], 36 | templatePublicSignals: ["a", "commitment"], 37 | } 38 | ); 39 | const w = await circuit.calculateWitness(testInput); 40 | 41 | const outputs = await circuit.getOutput(w, {"a": [2, 2], "commitment": 1}); 42 | await circuit.checkConstraints(w); 43 | console.log(outputs); 44 | }); 45 | 46 | it("wasm: gen main with template name, params & public signals in a given folder", async function () { 47 | const circuit = await wasm_tester( 48 | path.join(__dirname, "Arrays.circom"), 49 | { 50 | output: path.join(__dirname, "tmp"), 51 | templateName: "Arrays", 52 | templateParams: [2, 2n], 53 | templatePublicSignals: ["a", "commitment"], 54 | } 55 | ); 56 | const w = await circuit.calculateWitness(testInput); 57 | await circuit.checkConstraints(w); 58 | }); 59 | 60 | it("wasm: gen main with params, autodetect template name, in a given folder", async function () { 61 | const circuit = await wasm_tester( 62 | path.join(__dirname, "Arrays.circom"), 63 | { 64 | output: path.join(__dirname, "tmp"), 65 | templateParams: [2, 2n], 66 | } 67 | ); 68 | const w = await circuit.calculateWitness(testInput); 69 | await circuit.checkConstraints(w); 70 | }); 71 | 72 | it("wasm: gen main with params and public signals, autodetect template name, in a given folder", async function () { 73 | const circuit = await wasm_tester( 74 | path.join(__dirname, "Arrays.circom"), 75 | { 76 | output: path.join(__dirname, "tmp"), 77 | templateParams: [2, 2n], 78 | } 79 | ); 80 | const w = await circuit.calculateWitness(testInput); 81 | await circuit.checkConstraints(w); 82 | }); 83 | 84 | it("wasm: gen main with params & public signals, autodetect template name, in a given folder without recompiling", async function () { 85 | const circuit = await wasm_tester( 86 | path.join(__dirname, "Arrays.circom"), 87 | { 88 | output: path.join(__dirname, "tmp"), 89 | recompile: false, 90 | templateParams: [2, 2], 91 | } 92 | ); 93 | const w = await circuit.calculateWitness(testInput); 94 | await circuit.checkConstraints(w); 95 | 96 | }); 97 | 98 | it("c: gen main with params, autodetect template name", async function () { 99 | const circuit = await c_tester( 100 | path.join(__dirname, "Arrays.circom"), 101 | { 102 | templateParams: [2, 2], 103 | } 104 | ); 105 | try { 106 | const w = await circuit.calculateWitness(testInput); 107 | await circuit.checkConstraints(w); 108 | } catch (e) { 109 | if (e.message.includes("Illegal instruction")) { 110 | // GitHub Actions may run on older hardware that doesn't support ADX 111 | // instructions used in cpp witness calculator 112 | // If such a case, skip this test 113 | this.skip(); 114 | } else { 115 | throw e; 116 | } 117 | } 118 | }); 119 | 120 | it("c: gen main with params, autodetect template name, in a given folder", async function () { 121 | const circuit = await c_tester( 122 | path.join(__dirname, "Arrays.circom"), 123 | { 124 | output: path.join(__dirname, "tmp"), 125 | templateParams: [2, 2], 126 | } 127 | ); 128 | try { 129 | const w = await circuit.calculateWitness(testInput); 130 | await circuit.checkConstraints(w); 131 | } catch (e) { 132 | if (e.message.includes("Illegal instruction")) { 133 | this.skip(); 134 | } else { 135 | throw e; 136 | } 137 | } 138 | }); 139 | 140 | it("c: gen main with params, autodetect template name, in a given folder without recompiling", async function () { 141 | const circuit = await c_tester( 142 | path.join(__dirname, "Arrays.circom"), 143 | { 144 | output: path.join(__dirname, "tmp"), 145 | recompile: false, 146 | templateParams: [2, 2], 147 | } 148 | ); 149 | try { 150 | const w = await circuit.calculateWitness(testInput); 151 | await circuit.checkConstraints(w); 152 | } catch (e) { 153 | if (e.message.includes("Illegal instruction")) { 154 | this.skip(); 155 | } else { 156 | throw e; 157 | } 158 | } 159 | }); 160 | 161 | }); 162 | -------------------------------------------------------------------------------- /wasm/witness_calculator.js: -------------------------------------------------------------------------------- 1 | const utils = require("./utils"); 2 | 3 | module.exports = async function builder(code, options) { 4 | 5 | options = options || {}; 6 | 7 | let wasmModule; 8 | try { 9 | wasmModule = await WebAssembly.compile(code); 10 | } catch (err) { 11 | console.log(err); 12 | console.log("\nTry to run circom --c in order to generate c++ code instead\n"); 13 | throw new Error(err); 14 | } 15 | 16 | let wc; 17 | 18 | let errStr = ""; 19 | let msgStr = ""; 20 | 21 | const instance = await WebAssembly.instantiate(wasmModule, { 22 | runtime: { 23 | exceptionHandler: function (code) { 24 | let err; 25 | if (code === 1) { 26 | err = "Signal not found.\n"; 27 | } else if (code === 2) { 28 | err = "Too many signals set.\n"; 29 | } else if (code === 3) { 30 | err = "Signal already set.\n"; 31 | } else if (code === 4) { 32 | err = "Assert Failed.\n"; 33 | } else if (code === 5) { 34 | err = "Not enough memory.\n"; 35 | } else if (code === 6) { 36 | err = "Input signal array access exceeds the size.\n"; 37 | } else { 38 | err = "Unknown error.\n"; 39 | } 40 | throw new Error(err + errStr); 41 | }, 42 | printErrorMessage: function () { 43 | errStr += getMessage() + "\n"; 44 | // console.error(getMessage()); 45 | }, 46 | writeBufferMessage: function () { 47 | const msg = getMessage(); 48 | // Any calls to `log()` will always end with a `\n`, so that's when we print and reset 49 | if (msg === "\n") { 50 | console.log(msgStr); 51 | msgStr = ""; 52 | } else { 53 | // If we've buffered other content, put a space in between the items 54 | if (msgStr !== "") { 55 | msgStr += " " 56 | } 57 | // Then append the message to the message we are creating 58 | msgStr += msg; 59 | } 60 | }, 61 | showSharedRWMemory: function () { 62 | printSharedRWMemory(); 63 | } 64 | 65 | } 66 | }); 67 | 68 | const sanityCheck = 69 | options 70 | // options && 71 | // ( 72 | // options.sanityCheck || 73 | // options.logGetSignal || 74 | // options.logSetSignal || 75 | // options.logStartComponent || 76 | // options.logFinishComponent 77 | // ); 78 | 79 | 80 | wc = new WitnessCalculator(instance, sanityCheck); 81 | return wc; 82 | 83 | function getMessage() { 84 | let message = ""; 85 | let c = instance.exports.getMessageChar(); 86 | while (c != 0) { 87 | message += String.fromCharCode(c); 88 | c = instance.exports.getMessageChar(); 89 | } 90 | return message; 91 | } 92 | 93 | function printSharedRWMemory() { 94 | const shared_rw_memory_size = instance.exports.getFieldNumLen32(); 95 | const arr = new Uint32Array(shared_rw_memory_size); 96 | for (let j = 0; j < shared_rw_memory_size; j++) { 97 | arr[shared_rw_memory_size - 1 - j] = instance.exports.readSharedRWMemory(j); 98 | } 99 | 100 | // If we've buffered other content, put a space in between the items 101 | if (msgStr !== "") { 102 | msgStr += " " 103 | } 104 | // Then append the value to the message we are creating 105 | msgStr += (utils.fromArray32(arr).toString()); 106 | } 107 | 108 | }; 109 | 110 | class WitnessCalculator { 111 | constructor(instance, sanityCheck) { 112 | this.instance = instance; 113 | 114 | this.version = this.instance.exports.getVersion(); 115 | this.n32 = this.instance.exports.getFieldNumLen32(); 116 | 117 | this.instance.exports.getRawPrime(); 118 | const arr = new Uint32Array(this.n32); 119 | for (let i = 0; i < this.n32; i++) { 120 | arr[this.n32 - 1 - i] = this.instance.exports.readSharedRWMemory(i); 121 | } 122 | this.prime = utils.fromArray32(arr); 123 | 124 | this.witnessSize = this.instance.exports.getWitnessSize(); 125 | 126 | this.sanityCheck = sanityCheck; 127 | } 128 | 129 | circom_version() { 130 | return this.instance.exports.getVersion(); 131 | } 132 | 133 | async _doCalculateWitness(input, sanityCheck) { 134 | //input is assumed to be a map from signals to arrays of bigints 135 | this.instance.exports.init((this.sanityCheck || sanityCheck) ? 1 : 0); 136 | const keys = Object.keys(input); 137 | let input_counter = 0; 138 | keys.forEach((k) => { 139 | const h = utils.fnvHash(k); 140 | const hMSB = parseInt(h.slice(0, 8), 16); 141 | const hLSB = parseInt(h.slice(8, 16), 16); 142 | const fArr = utils.flatArray(input[k]); 143 | let signalSize = this.instance.exports.getInputSignalSize(hMSB, hLSB); 144 | if (signalSize < 0) { 145 | throw new Error(`Signal ${k} not found\n`); 146 | } 147 | if (fArr.length < signalSize) { 148 | throw new Error(`Not enough values for input signal ${k}\n`); 149 | } 150 | if (fArr.length > signalSize) { 151 | throw new Error(`Too many values for input signal ${k}\n`); 152 | } 153 | for (let i = 0; i < fArr.length; i++) { 154 | const arrFr = utils.toArray32(utils.normalize(fArr[i], this.prime), this.n32) 155 | for (let j = 0; j < this.n32; j++) { 156 | this.instance.exports.writeSharedRWMemory(j, arrFr[this.n32 - 1 - j]); 157 | } 158 | try { 159 | this.instance.exports.setInputSignal(hMSB, hLSB, i); 160 | input_counter++; 161 | } catch (err) { 162 | // console.log(`After adding signal ${i} of ${k}`) 163 | throw new Error(err); 164 | } 165 | } 166 | 167 | }); 168 | if (input_counter < this.instance.exports.getInputSize()) { 169 | throw new Error(`Not all inputs have been set. Only ${input_counter} out of ${this.instance.exports.getInputSize()}`); 170 | } 171 | } 172 | 173 | async calculateWitness(input, sanityCheck) { 174 | 175 | const w = []; 176 | 177 | await this._doCalculateWitness(input, sanityCheck); 178 | 179 | for (let i = 0; i < this.witnessSize; i++) { 180 | this.instance.exports.getWitness(i); 181 | const arr = new Uint32Array(this.n32); 182 | for (let j = 0; j < this.n32; j++) { 183 | arr[this.n32 - 1 - j] = this.instance.exports.readSharedRWMemory(j); 184 | } 185 | w.push(utils.fromArray32(arr)); 186 | } 187 | 188 | return w; 189 | } 190 | 191 | 192 | async calculateBinWitness(input, sanityCheck) { 193 | 194 | const buff32 = new Uint32Array(this.witnessSize * this.n32); 195 | const buff = new Uint8Array(buff32.buffer); 196 | await this._doCalculateWitness(input, sanityCheck); 197 | 198 | for (let i = 0; i < this.witnessSize; i++) { 199 | this.instance.exports.getWitness(i); 200 | const pos = i * this.n32; 201 | for (let j = 0; j < this.n32; j++) { 202 | buff32[pos + j] = this.instance.exports.readSharedRWMemory(j); 203 | } 204 | } 205 | 206 | return buff; 207 | } 208 | 209 | 210 | async calculateWTNSBin(input, sanityCheck) { 211 | 212 | const buff32 = new Uint32Array(this.witnessSize * this.n32 + this.n32 + 11); 213 | const buff = new Uint8Array(buff32.buffer); 214 | await this._doCalculateWitness(input, sanityCheck); 215 | 216 | //"wtns" 217 | buff[0] = "w".charCodeAt(0) 218 | buff[1] = "t".charCodeAt(0) 219 | buff[2] = "n".charCodeAt(0) 220 | buff[3] = "s".charCodeAt(0) 221 | 222 | //version 2 223 | buff32[1] = 2; 224 | 225 | //number of sections: 2 226 | buff32[2] = 2; 227 | 228 | //id section 1 229 | buff32[3] = 1; 230 | 231 | const n8 = this.n32 * 4; 232 | //id section 1 length in 64bytes 233 | const idSection1length = 8 + n8; 234 | const idSection1lengthHex = idSection1length.toString(16); 235 | buff32[4] = parseInt(idSection1lengthHex.slice(0, 8), 16); 236 | buff32[5] = parseInt(idSection1lengthHex.slice(8, 16), 16); 237 | 238 | //this.n32 239 | buff32[6] = n8; 240 | 241 | //prime number 242 | this.instance.exports.getRawPrime(); 243 | 244 | let pos = 7; 245 | for (let j = 0; j < this.n32; j++) { 246 | buff32[pos + j] = this.instance.exports.readSharedRWMemory(j); 247 | } 248 | pos += this.n32; 249 | 250 | // witness size 251 | buff32[pos] = this.witnessSize; 252 | pos++; 253 | 254 | //id section 2 255 | buff32[pos] = 2; 256 | pos++; 257 | 258 | // section 2 length 259 | const idSection2length = n8 * this.witnessSize; 260 | const idSection2lengthHex = idSection2length.toString(16); 261 | buff32[pos] = parseInt(idSection2lengthHex.slice(0, 8), 16); 262 | buff32[pos + 1] = parseInt(idSection2lengthHex.slice(8, 16), 16); 263 | 264 | pos += 2; 265 | for (let i = 0; i < this.witnessSize; i++) { 266 | this.instance.exports.getWitness(i); 267 | for (let j = 0; j < this.n32; j++) { 268 | buff32[pos + j] = this.instance.exports.readSharedRWMemory(j); 269 | } 270 | pos += this.n32; 271 | } 272 | 273 | return buff; 274 | } 275 | 276 | } 277 | 278 | 279 | 280 | -------------------------------------------------------------------------------- /common/tester.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | const path = require("path"); 3 | const { F1Field } = require("ffjavascript"); 4 | const { readR1cs } = require("r1csfile"); 5 | const util = require("util"); 6 | const tmp = require("tmp-promise"); 7 | const { createHash } = require('crypto'); 8 | const exec = util.promisify(require("child_process").exec); 9 | 10 | async function parseOptionsAndCompile(circomInput, options) { 11 | const compilerVersion = await compiler_above_version("2.0.0"); 12 | if (!compilerVersion) { 13 | throw new Error("Wrong compiler version. Must be at least 2.0.0"); 14 | } 15 | 16 | let baseName = path.basename(circomInput, ".circom"); 17 | 18 | options.sym = true; 19 | options.baseName = baseName; 20 | options.json = options.json || false; // constraints in json format 21 | options.r1cs = true; 22 | options.compile = (typeof options.recompile === 'undefined') ? true : options.recompile; // by default compile 23 | 24 | // if output is not set, create a temporary directory 25 | if (typeof options.output === 'undefined') { 26 | tmp.setGracefulCleanup(); 27 | const dir = await tmp.dir({prefix: "circom_", unsafeCleanup: true}); 28 | options.output = dir.path; 29 | } else { 30 | try { 31 | await fs.promises.access(options.output); 32 | } catch (err) { 33 | if (!options.compile) { 34 | throw new Error("Cannot set recompile to false if the output path does not exist"); 35 | } 36 | await fs.promises.mkdir(options.output, {recursive: true}); 37 | } 38 | } 39 | 40 | // read contents of circomInput 41 | const circomCode = await fs.promises.readFile(circomInput, "utf8"); 42 | 43 | // check if circomCode has main component instantiated 44 | const mainRegex = /^\s*component\s+main[\s={\/]/m; 45 | const mainDefined = mainRegex.test(circomCode); 46 | 47 | // if main is not defined, get all template names 48 | const templateNames = []; 49 | const pragmaLines = []; 50 | if (!mainDefined) { 51 | // get all pragma lines to put in temporary circom file 52 | const pragmaRegex = /^\s*pragma\s+.*$/gm; 53 | let pragmaMatches; 54 | while ((pragmaMatches = pragmaRegex.exec(circomCode)) !== null) { 55 | pragmaLines.push(pragmaMatches[0]); 56 | } 57 | 58 | // get all template names 59 | const templateRegex = /^\s*template\s+([a-zA-Z0-9_$]+)\s*\(/gm; 60 | let templateMatches; 61 | while ((templateMatches = templateRegex.exec(circomCode)) !== null) { 62 | templateNames.push(templateMatches[1]); 63 | } 64 | } 65 | 66 | // check for conflicting options 67 | if (mainDefined) { 68 | if (options.templateName || options.templateParams || options.templatePublicSignals) { 69 | throw new Error("Cannot set template name, params and public signals if main is already defined"); 70 | } 71 | } 72 | 73 | // when main is not defined, create temporary circom file using specified template as a main component 74 | if (!mainDefined) { 75 | // if templateName is not provided, try to autodetect it 76 | if (!options.templateName) { 77 | // if file has only one template, use it as main component 78 | if (templateNames.length === 1) { 79 | options.templateName = templateNames[0]; 80 | } else { 81 | throw new Error("No main component defined and template name to generate one is not provided"); 82 | } 83 | } 84 | 85 | // define main component with templateName 86 | let params = ""; 87 | if (options.templateParams) { 88 | params = options.templateParams.map((p) => p.toString()).join(", "); 89 | } 90 | 91 | // define public signals if any 92 | let publicSignals = ""; 93 | if (options.templatePublicSignals) { 94 | publicSignals = "{public [" + options.templatePublicSignals.map((p) => p.toString()).join(", ") + "]}"; 95 | } 96 | 97 | // define main component 98 | const mainComponent = `component main ${publicSignals} = ${options.templateName}(${params});`; 99 | 100 | // include original circom file 101 | const includes = "include \"" + baseName + ".circom\";"; 102 | 103 | const tmpCircomCodeLines = [...pragmaLines, includes, mainComponent]; 104 | const tmpCircomCode = tmpCircomCodeLines.join("\n"); 105 | 106 | // calculate the hash of the main component using sha256 107 | const h = createHash("sha256"); 108 | const hash = h.update(Buffer.from(tmpCircomCode, "utf8")).digest('hex'); 109 | // and use it as a suffix for the temporary directory name inside the output path 110 | let suffix = hash.substring(0, 8); 111 | const tmpCircomPath = path.join(options.output, baseName + "_" + options.templateName + "_" + suffix); 112 | 113 | // create the directory if it doesn't exist 114 | await fs.promises.mkdir(tmpCircomPath, {recursive: true}); 115 | 116 | // add the original circom file directory to the include path 117 | const includePath = path.dirname(path.resolve(circomInput)); 118 | if (options.include) { 119 | if (Array.isArray(options.include)) { 120 | options.include.push(includePath); 121 | } else { 122 | options.include = [options.include, includePath]; 123 | } 124 | } else { 125 | options.include = [includePath]; 126 | } 127 | 128 | // override baseName, output path and circomInput 129 | baseName = "circuit"; 130 | options.baseName = baseName; 131 | options.output = tmpCircomPath; 132 | circomInput = path.join(tmpCircomPath, baseName + ".circom"); 133 | 134 | // write the generated circom code to the temporary file circuit.circom 135 | await fs.promises.writeFile(circomInput, tmpCircomCode, "utf8"); 136 | 137 | } 138 | 139 | // compile flag is set by default, unless overwritten by recompile=false option 140 | if (options.compile) { 141 | await compile(baseName, circomInput, options); 142 | } else { 143 | const jsPath = path.join(options.output, baseName + "_js"); 144 | try { 145 | await fs.promises.access(jsPath); 146 | } catch (err) { 147 | throw new Error("Cannot set recompile to false if the " + jsPath + " folder does not exist") 148 | } 149 | } 150 | 151 | return options; 152 | } 153 | 154 | async function compile(baseName, fileName, options) { 155 | let flags = ""; 156 | if (options.include) { 157 | if (Array.isArray(options.include)) { 158 | for (let i = 0; i < options.include.length; i++) { 159 | flags += "-l " + options.include[i] + " "; 160 | } 161 | } else { 162 | flags += "-l " + options.include + " "; 163 | } 164 | } 165 | if (options.c) flags += "--c "; 166 | if (options.wasm) flags += "--wasm "; 167 | if (options.sym) flags += "--sym "; 168 | if (options.r1cs) flags += "--r1cs "; 169 | if (options.json) flags += "--json "; 170 | if (options.output) flags += "--output " + options.output + " "; 171 | if (options.prime) flags += "--prime " + options.prime + " "; 172 | if (options.O === 0) flags += "--O0 "; 173 | if (options.O === 1) flags += "--O1 "; 174 | if (options.O === 2) flags += "--O2 "; 175 | if (options.O2round) flags += "--O2round " + options.O2round + " "; 176 | if (options.verbose) flags += "--verbose "; 177 | if (options.inspect) flags += "--inspect "; 178 | if (options.simplification_substitution) flags += "--simplification_substitution "; 179 | if (options.no_asm) flags += "--no_asm "; 180 | if (options.no_init) flags += "--no_init "; 181 | 182 | try { 183 | let b = await exec("circom " + flags + fileName); 184 | if (options.verbose) { 185 | console.log(b.stdout); 186 | } 187 | if (b.stderr) { 188 | console.error(b.stderr); 189 | } 190 | } catch (e) { 191 | throw new Error("circom compiler error: " + e); 192 | } 193 | 194 | if (options.c) { 195 | const c_folder = path.join(options.output, baseName + "_cpp/") 196 | let b = await exec("make -C " + c_folder); 197 | if (b.stderr) { 198 | console.error(b.stderr); 199 | } 200 | } 201 | } 202 | 203 | 204 | class BaseTester { 205 | constructor(dir, baseName) { 206 | this.dir = dir; 207 | this.baseName = baseName; 208 | } 209 | 210 | async release() { 211 | await this.dir.cleanup(); 212 | } 213 | 214 | async loadSymbols() { 215 | if (this.symbols) return; 216 | this.symbols = {}; 217 | const symsStr = await fs.promises.readFile( 218 | path.join(this.dir, this.baseName + ".sym"), 219 | "utf8" 220 | ); 221 | const lines = symsStr.split("\n"); 222 | for (let i = 0; i < lines.length; i++) { 223 | const arr = lines[i].split(","); 224 | if (arr.length !== 4) continue; 225 | this.symbols[arr[3]] = { 226 | labelIdx: Number(arr[0]), 227 | varIdx: Number(arr[1]), 228 | componentIdx: Number(arr[2]), 229 | }; 230 | } 231 | } 232 | 233 | async loadConstraints() { 234 | const self = this; 235 | if (this.constraints) return; 236 | const r1cs = await readR1cs(path.join(this.dir, this.baseName + ".r1cs"), { 237 | loadConstraints: true, 238 | loadMap: false, 239 | getFieldFromPrime: (p, singlethread) => new F1Field(p) 240 | }); 241 | self.F = r1cs.F; 242 | self.nVars = r1cs.nVars; 243 | self.constraints = r1cs.constraints; 244 | } 245 | 246 | async assertOut(actualOut, expectedOut) { 247 | const self = this; 248 | if (!self.symbols) await self.loadSymbols(); 249 | 250 | checkObject("main", expectedOut); 251 | 252 | function checkObject(prefix, eOut) { 253 | 254 | if (Array.isArray(eOut)) { 255 | for (let i = 0; i < eOut.length; i++) { 256 | checkObject(prefix + "[" + i + "]", eOut[i]); 257 | } 258 | } else if (typeof eOut === "object" && eOut.constructor.name === "Object") { 259 | for (let k in eOut) { 260 | checkObject(prefix + "." + k, eOut[k]); 261 | } 262 | } else { 263 | if (typeof self.symbols[prefix] === "undefined") { 264 | throw new Error("Output variable not defined: " + prefix); 265 | } 266 | const ba = actualOut[self.symbols[prefix].varIdx].toString(); 267 | const be = eOut.toString(); 268 | if (ba !== be) { 269 | throw new Error(`Assertion failed for ${prefix}: expected ${be}, got ${ba}`); 270 | } 271 | } 272 | } 273 | } 274 | 275 | async getDecoratedOutput(witness) { 276 | const self = this; 277 | const lines = []; 278 | if (!self.symbols) await self.loadSymbols(); 279 | for (let n in self.symbols) { 280 | let v; 281 | if (witness[self.symbols[n].varIdx] !== undefined) { 282 | v = witness[self.symbols[n].varIdx].toString(); 283 | } else { 284 | v = "undefined"; 285 | } 286 | lines.push(`${n} --> ${v}`); 287 | } 288 | return lines.join("\n"); 289 | } 290 | 291 | async getOutput(witness, output, templateName = "main") { 292 | const self = this; 293 | if (!self.symbols) await self.loadSymbols(); 294 | 295 | let prefix = "main"; 296 | if (templateName !== "main") { 297 | const regex = new RegExp(`^.*${templateName}[^.]*\.[^.]+$`); 298 | Object.keys(self.symbols).find((k) => { 299 | if (regex.test(k)) { 300 | prefix = k.replace(/\.[^.]+$/, ""); 301 | return true; 302 | } 303 | }); 304 | } 305 | 306 | return get_by_prefix(prefix, output); 307 | 308 | function get_by_prefix(prefix, out) { 309 | if (typeof out === "object" && out.constructor.name === "Object") { 310 | return Object.fromEntries( 311 | Object.entries(out).map(([k, v]) => [ 312 | k, 313 | get_by_prefix(`${prefix}.${k}`, v), 314 | ]) 315 | ); 316 | } else if (Array.isArray(out)) { 317 | if (out.length === 1) { 318 | return get_by_prefix(prefix, out[0]); 319 | } else if (out.length === 0 || out.length > 2) { 320 | throw new Error(`Invalid output format: ${prefix} ${out}`); 321 | } 322 | 323 | return Array.from({ length: out[0] }, (_, i) => 324 | get_by_prefix(`${prefix}[${i}]`, out[1]) 325 | ); 326 | } else { 327 | if (out === 1) { 328 | const name = `${prefix}`; 329 | if (typeof self.symbols[name] == "undefined") { 330 | throw new Error(`Output variable not defined: ${name}`); 331 | } 332 | return witness[self.symbols[name].varIdx]; 333 | } else { 334 | return Array.from({ length: out }, (_, i) => { 335 | const name = `${prefix}[${i}]`; 336 | if (typeof self.symbols[name] == "undefined") { 337 | throw new Error(`Output variable not defined: ${name}`); 338 | } 339 | return witness[self.symbols[name].varIdx]; 340 | }); 341 | } 342 | } 343 | } 344 | } 345 | 346 | async checkConstraints(witness) { 347 | const self = this; 348 | if (!self.constraints) await self.loadConstraints(); 349 | const F = self.F; 350 | for (let i = 0; i < self.constraints.length; i++) { 351 | const constraint = self.constraints[i]; 352 | const a = evalLC(constraint[0]); 353 | const b = evalLC(constraint[1]); 354 | const c = evalLC(constraint[2]); 355 | if (!F.isZero(F.sub(F.mul(a, b), c))) { 356 | throw new Error("Constraint doesn't match"); 357 | } 358 | } 359 | 360 | function evalLC(lc) { 361 | const F = self.F; 362 | let v = F.zero; 363 | for (let w in lc) { 364 | v = F.add( 365 | v, 366 | F.mul(lc[w], F.e(witness[w])) 367 | ); 368 | } 369 | return v; 370 | } 371 | } 372 | 373 | } 374 | 375 | function version_to_list(v) { 376 | return v.split(".").map((x) => parseInt(x, 10)); 377 | } 378 | 379 | function check_versions(v1, v2) { 380 | //check if v1 is newer than or equal to v2 381 | for (let i = 0; i < v2.length; i++) { 382 | if (v1[i] > v2[i]) return true; 383 | if (v1[i] < v2[i]) return false; 384 | } 385 | return true; 386 | } 387 | 388 | async function compiler_above_version(v) { 389 | const output = (await exec("circom --version")).stdout; 390 | const compiler_version = version_to_list(output.slice(output.search(/\d/), -1)); 391 | const vlist = version_to_list(v); 392 | return check_versions(compiler_version, vlist); 393 | } 394 | 395 | module.exports = { BaseTester, version_to_list, check_versions, compile, compiler_above_version, parseOptionsAndCompile }; --------------------------------------------------------------------------------