arnaucube
arnaucube/circomPublic Self-hosted repository
circom/ports/c/builder.js
ports/c/builder.jsRaw
  1const streamFromMultiArray = require("../../src/streamfromarray_txt.js");
  2const utils = require("../../src/utils");
  3const assert = require("assert");
  4const Scalar = require("ffjavascript").Scalar;
  5const F1Field = require("ffjavascript").F1Field;
  6
  7function ref2src(c) {
  8    if ((c[0] == "R")||(c[0] == "RI")) {
  9        return c[1];
 10    } else if (c[0] == "V") {
 11        return c[1].toString();
 12    } else if (c[0] == "C") {
 13        return `(ctx->circuit->constants + ${c[1]})`;
 14    } else if (c[0] == "CC") {
 15        return "__cIdx";
 16    } else {
 17        assert(false);
 18    }
 19}
 20
 21class CodeBuilderC {
 22    constructor() {
 23        this.ops = [];
 24    }
 25
 26    addComment(comment) {
 27        this.ops.push({op: "COMMENT", comment});
 28    }
 29
 30    addBlock(block) {
 31        this.ops.push({op: "BLOCK", block});
 32    }
 33
 34    calcOffset(dLabel, offsets) {
 35        this.ops.push({op: "CALCOFFSETS", dLabel, offsets});
 36    }
 37
 38    assign(dLabel, src, sOffset) {
 39        this.ops.push({op: "ASSIGN", dLabel, src, sOffset});
 40    }
 41
 42    getSubComponentOffset(dLabel, component, hash, hashLabel) {
 43        this.ops.push({op: "GETSUBCOMPONENTOFFSET", dLabel, component, hash, hashLabel});
 44    }
 45
 46    getSubComponentSizes(dLabel, component, hash, hashLabel) {
 47        this.ops.push({op: "GETSUBCOMPONENTSIZES", dLabel, component, hash, hashLabel});
 48    }
 49
 50    getSignalOffset(dLabel, component, hash, hashLabel) {
 51        this.ops.push({op: "GETSIGNALOFFSET", dLabel, component, hash, hashLabel});
 52    }
 53
 54    getSignalSizes(dLabel, component, hash, hashLabel) {
 55        this.ops.push({op: "GETSIGNALSIZES", dLabel, component, hash, hashLabel});
 56    }
 57
 58    setSignal(component, signal, value) {
 59        this.ops.push({op: "SETSIGNAL", component, signal, value});
 60    }
 61
 62    getSignal(dLabel, component, signal) {
 63        this.ops.push({op: "GETSIGNAL", dLabel, component, signal});
 64    }
 65
 66    copyN(dLabel, offset, src, n) {
 67        this.ops.push({op: "COPYN", dLabel, offset, src, n});
 68    }
 69
 70    copyNRet(src, n) {
 71        this.ops.push({op: "COPYNRET", src, n});
 72    }
 73
 74    fieldOp(dLabel, fOp, params) {
 75        this.ops.push({op: "FOP", dLabel, fOp, params});
 76    }
 77
 78    ret() {
 79        this.ops.push({op: "RET"});
 80    }
 81
 82    addLoop(condLabel, body) {
 83        this.ops.push({op: "LOOP", condLabel, body});
 84    }
 85
 86    addIf(condLabel, thenCode, elseCode) {
 87        this.ops.push({op: "IF", condLabel, thenCode, elseCode});
 88    }
 89
 90    fnCall(fnName, retLabel, params) {
 91        this.ops.push({op: "FNCALL", fnName, retLabel, params});
 92    }
 93
 94    checkConstraint(a, b, strErr) {
 95        this.ops.push({op: "CHECKCONSTRAINT", a, b, strErr});
 96    }
 97
 98    log(val) {
 99        this.ops.push({op: "LOG", val});
100    }
101
102    concat(cb) {
103        this.ops.push(...cb.ops);
104    }
105
106    hasCode() {
107        for (let i=0; i<this.ops.length; i++) {
108            if (this.ops[i].op != "COMMENT") return true;
109        }
110        return false;
111    }
112
113    _buildOffset(offsets) {
114        let rN=0;
115        let S = "";
116        offsets.forEach((o) => {
117            if ((o[0][0] == "V") && (o[1][0]== "V")) {
118                rN += o[0][1]*o[1][1];
119                return;
120            }
121            let f="";
122            if (o[0][0] == "V") {
123                if (o[0][1]==0) return;
124                f += o[0][1];
125            } else if (o[0][0] == "RI") {
126                if (o[0][1]==0) return;
127                f += o[0][1];
128            } else if (o[0][0] == "R") {
129                f += `Fr_toInt(${o[0][1]})`;
130            } else {
131                assert(false);
132            }
133            if (o[1][0] == "V") {
134                if (o[1][1]==0) return;
135                if (o[1][1]>1) {
136                    f += "*" + o[1][1];
137                }
138            } else if (o[1][0] == "RS") {
139                f += `*${o[1][1]}[${o[1][2]}]`;
140            } else {
141                assert(false);
142            }
143            if (S!="") S+= " + ";
144            S += f;
145        });
146        if (rN>0) {
147            S = `${rN} + ${S}`;
148        }
149        return S;
150    }
151
152    build(code) {
153        this.ops.forEach( (o) => {
154            if (o.op == "COMMENT") {
155                code.push(`/* ${o.comment} */`);
156            } else if (o.op == "BLOCK") {
157                const codeBlock=[];
158                o.block.build(codeBlock);
159                code.push(utils.ident(codeBlock));
160            } else if (o.op == "CALCOFFSETS") {
161                code.push(`${o.dLabel} = ${this._buildOffset(o.offsets)};`);
162            } else if (o.op == "ASSIGN") {
163                const oS = ref2src(o.sOffset);
164                if (oS != "0") {
165                    code.push(`${o.dLabel} = ${ref2src(o.src)} + ${oS};`);
166                } else {
167                    code.push(`${o.dLabel} = ${ref2src(o.src)};`);
168                }
169            } else if (o.op == "GETSUBCOMPONENTOFFSET") {
170                code.push(`${o.dLabel} = ctx->getSubComponentOffset(${ref2src(o.component)}, 0x${o.hash}LL /* ${o.hashLabel} */);`);
171            } else if (o.op == "GETSUBCOMPONENTSIZES") {
172                code.push(`${o.dLabel} = ctx->getSubComponentSizes(${ref2src(o.component)}, 0x${o.hash}LL /* ${o.hashLabel} */);`);
173            } else if (o.op == "GETSIGNALOFFSET") {
174                code.push(`${o.dLabel} = ctx->getSignalOffset(${ref2src(o.component)}, 0x${o.hash}LL /* ${o.hashLabel} */);`);
175            } else if (o.op == "GETSIGNALSIZES") {
176                code.push(`${o.dLabel} = ctx->getSignalSizes(${ref2src(o.component)}, 0x${o.hash}LL /* ${o.hashLabel} */);`);
177            } else if (o.op == "SETSIGNAL") {
178                code.push(`ctx->setSignal(__cIdx, ${ref2src(o.component)}, ${ref2src(o.signal)}, ${ref2src(o.value)});`);
179            } else if (o.op == "GETSIGNAL") {
180                code.push(`ctx->getSignal(__cIdx, ${ref2src(o.component)}, ${ref2src(o.signal)}, ${o.dLabel});`);
181            } else if (o.op == "COPYN") {
182                const oS = ref2src(o.offset);
183                const dLabel = (oS != "0") ? (o.dLabel + "+" + oS) : o.dLabel;
184                code.push(`Fr_copyn(${dLabel}, ${ref2src(o.src)}, ${o.n});`);
185            } else if (o.op == "COPYNRET") {
186                code.push(`Fr_copyn(__retValue, ${ref2src(o.src)}, ${o.n});`);
187            } else if (o.op == "RET") {
188                code.push("goto returnFunc;");
189            } else if (o.op == "FOP") {
190                let paramsS = "";
191                for (let i=0; i<o.params.length; i++) {
192                    if (i>0) paramsS += ", ";
193                    paramsS += ref2src(o.params[i]);
194                }
195                code.push(`Fr_${o.fOp}(${o.dLabel}, ${paramsS});`);
196            } else if (o.op == "LOOP") {
197                code.push(`while (Fr_isTrue(${o.condLabel})) {`);
198                const body = [];
199                o.body.build(body);
200                code.push(utils.ident(body));
201                code.push("}");
202            } else if (o.op == "IF") {
203                code.push(`if (Fr_isTrue(${o.condLabel})) {`);
204                const thenCode = [];
205                o.thenCode.build(thenCode);
206                code.push(utils.ident(thenCode));
207                if (o.elseCode) {
208                    code.push("} else {");
209                    const elseCode = [];
210                    o.elseCode.build(elseCode);
211                    code.push(utils.ident(elseCode));
212                }
213                code.push("}");
214            } else if (o.op == "FNCALL") {
215                code.push(`${o.fnName}(ctx, ${o.retLabel}, ${o.params.join(",")});`);
216            } else if (o.op == "CHECKCONSTRAINT") {
217                code.push(`ctx->checkConstraint(__cIdx, ${ref2src(o.a)}, ${ref2src(o.b)}, "${o.strErr}");`);
218            } else if (o.op == "LOG") {
219                code.push(`ctx->log(${ref2src(o.val)});`);
220            }
221        });
222    }
223}
224
225class FunctionBuilderC {
226
227    constructor(name, instanceDef, type) {
228        this.name = name;
229        this.instanceDef = instanceDef;
230        this.type = type; // "COMPONENT" or "FUNCTIOM"
231        this.definedFrElements = [];
232        this.definedIntElements = [];
233        this.definedSizeElements = [];
234        this.definedPFrElements = [];
235        this.initializedElements = [];
236        this.initializedSignalOffset = [];
237        this.initializedSignalSizes = [];
238
239    }
240
241    defineFrElements(dLabel, size) {
242        this.definedFrElements.push({dLabel, size});
243    }
244
245    defineIntElement(dLabel) {
246        this.definedIntElements.push({dLabel});
247    }
248
249    defineSizesElement(dLabel) {
250        this.definedSizeElements.push({dLabel});
251    }
252
253    definePFrElement(dLabel) {
254        this.definedPFrElements.push({dLabel});
255    }
256
257    initializeFrElement(dLabel, offset, idConstant) {
258        this.initializedElements.push({dLabel, offset, idConstant});
259    }
260
261    initializeSignalOffset(dLabel, component, hash, hashLabel) {
262        this.initializedSignalOffset.push({dLabel, component, hash, hashLabel});
263    }
264
265    initializeSignalSizes(dLabel, component, hash, hashLabel) {
266        this.initializedSignalSizes.push({dLabel, component, hash, hashLabel});
267    }
268
269    setParams(params) {
270        this.params = params;
271    }
272
273    _buildHeader(code) {
274        this.definedFrElements.forEach( (o) => {
275            code.push(`FrElement ${o.dLabel}[${o.size}];`);
276        });
277        this.definedIntElements.forEach( (o) => {
278            code.push(`int ${o.dLabel};`);
279        });
280        this.definedSizeElements.forEach( (o) => {
281            code.push(`Circom_Sizes ${o.dLabel};`);
282        });
283        this.definedPFrElements.forEach( (o) => {
284            code.push(`PFrElement ${o.dLabel};`);
285        });
286        this.initializedElements.forEach( (o) => {
287            code.push(`Fr_copy(&(${o.dLabel}[${o.offset}]), ctx->circuit->constants +${o.idConstant});`);
288        });
289        this.initializedSignalOffset.forEach( (o) => {
290            code.push(`${o.dLabel} = ctx->getSignalOffset(${ref2src(o.component)}, 0x${o.hash}LL /* ${o.hashLabel} */);`);
291        });
292        this.initializedSignalSizes.forEach( (o) => {
293            code.push(`${o.dLabel} = ctx->getSignalSizes(${ref2src(o.component)}, 0x${o.hash}LL /* ${o.hashLabel} */);`);
294        });
295    }
296
297    _buildFooter(code) {
298    }
299
300    newCodeBuilder() {
301        return new CodeBuilderC();
302    }
303
304    setBody(body) {
305        this.body = body;
306    }
307
308    build(code) {
309        code.push(
310            "/*",
311            this.instanceDef,
312            "*/"
313        );
314
315        if (this.type=="COMPONENT") {
316            code.push(`void ${this.name}(Circom_CalcWit *ctx, int __cIdx) {`);
317        } else if (this.type=="FUNCTION") {
318            let sParams = "";
319            for (let i=0;i<this.params.length;i++ ) sParams += `, PFrElement ${this.params[i]}`;
320            code.push(`void ${this.name}(Circom_CalcWit *ctx, PFrElement __retValue ${sParams}) {`);
321        } else {
322            assert(false);
323        }
324
325        const fnCode = [];
326        this._buildHeader(fnCode);
327        this.body.build(fnCode);
328        if (this.type=="COMPONENT") {
329            fnCode.push("ctx->finished(__cIdx);");
330        } else if (this.type=="FUNCTION") {
331            fnCode.push("returnFunc: ;");
332        } else {
333            assert(false);
334        }
335        this._buildFooter(fnCode);
336
337        code.push(utils.ident(fnCode));
338        code.push("}");
339    }
340
341}
342
343class BuilderC {
344    constructor(p) {
345        this.F = new F1Field(p);
346
347        this.hashMaps={};
348        this.componentEntriesTables={};
349        this.sizes ={};
350        this.constants = [];
351        this.functions = [];
352        this.components = [];
353        this.usedConstants = {};
354    }
355
356    setHeader(header) {
357        this.header=header;
358    }
359
360    // ht is an array of 256 element that can be undefined or [Hash, Idx, KeyName] elements.
361    addHashMap(name, hm) {
362        this.hashMaps[name] = hm;
363    }
364
365    addComponentEntriesTable(name, cet) {
366        this.componentEntriesTables[name] = cet;
367    }
368
369    addSizes(name, accSizes) {
370        this.sizes[name] = accSizes;
371    }
372
373    addConstant(c) {
374        c = this.F.e(c);
375        const cS = c.toString();
376        if (typeof this.usedConstants[cS] != "undefined") return this.usedConstants[cS];
377        this.constants.push(c);
378        this.usedConstants[cS] = this.constants.length - 1;
379        return this.constants.length - 1;
380    }
381
382    addFunction(fnBuilder) {
383        this.functions.push(fnBuilder);
384    }
385
386    addComponent(component) {
387        this.components.push(component);
388    }
389
390    setMapIsInput(map) {
391        this.mapIsInput = map;
392    }
393
394    setWit2Sig(wit2sig) {
395        this.wit2sig = wit2sig;
396    }
397
398
399    newComponentFunctionBuilder(name, instanceDef) {
400        return new FunctionBuilderC(name, instanceDef, "COMPONENT");
401    }
402
403    newFunctionBuilder(name, instanceDef) {
404        return new FunctionBuilderC(name, instanceDef, "FUNCTION");
405    }
406
407
408    // Body functions
409
410    _buildHeader(code) {
411        code.push(
412            "#include \"circom.h\"",
413            "#include \"calcwit.h\"",
414            `#define NSignals ${this.header.NSignals}`,
415            `#define NComponents ${this.header.NComponents}`,
416            `#define NOutputs ${this.header.NOutputs}`,
417            `#define NInputs ${this.header.NInputs}`,
418            `#define NVars ${this.header.NVars}`,
419            `#define __P__ "${this.header.P.toString()}"`,
420            ""
421        );
422    }
423
424    _buildHashMaps(code) {
425
426        code.push("// Hash Maps ");
427        for (let hmName in this.hashMaps ) {
428            const hm = this.hashMaps[hmName];
429
430            let c = `Circom_HashEntry ${hmName}[256] = {`;
431            for (let i=0; i<256; i++) {
432                c += i>0 ? "," : "";
433                if (hm[i]) {
434                    c += `{0x${hm[i][0]}LL, ${hm[i][1]}} /* ${hm[i][2]} */`;
435                } else {
436                    c += "{0,0}";
437                }
438            }
439            c += "};";
440            code.push(c);
441        }
442
443    }
444
445    _buildComponentEntriesTables(code) {
446        code.push("// Component Entry tables");
447        for (let cetName in this.componentEntriesTables) {
448            const cet = this.componentEntriesTables[cetName];
449
450            code.push(`Circom_ComponentEntry ${cetName}[${cet.length}] = {`);
451            for (let j=0; j<cet.length; j++) {
452                const ty = cet[j].type == "S" ? "_typeSignal" : "_typeComponent";
453                code.push(`    ${j>0?",":" "}{${cet[j].offset},${cet[j].sizeName}, ${ty}}`);
454            }
455            code.push("};");
456        }
457    }
458
459    _buildSizes(code) {
460        code.push("// Sizes");
461        for (let sName in this.sizes) {
462            const accSizes = this.sizes[sName];
463
464            let c = `Circom_Size ${sName}[${accSizes.length}] = {`;
465            for (let i=0; i<accSizes.length; i++) {
466                if (i>0) c += ",";
467                c += accSizes[i];
468            }
469            c += "};";
470            code.push(c);
471        }
472    }
473
474    _buildConstants(code) {
475        const self = this;
476
477        code.push("// Constants");
478        code.push(`FrElement _constants[${self.constants.length}] = {`);
479        for (let i=0; i<self.constants.length; i++) {
480            code.push((i>0 ? "," : " ") + "{" + number2Code(self.constants[i]) + "}");
481        }
482        code.push("};");
483
484        function number2Code(n) {
485            const minShort = self.F.neg(self.F.e("80000000"));
486            const maxShort = self.F.e("7FFFFFFF", 16);
487
488            if (  (self.F.geq(n, minShort))
489                &&(self.F.leq(n, maxShort)))
490            {
491                if (self.F.geq(n, self.F.zero)) {
492                    return addShortMontgomeryPositive(n);
493                } else {
494                    return addShortMontgomeryNegative(n);
495                }
496            }
497
498            return addLongMontgomery(n);
499
500
501            function addShortMontgomeryPositive(a) {
502                return `${a.toString()}, 0x40000000, { ${getLongString(toMontgomery(a))} }`;
503            }
504
505
506            function addShortMontgomeryNegative(a) {
507                const b = -Scalar.toNumber(self.F.neg(a));
508                return `${b.toString()}, 0x40000000, { ${getLongString(toMontgomery(a))} }`;
509            }
510
511            function addLongMontgomery(a) {
512                return `0, 0xC0000000, { ${getLongString(toMontgomery(a))} }`;
513            }
514
515            function getLongString(a) {
516                let S = "";
517                const arr = Scalar.toArray(a, 0x100000000);
518                for (let i=0; i<self.F.n64*2; i+=2) {
519                    const idx = arr.length-2-i;
520
521                    if (i>0) S = S + ",";
522
523                    if ( idx >=0) {
524                        let msb = arr[idx].toString(16);
525                        while (msb.length<8) msb = "0" + msb;
526
527                        let lsb = arr[idx+1].toString(16);
528                        while (lsb.length<8) lsb = "0" + lsb;
529
530                        S += "0x" + msb + lsb + "LL";
531                    } else {
532                        S += "0LL";
533                    }
534                }
535
536                return S;
537            }
538
539            function toMontgomery(a) {
540                return self.F.mul(a, self.F.R);
541            }
542
543        }
544    }
545
546    _buildFunctions(code) {
547        for (let i=0; i<this.functions.length; i++) {
548            const cfb = this.functions[i];
549            cfb.build(code);
550        }
551    }
552
553    _buildComponents(code) {
554        code.push("// Components");
555        code.push(`Circom_Component _components[${this.components.length}] = {`);
556        for (let i=0; i<this.components.length; i++) {
557            const c = this.components[i];
558            const sep = i>0 ? "    ," : "     ";
559            code.push(`${sep}{${c.hashMapName}, ${c.entryTableName}, ${c.functionName}, ${c.nInSignals}, ${c.newThread}}`);
560        }
561        code.push("};");
562    }
563
564    _buildMapIsInput(code) {
565        code.push("// mapIsInput");
566        code.push(`u32 _mapIsInput[${this.mapIsInput.length}] = {`);
567        let line = "";
568        for (let i=0; i<this.mapIsInput.length; i++) {
569            line += i>0 ? ", " : "  ";
570            line += toHex(this.mapIsInput[i]);
571            if (((i+1) % 64)==0) {
572                code.push("    "+line);
573                line = "";
574            }
575        }
576        if (line != "") code.push("    "+line);
577        code.push("};");
578
579        function toHex(number) {
580            if (number < 0) number = 0xFFFFFFFF + number + 1;
581            let S=number.toString(16).toUpperCase();
582            while (S.length<8) S = "0" + S;
583            return "0x"+S;
584        }
585    }
586
587    _buildWit2Sig(code) {
588        code.push("// Witness to Signal Table");
589        code.push(`int _wit2sig[${this.wit2sig.length}] = {`);
590        let line = "";
591        for (let i=0; i<this.wit2sig.length; i++) {
592            line += i>0 ? "," : " ";
593            line += this.wit2sig[i];
594            if (((i+1) % 64) == 0) {
595                code.push("    "+line);
596                line = "";
597            }
598        }
599        if (line != "") code.push("    "+line);
600        code.push("};");
601    }
602
603    _buildCircuitVar(code) {
604
605        code.push(
606            "// Circuit Variable",
607            "Circom_Circuit _circuit = {" ,
608            "   NSignals,",
609            "   NComponents,",
610            "   NInputs,",
611            "   NOutputs,",
612            "   NVars,",
613            "   _wit2sig,",
614            "   _components,",
615            "   _mapIsInput,",
616            "   _constants,",
617            "   __P__",
618            "};"
619        );
620    }
621
622
623    build() {
624        const code=[];
625        this._buildHeader(code);
626        this._buildSizes(code);
627        this._buildConstants(code);
628        this._buildHashMaps(code);
629        this._buildComponentEntriesTables(code);
630        this._buildFunctions(code);
631        this._buildComponents(code);
632        this._buildMapIsInput(code);
633        this._buildWit2Sig(code);
634        this._buildCircuitVar(code);
635        return streamFromMultiArray(code);
636    }
637}
638
639
640module.exports = BuilderC;