-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlock.cpp
More file actions
49 lines (37 loc) · 975 Bytes
/
Copy pathBlock.cpp
File metadata and controls
49 lines (37 loc) · 975 Bytes
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
#include <sstream>
#include "Blockchain.h"
#include "sha256.h"
using namespace std;
Block::Block(uint32_t nIndexIn, const string &sDataIn) : _nIndex(nIndexIn), _sData(sDataIn) {
_nNonce = -1;
_tTime = time(nullptr);
}
string Block::GetHash() {
return _sHash;
}
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);
do {
_nNonce++;
_sHash = _CalculateHash();
} while (_sHash.substr(0, nDifficulty) != str);
cout << "Block mined: " << _sHash << endl;
}
inline string Block::_CalculateHash() const {
stringstream ss;
ss << _nIndex << _tTime << _sData << _nNonce << sPrevHash;
return sha256(ss.str());
}
void Blockchain::AddBlock(Block bNew) {
bNew.sPrevHash = _GetLastBlock().GetHash();
bNew.MineBlock(_nDifficulty);
_vChain.push_back(bNew);
}
Block Blockchain::_GetLastBlock() const {
return _vChain.back();
}