JSMongere / Test2

0 stars 0 forks source link

saving transaction in blockchain #3

Open mrfltvs opened 7 months ago

mrfltvs commented 7 months ago

include

include

include

include <openssl/sha.h>

using namespace std;

class Transaction { public: string sender; string receiver; float amount; time_t timestamp;

Transaction(string sender, string receiver, float amount) {
    this->sender = sender;
    this->receiver = receiver;
    this->amount = amount;
    this->timestamp = time(0);
}

string calculateHash() {
    string input = sender + receiver + to_string(amount) + to_string(timestamp);
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, input.c_str(), input.length());
    SHA256_Final(hash, &sha256);
    stringstream ss;
    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        ss << hex << setw(2) << setfill('0') << (unsigned int)hash[i];
    }
    return ss.str();
}

};

class Block { public: int index; string previousHash; time_t timestamp; vector transactions; string hash;

Block(int index, string previousHash, vector<Transaction> transactions) {
    this->index = index;
    this->previousHash = previousHash;
    this->transactions = transactions;
    this->timestamp = time(0);
    this->hash = calculateHash();
}

string calculateHash() {
    string input = to_string(index) + previousHash + to_string(timestamp);
    for(const auto& tx : transactions) {
        input += tx.calculateHash();
    }
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, input.c_str(), input.length());
    SHA256_Final(hash, &sha256);
    stringstream ss;
    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        ss << hex << setw(2) << setfill('0') << (unsigned int)hash[i];
    }
    return ss.str();
}

};

class Blockchain { public: vector chain;

Blockchain() {
    chain.push_back(createGenesisBlock());
}

Block createGenesisBlock() {
    vector<Transaction> transactions;
    return Block(0, "0", transactions);
}

Block getLatestBlock() {
    return chain.back();
}

void addBlock(Block newBlock) {
    newBlock.previousHash = getLatestBlock().hash;
    newBlock.hash = newBlock.calculateHash();
    chain.push_back(newBlock);
}

};

int main() { Blockchain blockchain;

Transaction tx1("Alice", "Bob", 10.5);
Transaction tx2("Bob", "Charlie", 5.2);

Block block1(1, blockchain.getLatestBlock().hash, {tx1});
blockchain.addBlock(block1);

Block block2(2, blockchain.getLatestBlock().hash, {tx2});
blockchain.addBlock(block2);

cout << "Genesis block hash: " << blockchain.chain[0].hash << endl;
cout << "Block 1 hash: " << blockchain.chain[1].hash << endl;
cout << "Block 2 hash: " << blockchain.chain[2].hash << endl;

return 0;

}