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.

239 lines
7.1 KiB

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