国外有个大侠用node.js写了区块链项目,一起来学习一下。
暂时还没包括POW和P2P协议和如何奖励。接下来几篇将详细叙述POW(nonce),P2P,reward
// 引入加密模块
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.caculateHash(); //hash 值
}
caculateHash(){
return SHA256(this.index+this.timestamp+
JSON.stringify(this.data)+this.previousHash).toString(); //计算hash值
}
}
//定义区块链
class Blockchain{
constructor()
{
this.chain=[this.createGensisBlock()]; //创建世纪块
}
//创世纪块
createGensisBlock(){
return new Block(0,"2017/01/01","GenesisBlock","");
}
//获取当前块
getLatestBlock(){
return this.chain[this.chain.length-1];
}
//增加区块到区块链中
addBlock(newBlock){
newBlock.previousHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.caculateHash();
this.chain.push(newBlock);
}
//验证块的有效性,当前块的hash等于nonce+前一个块的hash值 nonce相当于难度,暂时还没加入
//加入nonce后需要生成的hash值得前两位为0,正真的比特币hash至少要前72位为零,可见难度有多大,需要多大的计算能力
isChainValid(){
for(let i=1;i<this.chain.length;i++){
const currentBlock = this.chain[i];
const previousBlock = this.chain[i-1];
if(currentBlock.hash != currentBlock.caculateHash()){
return false;
}
if(currentBlock.previousHash!=previousBlock.hash){
return false;
}
return true;
}
}
}
let xuanBlock = new Blockchain();
xuanBlock.addBlock(new Block(1,"10/10/2017",{amount:4}));
xuanBlock.addBlock(new Block(2,"10/12/2017",{amount:2}));
console.log(JSON.stringify(xuanBlock,null,4));
热门工具 换一换