-
Notifications
You must be signed in to change notification settings - Fork 1
/
BlockChain.cpp
75 lines (60 loc) · 2.03 KB
/
BlockChain.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <ctime>
#include <string>
#include "include/Block.h"
#include "include/Blockchain.h"
#include <vector>
Blockchain::Blockchain() {
Block genesis = createGenesisBlock();
chain.push_back(genesis);
}
std::vector<Block> Blockchain::getChain() {
return chain;
}
Block Blockchain::createGenesisBlock() {
std::time_t current;
TransactionData d(0, "Genesis", "Genesis", time(¤t));
Block genesis(0, d, 0);
return genesis;
}
Block *Blockchain::getLatestBlock() {
return &chain.back();
}
void Blockchain::addBlock(TransactionData d) {
int index = (int)chain.size();
std::size_t previousHash = (int)chain.size() > 0 ? getLatestBlock()->getHash() : 0;
Block newBlock(index, d, previousHash);
chain.push_back(newBlock);
}
bool Blockchain::isChainValid() {
std::vector<Block>::iterator it;
for (it = chain.begin(); it != chain.end(); ++it) {
Block currentBlock = *it;
if (!currentBlock.isHashValid()) {
return false;
}
if (it != chain.begin()) {
Block previousBlock = *(it - 1);
if (currentBlock.getPreviousHash() != previousBlock.getHash())
{
return false;
}
}
}
return true;
}
void Blockchain::printChain() {
std::vector<Block>::iterator it;
for (it = chain.begin(); it != chain.end(); ++it) {
Block currentBlock = *it;
printf("\n\nBlock ===================================");
printf("\nIndex: %d", currentBlock.getIndex());
printf("\nAmount: %f", currentBlock.data.amount);
printf("\nSenderKey: %s", currentBlock.data.senderKey.c_str());
printf("\nReceiverKey: %s", currentBlock.data.receiverKey.c_str());
printf("\nTimestamp: %ld", currentBlock.data.timestamp);
printf("\nHash: %zu", currentBlock.getHash());
printf("\nPrevious Hash: %zu", currentBlock.getPreviousHash());
printf("\nIs Block Valid?: %d", currentBlock.isHashValid());
}
}