circom/ports/c/tester.js
ports/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");
7const compiler = require("../../src/compiler");
8const util = require("util");
9const exec = util.promisify(require("child_process").exec);
10
11const bigInt = require("big-integer");
12const utils = require("../../src/utils");
13const loadR1cs = require("r1csfile").load;
14const ZqField = require("ffjavascript").ZqField;
15const buildZqField = require("ffiasm").buildZqField;
16
17module.exports = c_tester;
18
19
20async function c_tester(circomFile, _options) {
21 tmp.setGracefulCleanup();
22
23 const dir = await tmp.dir({prefix: "circom_", unsafeCleanup: true });
24
25 // console.log(dir.path);
26
27 const baseName = path.basename(circomFile, ".circom");
28 const options = Object.assign({}, _options);
29
30 options.cSourceWriteStream = fs.createWriteStream(path.join(dir.path, baseName + ".cpp"));
31 options.symWriteStream = fs.createWriteStream(path.join(dir.path, baseName + ".sym"));
32 options.r1csFileName = path.join(dir.path, baseName + ".r1cs");
33
34 options.p = options.p || bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
35 await compiler(circomFile, options);
36
37 const source = await buildZqField(options.p, "Fr");
38
39 // console.log(dir.path);
40
41 await fs.promises.writeFile(path.join(dir.path, "fr.asm"), source.asm, "utf8");
42 await fs.promises.writeFile(path.join(dir.path, "fr.h"), source.h, "utf8");
43 await fs.promises.writeFile(path.join(dir.path, "fr.c"), source.c, "utf8");
44
45 if (process.platform === "darwin") {
46 await exec("nasm -fmacho64 --prefix _ " +
47 ` ${path.join(dir.path, "fr.asm")}`
48 );
49 } else if (process.platform === "linux") {
50 await exec("nasm -felf64 " +
51 ` ${path.join(dir.path, "fr.asm")}`
52 );
53 } else throw("Unsupported platform");
54
55 const cdir = path.join(path.dirname(require.resolve("circom_runtime")), "c");
56
57 await exec("g++" +
58 ` ${path.join(cdir, "main.cpp")}` +
59 ` ${path.join(cdir, "calcwit.cpp")}` +
60 ` ${path.join(cdir, "utils.cpp")}` +
61 ` ${path.join(dir.path, "fr.c")}` +
62 ` ${path.join(dir.path, "fr.o")}` +
63 ` ${path.join(dir.path, baseName + ".cpp")} ` +
64 ` -o ${path.join(dir.path, baseName)}` +
65 ` -I ${dir.path} -I${cdir}` +
66 " -lgmp -std=c++11 -DSANITY_CHECK -g"
67 );
68
69 // console.log(dir.path);
70 return new CTester(dir, baseName);
71}
72
73class CTester {
74
75 constructor(dir, baseName) {
76 this.dir=dir;
77 this.baseName = baseName;
78 }
79
80 async release() {
81 await this.dir.cleanup();
82 }
83
84 async calculateWitness(input) {
85 await fs.promises.writeFile(
86 path.join(this.dir.path, "in.json"),
87 JSON.stringify(utils.stringifyBigInts(input), null, 1)
88 );
89 const r = await exec(`${path.join(this.dir.path, this.baseName)}` +
90 ` ${path.join(this.dir.path, "in.json")}` +
91 ` ${path.join(this.dir.path, "out.json")}`
92 );
93 if (r.stdout) {
94 console.log(r.stdout);
95 }
96 const resStr = await fs.promises.readFile(
97 path.join(this.dir.path, "out.json")
98 );
99
100 const res = utils.unstringifyBigInts(JSON.parse(resStr));
101 return res;
102 }
103
104 async loadSymbols() {
105 if (this.symbols) return;
106 this.symbols = {};
107 const symsStr = await fs.promises.readFile(
108 path.join(this.dir.path, this.baseName + ".sym"),
109 "utf8"
110 );
111 const lines = symsStr.split("\n");
112 for (let i=0; i<lines.length; i++) {
113 const arr = lines[i].split(",");
114 if (arr.length!=4) continue;
115 this.symbols[arr[3]] = {
116 labelIdx: Number(arr[0]),
117 varIdx: Number(arr[1]),
118 componentIdx: Number(arr[2]),
119 };
120 }
121 }
122
123 async loadConstraints() {
124 const self = this;
125 if (this.constraints) return;
126 const r1cs = await loadR1cs(path.join(this.dir.path, this.baseName + ".r1cs"),true, false);
127 self.field = new ZqField(r1cs.prime);
128 self.nVars = r1cs.nVars;
129 self.constraints = r1cs.constraints;
130 }
131
132 async assertOut(actualOut, expectedOut) {
133 const self = this;
134 if (!self.symbols) await self.loadSymbols();
135
136 checkObject("main", expectedOut);
137
138 function checkObject(prefix, eOut) {
139
140 if (Array.isArray(eOut)) {
141 for (let i=0; i<eOut.length; i++) {
142 checkObject(prefix + "["+i+"]", eOut[i]);
143 }
144 } else if ((typeof eOut == "object")&&(eOut.constructor.name == "Object")) {
145 for (let k in eOut) {
146 checkObject(prefix + "."+k, eOut[k]);
147 }
148 } else {
149 if (typeof self.symbols[prefix] == "undefined") {
150 assert(false, "Output variable not defined: "+ prefix);
151 }
152 const ba = bigInt(actualOut[self.symbols[prefix].varIdx]).toString();
153 const be = bigInt(eOut).toString();
154 assert.strictEqual(ba, be, prefix);
155 }
156 }
157 }
158
159 async getDecoratedOutput(witness) {
160 const self = this;
161 const lines = [];
162 if (!self.symbols) await self.loadSymbols();
163 for (let n in self.symbols) {
164 let v;
165 if (utils.isDefined(witness[self.symbols[n].varIdx])) {
166 v = witness[self.symbols[n].varIdx].toString();
167 } else {
168 v = "undefined";
169 }
170 lines.push(`${n} --> ${v}`);
171 }
172 return lines.join("\n");
173 }
174
175 async checkConstraints(witness) {
176 const self = this;
177 if (!self.constraints) await self.loadConstraints();
178 for (let i=0; i<self.constraints.length; i++) {
179 checkConstraint(self.constraints[i]);
180 }
181
182 function checkConstraint(constraint) {
183 const F = self.field;
184 const a = evalLC(constraint[0]);
185 const b = evalLC(constraint[1]);
186 const c = evalLC(constraint[2]);
187
188 assert (F.sub(F.mul(a,b), c).isZero(), "Constraint doesn't match");
189 }
190
191 function evalLC(lc) {
192 const F = self.field;
193 let v = F.zero;
194 for (let w in lc) {
195 v = F.add(
196 v,
197 F.mul( lc[w], witness[w] )
198 );
199 }
200 return v;
201 }
202 }
203
204}
205
206