circom_tester/c/tester.js
c/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 = c_tester;
15
16async function c_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 = options.r1cs || false; // costraints in r1cs format
34 //if (!options.json) options.r1cs = true; // r1cs if not json
35 options.r1cs = true;
36 options.output = dir.path;
37
38 await compile(baseName, circomInput, options);
39
40 return new WasmTester(dir, baseName, run);
41}
42
43async function compile (baseName, fileName, options) {
44 var flags = "--c ";
45 if (options.sym) flags += "--sym ";
46 if (options.r1cs) flags += "--r1cs ";
47 if (options.json) flags += "--json ";
48 if (options.output) flags += "--output " + options.output + " ";
49
50 b = await exec("circom " + flags + fileName);
51 assert(b.stderr == "",
52 "circom compiler error \n" + b.stderr);
53
54 const c_folder = path.join(options.output, baseName+"_cpp/")
55 b = await exec("make -C "+c_folder);
56 assert(b.stderr == "",
57 "error building the executable C program\n" + b.stderr);
58}
59
60class WasmTester {
61
62 constructor(dir, baseName, witnessCalculator) {
63 this.dir=dir;
64 this.baseName = baseName;
65 this.witnessCalculator = witnessCalculator;
66 }
67
68 async release() {
69 await this.dir.cleanup();
70 }
71
72 async calculateWitness(input) {
73 const inputjson = JSON.stringify(input);
74 const inputFile = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName + ".json");
75 const wtnsFile = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName + ".wtns");
76 const runc = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName);
77 fs.writeFile(inputFile, inputjson, function(err) {
78 if (err) throw err;
79 });
80 await exec("ls " + path.join(this.dir.path, this.baseName+"_cpp/"));
81 await exec(runc + " " + inputFile + " " + wtnsFile);
82 return readBinaryFile(wtnsFile);
83 }
84
85 async loadSymbols() {
86 if (this.symbols) return;
87 this.symbols = {};
88 const symsStr = await fs.promises.readFile(
89 path.join(this.dir.path, this.baseName + ".sym"),
90 "utf8"
91 );
92 const lines = symsStr.split("\n");
93 for (let i=0; i<lines.length; i++) {
94 const arr = lines[i].split(",");
95 if (arr.length!=4) continue;
96 this.symbols[arr[3]] = {
97 labelIdx: Number(arr[0]),
98 varIdx: Number(arr[1]),
99 componentIdx: Number(arr[2]),
100 };
101 }
102 }
103
104 async loadConstraints() {
105 const self = this;
106 if (this.constraints) return;
107 const r1cs = await loadR1cs(path.join(this.dir.path, this.baseName + ".r1cs"),true, false);
108 self.F = new ZqField(r1cs.prime);
109 self.nVars = r1cs.nVars;
110 self.constraints = r1cs.constraints;
111 }
112
113 async assertOut(actualOut, expectedOut) {
114 const self = this;
115 if (!self.symbols) await self.loadSymbols();
116
117 checkObject("main", expectedOut);
118
119 function checkObject(prefix, eOut) {
120
121 if (Array.isArray(eOut)) {
122 for (let i=0; i<eOut.length; i++) {
123 checkObject(prefix + "["+i+"]", eOut[i]);
124 }
125 } else if ((typeof eOut == "object")&&(eOut.constructor.name == "Object")) {
126 for (let k in eOut) {
127 checkObject(prefix + "."+k, eOut[k]);
128 }
129 } else {
130 if (typeof self.symbols[prefix] == "undefined") {
131 assert(false, "Output variable not defined: "+ prefix);
132 }
133 const ba = actualOut[self.symbols[prefix].varIdx].toString();
134 const be = eOut.toString();
135 assert.strictEqual(ba, be, prefix);
136 }
137 }
138 }
139
140 async getDecoratedOutput(witness) {
141 const self = this;
142 const lines = [];
143 if (!self.symbols) await self.loadSymbols();
144 for (let n in self.symbols) {
145 let v;
146 if (utils.isDefined(witness[self.symbols[n].varIdx])) {
147 v = witness[self.symbols[n].varIdx].toString();
148 } else {
149 v = "undefined";
150 }
151 lines.push(`${n} --> ${v}`);
152 }
153 return lines.join("\n");
154 }
155
156 async checkConstraints(witness) {
157 const self = this;
158 if (!self.constraints) await self.loadConstraints();
159 for (let i=0; i<self.constraints.length; i++) {
160 checkConstraint(self.constraints[i]);
161 }
162
163 function checkConstraint(constraint) {
164
165 const F = self.F;
166 const a = evalLC(constraint[0]);
167 const b = evalLC(constraint[1]);
168 const c = evalLC(constraint[2]);
169 assert (F.isZero(F.sub(F.mul(a,b), c)), "Constraint doesn't match");
170 }
171
172 function evalLC(lc) {
173 const F = self.F;
174 let v = F.zero;
175 for (let w in lc) {
176 v = F.add(
177 v,
178 F.mul( lc[w], witness[w] )
179 );
180 }
181 return v;
182 }
183 }
184
185}
186
187function version_to_list ( v ) {
188 return v.split(".").map(function(x) {
189 return parseInt(x, 10);
190 });
191}
192
193function check_versions ( v1, v2 ) {
194 //check if v1 is newer than or equal to v2
195 for (let i = 0; i < v2.length; i++) {
196 if (v1[i] > v2[i]) return true;
197 if (v1[i] < v2[i]) return false;
198 }
199 return true;
200}
201
202async function compiler_above_version(v) {
203 let output = await exec('circom --version').toString();
204 let compiler_version = version_to_list(output.slice(output.search(/\d/),-1));
205 vlist = version_to_list(v);
206 return check_versions ( compiler_version, vlist );
207}
208
209function readBinaryFile(fileName) {
210 const buff = fs.readFileSync(fileName);
211 const n32 = fromArray8ToUint(buff.slice(24,27));
212 var pos = 28+n32;
213 const ws = fromArray8ToUint(buff.slice(pos,pos+3));
214 pos += 16;
215 const w = [];
216 for (let i=0; i<ws; i++) {
217 w.push(fromArray8(buff.slice(pos,pos+n32-1)));
218 pos += n32;
219 }
220 return w;
221}
222
223function fromArray8(arr) { //returns a BigInt
224 var res = BigInt(0);
225 const radix = BigInt(0x100);
226 for (let i = arr.length-1 ; i>=0; i--) {
227 res = res*radix + BigInt(arr[i]);
228 }
229 return res;
230}
231
232function fromArray8ToUint(arr) { //returns a BigInt
233 var res = 0;
234 const radix = 8;
235 for (let i = arr.length-1 ; i>=0; i--) {
236 res = res*radix + arr[i];
237 }
238 return res;
239}