Blockchain Slip no 7 solution

const sha256 = require('sha256');
class Transaction {
constructor(sender, receiver, amount) {
this.sender = sender;
this.receiver = receiver;
this.amount = amount;
}
calculateHash() {
return sha256(this.sender + this.receiver + this.amount);
}
}

class Block {
constructor(transactions, previousHash = '') {
this.timestamp = new Date();
this.transactions = transactions;
this.previousHash = previousHash;
this.nonce = 0;
this.hash = this.calculateHash();
}

calculateHash() {
return sha256(this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce);
}

mineBlock(difficulty) {
while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {
this.nonce++;
this.hash = this.calculateHash();
}
console.log('Block mined:', this.hash);
}
}

class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 2;
this.pendingTransactions = [];
this.miningReward = 100;
}

createGenesisBlock() {
return new Block([], '0');
}

getLatestBlock() {
return this.chain[this.chain.length - 1];
}

minePendingTransactions(miningRewardAddress) {
const rewardTx = new Transaction(null, miningRewardAddress, this.miningReward);
this.pendingTransactions.push(rewardTx);

const block = new Block(this.pendingTransactions, this.getLatestBlock().hash);
block.mineBlock(this.difficulty);

console.log('Block successfully mined!');
this.chain.push(block);

this.pendingTransactions = [];
}

createTransaction(transaction) {
this.pendingTransactions.push(transaction);
}

getBalanceOfAddress(address) {
let balance = 0;
for (const block of this.chain) {
for (const transaction of block.transactions) {
if (transaction.sender === address) {
balance -= transaction.amount;
}
if (transaction.receiver === address) {
balance += transaction.amount;
}
}
}
return balance;
}
}

const myBlockchain = new Blockchain();

const walletA = 'wallet-address-1';
const walletB = 'wallet-address-2';


myBlockchain.createTransaction(new Transaction(walletA, walletB, 50));
myBlockchain.createTransaction(new Transaction(walletA, walletB, 30));


console.log('Mining started...');
myBlockchain.minePendingTransactions('miner-reward-address');

console.log(`Balance of ${walletA}: ${myBlockchain.getBalanceOfAddress(walletA)}`);
console.log(`Balance of ${walletB}: ${myBlockchain.getBalanceOfAddress(walletB)}`);

No comments:

Post a Comment