- constructor(index, timestamp, data, previousHash = ''){ this.index = index; this.previousHash = previousHash; this.timestamp = timestamp; this.data = data; this.hash = this.calculateHash(); this.nonce = 0;}
- 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 枚币)。
- calculateHash() { return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce ).toString();}
将它们结合在一路,你会获得如下所示的区块类:
- class Block {
- constructor(index, timestamp, data, previousHash = '') {
- this.index = index; this.previousHash = previousHash;
- this.timestamp = timestamp;
- this.data = data;
- this.hash = this.calculateHash();
- this.nonce = 0;
- }
- calculateHash() { return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString(); }
- 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);
- }
- }
修改区块链如今,我们的区块已经拥有 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月31日 京东、微博、华为拭魅战专家与你合营商量容器技巧实践! 昨天数字泉币又一次全线暴跌,比特币的价格一度跌破了8000美元大年夜关。 据说比来币圈的社群氛围也都冷的出>>>详细阅读
本文标题:连编程语言都不懂?看完这篇你也会写区块链
地址:http://www.17bianji.com/lsqh/41009.html
1/2 1