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