Blockchain Slip No 6 Solution

6. Write a JavaScript code for the implementation of block chain technology.(At least two block).


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

class Block
{
constructor(index,timestamp,transaction, data, previousHash = '')
{
this.index=index;
this.timestamp = timestamp;
this.transaction=transaction;
this.data = data;
this.previousHash = previousHash;
this.hash=this.calculateHash()
}
calculateHash()
{
return SHA256(this.index+this.previous+this.timestamp+JSON.stringify(this.data)).toString();
}
}

classBlockchain
{
constructor()
{
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock()
{
return new Block(0,"01/06/2020", "Genesis block", "0");
}
getLatestBlock(){
return this.chain[this.chain.length - 1];
}
addBlock(newBlock)
{
newBlock.previousHash=this.getLatestBlock().hash;
newBlock.hash=newBlock.calculateHash();
this.chain.push(newBlock);
}
}

class Transaction
{
constructor(Ac_name, Address, Acc_type)
{ this.Ac_name = Ac_name;
this.Address = Address;
this.Acc_type = Acc_type;
}
createTransaction(transaction){
this.pendingTransactions.push(transaction);
}
}

let t1 = new Blockchain();
t1.addBlock(new Block(1,"20/06/2020", { Ac_name: "Mr.Shivaji", Address:"Bhor",Acc_type: "Seving"}));
t1.addBlock(new Block(1,"20/06/2020", { Ac_name: "Mr.Deepak", Address:"Natambi",Acc_type: "Current"}));
console.log(JSON.stringify(t1, null, 4));

No comments:

Post a Comment