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