Skip to content

Instantly share code, notes, and snippets.

@AroraShreshth
Created October 10, 2019 12:27
Show Gist options
  • Save AroraShreshth/8f9b4da20f3aa2c72ed5f05288c7fc7c to your computer and use it in GitHub Desktop.
Save AroraShreshth/8f9b4da20f3aa2c72ed5f05288c7fc7c to your computer and use it in GitHub Desktop.
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 = '';
}
calculateHash (){
return SHA256(this.index + this.previousHash +this.timestamp+ JSON.stringify(this.data) + this.nonce).toString();
}
}
class Blockchain {
constructor() {
this.chain =[this.createGenesisBlock()];
}
createGenesisBlock(){
var b = new Block(0, "21/02/2019","Genesis block", "0");
b.hash = b.calculateHash();
return b;
}
getLatestBlock(){
return this.chain[this.chain.length-1];
}
addBlock(newBlock){
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
isChainValid(){
for (let index = 1; index < this.chain.length; index++) {
const currentBlock = this.chain[index];
const previousBlock = this.chain[index-1];
if(currentBlock.hash !== currentBlock.calculateHash()){
return false;
}
if(currentBlock.previousHash !== previousBlock.hash){
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment