-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlock.cpp
55 lines (40 loc) · 879 Bytes
/
Block.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
#include <sstream>
#include "Block.h"
#include "sha256.h"
Block::Block(uint32_t nIndexIn, const std::string &sDataIn)
{
nNonce_ = -1;
tTime_ = time(nullptr);
}
std::string Block::GetHash()
{
return sHash_;
}
void Block::MineBlock(uint32_t nDifficulty)
{
char cstr[nDifficulty + 1] { '0' };
for (uint32_t i = 0; i < nDifficulty; ++i)
{
cstr[i] = '0';
}
cstr[nDifficulty] = '\0';
std::string str(cstr);
/*
std::string str = "";
for (uint32_t i = 0; i < nDifficulty; i++)
str += '0';
str += '\0';
*/
do
{
nNonce_++;
sHash_ = CalculateHash_();
} while( sHash_.substr(0, nDifficulty) != str );
std::cout << "Block mined: " << sHash_ << std::endl;
}
inline std::string Block::CalculateHash_() const
{
std::stringstream ss;
ss << nIndex_ << tTime_ << sData_ << nNonce_ << sPrevHash;
return sha256(ss.str());
}