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.

68 lines
2.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 bigInt = require("big-integer");
  9. const BuildZqField = require("./buildzqfield");
  10. const ZqField = require("fflib").ZqField;
  11. module.exports = testField;
  12. function toMontgomeryStr(a, prime) {
  13. const n64 = Math.floor((prime.bitLength() - 1) / 64)+1;
  14. return a.shiftLeft(n64*64).mod(prime).toString(10);
  15. }
  16. function fromMontgomeryStr(a, prime) {
  17. const n64 = Math.floor((prime.bitLength() - 1) / 64)+1;
  18. const R = bigInt.one.shiftLeft(n64*64).mod(prime);
  19. const RI = R.modInv(prime);
  20. return bigInt(a).times(RI).mod(prime);
  21. }
  22. async function testField(prime, test) {
  23. tmp.setGracefulCleanup();
  24. const F = new ZqField(prime);
  25. const dir = await tmp.dir({prefix: "circom_", unsafeCleanup: true });
  26. const [hSource, cSource] = BuildZqField(prime, "Fr");
  27. await fs.promises.writeFile(path.join(dir.path, "fr.h"), hSource, "utf8");
  28. await fs.promises.writeFile(path.join(dir.path, "fr.c"), cSource, "utf8");
  29. await exec("g++" +
  30. ` ${path.join(__dirname, "tester.c")}` +
  31. ` ${path.join(dir.path, "fr.c")}` +
  32. ` -o ${path.join(dir.path, "tester")}` +
  33. " -lgmp"
  34. );
  35. for (let i=0; i<test.length; i++) {
  36. let a = bigInt(test[i][1]).mod(prime);
  37. if (a.isNegative()) a = prime.add(a);
  38. let b = bigInt(test[i][2]).mod(prime);
  39. if (b.isNegative()) b = prime.add(b);
  40. const ec = F[test[i][0]](a,b);
  41. // console.log(toMontgomeryStr(a, prime));
  42. // console.log(toMontgomeryStr(b, prime));
  43. const res = await exec(`${path.join(dir.path, "tester")}` +
  44. ` ${test[i][0]}` +
  45. ` ${toMontgomeryStr(a, prime)}` +
  46. ` ${toMontgomeryStr(b, prime)}`
  47. );
  48. // console.log(res.stdout);
  49. const c=fromMontgomeryStr(res.stdout, prime);
  50. assert.equal(ec.toString(), c.toString());
  51. }
  52. }