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