【发布时间】:2018-12-03 11:58:12
【问题描述】:
我正在尝试从我在网上找到的网站重新创建一些代码。该代码应该在 Node.js 中创建一个区块链。但是,当我运行它时,它会识别命令:
return sha(JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp);
返回错误:
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)
我应该导入什么来定义 sha? 整个代码:
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));
链接到我从以下地址找到的网站:https://codingislove.com/simple-blockchain-javascript/
【问题讨论】:
-
有一个超级酷的东西叫谷歌,我曾经在
crypto中找到Hashclass。
标签: javascript node.js encryption blockchain sha