blockchain-test/Block.cpp

59 lines
1.5 KiB
C++

//
// Keszitette: Toldi Balázs Ádám
// Datum: 2020. 03. 14.
//
#include "Block.h"
size_t Block::max_height = 0;
void Block::calculateHash() {
memset(hash, 0, SHA256_DIGEST_LENGTH);
SHA256_CTX sha;
SHA256_Init(&sha);
SHA256_Update(&sha, this, sizeof(Block));
unsigned char md[SHA256_DIGEST_LENGTH];
SHA256_Final(md, &sha);
std::stringstream ss;
for (unsigned char i : md)
ss << std::hex << (int) i;
strcpy(hash,ss.str().c_str());
}
Block::Block(Transaction tr[], size_t count, const char *prev_hash) {
if(count > MAX_BLOCK_TRANSACTION) throw "Too much!";
memset(transactions,0, sizeof(Transaction)*MAX_BLOCK_TRANSACTION);
for (int i = 0; i < count; ++i) {
transactions[i] = tr[i];
}
if (strcmp(prev_hash, "") == 0)
memset(this->prev_hash, 0, SHA256_CBLOCK+1);
else
strcpy(this->prev_hash, prev_hash);
height = ++max_height;
calculateHash();
}
Transaction &Transaction::operator=(Transaction &tr) {
if(this != &tr){
strcpy(sender,tr.getSender());
strcpy(reciver,tr.getReciever());
strcpy(hash,tr.getHash());
amount = tr.getAmount();
}
return *this;
}
void Transaction::calculateHash() {
memset(hash, 0, SHA256_DIGEST_LENGTH);
SHA256_CTX sha;
SHA256_Init(&sha);
SHA256_Update(&sha, this, sizeof(Transaction));
unsigned char md[SHA256_DIGEST_LENGTH];
SHA256_Final(md, &sha);
std::stringstream ss;
for (unsigned char i : md)
ss << std::hex << (int) i;
strcpy(hash,ss.str().c_str());
}