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