arnaucube
arnaucube/circom_testerPublic Self-hosted repository
circom_tester/wasm/tester.js
wasm/tester.jsRaw
  1const chai = require("chai");
  2const assert = chai.assert;
  3
  4const fs = require("fs");
  5var tmp = require("tmp-promise");
  6const path = require("path");
  7
  8const util = require("util");
  9const exec = util.promisify(require("child_process").exec);
 10
 11const loadR1cs = require("r1csfile").load;
 12const ZqField = require("ffjavascript").ZqField;
 13
 14module.exports = wasm_tester;
 15
 16async function  wasm_tester(circomInput, _options) {
 17
 18    assert(await compiler_above_version("2.0.0"),"Wrong compiler version. Must be at least 2.0.0");
 19    
 20    tmp.setGracefulCleanup();
 21
 22    const dir = await tmp.dir({prefix: "circom_", unsafeCleanup: true });
 23
 24    //console.log(dir.path);
 25
 26    const baseName = path.basename(circomInput, ".circom");
 27    const options = Object.assign({}, _options);
 28
 29    options.wasm = true;
 30
 31    options.sym = true;
 32    options.json = options.json || false; // costraints in json format
 33    options.r1cs = true;
 34    options.output = dir.path;
 35
 36    await compile(circomInput, options);
 37
 38    const utils = require("./utils");
 39    const WitnessCalculator = require("./witness_calculator");
 40
 41    const wasm = await fs.promises.readFile(path.join(dir.path, baseName+"_js/"+ baseName + ".wasm"));
 42
 43    const wc = await WitnessCalculator(wasm);
 44
 45    return new WasmTester(dir, baseName, wc);
 46}
 47
 48async function compile (fileName, options) {    
 49    var flags = "--wasm ";
 50    if (options.sym) flags += "--sym ";
 51    if (options.r1cs) flags += "--r1cs ";
 52    if (options.json) flags += "--json ";
 53    if (options.output) flags += "--output " + options.output + " ";
 54    
 55    b = await exec("circom " + flags + fileName);
 56    assert(b.stderr == "",
 57	  "circom compiler error \n" + b.stderr);
 58}
 59    
 60class WasmTester {
 61
 62    constructor(dir, baseName, witnessCalculator) {
 63        this.dir=dir;
 64        this.baseName = baseName;
 65        this.witnessCalculator = witnessCalculator;
 66    }
 67
 68    async release() {
 69        await this.dir.cleanup();
 70    }
 71
 72    async calculateWitness(input, sanityCheck) {
 73        return await this.witnessCalculator.calculateWitness(input, sanityCheck);
 74    }
 75
 76    async loadSymbols() {
 77        if (this.symbols) return;
 78        this.symbols = {};
 79        const symsStr = await fs.promises.readFile(
 80            path.join(this.dir.path, this.baseName + ".sym"),
 81            "utf8"
 82        );
 83        const lines = symsStr.split("\n");
 84        for (let i=0; i<lines.length; i++) {
 85            const arr = lines[i].split(",");
 86            if (arr.length!=4) continue;
 87            this.symbols[arr[3]] = {
 88                labelIdx: Number(arr[0]),
 89                varIdx: Number(arr[1]),
 90                componentIdx: Number(arr[2]),
 91            };
 92        }
 93    }
 94
 95    async loadConstraints() {
 96        const self = this;
 97        if (this.constraints) return;
 98        const r1cs = await loadR1cs(path.join(this.dir.path, this.baseName + ".r1cs"),true, false);
 99        self.F = new ZqField(r1cs.prime);
100        self.nVars = r1cs.nVars;
101        self.constraints = r1cs.constraints;
102    }
103
104    async assertOut(actualOut, expectedOut) {
105        const self = this;
106        if (!self.symbols) await self.loadSymbols();
107
108        checkObject("main", expectedOut);
109
110        function checkObject(prefix, eOut) {
111
112            if (Array.isArray(eOut)) {
113                for (let i=0; i<eOut.length; i++) {
114                    checkObject(prefix + "["+i+"]", eOut[i]);
115                }
116            } else if ((typeof eOut == "object")&&(eOut.constructor.name == "Object")) {
117                for (let k in eOut) {
118                    checkObject(prefix + "."+k, eOut[k]);
119                }
120            } else {
121                if (typeof self.symbols[prefix] == "undefined") {
122                    assert(false, "Output variable not defined: "+ prefix);
123                }
124                const ba = actualOut[self.symbols[prefix].varIdx].toString();
125                const be = eOut.toString();
126                assert.strictEqual(ba, be, prefix);
127            }
128        }
129    }
130
131    async getDecoratedOutput(witness) {
132        const self = this;
133        const lines = [];
134        if (!self.symbols) await self.loadSymbols();
135        for (let n in self.symbols) {
136            let v;
137            if (utils.isDefined(witness[self.symbols[n].varIdx])) {
138                v = witness[self.symbols[n].varIdx].toString();
139            } else {
140                v = "undefined";
141            }
142            lines.push(`${n} --> ${v}`);
143        }
144        return lines.join("\n");
145    }
146
147    async checkConstraints(witness) {
148        const self = this;
149        if (!self.constraints) await self.loadConstraints();
150        for (let i=0; i<self.constraints.length; i++) {
151            checkConstraint(self.constraints[i]);
152        }
153
154        function checkConstraint(constraint) {
155	    
156            const F = self.F;
157            const a = evalLC(constraint[0]);
158            const b = evalLC(constraint[1]);
159            const c = evalLC(constraint[2]);
160            assert (F.isZero(F.sub(F.mul(a,b), c)), "Constraint doesn't match");
161        }
162
163        function evalLC(lc) {
164            const F = self.F;
165            let v = F.zero;
166            for (let w in lc) {
167                v = F.add(
168                    v,
169                    F.mul( lc[w], witness[w] )
170                );
171            }
172            return v;
173        }
174    }
175
176}
177
178function version_to_list ( v ) {
179    return v.split(".").map(function(x) {
180	return parseInt(x, 10);
181    });
182}
183
184function check_versions ( v1, v2 ) {
185    //check if v1 is newer than or equal to v2
186    for (let i = 0; i < v2.length; i++) {
187	if (v1[i] > v2[i]) return true;
188	if (v1[i] < v2[i]) return false;
189    }
190    return true;
191}
192
193async function compiler_above_version(v) {
194    let output = await exec('circom --version').toString();
195    let compiler_version = version_to_list(output.slice(output.search(/\d/),-1));
196    vlist = version_to_list(v);
197    return check_versions ( compiler_version, vlist );
198}
199