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