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.

234 lines
7.0 KiB

2 years ago
2 years ago
  1. const chai = require("chai");
  2. const assert = chai.assert;
  3. const fs = require("fs");
  4. var tmp = require("tmp-promise");
  5. const path = require("path");
  6. const util = require("util");
  7. const exec = util.promisify(require("child_process").exec);
  8. const loadR1cs = require("r1csfile").load;
  9. const ZqField = require("ffjavascript").ZqField;
  10. const readWtns = require("snarkjs").wtns.exportJson;
  11. module.exports = c_tester;
  12. async function c_tester(circomInput, _options) {
  13. assert(await compiler_above_version("2.0.0"),"Wrong compiler version. Must be at least 2.0.0");
  14. tmp.setGracefulCleanup();
  15. const dir = await tmp.dir({prefix: "circom_", unsafeCleanup: true });
  16. // console.log(dir.path);
  17. const baseName = path.basename(circomInput, ".circom");
  18. const options = Object.assign({}, _options);
  19. options.wasm = true;
  20. options.sym = true;
  21. options.json = options.json || false; // costraints in json format
  22. //options.r1cs = options.r1cs || false; // costraints in r1cs format
  23. //if (!options.json) options.r1cs = true; // r1cs if not json
  24. options.r1cs = true;
  25. options.output = dir.path;
  26. await compile(baseName, circomInput, options);
  27. return new WasmTester(dir, baseName, run);
  28. }
  29. async function compile (baseName, fileName, options) {
  30. var flags = "--c ";
  31. if (options.sym) flags += "--sym ";
  32. if (options.r1cs) flags += "--r1cs ";
  33. if (options.json) flags += "--json ";
  34. if (options.output) flags += "--output " + options.output + " ";
  35. if (options.O === 0) flags += "--O0 "
  36. if (options.O === 1) flags += "--O1 "
  37. b = await exec("circom " + flags + fileName);
  38. assert(b.stderr == "",
  39. "circom compiler error \n" + b.stderr);
  40. const c_folder = path.join(options.output, baseName+"_cpp/")
  41. b = await exec("make -C "+c_folder);
  42. assert(b.stderr == "",
  43. "error building the executable C program\n" + b.stderr);
  44. }
  45. class WasmTester {
  46. constructor(dir, baseName, witnessCalculator) {
  47. this.dir=dir;
  48. this.baseName = baseName;
  49. this.witnessCalculator = witnessCalculator;
  50. }
  51. async release() {
  52. await this.dir.cleanup();
  53. }
  54. async calculateWitness(input) {
  55. const inputjson = JSON.stringify(input);
  56. const inputFile = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName + ".json");
  57. const wtnsFile = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName + ".wtns");
  58. const runc = path.join(this.dir.path, this.baseName+"_cpp/" + this.baseName);
  59. fs.writeFile(inputFile, inputjson, function(err) {
  60. if (err) throw err;
  61. });
  62. await exec("ls " + path.join(this.dir.path, this.baseName+"_cpp/"));
  63. await exec(runc + " " + inputFile + " " + wtnsFile);
  64. return await readBinWitnessFile(wtnsFile);
  65. }
  66. async loadSymbols() {
  67. if (this.symbols) return;
  68. this.symbols = {};
  69. const symsStr = await fs.promises.readFile(
  70. path.join(this.dir.path, this.baseName + ".sym"),
  71. "utf8"
  72. );
  73. const lines = symsStr.split("\n");
  74. for (let i=0; i<lines.length; i++) {
  75. const arr = lines[i].split(",");
  76. if (arr.length!=4) continue;
  77. this.symbols[arr[3]] = {
  78. labelIdx: Number(arr[0]),
  79. varIdx: Number(arr[1]),
  80. componentIdx: Number(arr[2]),
  81. };
  82. }
  83. }
  84. async loadConstraints() {
  85. const self = this;
  86. if (this.constraints) return;
  87. const r1cs = await loadR1cs(path.join(this.dir.path, this.baseName + ".r1cs"),true, false);
  88. self.F = new ZqField(r1cs.prime);
  89. self.nVars = r1cs.nVars;
  90. self.constraints = r1cs.constraints;
  91. }
  92. async assertOut(actualOut, expectedOut) {
  93. const self = this;
  94. if (!self.symbols) await self.loadSymbols();
  95. checkObject("main", expectedOut);
  96. function checkObject(prefix, eOut) {
  97. if (Array.isArray(eOut)) {
  98. for (let i=0; i<eOut.length; i++) {
  99. checkObject(prefix + "["+i+"]", eOut[i]);
  100. }
  101. } else if ((typeof eOut == "object")&&(eOut.constructor.name == "Object")) {
  102. for (let k in eOut) {
  103. checkObject(prefix + "."+k, eOut[k]);
  104. }
  105. } else {
  106. if (typeof self.symbols[prefix] == "undefined") {
  107. assert(false, "Output variable not defined: "+ prefix);
  108. }
  109. const ba = actualOut[self.symbols[prefix].varIdx].toString();
  110. const be = eOut.toString();
  111. assert.strictEqual(ba, be, prefix);
  112. }
  113. }
  114. }
  115. async getDecoratedOutput(witness) {
  116. const self = this;
  117. const lines = [];
  118. if (!self.symbols) await self.loadSymbols();
  119. for (let n in self.symbols) {
  120. let v;
  121. if (utils.isDefined(witness[self.symbols[n].varIdx])) {
  122. v = witness[self.symbols[n].varIdx].toString();
  123. } else {
  124. v = "undefined";
  125. }
  126. lines.push(`${n} --> ${v}`);
  127. }
  128. return lines.join("\n");
  129. }
  130. async checkConstraints(witness) {
  131. const self = this;
  132. if (!self.constraints) await self.loadConstraints();
  133. for (let i=0; i<self.constraints.length; i++) {
  134. checkConstraint(self.constraints[i]);
  135. }
  136. function checkConstraint(constraint) {
  137. const F = self.F;
  138. const a = evalLC(constraint[0]);
  139. const b = evalLC(constraint[1]);
  140. const c = evalLC(constraint[2]);
  141. assert (F.isZero(F.sub(F.mul(a,b), c)), "Constraint doesn't match");
  142. }
  143. function evalLC(lc) {
  144. const F = self.F;
  145. let v = F.zero;
  146. for (let w in lc) {
  147. v = F.add(
  148. v,
  149. F.mul( lc[w], witness[w] )
  150. );
  151. }
  152. return v;
  153. }
  154. }
  155. }
  156. function version_to_list ( v ) {
  157. return v.split(".").map(function(x) {
  158. return parseInt(x, 10);
  159. });
  160. }
  161. function check_versions ( v1, v2 ) {
  162. //check if v1 is newer than or equal to v2
  163. for (let i = 0; i < v2.length; i++) {
  164. if (v1[i] > v2[i]) return true;
  165. if (v1[i] < v2[i]) return false;
  166. }
  167. return true;
  168. }
  169. async function compiler_above_version(v) {
  170. let output = await exec('circom --version').toString();
  171. let compiler_version = version_to_list(output.slice(output.search(/\d/),-1));
  172. vlist = version_to_list(v);
  173. return check_versions ( compiler_version, vlist );
  174. }
  175. async function readBinWitnessFile(fileName) {
  176. const buffWitness = await readWtns(fileName);
  177. return buffWitness;
  178. }
  179. function fromArray8(arr) { //returns a BigInt
  180. var res = BigInt(0);
  181. const radix = BigInt(0x100);
  182. for (let i = arr.length-1 ; i>=0; i--) {
  183. res = res*radix + BigInt(arr[i]);
  184. }
  185. return res;
  186. }
  187. function fromArray8ToUint(arr) { //returns a BigInt
  188. var res = 0;
  189. const radix = 8;
  190. for (let i = arr.length-1 ; i>=0; i--) {
  191. res = res*radix + arr[i];
  192. }
  193. return res;
  194. }