const SHA256 = require(“crypto-js/sha256”); class Block
{
constructor(index,timestamp,data,previoushash=‘‘)
{
this.index = index; this.timestamp = timestamp; this.data = data; this.previoushash = previoushash; this.hash = this.calculateHash();
}
calculateHash()
{
return SHA256(this.index+this.timestamp+this.previoushash+JSON.stringify(this.data)).toString();
}
} //close block class class Blockchain
{
constructor(index,timestamp,data,previoushash=‘‘)
{
this.index = index; this.timestamp = timestamp; this.data = data; this.previoushash = previoushash;
this.chain =[this.createGenesisBlock()];
}
createGenesisBlock()
{
return new Block(0,”23/11/2021”,”This is First Program of Blockchain creation”,”0”);
}
addBlock(newBlock)
{
newBlock.previoushash = this.getLatestBlock().hash; newBlock.hash = newBlock.calculateHash(); this.chain.push(newBlock);
}
getLatestBlock()
{
return this.chain[this.chain.length-1];
}
} // close blockchain class
let block1 = new Block(1,”22/11/2021”,”Data1”,”0”);
let block2 = new Block(2,”21/11/2021”,”Second Block”,”“); let block3 = new Block(3,”14/05/2021”,”Third Block”,”“);
let myBlockchain = new Blockchain(); myBlockchain.addBlock(block1); myBlockchain.addBlock(block2); myBlockchain.addBlock(block3); console.log(JSON.stringify(myBlockchain,null,4));
output: