tornado-nova/circuits/merkleTree.circom

32 lines
908 B
Plaintext
Raw Permalink Normal View History

2021-06-06 19:31:32 +02:00
include "../node_modules/circomlib/circuits/poseidon.circom";
2020-04-08 11:41:12 +02:00
// Helper template that computes hashes of the next tree layer
template TreeLayer(height) {
var nItems = 1 << height;
signal input ins[nItems * 2];
signal output outs[nItems];
2020-04-08 11:41:12 +02:00
component hash[nItems];
for(var i = 0; i < nItems; i++) {
hash[i] = Poseidon(2);
hash[i].inputs[0] <== ins[i * 2];
hash[i].inputs[1] <== ins[i * 2 + 1];
hash[i].out ==> outs[i];
}
}
2020-04-08 11:41:12 +02:00
// Builds a merkle tree from leaf array
template MerkleTree(levels) {
signal input leaves[1 << levels];
signal output root;
2021-08-24 18:19:26 +02:00
component layers[levels];
for(var level = levels - 1; level >= 0; level--) {
layers[level] = TreeLayer(level);
for(var i = 0; i < (1 << (level + 1)); i++) {
layers[level].ins[i] <== level == levels - 1 ? leaves[i] : layers[level + 1].outs[i];
2020-04-08 11:41:12 +02:00
}
}
2020-04-08 11:41:12 +02:00
root <== levels > 0 ? layers[0].outs[0] : leaves[0];
}