Posted By : Mohd
Cryptocurrency is a decentralized form of digital currency that operates independently of a central bank or government. Cryptocurrency development relies on blockchain technology, which is a distributed ledger that records all transactions across multiple computers or nodes. In this blog post, we will simulate a blockchain with javascript code in which users can have wallets that contain public and private keys.
We will simulate a blockchain using JavaScript code, where users can possess wallets containing public and private keys. Within this simulation, users have the ability to initiate transactions that are subsequently incorporated into blocks, eventually forming a complete blockchain structure.
For the implementation, we will have 4 classes - Transaction, Block, Wallet, and Chain.
This class simulates the transaction on a blockchain
Constructor:
toString() method:
Suggested Post | MPC Wallet Development | Enhancing Crypto Asset Security
Block Class
This class simulates the blocks on the blockchain.
Constructor:
getHash() method:
toString() method:
Also, Visit | AI Crypto Trading Bots | Reshaping Crypto Trading
This class simulates the wallet on the blockchain.
Constructor:
send(amount, receiverAddress) method:
This class simulates the blockchain itself.
Constructor:
getPreviousBlockHash() method:
insertBlock(transaction, senderAddress, sig) method:
getBalance(address) method:
Check It Out | Hiring Smart Contract Developers Made Easy"‹"‹"‹"‹"‹"‹"‹
"‹"‹"‹"‹"‹"‹"‹
const crypto = require('crypto');
// Transaction class to demostrate transactions on blockchain
class Transaction {
// A transaction will have amount, sender address, reciever address
constructor(amount, senderAddress, recieverAddress) {
this.amount = amount;
this.senderAddress = senderAddress;
this.recieverAddress = recieverAddress;
}
// Convert the transaction details to string
toString() {
return JSON.stringify(this);
}
}
// Block class to demonstrate blocks in blockchain
class Block {
// A block consists of hash of previous block, transactions and time
constructor(previousHash, transaction, timestamp = Date.now()) {
this.previousHash = previousHash;
this.transaction = transaction;
this.timestamp = timestamp;
}
// Function to get the hash of the block
getHash() {
const json = JSON.stringify(this);
const hash = crypto.createHash('SHA256');
hash.update(json).end();
const hex = hash.digest('hex');
return hex;
}
// Convert the block details to string
toString() {
return JSON.stringify(this);
}
}
class Wallet {
constructor() {
// Create public and private keys at the time of instantiation
const keys = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
});
this.privateKey = keys.privateKey;
this.publicKey = keys.publicKey;
}
// Function to send the transaction
send(amount, recieverAddress) {
const transaction = new Transaction(
amount,
this.publicKey,
recieverAddress
);
const shaSign = crypto.createSign('SHA256');
// add the transaction json
shaSign.update(transaction.toString()).end();
// sign the SHA with the private key
const signature = shaSign.sign(this.privateKey);
Chain.instance.insertBlock(transaction, this.publicKey, signature);
}
}
// Chain class to demonstrate the blockchain itself
class Chain {
// Only instance of the chain class
static instance = new Chain();
// initializing our chain with no records
constructor() {
this.chain = [new Block('', new Transaction(0, 'abc', 'xyz'))];
}
// Returns the hash of the previous block
getPreviousBlockHash() {
// sending the entire block itself
return this.chain[this.chain.length - 1].getHash();
}
// Add new block in the chain
insertBlock(transaction, senderAddress, sig) {
// create verifier
const verify = crypto.createVerify('SHA256');
// add the transaction JSON
verify.update(transaction.toString());
// Verify it with the sender's public key
const isValid = verify.verify(senderAddress, sig);
if (isValid) {
const block = new Block(this.getPreviousBlockHash(), transaction);
console.log('Block added: ', block.toString());
this.chain.push(block);
}
}
// Function to get the balance of a user
getBalance(address) {
let balance = 0;
this.chain.forEach((block) => {
if (block.transaction.senderAddress === address) {
balance -= block.transaction.amount;
}
if (block.transaction.recieverAddress === address) {
balance += block.transaction.amount;
}
});
return balance;
}
}
const satoshi = new Wallet();
const vitalik = new Wallet();
const sid = new Wallet();
satoshi.send(50, vitalik.publicKey);
vitalik.send(23, sid.publicKey);
sid.send(5, vitalik.publicKey);
const vitalikBal = Chain.instance.getBalance(vitalik.publicKey);
const sidBal = Chain.instance.getBalance(sid.publicKey);
console.log(Chain.instance);
console.log('Vitalik has: ', vitalikBal);
console.log('Sid has: ', sidBal);
September 8, 2024 at 02:34 am
Your comment is awaiting moderation.