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