circom/src/compiler.js
src/compiler.jsRaw
1/*
2 Copyright 2018 0KIMS association.
3
4 This file is part of circom (Zero Knowledge Circuit Compiler).
5
6 circom is a free software: you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 circom is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with circom. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20const fs = require("fs");
21const path = require("path");
22const bigInt = require("big-integer");
23const __P__ = new bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
24const __MASK__ = new bigInt(2).pow(253).minus(1);
25const assert = require("assert");
26const gen = require("./gencode");
27const exec = require("./exec");
28const lc = require("./lcalgebra");
29
30module.exports = compile;
31
32const parser = require("../parser/jaz.js").parser;
33
34const timeout = ms => new Promise(res => setTimeout(res, ms));
35
36async function compile(srcFile, options) {
37 if (!options) {
38 options = {};
39 }
40 if (typeof options.reduceConstraints === "undefined") {
41 options.reduceConstraints = true;
42 }
43 const fullFileName = srcFile;
44 const fullFilePath = path.dirname(fullFileName);
45
46 const src = fs.readFileSync(fullFileName, "utf8");
47 const ast = parser.parse(src);
48
49 assert(ast.type == "BLOCK");
50
51 const ctx = {
52 scopes: [{}],
53 signals: {
54 one: {
55 fullName: "one",
56 value: bigInt(1),
57 equivalence: "",
58 direction: ""
59 }
60 },
61 currentComponent: "",
62 constraints: [],
63 components: {},
64 templates: {},
65 functions: {},
66 functionParams: {},
67 filePath: fullFilePath,
68 fileName: fullFileName
69 };
70
71
72 exec(ctx, ast);
73
74 if (!ctx.components["main"]) {
75 throw new Error("A main component must be defined");
76 }
77
78 classifySignals(ctx);
79
80 if (options.reduceConstraints) {
81 reduceConstants(ctx);
82
83 // Repeat while reductions are performed
84 let oldNConstrains = -1;
85 while (ctx.constraints.length != oldNConstrains) {
86 oldNConstrains = ctx.constraints.length;
87 reduceConstrains(ctx);
88 }
89 }
90
91 generateWitnessNames(ctx);
92
93 if (ctx.error) {
94 throw(ctx.error);
95 }
96
97 ctx.scopes = [{}];
98
99 const mainCode = gen(ctx,ast);
100 if (ctx.error) throw(ctx.error);
101
102 const def = buildCircuitDef(ctx, mainCode);
103
104 return def;
105}
106
107
108function classifySignals(ctx) {
109
110 function priorize(t1, t2) {
111 if ((t1 == "error") || (t2=="error")) return "error";
112 if (t1 == "internal") {
113 return t2;
114 } else if (t2=="internal") {
115 return t1;
116 }
117 if ((t1 == "one") || (t2 == "one")) return "one";
118 if ((t1 == "constant") || (t2 == "constant")) return "constant";
119 if (t1!=t2) return "error";
120 return t1;
121 }
122
123 // First classify the signals
124 for (let s in ctx.signals) {
125 const signal = ctx.signals[s];
126 let tAll = "internal";
127 let lSignal = signal;
128 let end = false;
129 while (!end) {
130 let t = lSignal.category || "internal";
131 if (s == "one") {
132 t = "one";
133 } else if (lSignal.value) {
134 t = "constant";
135 } else if (lSignal.component=="main") {
136 if (lSignal.direction == "IN") {
137 if (lSignal.private) {
138 t = "prvInput";
139 } else {
140 t = "pubInput";
141 }
142 } else if (lSignal.direction == "OUT") {
143 t = "output";
144 }
145 }
146 tAll = priorize(t,tAll);
147 if (lSignal.equivalence) {
148 lSignal = ctx.signals[lSignal.equivalence];
149 } else {
150 end=true;
151 }
152 }
153 if (tAll == "error") {
154 throw new Error("Incompatible types in signal: " + s);
155 }
156 lSignal.category = tAll;
157 }
158}
159
160
161function generateWitnessNames(ctx) {
162
163 const totals = {
164 "output": 0,
165 "pubInput": 0,
166 "one": 0,
167 "prvInput": 0,
168 "internal": 0,
169 "constant": 0,
170 };
171 const ids = {};
172
173 const counted = {};
174
175 // First classify the signals
176 for (let s in ctx.signals) {
177 const signal = ctx.signals[s];
178 let lSignal = signal;
179 while (lSignal.equivalence) lSignal = ctx.signals[lSignal.equivalence];
180
181 if (!counted[lSignal.fullName]) {
182 counted[lSignal.fullName] = true;
183 totals[lSignal.category] ++;
184 }
185 }
186
187 ids["one"] = 0;
188 ids["output"] = 1;
189 ids["pubInput"] = ids["output"] + totals["output"];
190 ids["prvInput"] = ids["pubInput"] + totals["pubInput"];
191 ids["internal"] = ids["prvInput"] + totals["prvInput"];
192 ids["constant"] = ids["internal"] + totals["internal"];
193 const nSignals = ids["constant"] + totals["constant"];
194
195 ctx.signalNames = new Array(nSignals);
196 for (let i=0; i< nSignals; i++) ctx.signalNames[i] = [];
197 ctx.signalName2Idx = {};
198
199 for (let s in ctx.signals) {
200 const signal = ctx.signals[s];
201 let lSignal = signal;
202 while (lSignal.equivalence) {
203 lSignal = ctx.signals[lSignal.equivalence];
204 }
205 if ( typeof(lSignal.id) === "undefined" ) {
206 lSignal.id = ids[lSignal.category] ++;
207 }
208
209 signal.id = lSignal.id;
210 ctx.signalNames[signal.id].push(signal.fullName);
211 ctx.signalName2Idx[signal.fullName] = signal.id;
212 }
213
214 ctx.totals = totals;
215}
216
217function reduceConstants(ctx) {
218 const newConstraints = [];
219 for (let i=0; i<ctx.constraints.length; i++) {
220 const c = lc.canonize(ctx, ctx.constraints[i]);
221 if (!lc.isZero(c)) {
222 newConstraints.push(c);
223 }
224 }
225 ctx.constraints = newConstraints;
226}
227
228function reduceConstrains(ctx) {
229 const newConstraints = [];
230 for (let i=0; i<ctx.constraints.length; i++) {
231 const c = ctx.constraints[i];
232
233 // Swap a and b if b has more variables.
234 if (Object.keys(c.b).length > Object.keys(c.a).length) {
235 const aux = c.a;
236 c.a=c.b;
237 c.b=aux;
238 }
239
240 // Mov to C if possible.
241 if (isConstant(c.a)) {
242 const ct = {type: "NUMBER", value: c.a.values["one"]};
243 c.c = lc.add(lc.mul(c.b, ct), c.c);
244 c.a = { type: "LINEARCOMBINATION", values: {} };
245 c.b = { type: "LINEARCOMBINATION", values: {} };
246 }
247 if (isConstant(c.b)) {
248 const ct = {type: "NUMBER", value: c.b.values["one"]};
249 c.c = lc.add(lc.mul(c.a, ct), c.c);
250 c.a = { type: "LINEARCOMBINATION", values: {} };
251 c.b = { type: "LINEARCOMBINATION", values: {} };
252 }
253
254 if (lc.isZero(c.a) || lc.isZero(c.b)) {
255 const isolatedSignal = getFirstInternalSignal(ctx, c.c);
256 if (isolatedSignal) {
257 const isolatedSignalEquivalence = {
258 type: "LINEARCOMBINATION",
259 values: {}
260 };
261 const invCoef = c.c.values[isolatedSignal].modInv(__P__);
262 for (const s in c.c.values) {
263 if (s != isolatedSignal) {
264 const v = __P__.minus(c.c.values[s]).times(invCoef).mod(__P__);
265 if (!v.isZero()) {
266 isolatedSignalEquivalence.values[s] = v;
267 }
268 }
269 }
270
271 for (let j=0; j<newConstraints.length; j++) {
272 newConstraints[j] = lc.substitute(newConstraints[j], isolatedSignal, isolatedSignalEquivalence);
273 }
274 for (let j=i+1; j<ctx.constraints.length; j++ ) {
275 ctx.constraints[j] = lc.substitute(ctx.constraints[j], isolatedSignal, isolatedSignalEquivalence);
276 }
277 c.a={ type: "LINEARCOMBINATION", values: {} };
278 c.b={ type: "LINEARCOMBINATION", values: {} };
279 c.c={ type: "LINEARCOMBINATION", values: {} };
280 isolatedSignal.category = "constant";
281 }
282 }
283
284 if (!lc.isZero(c)) {
285 newConstraints.push(c);
286 }
287 }
288 ctx.constraints = newConstraints;
289
290 function getFirstInternalSignal(ctx, l) {
291 for (let k in l.values) {
292 const signal = ctx.signals[k];
293 if (signal.category == "internal") return k;
294 }
295 return null;
296 }
297
298 function isConstant(l) {
299 for (let k in l.values) {
300 if ((k != "one") && (!l.values[k].isZero())) return false;
301 }
302 if (!l.values["one"] || l.values["one"].isZero()) return false;
303 return true;
304 }
305
306}
307
308
309function buildCircuitDef(ctx, mainCode) {
310 const res = {
311 mainCode: mainCode
312 };
313 res.signalName2Idx = ctx.signalName2Idx;
314
315 res.components = [];
316 res.componentName2Idx = {};
317 for (let c in ctx.components) {
318 const idCoponent = res.components.length;
319 res.components.push({
320 name: c,
321 params: ctx.components[c].params,
322 template: ctx.components[c].template,
323 inputSignals: 0
324 });
325 res.componentName2Idx[c] = idCoponent;
326 }
327
328 res.signals = new Array(ctx.signalNames.length);
329 for (let i=0; i<ctx.signalNames.length; i++) {
330 res.signals[i] = {
331 names: ctx.signalNames[i],
332 triggerComponents: []
333 };
334 ctx.signalNames[i].map( (fullName) => {
335 const idComponet = res.componentName2Idx[ctx.signals[fullName].component];
336 if (ctx.signals[fullName].direction == "IN") {
337 res.signals[i].triggerComponents.push(idComponet);
338 res.components[idComponet].inputSignals++;
339 }
340 });
341 }
342
343 res.constraints = buildConstraints(ctx);
344
345 res.templates = ctx.templates;
346
347 res.functions = {};
348 for (let f in ctx.functions) {
349 res.functions[f] = {
350 params: ctx.functionParams[f],
351 func: ctx.functions[f]
352 };
353 }
354
355 res.nPrvInputs = ctx.totals.prvInput;
356 res.nPubInputs = ctx.totals.pubInput;
357 res.nInputs = res.nPrvInputs + res.nPubInputs;
358 res.nOutputs = ctx.totals.output;
359 res.nVars = res.nInputs + res.nOutputs + ctx.totals.one + ctx.totals.internal;
360 res.nConstants = ctx.totals.constant;
361 res.nSignals = res.nVars + res.nConstants;
362
363 return res;
364}
365
366/*
367 Build constraints
368
369A constraint like this
370
371 [s1 + 2*s2 + 3*s3] * [ s2 + 5*s4] - [s0 ] = 0
372 [ 5*s2 + 6*s3] * [ s2 + ] - [s0 + 2* s2] = 0
373 [s1 + s3] * [ s2 + 5*s3] - [s4 ] = 0
374
375is converted to
376
377[
378 [{"1":"1","2":"2","3":"3"} , {"2":"1","4":"5"} , {"0":"1" }],
379 [{ "2":"5","3":"6"} , {"2":"1" } , {"0":"1", "2":"2"}],
380 [{"1":"1", "3":"1"} , {"2":"1","3":"5"} , {"4":"1" }]
381]
382 ^ ^ ^
383 | | |
384 A B C
385
386*/
387
388function buildConstraints(ctx) {
389 const res = [];
390
391 function fillLC(dst, src) {
392 if (src.type != "LINEARCOMBINATION") throw new Error("Constraint is not a LINEARCOMBINATION");
393 for (let s in src.values) {
394 const v = src.values[s].toString();
395 const id = ctx.signalName2Idx[s];
396 dst[id] = v;
397 }
398 }
399
400 for (let i=0; i<ctx.constraints.length; i++) {
401 const A = {};
402 const B = {};
403 const C = {};
404
405 fillLC(A, ctx.constraints[i].a);
406 fillLC(B, ctx.constraints[i].b);
407 fillLC(C, lc.negate(ctx.constraints[i].c));
408
409 res.push([A,B,C]);
410 }
411
412 return res;
413}
414
415
416