-
Notifications
You must be signed in to change notification settings - Fork 16
/
MerkleTree.cpp
executable file
·54 lines (40 loc) · 1.73 KB
/
MerkleTree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "MerkleTree.h"
#include "Serialization/streams.h"
#include "Crypto/Sha256.h"
#include "ChainParams.h"
/*
* @TODO Test this code, write unit tests
*/
std::vector<unsigned char> MerkleTree::computeMerkleTreeRootValue(std::vector<Transaction> transactions) {
if(transactions.size() == 0) {
return std::vector<unsigned char>();
}
std::vector<std::vector<unsigned char> > leaves;
for(Transaction transaction: transactions) {
CDataStream s(SER_DISK, SERIALIZATION_VERSION);
s << transaction;
leaves.emplace_back(Sha256::sha256(std::vector<unsigned char>(s.data(), s.data() + s.size())));
}
while(leaves.size() > 1) {
std::vector<std::vector<unsigned char> > newLeaves;
while(leaves.size() > 0) {
if (leaves.size() == 1) {
newLeaves.emplace_back((std::vector<unsigned char>)leaves.back());
leaves.pop_back();
} else if(leaves.size() > 1) {
std::vector<unsigned char> leave1 = (std::vector<unsigned char>)leaves.back();
leaves.pop_back();
std::vector<unsigned char> leave2 = (std::vector<unsigned char>)leaves.back();
leaves.pop_back();
leave1.insert( leave1.end(), leave2.begin(), leave2.end() ); // concat leaves
newLeaves.emplace_back(Sha256::sha256(leave1));
}
}
leaves = newLeaves;
}
return leaves.at(0);
}
bool MerkleTree::verifyMerkleTreeRootValue(std::vector<Transaction> transactions, std::vector<unsigned char> merkleRoot) {
std::vector<unsigned char> calculatedMerkleRoot = MerkleTree::computeMerkleTreeRootValue(transactions);
return calculatedMerkleRoot == merkleRoot;
}