arnaucube
arnaucube/circomlibPublic Self-hosted repository
circomlib/src/mimc7.js
src/mimc7.jsRaw
 1const bn128 = require("snarkjs").bn128;
 2const bigInt = require("snarkjs").bigInt;
 3const Web3 = require("web3");
 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 = Web3.utils.keccak256(seed+"_iv");
12    const cn = bigInt(Web3.utils.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 = Web3.utils.keccak256(SEED);
22    for (let i=1; i<nRounds; i++) {
23        c = Web3.utils.keccak256(c);
24
25        const n1 = Web3.utils.toBN(c).mod(Web3.utils.toBN(F.q.toString()));
26        const c2 = Web3.utils.padLeft(Web3.utils.toHex(n1), 64);
27        cts[i] = bigInt(Web3.utils.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) => {
48    let r = exports.getIV();
49    for (let i=0; i<arr.length; i++) {
50        r = exports.hash(r, bigInt(arr[i]));
51    }
52    return r;
53};