You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

640 lines
19 KiB

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