arnaucube
arnaucube/circomPublic Self-hosted repository
circom/src/build.js
src/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 utils = require("./utils");
 22const gen = require("./gencode").gen;
 23const createRefs = require("./gencode").createRefs;
 24const BigArray = require("./bigarray");
 25
 26module.exports =  build;
 27
 28
 29function build(ctx) {
 30    ctx.definedFunctions = {};
 31    ctx.functionCodes = [];
 32    ctx.buildFunction = buildFunction;
 33    ctx.conditionalCodeHeader = "";
 34    ctx.codes_sizes = [];
 35    ctx.definedSizes = {};
 36    ctx.addSizes = addSizes;
 37    ctx.addConstant = addConstant;
 38    ctx.addConstant(ctx.F.zero);
 39    ctx.addConstant(ctx.F.one);
 40
 41    if (ctx.verbose) console.log("buildHeader...");
 42    buildHeader(ctx);
 43    if (ctx.verbose) console.log("buildEntryTables...");
 44    buildEntryTables(ctx);
 45    ctx.globalNames = ctx.uniqueNames;
 46
 47    if (ctx.verbose) console.log("buildCode...");
 48    buildCode(ctx);
 49
 50    if (ctx.verbose) console.log("buildComponentsArray...");
 51    buildComponentsArray(ctx);
 52
 53    if (ctx.verbose) console.log("buildMapIsInput...");
 54    buildMapIsInput(ctx);
 55
 56    if (ctx.verbose) console.log("buildWit2Sig...");
 57    buildWit2Sig(ctx);
 58
 59}
 60
 61function buildEntryTables(ctx) {
 62
 63    const definedHashMaps = {};
 64    for (let i=0; i<ctx.components.length; i++) {
 65        if (ctx.verbose && (i%100000 ==0)) console.log(`buildEntryTables component: ${i}/${ctx.components.length}`);
 66        const {htName, htMap} = addHashTable(i);
 67
 68        const componentEntriesTableName = ctx.getUniqueName("_entryTable" + ctx.components[i].template);
 69
 70        const componentEntriesTable = [];
 71        for (let j=0; j<htMap.length; j++) {
 72            const entry = ctx.components[i].names.o[htMap[j]];
 73            const sizeName = ctx.addSizes(entry.sizes);
 74            componentEntriesTable.push({
 75                offset: entry.offset,
 76                sizeName: sizeName,
 77                type: entry.type
 78            });
 79        }
 80
 81        ctx.builder.addComponentEntriesTable(componentEntriesTableName, componentEntriesTable);
 82
 83        ctx.components[i].htName = htName;
 84        ctx.components[i].etName = componentEntriesTableName;
 85    }
 86
 87
 88    return;
 89
 90    function addHashTable(cIdx) {
 91        const keys = Object.keys(ctx.components[cIdx].names.o);
 92        assert(keys.length<128);
 93        keys.sort((a,b) => ((a>b) ? 1 : -1));
 94        const h = utils.fnvHash(keys.join(","));
 95        if (definedHashMaps[h]) return definedHashMaps[h];
 96        definedHashMaps[h] = {};
 97        definedHashMaps[h].htName = ctx.getUniqueName("_ht"+ctx.components[cIdx].template);
 98        definedHashMaps[h].htMap = [];
 99        const t = [];
100        for (let i=0; i<keys.length; i++) {
101            definedHashMaps[h].htMap[i] = keys[i];
102
103            const h2 = utils.fnvHash(keys[i]);
104            let pos = parseInt(h2.slice(-2), 16);
105            while (t[pos]) pos = (pos + 1) % 256;
106            t[pos] = [h2, i, keys[i]];
107        }
108        ctx.builder.addHashMap(definedHashMaps[h].htName, t);
109
110        return definedHashMaps[h];
111    }
112}
113
114function buildCode(ctx) {
115
116    const fDefined = {};
117
118    const fnComponents = [];
119    for (let i=0; i<ctx.components.length; i++) {
120        if (ctx.verbose && (i%100000 ==0)) console.log(`buildCode component: ${i}/${ctx.components.length}`);
121        const {h, instanceDef} = hashComponentCall(ctx, i);
122        const fName = ctx.components[i].template+"_"+h;
123        if (!fDefined[fName]) {
124
125
126            ctx.scopes = [{}];
127            ctx.conditionalCode = false;
128            ctx.fnBuilder = ctx.builder.newComponentFunctionBuilder(fName, instanceDef);
129            ctx.codeBuilder = ctx.fnBuilder.newCodeBuilder();
130            ctx.uniqueNames = Object.assign({},ctx.globalNames);
131            ctx.refs = [];
132            ctx.fileName = ctx.templates[ctx.components[i].template].fileName;
133            ctx.filePath = ctx.templates[ctx.components[i].template].filePath;
134            ctx.getSignalSizesCache = {};
135            ctx.getSignalOffsetCache = {};
136
137            for (let p in ctx.components[i].params) {
138                if (ctx.scopes[0][p]) return ctx.throwError(`Repeated parameter at ${ctx.components[i].template}: ${p}`);
139                const refId = ctx.refs.length;
140                ctx.refs.push({
141                    type: "BIGINT",
142                    used: false,
143                    value: utils.flatArray(ctx.components[i].params[p]),
144                    sizes: utils.accSizes(utils.extractSizes(ctx.components[i].params[p])),
145                    label: ctx.getUniqueName(p)
146                });
147                ctx.scopes[0][p] = refId;
148            }
149
150            createRefs(ctx, ctx.templates[ctx.components[i].template].block);
151            if (ctx.error) return;
152
153            gen(ctx, ctx.templates[ctx.components[i].template].block);
154            if (ctx.error) return;
155
156            ctx.fnBuilder.setBody(ctx.codeBuilder);
157
158            ctx.builder.addFunction(ctx.fnBuilder);
159
160            fDefined[fName] = true;
161        }
162        ctx.components[i].fnName = fName;
163    }
164
165    return fnComponents;
166}
167
168function buildComponentsArray(ctx) {
169    for (let i=0; i< ctx.components.length; i++) {
170        if (ctx.verbose && (i%1000000 ==0)) console.log(`buildComponentsArray component: ${i}/${ctx.components.length}`);
171        let newThread;
172        if (ctx.newThreadTemplates) {
173            if (ctx.newThreadTemplates.test(ctx.components[i].template)) {
174                newThread = true;
175            } else {
176                newThread = false;
177            }
178        } else {
179            newThread = false;
180        }
181        ctx.builder.addComponent({
182            hashMapName: ctx.components[i].htName,
183            entryTableName: ctx.components[i].etName,
184            functionName: ctx.components[i].fnName,
185            nInSignals: ctx.components[i].nInSignals,
186            newThread: newThread
187        });
188    }
189}
190
191
192function buildHeader(ctx) {
193    ctx.builder.setHeader({
194        NSignals: ctx.signals.length,
195        NComponents: ctx.components.length,
196        NInputs: ctx.components[ ctx.getComponentIdx("main") ].nInSignals,
197        NOutputs: ctx.totals[ ctx.stOUTPUT ],
198        NVars: ctx.totals[ctx.stONE] + ctx.totals[ctx.stOUTPUT] + ctx.totals[ctx.stPUBINPUT] + ctx.totals[ctx.stPRVINPUT] + ctx.totals[ctx.stINTERNAL],
199        P: ctx.F.p
200    });
201}
202
203function buildMapIsInput(ctx) {
204    let i;
205    let map = [];
206    let acc = 0;
207    for (i=0; i<ctx.signals.length; i++) {
208        if (ctx.verbose && (i%1000000 ==0)) console.log(`buildMapIsInput signal: ${i}/${ctx.signals.length}`);
209        if (ctx.signals[i].o & ctx.IN) {
210            acc = acc | (1 << (i%32) );
211        }
212        if ((i+1)%32==0) {
213            map.push(acc);
214            acc = 0;
215        }
216    }
217    if ((i%32) != 0) {
218        map.push(acc);
219    }
220
221    ctx.builder.setMapIsInput(map);
222}
223
224
225
226function buildWit2Sig(ctx) {
227    const NVars =
228        ctx.totals[ctx.stONE] +
229        ctx.totals[ctx.stOUTPUT] +
230        ctx.totals[ctx.stPUBINPUT] +
231        ctx.totals[ctx.stPRVINPUT] +
232        ctx.totals[ctx.stINTERNAL];
233    const arr = new BigArray(NVars);
234    for (let i=0; i<ctx.signals.length; i++) {
235        if (ctx.verbose && (i%1000000 ==0)) console.log(`buildWit2Sig signal: ${i}/${ctx.signals.length}`);
236        const outIdx = ctx.signals[i].id;
237        if (ctx.signals[i].e>=0) continue;     // If has an alias, continue..
238        assert(typeof outIdx  != "undefined", `Signal ${i} does not have index`);
239        if (outIdx>=NVars) continue; // Is a constant or a discarded variable
240        if (typeof arr[ctx.signals[i].id] == "undefined") {
241            arr[outIdx] = i;
242        }
243    }
244
245    ctx.builder.setWit2Sig(arr);
246}
247
248
249
250function addSizes(_sizes) {
251    const sizes = _sizes || [];
252    let name = "sizes";
253    for (let i=0; i<sizes.length;i++) {
254        name+="_"+sizes[i];
255    }
256    if (name=="sizes") name="sizes_0";
257
258    if (this.definedSizes[name]) return this.definedSizes[name];
259    const labelName = this.getUniqueName(name);
260    this.definedSizes[name] = labelName;
261
262    const accSizes = utils.accSizes(sizes);
263
264    this.builder.addSizes(labelName, accSizes);
265
266    let code = `Circom_Size ${labelName}[${accSizes.length}] = {`;
267    for (let i=0; i<accSizes.length; i++) {
268        if (i>0) code += ",";
269        code += accSizes[i];
270    }
271    code += "};\n";
272    this.codes_sizes.push(code);
273
274    return labelName;
275}
276
277function addConstant(c) {
278    return this.builder.addConstant(c);
279}
280
281function buildFunction(name, paramValues) {
282    const ctx = this;
283    const {h, instanceDef} = hashFunctionCall(ctx, name, paramValues);
284
285    if (ctx.definedFunctions[h]) return ctx.definedFunctions[h];
286
287    const res = {
288        fnName: `${name}_${h}`
289    };
290
291    const oldRefs = ctx.refs;
292    const oldConditionalCode = ctx.conditionalCode;
293    const oldCodeBuilder = ctx.codeBuilder;
294    const oldFnBuilder = ctx.fnBuilder;
295
296    const oldUniqueNames = ctx.uniqueNames;
297    const oldFileName = ctx.fileName;
298    const oldFilePath = ctx.oldFilePath;
299    const oldReturnSizes = ctx.returnSizes;
300    const oldReturnValue = ctx.returnValue;
301
302
303    ctx.scopes = [{}];
304    ctx.refs = [];
305    ctx.conditionalCode = false;
306    ctx.fnBuilder = ctx.builder.newFunctionBuilder(`${name}_${h}`, instanceDef, ctx.functions[name].params);
307    ctx.codeBuilder = ctx.fnBuilder.newCodeBuilder();
308    ctx.uniqueNames = Object.assign({},ctx.globalNames);
309    ctx.returnValue = null;
310    ctx.returnSizes = null;
311    ctx.fileName = ctx.functions[name].fileName;
312    ctx.filePath = ctx.functions[name].filePath;
313
314    let paramLabels = [];
315
316    for (let i=0; i<ctx.functions[name].params.length; i++) {
317
318        if (paramValues[i].used) {
319            paramLabels.push(ctx.functions[name].params[i]);
320            const idRef = ctx.refs.length;
321            ctx.refs.push({
322                type: "BIGINT",
323                used: true,
324                sizes: paramValues[i].sizes,
325                label: ctx.functions[name].params[i],
326            });
327            ctx.scopes[0][ctx.functions[name].params[i]] = idRef;
328        } else {
329            const idRef = ctx.refs.length;
330            ctx.refs.push({
331                type: "BIGINT",
332                used: false,
333                sizes: paramValues[i].sizes,
334                label: ctx.functions[name].params[i],
335                value: paramValues[i].value
336            });
337            ctx.scopes[0][ctx.functions[name].params[i]] = idRef;
338        }
339    }
340
341    ctx.fnBuilder.setParams(paramLabels);
342
343    createRefs(ctx, ctx.functions[name].block);
344    if (ctx.error) return;
345
346    gen(ctx, ctx.functions[name].block);
347    if (ctx.error) return;
348
349    if (ctx.returnValue == null) {
350        if (ctx.returnSizes ==  null) assert(false, `Funciont ${name} does not return any value`);
351
352        ctx.fnBuilder.setBody(ctx.codeBuilder);
353        ctx.builder.addFunction(ctx.fnBuilder);
354
355        res.type = "VARVAL_CONSTSIZE";
356        res.returnSizes = ctx.returnSizes;
357    } else {
358        res.type = "CONSTVAL";
359        res.returnValue = ctx.returnValue;
360        res.returnSizes = ctx.returnSizes;
361    }
362
363    ctx.refs = oldRefs;
364    ctx.conditionalCode = oldConditionalCode;
365    ctx.codeBuilder = oldCodeBuilder;
366    ctx.fnBuilder = oldFnBuilder;
367    ctx.uniqueNames = oldUniqueNames;
368    ctx.fileName = oldFileName;
369    ctx.filePath = oldFilePath;
370    ctx.returnSizes = oldReturnSizes;
371    ctx.returnValue = oldReturnValue;
372
373    ctx.definedFunctions[h] = res;
374
375    return res;
376}
377
378
379function hashComponentCall(ctx, cIdx) {
380    // TODO: At the moment generate a diferent function for each instance of the component
381    const constParams = [];
382    for (let p in ctx.components[cIdx].params) {
383        constParams.push(p + "=" + value2str(ctx.F, ctx.components[cIdx].params[p]));
384    }
385
386    for (let n in ctx.components[cIdx].names.o) {
387        const entry = ctx.components[cIdx].names.o[n];
388        if ((entry.type == "S")&&(ctx.signals[entry.offset].o & ctx.IN)) {
389            travelSizes(n, entry.offset, entry.sizes, (prefix, offset) => {
390                if (utils.isDefined(ctx.signals[offset].v)) {
391                    constParams.push(prefix + "=" + ctx.F.e(ctx.signals[offset].v));
392                }
393            });
394        }
395    }
396
397    let instanceDef = ctx.components[cIdx].template;
398    if (constParams.length>0) {
399        instanceDef += "\n";
400        constParams.sort();
401        instanceDef += constParams.join("\n");
402    }
403    const h = utils.fnvHash(instanceDef);
404    return {h, instanceDef};
405
406    function travelSizes(prefix, offset, sizes, fn) {
407        if (sizes.length == 0) {
408            fn(prefix, offset);
409            return 1;
410        } else {
411            let o = offset;
412            for (let i=0; i<sizes[0]; i++) {
413                o += travelSizes(prefix + "[" + i + "]", o, sizes.slice(1), fn);
414            }
415            return o-offset;
416        }
417    }
418}
419
420function hashFunctionCall(ctx, name, paramValues) {
421    // TODO
422    const constParams = [];
423    for (let i=0; i<ctx.functions[name].params.length; i++) {
424        if (!paramValues[i].used) {
425            constParams.push(ctx.functions[name].params[i] + utils.accSizes2Str(paramValues[i].sizes) + "=" + value2str(ctx.F, paramValues[i].value));
426        }
427    }
428    let instanceDef = name;
429    if (constParams.length>0) {
430        instanceDef += "\n";
431        constParams.sort();
432        instanceDef += constParams.join("\n");
433    }
434
435    const h = utils.fnvHash(instanceDef);
436    return {h, instanceDef};
437}
438
439function value2str(F, v) {
440    if (Array.isArray(v)) {
441        let S="[";
442        for (let i=0; i<v.length; i++) {
443            if (i>0) S+=",";
444            S+=value2str(F, v[i]);
445        }
446        S+="]";
447        return S;
448    } else {
449        return F.toString(F.e(v));
450    }
451}