tornado-trees/circuits/TreeUpdateArgsHasher.circom

70 lines
2.5 KiB
Plaintext
Raw Normal View History

2021-02-01 16:40:32 +03:00
include "../node_modules/circomlib/circuits/bitify.circom";
include "../node_modules/circomlib/circuits/sha256/sha256.circom";
2021-03-20 23:48:26 +03:00
// Computes a SHA256 hash of all inputs packed into a byte array
// Field elements are padded to 256 bits with zeroes
2021-02-01 16:40:32 +03:00
template TreeUpdateArgsHasher(nLeaves) {
2021-03-20 23:48:26 +03:00
signal input oldRoot;
signal input newRoot;
signal input pathIndices;
signal input instances[nLeaves];
signal input hashes[nLeaves];
signal input blocks[nLeaves];
2021-02-01 16:40:32 +03:00
signal output out;
var header = 256 + 256 + 32;
2021-03-19 23:08:46 +03:00
var bitsPerLeaf = 256 + 160 + 32;
2021-02-01 16:40:32 +03:00
component hasher = Sha256(header + nLeaves * bitsPerLeaf);
2021-02-24 13:39:14 +03:00
// the range check on old root is optional, it's enforced by smart contract anyway
2021-02-23 12:13:51 +03:00
component bitsOldRoot = Num2Bits_strict();
component bitsNewRoot = Num2Bits_strict();
2021-02-01 16:40:32 +03:00
component bitsPathIndices = Num2Bits(32);
component bitsInstance[nLeaves];
component bitsHash[nLeaves];
component bitsBlock[nLeaves];
2021-02-23 12:13:51 +03:00
2021-02-01 16:40:32 +03:00
bitsOldRoot.in <== oldRoot;
bitsNewRoot.in <== newRoot;
bitsPathIndices.in <== pathIndices;
2021-02-23 12:13:51 +03:00
hasher.in[0] <== 0;
hasher.in[1] <== 0;
for(var i = 0; i < 254; i++) {
hasher.in[i + 2] <== bitsOldRoot.out[253 - i];
2021-02-01 16:40:32 +03:00
}
2021-02-23 12:13:51 +03:00
hasher.in[256] <== 0;
hasher.in[257] <== 0;
for(var i = 0; i < 254; i++) {
hasher.in[i + 258] <== bitsNewRoot.out[253 - i];
2021-02-01 16:40:32 +03:00
}
for(var i = 0; i < 32; i++) {
hasher.in[i + 512] <== bitsPathIndices.out[31 - i];
}
for(var leaf = 0; leaf < nLeaves; leaf++) {
2021-02-24 13:39:14 +03:00
// the range check on hash is optional, it's enforced by the smart contract anyway
bitsHash[leaf] = Num2Bits_strict();
2021-02-01 16:40:32 +03:00
bitsInstance[leaf] = Num2Bits(160);
bitsBlock[leaf] = Num2Bits(32);
bitsHash[leaf].in <== hashes[leaf];
bitsInstance[leaf].in <== instances[leaf];
bitsBlock[leaf].in <== blocks[leaf];
2021-02-24 13:39:14 +03:00
hasher.in[header + leaf * bitsPerLeaf + 0] <== 0;
hasher.in[header + leaf * bitsPerLeaf + 1] <== 0;
for(var i = 0; i < 254; i++) {
hasher.in[header + leaf * bitsPerLeaf + i + 2] <== bitsHash[leaf].out[253 - i];
2021-02-01 16:40:32 +03:00
}
for(var i = 0; i < 160; i++) {
hasher.in[header + leaf * bitsPerLeaf + i + 256] <== bitsInstance[leaf].out[159 - i];
}
for(var i = 0; i < 32; i++) {
hasher.in[header + leaf * bitsPerLeaf + i + 416] <== bitsBlock[leaf].out[31 - i];
}
}
component b2n = Bits2Num(256);
for (var i = 0; i < 256; i++) {
b2n.in[i] <== hasher.out[255 - i];
}
out <== b2n.out;
2021-02-23 12:13:51 +03:00
}