区块链源代码分析(1)

国外有个大侠用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));
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值