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 let R = F.zero;
57 let C = F.zero;
58
59 for (let i=0; i<arr.length; i++) {
60 R = F.add(R, bigInt(arr[i]));
61 const S = exports.hash(R, C, key);
62 R = S.xL;
63 C = S.xR;
64 }
65 let outputs = [R];
66 for (let i=1; i < numOutputs; i++) {
67 const S = exports.hash(R, C, key);
68 R = S.xL;
69 C = S.xR;
70 outputs.push(R);
71 }
72 if (numOutputs == 1) {
73 return F.affine(outputs[0]);
74 } else {
75 return outputs.map(x => F.affine(x));
76 }
77};