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
 6module.exports.hash = MiMC7Hash;
 7module.exports.getConstants = getConstants;
 8
 9const SEED = "iden3_mimc";
10
11function getConstants(seed, nRounds) {
12    const cts = new Array(nRounds);
13    let c = Web3.utils.keccak256(SEED);
14    for (let i=1; i<nRounds; i++) {
15        c = Web3.utils.keccak256(c);
16
17        const n1 = Web3.utils.toBN(c).mod(Web3.utils.toBN(F.q.toString()));
18        cts[i] = Web3.utils.padLeft(Web3.utils.toHex(n1), 64);
19    }
20    cts[0] = "0x0000000000000000000000000000000000000000000000000000000000000000";
21    return cts;
22}
23
24function MiMC7Hash(_x_in, _k, nRounds) {
25    const x_in = bigInt(_x_in);
26    const k = bigInt(_k);
27    const cts = getConstants(SEED, nRounds);
28    let r;
29    for (let i=0; i<nRounds; i++) {
30        const c = bigInt(Web3.utils.toBN(cts[i]).toString());
31        let t = (i==0) ? F.add(x_in, k) : F.add(F.add(r, k), c);
32        let t2 = F.square(t);
33        let t4 = F.square(t2);
34        r = F.mul(F.mul(t4, t2), t);
35    }
36    return F.affine(F.add(r, k));
37}