-
Notifications
You must be signed in to change notification settings - Fork 2
/
Blockchain.cpp
90 lines (74 loc) · 2.43 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//
// Blockchain.cpp
// Created by Roshan Lamichhane on 12/7/19.
// Copyright © 2019 Roshan Lamichhane. All rights reserved.
//
#include <stdio.h>
#include <ctime>
#include <string>
#include "Block.h"
#include "Blockchain.h"
#include <vector>
// Blockchain Constructor
Blockchain::Blockchain(){
Block genesis = createGenesisBlock();
chain.push_back(genesis);
}
// Public Chain Getter
std::vector<Block> Blockchain::getChain() {
return chain;
}
// Create Genesis Block
Block Blockchain::createGenesisBlock(){
// Get Current Time
std::time_t current;
// Setup Initial Transaction Data
TransactionData d(0, "Genesis", "Genesis", time(¤t));
// Return Genesis Block
Block genesis(0, d, 0);
return genesis;
}
// We only need pointer here
// to demonstrate manipulation of transaction data
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;
}
// Don't forget to check if this is the first item
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());
}
}