arnaucube
arnaucube/circom_testerPublic Self-hosted repository
circom_tester/c/tester.js
c/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 = c_tester;
 15
 16async function  c_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 = options.r1cs || false; // costraints in r1cs format
 34    //if (!options.json) options.r1cs = true; // r1cs if not json
 35    options.r1cs = true;
 36    options.output = dir.path;
 37
 38    await compile(baseName, circomInput, options);
 39
 40    return new WasmTester(dir, baseName, run);
 41}
 42
 43async function compile (baseName, fileName, options) {    
 44    var flags = "--c ";
 45    if (options.sym) flags += "--sym ";
 46    if (options.r1cs) flags += "--r1cs ";
 47    if (options.json) flags += "--json ";
 48    if (options.output) flags += "--output " + options.output + " ";
 49    if (options.O === 0) flags += "--O0 "
 50    if (options.O === 1) flags += "--O1 "
 51
 52    b = await exec("circom " + flags + fileName); 
 53    assert(b.stderr == "",
 54	   "circom compiler error \n" + b.stderr);
 55    
 56    const c_folder = path.join(options.output, baseName+"_cpp/")
 57    b = await exec("make -C "+c_folder);
 58    assert(b.stderr == "",
 59	   "error building the executable C program\n" + b.stderr);
 60}
 61    
 62class WasmTester {
 63
 64    constructor(dir, baseName, witnessCalculator) {
 65        this.dir=dir;
 66        this.baseName = baseName;
 67        this.witnessCalculator = witnessCalculator;
 68    }
 69
 70    async release() {
 71        await this.dir.cleanup();
 72    }
 73
 74    async calculateWitness(input) {
 75	const inputjson = JSON.stringify(input);
 76	const inputFile = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName + ".json");
 77	const wtnsFile = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName + ".wtns");
 78	const runc = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName);	
 79        fs.writeFile(inputFile, inputjson, function(err) {
 80	    if (err) throw err;
 81	});
 82	await exec("ls " + path.join(this.dir.path, this.baseName+"_cpp/"));
 83	await exec(runc + " " + inputFile + " " + wtnsFile);
 84	return readBinaryFile(wtnsFile);
 85    }
 86
 87    async loadSymbols() {
 88        if (this.symbols) return;
 89        this.symbols = {};
 90        const symsStr = await fs.promises.readFile(
 91            path.join(this.dir.path, this.baseName + ".sym"),
 92            "utf8"
 93        );
 94        const lines = symsStr.split("\n");
 95        for (let i=0; i<lines.length; i++) {
 96            const arr = lines[i].split(",");
 97            if (arr.length!=4) continue;
 98            this.symbols[arr[3]] = {
 99                labelIdx: Number(arr[0]),
100                varIdx: Number(arr[1]),
101                componentIdx: Number(arr[2]),
102            };
103        }
104    }
105
106    async loadConstraints() {
107        const self = this;
108        if (this.constraints) return;
109        const r1cs = await loadR1cs(path.join(this.dir.path, this.baseName + ".r1cs"),true, false);
110        self.F = new ZqField(r1cs.prime);
111        self.nVars = r1cs.nVars;
112        self.constraints = r1cs.constraints;
113    }
114
115    async assertOut(actualOut, expectedOut) {
116        const self = this;
117        if (!self.symbols) await self.loadSymbols();
118
119        checkObject("main", expectedOut);
120
121        function checkObject(prefix, eOut) {
122
123            if (Array.isArray(eOut)) {
124                for (let i=0; i<eOut.length; i++) {
125                    checkObject(prefix + "["+i+"]", eOut[i]);
126                }
127            } else if ((typeof eOut == "object")&&(eOut.constructor.name == "Object")) {
128                for (let k in eOut) {
129                    checkObject(prefix + "."+k, eOut[k]);
130                }
131            } else {
132                if (typeof self.symbols[prefix] == "undefined") {
133                    assert(false, "Output variable not defined: "+ prefix);
134                }
135                const ba = actualOut[self.symbols[prefix].varIdx].toString();
136                const be = eOut.toString();
137                assert.strictEqual(ba, be, prefix);
138            }
139        }
140    }
141
142    async getDecoratedOutput(witness) {
143        const self = this;
144        const lines = [];
145        if (!self.symbols) await self.loadSymbols();
146        for (let n in self.symbols) {
147            let v;
148            if (utils.isDefined(witness[self.symbols[n].varIdx])) {
149                v = witness[self.symbols[n].varIdx].toString();
150            } else {
151                v = "undefined";
152            }
153            lines.push(`${n} --> ${v}`);
154        }
155        return lines.join("\n");
156    }
157
158    async checkConstraints(witness) {
159        const self = this;
160        if (!self.constraints) await self.loadConstraints();
161        for (let i=0; i<self.constraints.length; i++) {
162            checkConstraint(self.constraints[i]);
163        }
164
165        function checkConstraint(constraint) {
166	    
167            const F = self.F;
168            const a = evalLC(constraint[0]);
169            const b = evalLC(constraint[1]);
170            const c = evalLC(constraint[2]);
171            assert (F.isZero(F.sub(F.mul(a,b), c)), "Constraint doesn't match");
172        }
173
174        function evalLC(lc) {
175            const F = self.F;
176            let v = F.zero;
177            for (let w in lc) {
178                v = F.add(
179                    v,
180                    F.mul( lc[w], witness[w] )
181                );
182            }
183            return v;
184        }
185    }
186
187}
188
189function version_to_list ( v ) {
190    return v.split(".").map(function(x) {
191	return parseInt(x, 10);
192    });
193}
194
195function check_versions ( v1, v2 ) {
196    //check if v1 is newer than or equal to v2
197    for (let i = 0; i < v2.length; i++) {
198	if (v1[i] > v2[i]) return true;
199	if (v1[i] < v2[i]) return false;
200    }
201    return true;
202}
203
204async function compiler_above_version(v) {
205    let output = await exec('circom --version').toString();
206    let compiler_version = version_to_list(output.slice(output.search(/\d/),-1));
207    vlist = version_to_list(v);
208    return check_versions ( compiler_version, vlist );
209}
210
211function readBinaryFile(fileName) {
212    const buff = fs.readFileSync(fileName);
213    const n32 = fromArray8ToUint(buff.slice(24,27));
214    var pos = 28+n32;
215    const ws = fromArray8ToUint(buff.slice(pos,pos+3));
216    pos += 16;
217    const w = [];
218    for (let i=0; i<ws; i++) {
219	w.push(fromArray8(buff.slice(pos,pos+n32-1)));
220	pos += n32;
221    }
222    return w;
223}
224
225function fromArray8(arr) { //returns a BigInt
226    var res = BigInt(0);
227    const radix = BigInt(0x100);
228    for (let i = arr.length-1 ; i>=0; i--) {
229        res = res*radix + BigInt(arr[i]);
230    }
231    return res;
232}
233
234function fromArray8ToUint(arr) { //returns a BigInt
235    var res = 0;
236    const radix = 8;
237    for (let i = arr.length-1 ; i>=0; i--) {
238        res = res*radix + arr[i];
239    }
240    return res;
241}