arnaucube
arnaucube/circomPublic Self-hosted repository
circom/ports/wasm/tester.js
ports/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");
  7const compiler = require("../../src/compiler");
  8
  9const bigInt = require("big-integer");
 10const utils = require("../../src/utils");
 11const loadR1cs = require("r1csfile").load;
 12const ZqField = require("ffjavascript").ZqField;
 13
 14const WitnessCalculatorBuilder = require("circom_runtime").WitnessCalculatorBuilder;
 15
 16module.exports = wasm_tester;
 17
 18async function  wasm_tester(circomFile, _options) {
 19    tmp.setGracefulCleanup();
 20
 21    const dir = await tmp.dir({prefix: "circom_", unsafeCleanup: true });
 22
 23    // console.log(dir.path);
 24
 25    const baseName = path.basename(circomFile, ".circom");
 26    const options = Object.assign({}, _options);
 27
 28    options.wasmWriteStream = fs.createWriteStream(path.join(dir.path, baseName + ".wasm"));
 29    options.symWriteStream = fs.createWriteStream(path.join(dir.path, baseName + ".sym"));
 30    options.r1csFileName = path.join(dir.path, baseName + ".r1cs");
 31
 32    const promisesArr = [];
 33    promisesArr.push(new Promise(fulfill => options.wasmWriteStream.on("finish", fulfill)));
 34
 35    await compiler(circomFile, options);
 36
 37    await Promise.all(promisesArr);
 38
 39    const wasm = await fs.promises.readFile(path.join(dir.path, baseName + ".wasm"));
 40
 41    const wc = await WitnessCalculatorBuilder(wasm);
 42
 43    return new WasmTester(dir, baseName, wc);
 44}
 45
 46class WasmTester {
 47
 48    constructor(dir, baseName, witnessCalculator) {
 49        this.dir=dir;
 50        this.baseName = baseName;
 51        this.witnessCalculator = witnessCalculator;
 52    }
 53
 54    async release() {
 55        await this.dir.cleanup();
 56    }
 57
 58    async calculateWitness(input, sanityCheck) {
 59        return await this.witnessCalculator.calculateWitness(input, sanityCheck);
 60    }
 61
 62    async loadSymbols() {
 63        if (this.symbols) return;
 64        this.symbols = {};
 65        const symsStr = await fs.promises.readFile(
 66            path.join(this.dir.path, this.baseName + ".sym"),
 67            "utf8"
 68        );
 69        const lines = symsStr.split("\n");
 70        for (let i=0; i<lines.length; i++) {
 71            const arr = lines[i].split(",");
 72            if (arr.length!=4) continue;
 73            this.symbols[arr[3]] = {
 74                labelIdx: Number(arr[0]),
 75                varIdx: Number(arr[1]),
 76                componentIdx: Number(arr[2]),
 77            };
 78        }
 79    }
 80
 81    async loadConstraints() {
 82        const self = this;
 83        if (this.constraints) return;
 84        const r1cs = await loadR1cs(path.join(this.dir.path, this.baseName + ".r1cs"),true, false);
 85        self.field = new ZqField(r1cs.prime);
 86        self.nVars = r1cs.nVars;
 87        self.constraints = r1cs.constraints;
 88    }
 89
 90    async assertOut(actualOut, expectedOut) {
 91        const self = this;
 92        if (!self.symbols) await self.loadSymbols();
 93
 94        checkObject("main", expectedOut);
 95
 96        function checkObject(prefix, eOut) {
 97
 98            if (Array.isArray(eOut)) {
 99                for (let i=0; i<eOut.length; i++) {
100                    checkObject(prefix + "["+i+"]", eOut[i]);
101                }
102            } else if ((typeof eOut == "object")&&(eOut.constructor.name == "Object")) {
103                for (let k in eOut) {
104                    checkObject(prefix + "."+k, eOut[k]);
105                }
106            } else {
107                if (typeof self.symbols[prefix] == "undefined") {
108                    assert(false, "Output variable not defined: "+ prefix);
109                }
110                const ba = bigInt(actualOut[self.symbols[prefix].varIdx]).toString();
111                const be = bigInt(eOut).toString();
112                assert.strictEqual(ba, be, prefix);
113            }
114        }
115    }
116
117    async getDecoratedOutput(witness) {
118        const self = this;
119        const lines = [];
120        if (!self.symbols) await self.loadSymbols();
121        for (let n in self.symbols) {
122            let v;
123            if (utils.isDefined(witness[self.symbols[n].varIdx])) {
124                v = witness[self.symbols[n].varIdx].toString();
125            } else {
126                v = "undefined";
127            }
128            lines.push(`${n} --> ${v}`);
129        }
130        return lines.join("\n");
131    }
132
133    async checkConstraints(witness) {
134        const self = this;
135        if (!self.constraints) await self.loadConstraints();
136        for (let i=0; i<self.constraints.length; i++) {
137            checkConstraint(self.constraints[i]);
138        }
139
140        function checkConstraint(constraint) {
141            const F = self.field;
142            const a = evalLC(constraint[0]);
143            const b = evalLC(constraint[1]);
144            const c = evalLC(constraint[2]);
145
146            assert (F.sub(F.mul(a,b), c).isZero(), "Constraint doesn't match");
147        }
148
149        function evalLC(lc) {
150            const F = self.field;
151            let v = F.zero;
152            for (let w in lc) {
153                v = F.add(
154                    v,
155                    F.mul( lc[w], witness[w] )
156                );
157            }
158            return v;
159        }
160    }
161
162}
163
164