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