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