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.

45 lines
1.3 KiB

  1. const bn128 = require("snarkjs").bn128;
  2. const bigInt = require("snarkjs").bigInt;
  3. const Web3 = require("web3");
  4. const F = bn128.Fr;
  5. const SEED = "mimc";
  6. const NROUNDS = 91;
  7. exports.getIV = (seed) => {
  8. if (typeof seed === "undefined") seed = SEED;
  9. const c = Web3.utils.keccak256(seed+"_iv");
  10. const cn = bigInt(Web3.utils.toBN(c).toString());
  11. const iv = cn.mod(F.q);
  12. return iv;
  13. };
  14. exports.getConstants = (seed, nRounds) => {
  15. if (typeof seed === "undefined") seed = SEED;
  16. if (typeof nRounds === "undefined") nRounds = NROUNDS;
  17. const cts = new Array(nRounds);
  18. let c = Web3.utils.keccak256(SEED);
  19. for (let i=1; i<nRounds; i++) {
  20. c = Web3.utils.keccak256(c);
  21. const n1 = Web3.utils.toBN(c).mod(Web3.utils.toBN(F.q.toString()));
  22. const c2 = Web3.utils.padLeft(Web3.utils.toHex(n1), 64);
  23. cts[i] = bigInt(Web3.utils.toBN(c2).toString());
  24. }
  25. cts[0] = bigInt(0);
  26. return cts;
  27. };
  28. const cts = exports.getConstants(SEED, 91);
  29. exports.hash = (_x_in, _k) =>{
  30. const x_in = bigInt(_x_in);
  31. const k = bigInt(_k);
  32. let r;
  33. for (let i=0; i<NROUNDS; i++) {
  34. const c = cts[i];
  35. const t = (i==0) ? F.add(x_in, k) : F.add(F.add(r, k), c);
  36. r = F.exp(t, 7);
  37. }
  38. return F.affine(F.add(r, k));
  39. };