tornado-core/circuits/merkleTree.circom

73 lines
2.0 KiB
Plaintext
Raw Normal View History

2019-10-04 08:36:17 -04:00
include "../node_modules/circomlib/circuits/poseidon.circom";
2019-07-09 09:05:30 -04:00
2019-10-04 08:36:17 -04:00
// Computes Poseidon(left + right)
2019-07-09 09:05:30 -04:00
template HashLeftRight(rounds) {
signal input left;
signal input right;
signal output hash;
2019-10-04 08:36:17 -04:00
component hasher = Poseidon(2, 6, 8, 57);
hasher.inputs[0] <== left;
hasher.inputs[1] <== right;
2019-07-09 09:05:30 -04:00
2019-10-04 08:36:17 -04:00
hash <== hasher.out;
2019-07-09 09:05:30 -04:00
}
2019-07-10 08:35:46 -04:00
// if pathIndex == 0 returns (left = inputElement, right = pathElement)
// if pathIndex == 1 returns (left = pathElement, right = inputElement)
2019-07-09 09:05:30 -04:00
template Selector() {
signal input inputElement;
signal input pathElement;
signal input pathIndex;
signal output left;
signal output right;
signal leftSelector1;
signal leftSelector2;
signal rightSelector1;
signal rightSelector2;
pathIndex * (1-pathIndex) === 0
leftSelector1 <== (1 - pathIndex) * inputElement;
leftSelector2 <== (pathIndex) * pathElement;
rightSelector1 <== (pathIndex) * inputElement;
rightSelector2 <== (1 - pathIndex) * pathElement;
left <== leftSelector1 + leftSelector2;
right <== rightSelector1 + rightSelector2;
}
2019-07-10 08:35:46 -04: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-07-09 09:05:30 -04:00
template MerkleTree(levels, rounds) {
signal input leaf;
2019-07-10 08:35:46 -04:00
signal input root;
2019-07-09 09:05:30 -04: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] = Selector();
hashers[i] = HashLeftRight(rounds);
selectors[i].pathElement <== pathElements[i];
selectors[i].pathIndex <== pathIndex[i];
hashers[i].left <== selectors[i].left;
hashers[i].right <== selectors[i].right;
}
selectors[0].inputElement <== leaf;
for (var i = 1; i < levels; i++) {
selectors[i].inputElement <== hashers[i-1].hash;
}
2019-07-10 08:35:46 -04:00
root === hashers[levels - 1].hash;
2019-07-12 12:34:25 -04:00
}