用js代码理解区块链,最简版本

要想理解区块链的应用场景,需要首先理解区块链的技术,用50行代码就可以初步理解什么是区块链

const SHA256 = require('js-sha256')//哈希算法

class Block{

constructor(index,data,previousHash){

this.index = index;

this.timestamp = new Date();

this.data = data

this.previousHash = previousHash;

this.hash = this.calcHash();

}

calcHash(){

var sha = SHA256.create();

return sha.hex();//blockchain的关键所在

}

static first(data='Genesis'){//创世区块

return new Block(0,data,'0')

}

static next(previous,data='Tranaction data...'){

return new Block(previous.index+1,data,previous.hash)

}

}

//let's get started

b0 = Block.first("Gensis")

b1 = Block.next(b0,"Tranaction Data...")

b2 = Block.next(b1,"Tranaction Data...")

b3 = Block.next(b2,"More Transaction Datasss...")

blockchain = [b0,b1,b2,b3]

console.log(blockchain)

输出结果如下

[ Block { index: 0, timestamp: 2017-12-29T17:39:00.839Z, data:'Gensis', previousHash:'0',hash:'b83beefe99777acf14995d6450cca2ffa3da9223eac4feb39d70bd9201880364'}, Block { index: 1, timestamp: 2017-12-29T17:39:00.841Z, data:'Tranaction Data...', previousHash:'b83beefe99777acf14995d6450cca2ffa3da9223eac4feb39d70bd9201880364',hash:'30653cac3d6415c677cfbbe881ad192979c61029843d03f9b40a3a192f76b593'}, Block { index: 2, timestamp: 2017-12-29T17:39:00.841Z, data:'Tranaction Data...', previousHash:'30653cac3d6415c677cfbbe881ad192979c61029843d03f9b40a3a192f76b593',hash:'9a629894800467082cb475f075e0ff1b600282a76264c9e29c88473b7fb31179'}, Block { index: 3, timestamp: 2017-12-29T17:39:00.841Z, data:'More Transaction Data...', previousHash:'9a629894800467082cb475f075e0ff1b600282a76264c9e29c88473b7fb31179',hash:'8036f9d8537c00099e71841e9803b128e802ab0f10323cbf1a1a786aeef84569'} ]

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20171230G01NRN00?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券