74 lines
1.8 KiB
C++
74 lines
1.8 KiB
C++
//
|
|
// Keszitette: Toldi Balázs Ádám
|
|
// Datum: 2020. 03. 14.
|
|
//
|
|
|
|
#include "Block.h"
|
|
|
|
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);
|
|
calculateHash();
|
|
}
|
|
|
|
void Block::mine(size_t diff) {
|
|
difficulty = diff;
|
|
std::string str;
|
|
for (int i = 0; i < diff; ++i) {
|
|
str += '0';
|
|
}
|
|
|
|
while(strncmp(hash,str.c_str(),diff) != 0){
|
|
nonce++;
|
|
calculateHash();
|
|
std::cout << nonce << std::endl;
|
|
}
|
|
}
|
|
|
|
size_t Block::getDifficulty() const {
|
|
return difficulty;
|
|
}
|
|
|
|
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());
|
|
}
|