tornado-core/circuits/merkleTree.circom

52 lines
1.4 KiB
Plaintext
Raw Permalink Normal View History

2019-07-09 13:05:30 +00:00
include "../node_modules/circomlib/circuits/mimcsponge.circom";
2019-11-03 08:41:05 +00:00
// Computes MiMC([left, right])
2019-11-02 01:33:19 +00:00
template HashLeftRight() {
2019-07-09 13:05:30 +00:00
signal input left;
signal input right;
signal output hash;
2019-12-13 21:18:16 +00:00
component hasher = MiMCSponge(2, 1);
2019-07-09 13:05:30 +00: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]]
2019-11-15 08:43:30 +00:00
template DualMux() {
signal input in[2];
signal input s;
signal output out[2];
2019-11-20 17:27:08 +00:00
s * (1 - s) === 0
out[0] <== (in[1] - in[0])*s + in[0];
out[1] <== (in[0] - in[1])*s + in[1];
2019-07-09 13:05:30 +00:00
}
2019-07-10 12:35:46 +00:00
// Verifies that merkle proof is correct for given merkle root and a leaf
2019-11-02 02:05:25 +00:00
// pathIndices input is an array of 0/1 selectors telling whether given pathElement is on the left or right side of merkle path
template MerkleTreeChecker(levels) {
2019-07-09 13:05:30 +00:00
signal input leaf;
2019-07-10 12:35:46 +00:00
signal input root;
signal input pathElements[levels];
signal input pathIndices[levels];
2019-07-09 13:05:30 +00:00
component selectors[levels];
component hashers[levels];
for (var i = 0; i < levels; i++) {
2019-11-15 08:43:30 +00:00
selectors[i] = DualMux();
2019-11-03 08:41:05 +00:00
selectors[i].in[0] <== i == 0 ? leaf : hashers[i - 1].hash;
selectors[i].in[1] <== pathElements[i];
2019-11-02 02:05:25 +00:00
selectors[i].s <== pathIndices[i];
2019-07-09 13:05:30 +00:00
2019-11-03 08:41:05 +00:00
hashers[i] = HashLeftRight();
hashers[i].left <== selectors[i].out[0];
hashers[i].right <== selectors[i].out[1];
2019-07-09 13:05:30 +00:00
}
2019-07-10 12:35:46 +00:00
root === hashers[levels - 1].hash;
2019-07-12 16:34:25 +00:00
}