arnaucube
arnaucube/circomlibPublic Self-hosted repository
circomlib/src/mimcsponge.js
src/mimcsponge.jsRaw
 1const bn128 = require("snarkjs").bn128;
 2const bigInt = require("snarkjs").bigInt;
 3const Web3Utils = require("web3-utils");
 4const F = bn128.Fr;
 5
 6const SEED = "mimcsponge";
 7const NROUNDS = 220;
 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, 220);
34
35exports.hash = (_xL_in, _xR_in, _k) =>{
36    let xL = bigInt(_xL_in);
37    let xR = bigInt(_xR_in);
38    const k = bigInt(_k);
39    for (let i=0; i<NROUNDS; i++) {
40        const c = cts[i];
41        const t = (i==0) ? F.add(xL, k) : F.add(F.add(xL, k), c);
42        const xR_tmp = bigInt(xR);
43        xR = xL;
44        xL = F.add(xR_tmp, F.exp(t, 5));
45    }
46    return {
47      xL: F.affine(xL),
48      xR: F.affine(xR),
49    };
50};
51
52exports.multiHash = (arr, key, numOutputs) => {
53    if (typeof(numOutputs) === "undefined") {
54      numOutputs = 1;
55    }
56    if (typeof(key) === "undefined") {
57        key = F.zero;
58    }
59
60    let R = F.zero;
61    let C = F.zero;
62
63    for (let i=0; i<arr.length; i++) {
64      R = F.add(R, bigInt(arr[i]));
65      const S = exports.hash(R, C, key);
66      R = S.xL;
67      C = S.xR;
68    }
69    let outputs = [R];
70    for (let i=1; i < numOutputs; i++) {
71      const S = exports.hash(R, C, key);
72      R = S.xL;
73      C = S.xR;
74      outputs.push(R);
75    }
76    if (numOutputs == 1) {
77      return F.affine(outputs[0]);
78    } else {
79      return outputs.map(x => F.affine(x));
80    }
81};