-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlock.cpp
More file actions
51 lines (44 loc) · 935 Bytes
/
Block.cpp
File metadata and controls
51 lines (44 loc) · 935 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
48
49
50
51
#include "Block.h"
#include "sha256.h"
/**
* CONSTRUCTOR
*/
Block::Block(uint32_t indexIn, const string &dataIn) : _index(indexIn), _data(dataIn)
{
_nonce = -1;
_time = time(nullptr);
}
/**
* block's hash accessor
*/
string Block::getHash()
{
return _hash;
}
/**
* block mining method
*/
void Block::mineBlock(uint32_t diff)
{
// create a string of zeros as long as the difficulty
char chstr[diff + 1];
for (uint32_t i = 0; i < diff; i++)
{
chstr[i] = '0';
}
chstr[diff] = '\0';
string str(chstr);
// loop until the beginning of the hash starts with zeros
while (_hash.substr(0, diff) != str)
{
_nonce++;
_hash = _calculateHash();
}
cout << "Block mined: " << _hash << endl;
}
inline string Block::_calculateHash() const
{
stringstream strs;
strs << _index << _time << _data << _nonce << prevHash;
return sha256(strs.str());
}