Blockchain Slip No 2 Solution

Write a blockchain application in JavaScript to calculate hash code for the transaction.

1. Install crypto-js:
To perform hashing, you can use the crypto-js library. Install it using npm:
npm install crypto-js
2. Create the Blockchain Application:
Create a JavaScript file, e.g., blockchain.js, with the following code:

const SHA256 = require('crypto-js/sha256');

// Transaction class represents a single transaction
class Transaction {
constructor(fromAddress, toAddress, amount) {
this.fromAddress = fromAddress;
this.toAddress = toAddress;
this.amount = amount;
}
}

// Block class represents a block in the blockchain
class Block {
constructor(timestamp, transactions, previousHash = '') {
this.timestamp = timestamp;
this.transactions = transactions;
this.previousHash = previousHash;
this.nonce = 0; // Used in proof-of-work
this.hash = this.calculateHash();
}
calculateHash() {
return SHA256(this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce).toString();
}
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);
}
}

// Blockchain class represents the entire blockchain
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
this.difficulty = 2; // Proof-of-work difficulty
}
createGenesisBlock() {
return new Block('01/01/2023', 'Genesis Block', '0');
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.mineBlock(this.difficulty);
this.chain.push(newBlock);
}
}

// Create a blockchain
const myCoin = new Blockchain();

// Create transactions
const transaction1 = new Transaction('address1', 'address2', 100);
const transaction2 = new Transaction('address2', 'address1', 50);

// Add transactions to a new block
const newBlock = new Block(Date.now(), [transaction1, transaction2]);
myCoin.addBlock(newBlock);

// Output the blockchain
console.log(JSON.stringify(myCoin, null, 4));

3. Run the Application:
Run the blockchain application using Node.js:
node blockchain.js

No comments:

Post a Comment