-
Notifications
You must be signed in to change notification settings - Fork 2
/
Block.cpp
54 lines (44 loc) · 1.25 KB
/
Block.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
//
// Block.cpp
// Created by Roshan Lamichhane on 12/7/19.
// Copyright © 2019 Roshan Lamichhane. All rights reserved.
//
#include <stdio.h>
#include <string>
#include "Block.h"
#include "TransactionData.h"
// Constructor with params
Block::Block(int idx, TransactionData d, size_t prevHash){
index = idx;
data = d;
previousHash = prevHash;
blockHash = generateHash();
}
// private functions
int Block::getIndex(){
return index;
}
/*
Generates hash for current block
- Includes previousHash in generation
- ^ Very important
*/
size_t Block::generateHash(){
// creating string of transaction data
std::string toHashS = std::to_string(data.amount) + data.receiverKey + data.senderKey + std::to_string(data.timestamp);
// 2 hashes to combine
std::hash<std::string> tDataHash; // hashes transaction data string
std::hash<std::string> prevHash; // re-hashes previous hash (for combination)
// combine hashes and get size_t for block hash
return tDataHash(toHashS) ^ (prevHash(std::to_string(previousHash)) << 1);
}
// Public Functions
size_t Block::getHash(){
return blockHash;
}
size_t Block::getPreviousHash(){
return previousHash;
}
bool Block::isHashValid(){
return generateHash() == getHash();
}