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.

65 lines
1.7 KiB

5 years ago
5 years ago
5 years ago
5 years ago
  1. const bigInt = require("big-integer");
  2. const ZqField = require("ffjavascript").ZqField;
  3. const Web3Utils = require("web3-utils");
  4. const F = new ZqField(bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"));
  5. const SEED = "mimc";
  6. const NROUNDS = 91;
  7. exports.getIV = (seed) => {
  8. if (typeof seed === "undefined") seed = SEED;
  9. const c = Web3Utils.keccak256(seed+"_iv");
  10. const cn = bigInt(Web3Utils.toBN(c).toString());
  11. const iv = cn.mod(F.p);
  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 = Web3Utils.keccak256(SEED);
  19. for (let i=1; i<nRounds; i++) {
  20. c = Web3Utils.keccak256(c);
  21. const n1 = Web3Utils.toBN(c).mod(Web3Utils.toBN(F.p.toString()));
  22. const c2 = Web3Utils.padLeft(Web3Utils.toHex(n1), 64);
  23. cts[i] = bigInt(Web3Utils.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.pow(t, 7);
  37. }
  38. return F.add(r, k);
  39. };
  40. exports.multiHash = (arr, key) => {
  41. let r;
  42. if (typeof(key) === "undefined") {
  43. r = F.zero;
  44. } else {
  45. r = key;
  46. }
  47. for (let i=0; i<arr.length; i++) {
  48. r = F.add(
  49. F.add(
  50. r,
  51. arr[i]
  52. ),
  53. exports.hash(bigInt(arr[i]), r)
  54. );
  55. }
  56. return r;
  57. };