I'm trying to recreate some code from a website I found online. The code is supposed to create a blockchain in Node.js. However, when I run it, it does the recognize the command:
return sha(JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp);
It returns the error:
return sha(JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp);
^
ReferenceError: sha is not defined
at Block.getHash (C:\Users\winst\OneDrive\Documents\Blockchain\main.js:12:3)
at new Block (C:\Users\winst\OneDrive\Documents\Blockchain\main.js:8:19)
at BlockChain.addBlock (C:\Users\winst\OneDrive\Documents\Blockchain\main.js:22:14)
at Object.<anonymous> (C:\Users\winst\OneDrive\Documents\Blockchain\main.js:42:9)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
What should I import in order to sha to be defined? The whole code:
class Block{
constructor(index, data, prevHash){
this.index = index;
this.timestamp = Math.floor(Date.now() / 1000);
this.data = data;
this.prevHash = prevHash;
this.hash = this.getHash();
}
getHash(){
return sha(JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp);
}
}
class BlockChain{
constructor(){
this.chain = [];
}
addBlock(data){
let index = this.chain.length;
let prevHash = this.chain.length !== 0 ? this.chain[this.chain.length - 1].hash : 0;
let block = new Block(index, data, prevHash);
this.chain.push(block);
}
chainIsValid(){
for(var i=0;i<this.chain.length;i++){
if(this.chain[i].hash !== this.chain[i].getHash())
return false;
if(i > 0 && this.chain[i].prevHash !== this.chain[i-1].hash)
return false;
}
return true;
}
}
const CILCoin = new BlockChain();
CILCoin.addBlock({sender: "Bruce wayne", reciver: "Tony stark", amount: 100});
CILCoin.addBlock({sender: "Harrison wells", reciver: "Han solo", amount: 50});
CILCoin.addBlock({sender: "Tony stark", reciver: "Ned stark", amount: 75});
console.log(JSON.stringify(CILCoin, null, 4));