tornado-core/circuits/merkleTree.circom

59 lines
1.5 KiB
Plaintext
Raw Normal View History

2019-07-09 15:05:30 +02:00
include "../node_modules/circomlib/circuits/mimcsponge.circom";
2019-07-10 14:35:46 +02:00
// Computes MiMC(left + right)
2019-11-02 02:33:19 +01:00
template HashLeftRight() {
2019-07-09 15:05:30 +02:00
signal input left;
signal input right;
signal output hash;
2019-11-02 02:33:19 +01:00
component hasher = MiMCSponge(2, 220, 1);
2019-07-09 15:05:30 +02:00
hasher.ins[0] <== left;
hasher.ins[1] <== right;
hasher.k <== 0;
hash <== hasher.outs[0];
}
// if s == 0 returns [in[0], in[1]]
// if s == 1 returns [in[1], in[0]]
template Mux() {
signal input in[2];
signal input s;
signal output out[2];
out[0] <== (in[1] - in[0])*s + in[0];
out[1] <== (in[0] - in[1])*s + in[1];
2019-07-09 15:05:30 +02:00
}
2019-07-10 14:35:46 +02:00
// Verifies that merkle proof is correct for given merkle root and a leaf
// pathIndex input is an array of 0/1 selectors telling whether given pathElement is on the left or right side of merkle path
2019-11-02 02:33:19 +01:00
template MerkleTree(levels) {
2019-07-09 15:05:30 +02:00
signal input leaf;
2019-07-10 14:35:46 +02:00
signal input root;
2019-07-09 15:05:30 +02:00
signal private input pathElements[levels];
signal private input pathIndex[levels];
component selectors[levels];
component hashers[levels];
for (var i = 0; i < levels; i++) {
selectors[i] = Mux();
2019-11-02 02:33:19 +01:00
hashers[i] = HashLeftRight();
2019-07-09 15:05:30 +02:00
selectors[i].in[1] <== pathElements[i];
selectors[i].s <== pathIndex[i];
2019-07-09 15:05:30 +02:00
hashers[i].left <== selectors[i].out[0];
hashers[i].right <== selectors[i].out[1];
2019-07-09 15:05:30 +02:00
}
selectors[0].in[0] <== leaf;
2019-07-09 15:05:30 +02:00
for (var i = 1; i < levels; i++) {
selectors[i].in[0] <== hashers[i-1].hash;
2019-07-09 15:05:30 +02:00
}
2019-07-10 14:35:46 +02:00
root === hashers[levels - 1].hash;
2019-07-12 18:34:25 +02:00
}