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.

66 lines
1.7 KiB

5 years ago
5 years ago
5 years ago
5 years ago
  1. const Scalar = require("ffjavascript").Scalar;
  2. const ZqField = require("ffjavascript").ZqField;
  3. const Web3Utils = require("web3-utils");
  4. const F = new ZqField(Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"));
  5. exports.F = F;
  6. const SEED = "mimc";
  7. const NROUNDS = 91;
  8. exports.getIV = (seed) => {
  9. if (typeof seed === "undefined") seed = SEED;
  10. const c = Web3Utils.keccak256(seed+"_iv");
  11. const cn = Scalar.FromString(Web3Utils.toBN(c).toString());
  12. const iv = cn.mod(F.p);
  13. return iv;
  14. };
  15. exports.getConstants = (seed, nRounds) => {
  16. if (typeof seed === "undefined") seed = SEED;
  17. if (typeof nRounds === "undefined") nRounds = NROUNDS;
  18. const cts = new Array(nRounds);
  19. let c = Web3Utils.keccak256(SEED);
  20. for (let i=1; i<nRounds; i++) {
  21. c = Web3Utils.keccak256(c);
  22. const n1 = Web3Utils.toBN(c).mod(Web3Utils.toBN(F.p.toString()));
  23. const c2 = Web3Utils.padLeft(Web3Utils.toHex(n1), 64);
  24. cts[i] = Scalar.fromString(Web3Utils.toBN(c2).toString());
  25. }
  26. cts[0] = F.e(0);
  27. return cts;
  28. };
  29. const cts = exports.getConstants(SEED, 91);
  30. exports.hash = (_x_in, _k) =>{
  31. const x_in = F.e(_x_in);
  32. const k = F.e(_k);
  33. let r;
  34. for (let i=0; i<NROUNDS; i++) {
  35. const c = cts[i];
  36. const t = (i==0) ? F.add(x_in, k) : F.add(F.add(r, k), c);
  37. r = F.pow(t, 7);
  38. }
  39. return F.add(r, k);
  40. };
  41. exports.multiHash = (arr, key) => {
  42. let r;
  43. if (typeof(key) === "undefined") {
  44. r = F.zero;
  45. } else {
  46. r = key;
  47. }
  48. for (let i=0; i<arr.length; i++) {
  49. r = F.add(
  50. F.add(
  51. r,
  52. arr[i]
  53. ),
  54. exports.hash(F.e(arr[i]), r)
  55. );
  56. }
  57. return r;
  58. };