circom/src/c_build.js
src/c_build.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 assert = require("assert");
21const bigInt = require("big-integer");
22const utils = require("./utils");
23const gen = require("./c_gen").gen;
24const createRefs = require("./c_gen").createRefs;
25
26module.exports = buildC;
27
28
29function buildC(ctx) {
30 ctx.definedFunctions = {};
31 ctx.functionCodes = [];
32 ctx.buildFunction = buildFunction;
33 ctx.code = "";
34 ctx.conditionalCodeHeader = "";
35 ctx.codes_sizes = [];
36 ctx.definedSizes = {};
37 ctx.addSizes = addSizes;
38
39 const entryTables = buildEntryTables(ctx);
40 ctx.globalNames = ctx.uniqueNames;
41
42 const code = buildCode(ctx);
43 const functions = buildFuncFunctions(ctx);
44 const compnentsArray = buildComponentsArray(ctx);
45
46 const headder = buildHeader(ctx);
47 const sizes = buildSizes(ctx);
48 const mapIsInput = buildMapIsInput(ctx);
49 const wit2Sig = buildWit2Sig(ctx);
50 const circuitVar = buildCircuitVar(ctx);
51
52 return "" +
53 headder + "\n" +
54 sizes + "\n" +
55 entryTables + "\n" +
56 functions + "\n" +
57 code + "\n" +
58 compnentsArray + "\n" +
59 mapIsInput + "\n" +
60 wit2Sig +"\n" +
61 circuitVar;
62}
63
64function buildEntryTables(ctx) {
65
66 const codes_hashMaps = [];
67 const codes_componentEntries = [];
68 const definedHashTables = {};
69 for (let i=0; i<ctx.components.length; i++) {
70 const {htName, htMap} = addHashTable(i);
71
72 let code = "";
73 const componentEntriesTableName = ctx.getUniqueName("_entryTable" + ctx.components[i].template);
74
75 code += `Circom_ComponentEntry ${componentEntriesTableName}[${htMap.length}] = {\n`;
76 for (let j=0; j<htMap.length; j++) {
77 const entry = ctx.components[i].names.o[htMap[j]];
78 code += j>0 ? " ," : " ";
79 const sizeName = ctx.addSizes(entry.sizes);
80
81 const ty = entry.type == "S" ? "_typeSignal" : "_typeComponent";
82 code += `{${entry.offset},${sizeName}, ${ty}}\n`;
83 }
84 code += "};\n";
85 codes_componentEntries.push(code);
86
87 ctx.components[i].htName = htName;
88 ctx.components[i].etName = componentEntriesTableName;
89 }
90
91
92 return "" +
93 "// HashMaps\n" +
94 codes_hashMaps.join("\n") + "\n" +
95 "\n" +
96 "// Component Entries\n" +
97 codes_componentEntries.join("\n") + "\n" +
98 "\n";
99
100 function addHashTable(cIdx) {
101 const keys = Object.keys(ctx.components[cIdx].names.o);
102 assert(keys.length<128);
103 keys.sort((a,b) => ((a>b) ? 1 : -1));
104 const h = utils.fnvHash(keys.join(","));
105 if (definedHashTables[h]) return definedHashTables[h];
106 definedHashTables[h] = {};
107 definedHashTables[h].htName = ctx.getUniqueName("_ht"+ctx.components[cIdx].template);
108 definedHashTables[h].htMap = [];
109 const t = [];
110 for (let i=0; i<keys.length; i++) {
111 definedHashTables[h].htMap[i] = keys[i];
112
113 const h2 = utils.fnvHash(keys[i]);
114 let pos = parseInt(h2.slice(-2), 16);
115 while (t[pos]) pos = (pos + 1) % 256;
116 t[pos] = [h2, i];
117 }
118 let code = `Circom_HashEntry ${definedHashTables[h].htName}[256] = {`;
119 for (let i=0; i<256; i++) {
120 code += i>0 ? "," : "";
121 if (t[i]) {
122 code += `{0x${t[i][0]}LL, ${t[i][1]}} /* ${keys[t[i][1]]} */`;
123 } else {
124 code += "{0,0}";
125 }
126 }
127 code += "};\n";
128
129 codes_hashMaps.push(code);
130
131 return definedHashTables[h];
132 }
133}
134
135function buildCode(ctx) {
136
137 const fDefined = {};
138
139 const fnComponents = [];
140 for (let i=0; i<ctx.components.length; i++) {
141 const {h, instanceDef} = hashComponentCall(ctx, i);
142 const fName = ctx.components[i].template+"_"+h;
143 if (!fDefined[fName]) {
144
145
146 ctx.scopes = [{}];
147 ctx.conditionalCode = false;
148 ctx.code = "";
149 ctx.codeHeader = "// Header\n";
150 ctx.codeFooter = "// Footer\n";
151 ctx.uniqueNames = Object.assign({},ctx.globalNames);
152 ctx.refs = [];
153 ctx.fileName = ctx.templates[ctx.components[i].template].fileName;
154 ctx.filePath = ctx.templates[ctx.components[i].template].filePath;
155
156 for (let p in ctx.components[i].params) {
157 if (ctx.scopes[0][p]) return ctx.throwError(`Repeated parameter at ${ctx.components[i].template}: ${p}`);
158 const refId = ctx.refs.length;
159 ctx.refs.push({
160 type: "BIGINT",
161 used: false,
162 value: utils.flatArray(ctx.components[i].params[p]),
163 sizes: utils.accSizes(utils.extractSizes(ctx.components[i].params[p])),
164 label: ctx.getUniqueName(p)
165 });
166 ctx.scopes[0][p] = refId;
167 }
168
169 createRefs(ctx, ctx.templates[ctx.components[i].template].block);
170 if (ctx.error) return;
171
172 gen(ctx, ctx.templates[ctx.components[i].template].block);
173 if (ctx.error) return;
174
175 const S =
176 "/*\n" +
177 instanceDef +
178 "\n*/\n" +
179 `void ${fName}(Circom_CalcWit *ctx) {\n` +
180 utils.ident(
181 ctx.codeHeader + "\n" +
182 ctx.code + "\n" +
183 ctx.codeFooter
184 ) +
185 "}\n";
186
187 fnComponents.push(S);
188 fDefined[fName] = true;
189 }
190 ctx.components[i].fnName = fName;
191 }
192
193 return fnComponents.join("\n");
194}
195
196function buildFuncFunctions(ctx) {
197 return "// Functions\n" +
198 ctx.functionCodes.join("\n");
199}
200
201function buildComponentsArray(ctx) {
202
203 const ccodes = [];
204 ccodes.push(`Circom_Component _components[${ctx.components.length}] = {\n`);
205 for (let i=0; i< ctx.components.length; i++) {
206 ccodes.push(i>0 ? " ," : " ");
207 ccodes.push(`{${ctx.components[i].htName},${ctx.components[i].etName},${ctx.components[i].fnName}, ${ctx.components[i].nInSignals}}\n`);
208 }
209 ccodes.push("};\n");
210 const codeComponents = ccodes.join("");
211
212 return "" +
213 "// Components\n" +
214 codeComponents +
215 "\n";
216}
217
218
219function buildHeader(ctx) {
220 return "#include \"circom.h\"\n" +
221 "#include \"calcwit.h\"\n" +
222 `#define NSignals ${ctx.signals.length}\n` +
223 `#define NComponents ${ctx.components.length}\n` +
224 `#define NInputs ${ctx.components[ ctx.getComponentIdx("main") ].nInSignals}\n`+
225 `#define NOutputs ${ctx.totals[ ctx.stOUTPUT ]}\n`+
226 `#define NVars ${ctx.totals[ctx.stONE] + ctx.totals[ctx.stOUTPUT] + ctx.totals[ctx.stPUBINPUT] + ctx.totals[ctx.stPRVINPUT] + ctx.totals[ctx.stINTERNAL]}\n` +
227 `#define __P__ "${ctx.field.p.toString()}"\n` +
228 "\n";
229}
230
231function buildSizes(ctx) {
232 return "// Sizes\n" +
233 ctx.codes_sizes.join("\n");
234}
235
236
237function buildMapIsInput(ctx) {
238 const arr = [];
239 let line = "";
240 let acc = 0;
241 let i;
242 for (i=0; i<ctx.signals.length; i++) {
243 if (ctx.signals[i].o & ctx.IN) {
244 acc = acc | (1 << (i%32) );
245 }
246 if ((i+1)%32==0) {
247 line += (i>31) ? "," : " ";
248 line += toHex(acc);
249 acc = 0;
250 if ( (i+1) % (32*64) == 0) {
251 arr.push(line);
252 line = "";
253 }
254 }
255 }
256
257 if ((i%32) != 0) {
258 line += (i>31) ? "," : " ";
259 line += toHex(acc);
260 }
261 if (line != "") {
262 arr.push(line);
263 }
264
265 return "// mapIsArray\n" +
266 `u32 _mapIsInput[${Math.floor((ctx.signals.length-1) / 32)+1}] = {\n`+
267 arr.join("\n") + "\n" +
268 "};\n";
269
270 function toHex(number) {
271 if (number < 0) number = 0xFFFFFFFF + number + 1;
272 let S=number.toString(16).toUpperCase();
273 while (S.length<8) S = "0" + S;
274 return "0x"+S;
275 }
276}
277
278
279function buildWit2Sig(ctx) {
280 const codes = [];
281 const NVars =
282 ctx.totals[ctx.stONE] +
283 ctx.totals[ctx.stOUTPUT] +
284 ctx.totals[ctx.stPUBINPUT] +
285 ctx.totals[ctx.stPRVINPUT] +
286 ctx.totals[ctx.stINTERNAL];
287 const arr = Array(NVars);
288 for (let i=0; i<ctx.signals.length; i++) {
289 const outIdx = ctx.signals[i].id;
290 if (ctx.signals[i].e>=0) continue; // If has an alias, continue..
291 assert(typeof outIdx != "undefined", `Signal ${i} does not have index`);
292 if (outIdx>=NVars) continue; // Is a constant or a discarded variable
293 if (typeof arr[ctx.signals[i].id] == "undefined") {
294 arr[outIdx] = i;
295 }
296 }
297 codes.push("// Signal Table\n");
298 codes.push(`int _wit2sig[${NVars}] = {\n`);
299 let code = "";
300 for (let i=0; i<NVars; i++) {
301 code += (i>0) ? ",": " ";
302 code += arr[i];
303 if ((i>0)&&(i%64 == 0)) {
304 if (code != "") {
305 codes.push(code + "\n");
306 } else {
307 codes.push(code);
308 }
309 code ="";
310 }
311 }
312 if (code != "") codes.push(code + "\n");
313 codes.push("};\n");
314
315 return codes.join("");
316
317}
318
319
320function buildCircuitVar() {
321 return "Circom_Circuit _circuit = {\n" +
322 " NSignals,\n"+
323 " NComponents,\n"+
324 " NInputs,\n"+
325 " NOutputs,\n"+
326 " NVars,\n"+
327 " _wit2sig,\n"+
328 " _components,\n"+
329 " _mapIsInput,\n"+
330 " __P__\n" +
331 "};\n";
332}
333
334
335
336
337function addSizes(_sizes) {
338 const sizes = _sizes || [];
339 let name = "sizes";
340 for (let i=0; i<sizes.length;i++) {
341 name+="_"+sizes[i];
342 }
343 if (name=="sizes") name="sizes_0";
344
345 if (this.definedSizes[name]) return this.definedSizes[name];
346 const labelName = this.getUniqueName(name);
347 this.definedSizes[name] = labelName;
348
349 const accSizes = utils.accSizes(sizes);
350
351 let code = `Circom_Size ${labelName}[${accSizes.length}] = {`;
352 for (let i=0; i<accSizes.length; i++) {
353 if (i>0) code += ",";
354 code += accSizes[i];
355 }
356 code += "};\n";
357 this.codes_sizes.push(code);
358
359 return labelName;
360}
361
362function buildFunction(name, paramValues) {
363 const ctx = this;
364 const {h, instanceDef} = hashFunctionCall(ctx, name, paramValues);
365
366 if (ctx.definedFunctions[h]) return ctx.definedFunctions[h];
367
368 const res = {
369 fnName: `${name}_${h}`
370 };
371
372 const oldRefs = ctx.refs;
373 const oldConditionalCode = ctx.conditionalCode;
374 const oldCode = ctx.code;
375 const oldCodeHeader = ctx.codeHeader;
376 const oldCodeFooter = ctx.codeFooter;
377 const oldUniqueNames = ctx.uniqueNames;
378 const oldFileName = ctx.fileName;
379 const oldFilePath = ctx.oldFilePath;
380 const oldReturnSizes = ctx.returnSizes;
381 const oldReturnValue = ctx.returnValue;
382
383
384 ctx.scopes = [{}];
385 ctx.refs = [];
386 ctx.conditionalCode = false;
387 ctx.code = "";
388 ctx.codeHeader = "// Header\n";
389 ctx.codeFooter = "// Footer\n";
390 ctx.uniqueNames = Object.assign({},ctx.globalNames);
391 ctx.returnValue = null;
392 ctx.returnSizes = null;
393 ctx.fileName = ctx.functions[name].fileName;
394 ctx.filePath = ctx.functions[name].filePath;
395
396 let paramsStr = "";
397
398 for (let i=0; i<ctx.functions[name].params.length; i++) {
399
400 if (paramValues[i].used) {
401 paramsStr += `,PBigInt ${ctx.functions[name].params[i]}`;
402 const idRef = ctx.refs.length;
403 ctx.refs.push({
404 type: "BIGINT",
405 used: true,
406 sizes: paramValues[i].sizes,
407 label: ctx.functions[name].params[i],
408 });
409 ctx.scopes[0][ctx.functions[name].params[i]] = idRef;
410 } else {
411 const idRef = ctx.refs.length;
412 ctx.refs.push({
413 type: "BIGINT",
414 used: false,
415 sizes: paramValues[i].sizes,
416 label: ctx.functions[name].params[i],
417 value: paramValues[i].value
418 });
419 ctx.scopes[0][ctx.functions[name].params[i]] = idRef;
420 }
421 }
422
423 createRefs(ctx, ctx.functions[name].block);
424 if (ctx.error) return;
425
426 gen(ctx, ctx.functions[name].block);
427 if (ctx.error) return;
428
429 if (ctx.returnValue == null) {
430 if (ctx.returnSizes == null) assert(false, `Funciont ${name} does not return any value`);
431 res.type = "VARVAL_CONSTSIZE";
432 let code =
433 "/*\n" +
434 instanceDef +
435 "\n*/\n" +
436 `void ${name}_${h}(Circom_CalcWit *ctx, PBigInt __retValue ${paramsStr}) {`;
437 code += utils.ident(ctx.codeHeader);
438 code += utils.ident(ctx.code);
439 code += utils.ident("returnFunc:\n");
440 code += utils.ident(ctx.codeFooter);
441 code += "}\n";
442 res.returnSizes = ctx.returnSizes;
443 ctx.functionCodes.push(code);
444 } else {
445 res.type = "CONSTVAL";
446 res.returnValue = ctx.returnValue;
447 res.returnSizes = ctx.returnSizes;
448 }
449
450 ctx.refs = oldRefs;
451 ctx.conditionalCode = oldConditionalCode;
452 ctx.code = oldCode;
453 ctx.codeHeader = oldCodeHeader;
454 ctx.codeFooter = oldCodeFooter;
455 ctx.uniqueNames = oldUniqueNames;
456 ctx.fileName = oldFileName;
457 ctx.filePath = oldFilePath;
458 ctx.returnSizes = oldReturnSizes;
459 ctx.returnValue = oldReturnValue;
460
461 ctx.definedFunctions[h] = res;
462
463 return res;
464}
465
466
467
468function hashComponentCall(ctx, cIdx) {
469 // TODO: At the moment generate a diferent function for each instance of the component
470 const constParams = [];
471 for (let p in ctx.components[cIdx].params) {
472 constParams.push(p + "=" + value2str(ctx.components[cIdx].params[p]));
473 }
474
475 for (let n in ctx.components[cIdx].names.o) {
476 const entry = ctx.components[cIdx].names.o[n];
477 if ((entry.type == "S")&&(ctx.signals[entry.offset].o & ctx.IN)) {
478 travelSizes(n, entry.offset, entry.sizes, (prefix, offset) => {
479 if (utils.isDefined(ctx.signals[offset].v)) {
480 constParams.push(prefix + "=" + bigInt(ctx.signals[offset].value));
481 }
482 });
483 }
484 }
485
486 let instanceDef = ctx.components[cIdx].template;
487 if (constParams.length>0) {
488 instanceDef += "\n";
489 constParams.sort();
490 instanceDef += constParams.join("\n");
491 }
492 const h = utils.fnvHash(instanceDef);
493 return {h, instanceDef};
494
495 function travelSizes(prefix, offset, sizes, fn) {
496 if (sizes.length == 0) {
497 fn(prefix, offset);
498 return 1;
499 } else {
500 let o = offset;
501 for (let i=0; i<sizes[0]; i++) {
502 o += travelSizes(prefix + "[" + i + "]", o, sizes.slice(1), fn);
503 }
504 return o-offset;
505 }
506 }
507}
508
509function hashFunctionCall(ctx, name, paramValues) {
510 // TODO
511 const constParams = [];
512 for (let i=0; i<ctx.functions[name].params.length; i++) {
513 if (!paramValues[i].used) {
514 constParams.push(ctx.functions[name].params[i] + utils.accSizes2Str(paramValues[i].sizes) + "=" + value2str(paramValues[i].value));
515 }
516 }
517 let instanceDef = name;
518 if (constParams.length>0) {
519 instanceDef += "\n";
520 constParams.sort();
521 instanceDef += constParams.join("\n");
522 }
523
524 const h = utils.fnvHash(instanceDef);
525 return {h, instanceDef};
526}
527
528function value2str(v) {
529 if (Array.isArray(v)) {
530 let S="[";
531 for (let i=0; i<v.length; i++) {
532 if (i>0) S+=",";
533 S+=value2str(v[i]);
534 }
535 S+="]";
536 return S;
537 } else {
538 return bigInt(v).toString();
539 }
540}