-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbitcoin.cpp
111 lines (100 loc) · 2.58 KB
/
bitcoin.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "bitcoin.h"
namespace bitcoin {
int sha256(const uint8_t preimageBytes[], size_t len, Bytes& res)
{
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, preimageBytes, len);
int ret = SHA256_Final(res.data(), &sha256);
return ret;
}
int doubleSHA256(const uint8_t preimageBytes[], size_t len, Bytes& res)
{
sha256(preimageBytes, len, res);
return sha256(res.data(), res.size(), res);
}
int hexDigitToInt(char digit)
{
digit = tolower(digit);
if (digit >= '0' && digit <='9')
return (int)(digit - '0');
else if (digit >= 'a' && digit <= 'f') {
return (int)(digit - '1' - '0') + 10;
}
return -1;
}
int hexstringToBytes(std::string const& hexstring, Bytes& result)
{
if (hexstring.size() % 2) {
std::cerr << "The hexstring is not an even number of characters.\n";
exit(EXIT_FAILURE);
}
size_t resultLength = hexstring.size() / 2;
size_t i = 0;
for (auto it = hexstring.begin(); it != hexstring.end(); it += 2) {
int sixteens = hexDigitToInt(*it);
int units = hexDigitToInt(*std::next(it));
result.push_back((sixteens << 4) | units);
i++;
}
return resultLength;
}
/**
* Compute the Merkle root
* */
void merkleRoot(std::vector<Bytes> txids, Bytes& result)
{
if (txids.empty()) {
throw;
}
while (txids.size() > 1) {
writeLog("while loop");
// If odd number, add the last element to end of vector.
// Note that this is required at every level of the tree.
if (txids.size() & 1) {
writeLog("duplicating last element.\n");
txids.push_back(txids.back());
}
std::vector<Bytes> tmp;
for (auto it = std::begin(txids); it != std::end(txids) && std::next(it) != txids.end(); it += 2) {
Bytes concat = *it;
Bytes result(hash_size);
concat.insert(concat.end(), (*(it + 1)).begin(), (*(it + 1)).end());
doubleSHA256(concat.data(), concat.size(), result);
tmp.push_back(result);
concat.clear();
}
std::ostringstream ss;
ss << "Current hashes:\n";
ss << "---------------\n";
ss << txids.size() << "txids in this iteration.\n";
for (auto& el : tmp)
ss << bytesToHexstring(el) << '\n';
writeLog(ss.str());
txids = tmp;
}
result = txids[0];
}
void byteSwap(Bytes& b)
{
Bytes tmp;
for (auto i = b.size(); i-- > 0;) {
tmp.push_back(b[i]);
}
b = tmp;
}
void writeLog(const std::string &text)
{
std::ofstream log_file(
"log_file.txt", std::ios_base::out | std::ios_base::app );
log_file << text << std::endl;
}
std::string bytesToHexstring(const Bytes& b)
{
std::ostringstream ss;
for (auto& el : b) {
ss << std::hex << std::setw(2) << std::setfill('0') << (int)el;
}
return ss.str();
}
} // bitcoin