Blockchain Slip No 3 Solution

3. Write a blockchain application in JavaScript for the implementation of SHA256 () function.

//The structure of blockchain program

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.previous+this.timestamp+JSON.stringify(this.data)).toString();
}
}

class Blockchain
{
constructor()
{
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock()
{
return new Block(0,"01/01/2017", "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);
}
}
let t1 = new Blockchain();

t1.addBlock(new Block(1,"20/07/2017", { amount: 4 }));
t1.addBlock(new Block(2,"22/07/2017", { amount: 10 }));
console.log(JSON.stringify(t1, null, 4));

No comments:

Post a Comment