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 if (options.O === 0) flags += "--O0 "
55 if (options.O === 1) flags += "--O1 "
56
57 b = await exec("circom " + flags + fileName);
58 assert(b.stderr == "",
59 "circom compiler error \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, sanityCheck) {
75 return await this.witnessCalculator.calculateWitness(input, sanityCheck);
76 }
77
78 async loadSymbols() {
79 if (this.symbols) return;
80 this.symbols = {};
81 const symsStr = await fs.promises.readFile(
82 path.join(this.dir.path, this.baseName + ".sym"),
83 "utf8"
84 );
85 const lines = symsStr.split("\n");
86 for (let i=0; i<lines.length; i++) {
87 const arr = lines[i].split(",");
88 if (arr.length!=4) continue;
89 this.symbols[arr[3]] = {
90 labelIdx: Number(arr[0]),
91 varIdx: Number(arr[1]),
92 componentIdx: Number(arr[2]),
93 };
94 }
95 }
96
97 async loadConstraints() {
98 const self = this;
99 if (this.constraints) return;
100 const r1cs = await loadR1cs(path.join(this.dir.path, this.baseName + ".r1cs"),true, false);
101 self.F = new ZqField(r1cs.prime);
102 self.nVars = r1cs.nVars;
103 self.constraints = r1cs.constraints;
104 }
105
106 async assertOut(actualOut, expectedOut) {
107 const self = this;
108 if (!self.symbols) await self.loadSymbols();
109
110 checkObject("main", expectedOut);
111
112 function checkObject(prefix, eOut) {
113
114 if (Array.isArray(eOut)) {
115 for (let i=0; i<eOut.length; i++) {
116 checkObject(prefix + "["+i+"]", eOut[i]);
117 }
118 } else if ((typeof eOut == "object")&&(eOut.constructor.name == "Object")) {
119 for (let k in eOut) {
120 checkObject(prefix + "."+k, eOut[k]);
121 }
122 } else {
123 if (typeof self.symbols[prefix] == "undefined") {
124 assert(false, "Output variable not defined: "+ prefix);
125 }
126 const ba = actualOut[self.symbols[prefix].varIdx].toString();
127 const be = eOut.toString();
128 assert.strictEqual(ba, be, prefix);
129 }
130 }
131 }
132
133 async getDecoratedOutput(witness) {
134 const self = this;
135 const lines = [];
136 if (!self.symbols) await self.loadSymbols();
137 for (let n in self.symbols) {
138 let v;
139 if (utils.isDefined(witness[self.symbols[n].varIdx])) {
140 v = witness[self.symbols[n].varIdx].toString();
141 } else {
142 v = "undefined";
143 }
144 lines.push(`${n} --> ${v}`);
145 }
146 return lines.join("\n");
147 }
148
149 async checkConstraints(witness) {
150 const self = this;
151 if (!self.constraints) await self.loadConstraints();
152 for (let i=0; i<self.constraints.length; i++) {
153 checkConstraint(self.constraints[i]);
154 }
155
156 function checkConstraint(constraint) {
157
158 const F = self.F;
159 const a = evalLC(constraint[0]);
160 const b = evalLC(constraint[1]);
161 const c = evalLC(constraint[2]);
162 assert (F.isZero(F.sub(F.mul(a,b), c)), "Constraint doesn't match");
163 }
164
165 function evalLC(lc) {
166 const F = self.F;
167 let v = F.zero;
168 for (let w in lc) {
169 v = F.add(
170 v,
171 F.mul( lc[w], witness[w] )
172 );
173 }
174 return v;
175 }
176 }
177
178}
179
180function version_to_list ( v ) {
181 return v.split(".").map(function(x) {
182 return parseInt(x, 10);
183 });
184}
185
186function check_versions ( v1, v2 ) {
187 //check if v1 is newer than or equal to v2
188 for (let i = 0; i < v2.length; i++) {
189 if (v1[i] > v2[i]) return true;
190 if (v1[i] < v2[i]) return false;
191 }
192 return true;
193}
194
195async function compiler_above_version(v) {
196 let output = await exec('circom --version').toString();
197 let compiler_version = version_to_list(output.slice(output.search(/\d/),-1));
198 vlist = version_to_list(v);
199 return check_versions ( compiler_version, vlist );
200}
201