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 reduceConstants(ctx);
81 if (options.reduceConstraints) {
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
281 let lSignal = ctx.signals[isolatedSignal];
282 while (lSignal.equivalence) {
283 lSignal = ctx.signals[lSignal.equivalence];
284 }
285 lSignal.category = "constant";
286 }
287 }
288
289 if (!lc.isZero(c)) {
290 newConstraints.push(c);
291 }
292 }
293 ctx.constraints = newConstraints;
294
295 function getFirstInternalSignal(ctx, l) {
296 for (let k in l.values) {
297 const signal = ctx.signals[k];
298 if (signal.category == "internal") return k;
299 }
300 return null;
301 }
302
303 function isConstant(l) {
304 for (let k in l.values) {
305 if ((k != "one") && (!l.values[k].isZero())) return false;
306 }
307 if (!l.values["one"] || l.values["one"].isZero()) return false;
308 return true;
309 }
310
311}
312
313
314function buildCircuitDef(ctx, mainCode) {
315 const res = {
316 mainCode: mainCode
317 };
318 res.signalName2Idx = ctx.signalName2Idx;
319
320 res.components = [];
321 res.componentName2Idx = {};
322 for (let c in ctx.components) {
323 const idCoponent = res.components.length;
324 res.components.push({
325 name: c,
326 params: ctx.components[c].params,
327 template: ctx.components[c].template,
328 inputSignals: 0
329 });
330 res.componentName2Idx[c] = idCoponent;
331 }
332
333 res.signals = new Array(ctx.signalNames.length);
334 for (let i=0; i<ctx.signalNames.length; i++) {
335 res.signals[i] = {
336 names: ctx.signalNames[i],
337 triggerComponents: []
338 };
339 ctx.signalNames[i].map( (fullName) => {
340 const idComponet = res.componentName2Idx[ctx.signals[fullName].component];
341 if (ctx.signals[fullName].direction == "IN") {
342 res.signals[i].triggerComponents.push(idComponet);
343 res.components[idComponet].inputSignals++;
344 }
345 });
346 }
347
348 res.constraints = buildConstraints(ctx);
349
350 res.templates = ctx.templates;
351
352 res.functions = {};
353 for (let f in ctx.functions) {
354 res.functions[f] = {
355 params: ctx.functionParams[f],
356 func: ctx.functions[f]
357 };
358 }
359
360 res.nPrvInputs = ctx.totals.prvInput;
361 res.nPubInputs = ctx.totals.pubInput;
362 res.nInputs = res.nPrvInputs + res.nPubInputs;
363 res.nOutputs = ctx.totals.output;
364 res.nVars = res.nInputs + res.nOutputs + ctx.totals.one + ctx.totals.internal;
365 res.nConstants = ctx.totals.constant;
366 res.nSignals = res.nVars + res.nConstants;
367
368 return res;
369}
370
371/*
372 Build constraints
373
374A constraint like this
375
376 [s1 + 2*s2 + 3*s3] * [ s2 + 5*s4] - [s0 ] = 0
377 [ 5*s2 + 6*s3] * [ s2 + ] - [s0 + 2* s2] = 0
378 [s1 + s3] * [ s2 + 5*s3] - [s4 ] = 0
379
380is converted to
381
382[
383 [{"1":"1","2":"2","3":"3"} , {"2":"1","4":"5"} , {"0":"1" }],
384 [{ "2":"5","3":"6"} , {"2":"1" } , {"0":"1", "2":"2"}],
385 [{"1":"1", "3":"1"} , {"2":"1","3":"5"} , {"4":"1" }]
386]
387 ^ ^ ^
388 | | |
389 A B C
390
391*/
392
393function buildConstraints(ctx) {
394 const res = [];
395
396 function fillLC(dst, src) {
397 if (src.type != "LINEARCOMBINATION") throw new Error("Constraint is not a LINEARCOMBINATION");
398 for (let s in src.values) {
399 const v = src.values[s].toString();
400 const id = ctx.signalName2Idx[s];
401 dst[id] = v;
402 }
403 }
404
405 for (let i=0; i<ctx.constraints.length; i++) {
406 const A = {};
407 const B = {};
408 const C = {};
409
410 fillLC(A, ctx.constraints[i].a);
411 fillLC(B, ctx.constraints[i].b);
412 fillLC(C, lc.negate(ctx.constraints[i].c));
413
414 res.push([A,B,C]);
415 }
416
417 return res;
418}
419
420
421