circom/c/buildasm/buildzqfield.js
c/buildasm/buildzqfield.jsRaw
1const bigInt=require("big-integer");
2const path = require("path");
3const util = require("util");
4const renderFile = util.promisify(require("ejs").renderFile);
5
6const runningAsScript = !module.parent;
7
8
9class ZqBuilder {
10 constructor(q, name) {
11 const self = this;
12 this.q=bigInt(q);
13 this.n64 = Math.floor((this.q.bitLength() - 1) / 64)+1;
14 this.name = name;
15 this.bigInt = bigInt;
16 this.lastTmp=0;
17 this.global = {};
18 this.global.tmpLabel = function(label) {
19 self.lastTmp++;
20 label = label || "tmp";
21 return label+"_"+self.lastTmp;
22 };
23 }
24
25 constantElement(v) {
26 let S = "";
27 const mask = bigInt("FFFFFFFFFFFFFFFF", 16);
28 for (let i=0; i<this.n64; i++) {
29 if (i>0) S = S+",";
30 let shex = v.shiftRight(i*64).and(mask).toString(16);
31 while (shex.length <16) shex = "0" + shex;
32 S = S + "0x" + shex;
33 }
34 return S;
35 }
36
37}
38
39async function buildField(q, name) {
40 const builder = new ZqBuilder(q, name);
41
42 const asm = await renderFile(path.join(__dirname, "fr.asm.ejs"), builder);
43 const c = await renderFile(path.join(__dirname, "fr.c.ejs"), builder);
44 const h = await renderFile(path.join(__dirname, "fr.h.ejs"), builder);
45
46 return {asm: asm, h: h, c: c};
47}
48
49if (runningAsScript) {
50 const fs = require("fs");
51 var argv = require("yargs")
52 .usage("Usage: $0 -q [primeNum] -n [name] -oc [out .c file] -oh [out .h file]")
53 .demandOption(["q","n"])
54 .alias("q", "prime")
55 .alias("n", "name")
56 .argv;
57
58 const q = bigInt(argv.q);
59
60 const asmFileName = (argv.oc) ? argv.oc : argv.name.toLowerCase() + ".asm";
61 const hFileName = (argv.oc) ? argv.oc : argv.name.toLowerCase() + ".h";
62 const cFileName = (argv.oc) ? argv.oc : argv.name.toLowerCase() + ".c";
63
64 buildField(q, argv.name).then( (res) => {
65 fs.writeFileSync(asmFileName, res.asm, "utf8");
66 fs.writeFileSync(hFileName, res.h, "utf8");
67 fs.writeFileSync(cFileName, res.c, "utf8");
68 });
69
70} else {
71 module.exports = buildField;
72}