作家
登录

连编程语言都不懂?看完这篇你也会写区块链

作者: 来源: 2018-03-29 03:05:07 阅读 我要评论

  1. constructor(indextimestamp, data, previousHash = ''){ this.index = index; this.previousHash = previousHash; this.timestamp = timestamp; this.data = data; this.hash = this.calculateHash(); this.nonce = 0;} 
  1. mineBlock(difficulty) { while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")) { this.nonce++; this.hash = this.calculateHash(); } console.log("BLOCK MINED: " + this.hash);} 

最后,我们还须要更改一下 calculateHash() 函数。因为今朝它还没有应用 Nonce 来计算 hash。

请留意,该办法采取了参数 miningRewardAddress。如不雅你开端挖矿,你可以将你的钱包地址传递给此办法。一旦成功挖到矿,体系将创建一个新的交易来给你挖矿嘉奖(在这个栗子里是 100 枚币)。

  1. calculateHash() { return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce ).toString();} 

将它们结合在一路,你会获得如下所示的区块类:

  1. class Block {  
  2.   constructor(indextimestamp, data, previousHash = '') {  
  3.     this.index = index; this.previousHash = previousHash;  
  4.     this.timestamp = timestamp 
  5.     this.data = data;  
  6.     this.hash = this.calculateHash();  
  7.     this.nonce = 0;  
  8.   }  
  9.   calculateHash() { return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString(); }  
  10.   mineBlock(difficulty) {  
  11.         while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")) { this.nonce++; this.hash = this.calculateHash(); }  
  12.         console.log("BLOCK MINED: " + this.hash);  
  13.   }  

修改区块链如今,我们的区块已经拥有 Nonce 并且可以被开采了,我们还须要确保我们的区块链支撑这种新的行动。让我们先在区块链中添加一个新的属性来跟踪整条链的难度。我会将它设置为 2(这意味着区块的 hash 必须以 2 个 0 开首)。

在这里我仅仅是创建了一个区块链的实例,并且定名它为 SavjeeCoin。之后我在链上添加了一些区块。区块里可以包含任何你想要放的数据,不过在膳绫擎的代率攀里,我选择添加了一个带有 amount 属性的对象。 试着操作吧!在介绍里我曾说过区块链是弗成变的。一旦添加,区块就弗成能再变革了。让我们试一下。// 检查是否有效(将会返回true)console.log('Blockchain valid? ' + savjeeCoin.isChainValid());// 如今测验测验操作变革数据savjeeCoin.chain[1].data = http://developer.51cto.com/art/201803/{ amount: 100 };// 再次检查是否有效 (将会返回false)


  推荐阅读

  区块链未来3大发展趋势,它在2018年会凉透吗?

沙龙晃荡 | 3月31日 京东、微博、华为拭魅战专家与你合营商量容器技巧实践! 昨天数字泉币又一次全线暴跌,比特币的价格一度跌破了8000美元大年夜关。 据说比来币圈的社群氛围也都冷的出>>>详细阅读


本文标题:连编程语言都不懂?看完这篇你也会写区块链

地址:http://www.17bianji.com/lsqh/41009.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)