-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockchain.cpp
More file actions
109 lines (81 loc) · 2.29 KB
/
Blockchain.cpp
File metadata and controls
109 lines (81 loc) · 2.29 KB
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
#include "Block.h"
#include "Blockchain.h"
using namespace std;
namespace myCoin{
Blockchain::Blockchain() : size(0), difficulty(3){
createGenesisBlock();
}
Blockchain::~Blockchain(){
for(Block* blockPtr : chain){
delete blockPtr;
}
chain.clear();
}
Blockchain::Blockchain(const Blockchain& rhs){
for(const Block* blockPtr : rhs.chain){
Block* currBlock = new Block(*blockPtr);
chain.push_back(currBlock);
}
}
Blockchain& Blockchain::operator=(const Blockchain& rhs){
if(this != &rhs){
for(Block* blockPtr : chain){
delete blockPtr;
}
chain.clear();
for(const Block* blockPtr : rhs.chain){
Block* currBlock = new Block(*blockPtr);
chain.push_back(currBlock);
}
}
return *this;
}
void Blockchain::createGenesisBlock(){
cout << "Creating Genesis Block..." << endl << endl;
Block* genesisBlock = new Block(0,"0","genesisTrans",0);
chain.push_back(genesisBlock);
++size;
}
const Block& Blockchain::getLastBlock() const {
return *(chain[size-1]);
}
bool Blockchain::isValidChain() const {
if(size > 0){
for(size_t index = 1; index < size; ++index){
const Block* currBlock = chain[index];
const Block* prevBlock = chain[index-1];
if(currBlock->previousHash != prevBlock->blockHash){
return false;
}
if(currBlock->blockHash != currBlock->calculateHash()){
//cout << currBlock->blockHash << endl << currBlock->calculateHash();
return false;
}
}
}
return true;
}
void Blockchain::createTransaction(const string& name, double amount){
mineBlock(name,amount);
}
void Blockchain::mineBlock(const string& name, double amount){
Block lastBlock = getLastBlock();
Block* newBlock = new Block(size,lastBlock.blockHash,name, amount);
newBlock->mineBlock(difficulty);
chain.push_back(newBlock);
++size;
cout << "BLOCK SUCCESFULLY MINED..." << endl << endl ;
}
void Blockchain::generateBlock(){
createTransaction("NULL",00000);
}
ostream& operator<<(std::ostream& os, const Blockchain& blockchain){
os << "-------------------------------------------- \n";
os << "Blockchain has " << blockchain.size-1 << " block(s)" << endl;
for(const Block* blockPtr : blockchain.chain){
os << *blockPtr << endl;
os << "-------------------------------------------- \n";
}
return os;
}
}