Creating A Simple BlockChain using JavaScript

  • index(optional) — where exactly the block lies in the blockchain
  • timestamp- time at which block was created
  • data- Information that needs to be passed
  • hash- A unique identifier of the block
  • previousHash- hash of previous block that is connected
constSH256 = require("cryptjs/sha256");
class Block {
constructor(index, timestamp, data, previousHash = "") {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = "";
}
createHash() {
returnSH256(
this.index + this.timestamp + JSON.stringify(this.data)
).toString();
}
}
class BlockChain {
constructor() {
this.blockchain = [this.startGenesisBlock()];
}
startGenesisBlock() {
return new Block(0, "01/01/2020", "Initial Block in the Chain", "0");
}
getLatestBlock() {
return this.blockchain[this.blockchain.length - 1];
}
addNewBlock(newBlock) {
newBlock.precedingHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.createHash();
this.blockchain.push(newBlock);
}
}
  • startGenesisBlock- Genesis Block is the initial block in a chain. It uses the same Block class which we created earlier
  • getLatestBlock- To get the Latest block
  • addNewBlock- To add a new block. precedingHash of the block is updated with the hash of the latest block and a new hash is also created after which it gets added into the chain
letJBCoin = newBlockChain();
JBCoin.addNewBlock(
newBlock(1, "25/05/2021", {
sender: "Jay Bhanushali",
recipient: "Elon Musk",
quantity: 20,
})
);
JBCoin.addNewBlock(
newBlock(1, "26/05/2021", {
sender: "Elon Musk",
recipient: "Jay Bhanushali",
quantity: 100,
})
);
console.log(JSON.stringify(JBCoin, null, 4));

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jay Bhanushali

Jay Bhanushali

3 Followers

Venturing life, one bit at a time . I love to travel, read and write code