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;
 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, int __cIdx) {\n` +
180                        utils.ident(
181                            ctx.codeHeader + "\n" +
182                            ctx.code + "\n" +
183                            "ctx->finished(__cIdx);\n" +
184                            ctx.codeFooter
185                        ) +
186                    "}\n";
187
188            fnComponents.push(S);
189            fDefined[fName] = true;
190        }
191        ctx.components[i].fnName = fName;
192    }
193
194    return fnComponents.join("\n");
195}
196
197function buildFuncFunctions(ctx) {
198    return "// Functions\n" +
199        ctx.functionCodes.join("\n");
200}
201
202function buildComponentsArray(ctx) {
203
204    const ccodes = [];
205    ccodes.push(`Circom_Component _components[${ctx.components.length}] = {\n`);
206    for (let i=0; i< ctx.components.length; i++) {
207        ccodes.push(i>0 ? "    ," : "     ");
208        ccodes.push(`{${ctx.components[i].htName},${ctx.components[i].etName},${ctx.components[i].fnName}, ${ctx.components[i].nInSignals}, true}\n`);
209    }
210    ccodes.push("};\n");
211    const codeComponents = ccodes.join("");
212
213    return "" +
214        "// Components\n" +
215        codeComponents +
216        "\n";
217}
218
219
220function buildHeader(ctx) {
221    return "#include \"circom.h\"\n" +
222           "#include \"calcwit.h\"\n" +
223           `#define NSignals ${ctx.signals.length}\n` +
224           `#define NComponents ${ctx.components.length}\n` +
225           `#define NInputs ${ctx.components[ ctx.getComponentIdx("main") ].nInSignals}\n`+
226           `#define NOutputs ${ctx.totals[ ctx.stOUTPUT ]}\n`+
227           `#define NVars ${ctx.totals[ctx.stONE] + ctx.totals[ctx.stOUTPUT] + ctx.totals[ctx.stPUBINPUT] + ctx.totals[ctx.stPRVINPUT] + ctx.totals[ctx.stINTERNAL]}\n` +
228           `#define __P__ "${ctx.field.p.toString()}"\n` +
229           "\n";
230}
231
232function buildSizes(ctx) {
233    return "// Sizes\n" +
234            ctx.codes_sizes.join("\n");
235}
236
237
238function buildMapIsInput(ctx) {
239    const arr = [];
240    let line = "";
241    let acc = 0;
242    let i;
243    for (i=0; i<ctx.signals.length; i++) {
244        if (ctx.signals[i].o & ctx.IN) {
245            acc = acc | (1 << (i%32) );
246        }
247        if ((i+1)%32==0) {
248            line += (i>31) ? "," : " ";
249            line += toHex(acc);
250            acc = 0;
251            if ( (i+1) % (32*64) == 0) {
252                arr.push(line);
253                line = "";
254            }
255        }
256    }
257
258    if ((i%32) != 0) {
259        line += (i>31) ? "," : " ";
260        line += toHex(acc);
261    }
262    if (line != "") {
263        arr.push(line);
264    }
265
266    return "// mapIsArray\n" +
267        `u32 _mapIsInput[${Math.floor((ctx.signals.length-1) / 32)+1}] = {\n`+
268        arr.join("\n") + "\n" +
269        "};\n";
270
271    function toHex(number) {
272        if (number < 0) number = 0xFFFFFFFF + number + 1;
273        let S=number.toString(16).toUpperCase();
274        while (S.length<8) S = "0" + S;
275        return "0x"+S;
276    }
277}
278
279
280function buildWit2Sig(ctx) {
281    const codes = [];
282    const NVars =
283        ctx.totals[ctx.stONE] +
284        ctx.totals[ctx.stOUTPUT] +
285        ctx.totals[ctx.stPUBINPUT] +
286        ctx.totals[ctx.stPRVINPUT] +
287        ctx.totals[ctx.stINTERNAL];
288    const arr = Array(NVars);
289    for (let i=0; i<ctx.signals.length; i++) {
290        const outIdx = ctx.signals[i].id;
291        if (ctx.signals[i].e>=0) continue;     // If has an alias, continue..
292        assert(typeof outIdx  != "undefined", `Signal ${i} does not have index`);
293        if (outIdx>=NVars) continue; // Is a constant or a discarded variable
294        if (typeof arr[ctx.signals[i].id] == "undefined") {
295            arr[outIdx] = i;
296        }
297    }
298    codes.push("// Signal Table\n");
299    codes.push(`int _wit2sig[${NVars}] = {\n`);
300    let code = "";
301    for (let i=0; i<NVars; i++) {
302        code += (i>0) ? ",": " ";
303        code += arr[i];
304        if ((i>0)&&(i%64 == 0)) {
305            if (code != "") {
306                codes.push(code + "\n");
307            } else {
308                codes.push(code);
309            }
310            code ="";
311        }
312    }
313    if (code != "") codes.push(code + "\n");
314    codes.push("};\n");
315
316    return codes.join("");
317
318}
319
320
321function buildCircuitVar() {
322    return "Circom_Circuit _circuit = {\n" +
323        "   NSignals,\n"+
324        "   NComponents,\n"+
325        "   NInputs,\n"+
326        "   NOutputs,\n"+
327        "   NVars,\n"+
328        "   _wit2sig,\n"+
329        "   _components,\n"+
330        "   _mapIsInput,\n"+
331        "   __P__\n" +
332        "};\n";
333}
334
335
336
337
338function addSizes(_sizes) {
339    const sizes = _sizes || [];
340    let name = "sizes";
341    for (let i=0; i<sizes.length;i++) {
342        name+="_"+sizes[i];
343    }
344    if (name=="sizes") name="sizes_0";
345
346    if (this.definedSizes[name]) return this.definedSizes[name];
347    const labelName = this.getUniqueName(name);
348    this.definedSizes[name] = labelName;
349
350    const accSizes = utils.accSizes(sizes);
351
352    let code = `Circom_Size ${labelName}[${accSizes.length}] = {`;
353    for (let i=0; i<accSizes.length; i++) {
354        if (i>0) code += ",";
355        code += accSizes[i];
356    }
357    code += "};\n";
358    this.codes_sizes.push(code);
359
360    return labelName;
361}
362
363function buildFunction(name, paramValues) {
364    const ctx = this;
365    const {h, instanceDef} = hashFunctionCall(ctx, name, paramValues);
366
367    if (ctx.definedFunctions[h]) return ctx.definedFunctions[h];
368
369    const res = {
370        fnName: `${name}_${h}`
371    };
372
373    const oldRefs = ctx.refs;
374    const oldConditionalCode = ctx.conditionalCode;
375    const oldCode = ctx.code;
376    const oldCodeHeader = ctx.codeHeader;
377    const oldCodeFooter = ctx.codeFooter;
378    const oldUniqueNames = ctx.uniqueNames;
379    const oldFileName = ctx.fileName;
380    const oldFilePath = ctx.oldFilePath;
381    const oldReturnSizes = ctx.returnSizes;
382    const oldReturnValue = ctx.returnValue;
383
384
385    ctx.scopes = [{}];
386    ctx.refs = [];
387    ctx.conditionalCode = false;
388    ctx.code = "";
389    ctx.codeHeader = "// Header\n";
390    ctx.codeFooter = "// Footer\n";
391    ctx.uniqueNames = Object.assign({},ctx.globalNames);
392    ctx.returnValue = null;
393    ctx.returnSizes = null;
394    ctx.fileName = ctx.functions[name].fileName;
395    ctx.filePath = ctx.functions[name].filePath;
396
397    let paramsStr = "";
398
399    for (let i=0; i<ctx.functions[name].params.length; i++) {
400
401        if (paramValues[i].used) {
402            paramsStr += `,PBigInt ${ctx.functions[name].params[i]}`;
403            const idRef = ctx.refs.length;
404            ctx.refs.push({
405                type: "BIGINT",
406                used: true,
407                sizes: paramValues[i].sizes,
408                label: ctx.functions[name].params[i],
409            });
410            ctx.scopes[0][ctx.functions[name].params[i]] = idRef;
411        } else {
412            const idRef = ctx.refs.length;
413            ctx.refs.push({
414                type: "BIGINT",
415                used: false,
416                sizes: paramValues[i].sizes,
417                label: ctx.functions[name].params[i],
418                value: paramValues[i].value
419            });
420            ctx.scopes[0][ctx.functions[name].params[i]] = idRef;
421        }
422    }
423
424    createRefs(ctx, ctx.functions[name].block);
425    if (ctx.error) return;
426
427    gen(ctx, ctx.functions[name].block);
428    if (ctx.error) return;
429
430    if (ctx.returnValue == null) {
431        if (ctx.returnSizes ==  null) assert(false, `Funciont ${name} does not return any value`);
432        res.type = "VARVAL_CONSTSIZE";
433        let code =
434            "/*\n" +
435            instanceDef +
436            "\n*/\n" +
437            `void ${name}_${h}(Circom_CalcWit *ctx, PBigInt __retValue ${paramsStr}) {`;
438        code += utils.ident(ctx.codeHeader);
439        code += utils.ident(ctx.code);
440        code += utils.ident("returnFunc:\n");
441        code += utils.ident(ctx.codeFooter);
442        code += "}\n";
443        res.returnSizes = ctx.returnSizes;
444        ctx.functionCodes.push(code);
445    } else {
446        res.type = "CONSTVAL";
447        res.returnValue = ctx.returnValue;
448        res.returnSizes = ctx.returnSizes;
449    }
450
451    ctx.refs = oldRefs;
452    ctx.conditionalCode = oldConditionalCode;
453    ctx.code = oldCode;
454    ctx.codeHeader = oldCodeHeader;
455    ctx.codeFooter = oldCodeFooter;
456    ctx.uniqueNames = oldUniqueNames;
457    ctx.fileName = oldFileName;
458    ctx.filePath = oldFilePath;
459    ctx.returnSizes = oldReturnSizes;
460    ctx.returnValue = oldReturnValue;
461
462    ctx.definedFunctions[h] = res;
463
464    return res;
465}
466
467
468
469function hashComponentCall(ctx, cIdx) {
470    // TODO: At the moment generate a diferent function for each instance of the component
471    const constParams = [];
472    for (let p in ctx.components[cIdx].params) {
473        constParams.push(p + "=" + value2str(ctx.components[cIdx].params[p]));
474    }
475
476    for (let n in ctx.components[cIdx].names.o) {
477        const entry = ctx.components[cIdx].names.o[n];
478        if ((entry.type == "S")&&(ctx.signals[entry.offset].o & ctx.IN)) {
479            travelSizes(n, entry.offset, entry.sizes, (prefix, offset) => {
480                if (utils.isDefined(ctx.signals[offset].v)) {
481                    constParams.push(prefix + "=" + bigInt(ctx.signals[offset].value));
482                }
483            });
484        }
485    }
486
487    let instanceDef = ctx.components[cIdx].template;
488    if (constParams.length>0) {
489        instanceDef += "\n";
490        constParams.sort();
491        instanceDef += constParams.join("\n");
492    }
493    const h = utils.fnvHash(instanceDef);
494    return {h, instanceDef};
495
496    function travelSizes(prefix, offset, sizes, fn) {
497        if (sizes.length == 0) {
498            fn(prefix, offset);
499            return 1;
500        } else {
501            let o = offset;
502            for (let i=0; i<sizes[0]; i++) {
503                o += travelSizes(prefix + "[" + i + "]", o, sizes.slice(1), fn);
504            }
505            return o-offset;
506        }
507    }
508}
509
510function hashFunctionCall(ctx, name, paramValues) {
511    // TODO
512    const constParams = [];
513    for (let i=0; i<ctx.functions[name].params.length; i++) {
514        if (!paramValues[i].used) {
515            constParams.push(ctx.functions[name].params[i] + utils.accSizes2Str(paramValues[i].sizes) + "=" + value2str(paramValues[i].value));
516        }
517    }
518    let instanceDef = name;
519    if (constParams.length>0) {
520        instanceDef += "\n";
521        constParams.sort();
522        instanceDef += constParams.join("\n");
523    }
524
525    const h = utils.fnvHash(instanceDef);
526    return {h, instanceDef};
527}
528
529function value2str(v) {
530    if (Array.isArray(v)) {
531        let S="[";
532        for (let i=0; i<v.length; i++) {
533            if (i>0) S+=",";
534            S+=value2str(v[i]);
535        }
536        S+="]";
537        return S;
538    } else {
539        return bigInt(v).toString();
540    }
541}