forked from teaandcode/TestChain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlock.cpp
42 lines (33 loc) · 798 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
//
// Created by Dave Nash on 20/10/2017.
//
#include "Block.h"
#include "sha256.h"
Block::Block(uint32_t nIndexIn, const string &sDataIn) : _nIndex(nIndexIn), _sData(sDataIn)
{
_nNonce = 0;
_tTime = time(nullptr);
sHash = _CalculateHash();
}
void Block::MineBlock(uint32_t nDifficulty)
{
char cstr[nDifficulty + 1];
for (uint32_t i = 0; i < nDifficulty; ++i)
{
cstr[i] = '0';
}
cstr[nDifficulty] = '\0';
string str(cstr);
while (sHash.substr(0, nDifficulty) != str)
{
_nNonce++;
sHash = _CalculateHash();
}
cout << "Block mined: " << sHash << endl;
}
inline string Block::_CalculateHash() const
{
stringstream ss;
ss << _nIndex << sPrevHash << _tTime << _sData << _nNonce;
return sha256(ss.str());
}