哈希力量归集文库路径访问: 首页 > 无人驾驶智能汽车 > 飞行汽车/无人机

用 Python 撸一个区块链

Python开发 ☉ 文 来源:Python开发 2018-06-24 @ 哈希力量

【小哈划重点:首先你需要知道区块链是由被称为区块的记录构成的不可变的、有序的链式结构,这些记录可以是交易、文件或任何你想要的数据,最重要的是它们是通过 Hash 连接起来的。】

相信你和我一样对数字货币的崛起感到新奇,并且想知道其背后的技术——区块链是怎样实现的。reB哈希力量 | 通用人工智能文库

但是理解区块链并非易事,至少对于我来说是如此。晦涩难懂的视频、漏洞百出的教程以及示例的匮乏令我倍受挫折。reB哈希力量 | 通用人工智能文库

我喜欢在实践中学习,通过写代码来学习技术会掌握得更牢固。如果你也这样做,那么读完本文,你将获得一个可用的区块链以及对区块链的深刻理解。reB哈希力量 | 通用人工智能文库

开始之前...reB哈希力量 | 通用人工智能文库

首先你需要知道区块链是由被称为区块的记录构成的不可变的、有序的链式结构,这些记录可以是交易、文件或任何你想要的数据,最重要的是它们是通过 Hash 连接起来的。reB哈希力量 | 通用人工智能文库

如果你不了解 Hash,这里有个例子reB哈希力量 | 通用人工智能文库

其次,你需要安装 Python3.6+,Flask,RequestreB哈希力量 | 通用人工智能文库

  1. pip install Flask==0.12.2 requests==2.18.4reB哈希力量 | 通用人工智能文库

同时你还需要一个 HTTP 客户端,比如 Postman,cURL 或任何其它客户端。reB哈希力量 | 通用人工智能文库

最终的源代码在这里:reB哈希力量 | 通用人工智能文库

第一步: 打造一个 BlockchainreB哈希力量 | 通用人工智能文库

新建一个文件 blockchain.py,本文所有的代码都写在这一个文件中。首先创建一个 Blockchain 类,在构造函数中我们创建了两个列表,一个用于储存区块链,一个用于储存交易。reB哈希力量 | 通用人工智能文库

  1. class Blockchain(object):reB哈希力量 | 通用人工智能文库

  2. def __init__(self):reB哈希力量 | 通用人工智能文库

  3. self.chain = []reB哈希力量 | 通用人工智能文库

  4. self.current_transactions = []reB哈希力量 | 通用人工智能文库


  5. reB哈希力量 | 通用人工智能文库

  6. def new_block(self):reB哈希力量 | 通用人工智能文库

  7. # Creates a new Block and adds it to the chainreB哈希力量 | 通用人工智能文库

  8. passreB哈希力量 | 通用人工智能文库


  9. reB哈希力量 | 通用人工智能文库

  10. def new_transaction(self):reB哈希力量 | 通用人工智能文库

  11. # Adds a new transaction to the list of transactionsreB哈希力量 | 通用人工智能文库

  12. passreB哈希力量 | 通用人工智能文库


  13. reB哈希力量 | 通用人工智能文库

  14. @staticmethodreB哈希力量 | 通用人工智能文库

  15. def hash(block):reB哈希力量 | 通用人工智能文库

  16. # Hashes a BlockreB哈希力量 | 通用人工智能文库

  17. passreB哈希力量 | 通用人工智能文库


  18. reB哈希力量 | 通用人工智能文库

  19. @propertyreB哈希力量 | 通用人工智能文库

  20. def last_block(self):reB哈希力量 | 通用人工智能文库

  21. # Returns the last Block in the chainreB哈希力量 | 通用人工智能文库

  22. passreB哈希力量 | 通用人工智能文库

一个区块有五个基本属性:index,timestamp(in Unix time),transaction 列表,工作量证明(稍后解释)以及前一个区块的 Hash 值。reB哈希力量 | 通用人工智能文库

  1. block = {reB哈希力量 | 通用人工智能文库

  2. 'index': 1,reB哈希力量 | 通用人工智能文库

  3. 'timestamp': 1506057125.900785,reB哈希力量 | 通用人工智能文库

  4. 'transactions': [reB哈希力量 | 通用人工智能文库

  5. {reB哈希力量 | 通用人工智能文库

  6. 'sender': "8527147fe1f5426f9dd545de4b27ee00",reB哈希力量 | 通用人工智能文库

  7. 'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",reB哈希力量 | 通用人工智能文库

  8. 'amount': 5,reB哈希力量 | 通用人工智能文库

  9. }reB哈希力量 | 通用人工智能文库

  10. ],reB哈希力量 | 通用人工智能文库

  11. 'proof': 324984774000,reB哈希力量 | 通用人工智能文库

  12. 'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"reB哈希力量 | 通用人工智能文库

  13. }reB哈希力量 | 通用人工智能文库

到这里,区块链的概念应该比较清楚了:每个新的区块都会包含上一个区块的 Hash 值。这一点非常关键,它是区块链不可变性的根本保障。如果攻击者破坏了前面的某个区块,那么后面所有区块的 Hash 都会变得不正确。不理解?慢慢消化~reB哈希力量 | 通用人工智能文库

我们需要一个向区块添加交易的方法:reB哈希力量 | 通用人工智能文库

  1. class Blockchain(object):reB哈希力量 | 通用人工智能文库

  2. ...reB哈希力量 | 通用人工智能文库


  3. reB哈希力量 | 通用人工智能文库

  4. def new_transaction(self, sender, recipient, amount):reB哈希力量 | 通用人工智能文库

  5. """reB哈希力量 | 通用人工智能文库

  6. Creates a new transaction to go into the next mined BlockreB哈希力量 | 通用人工智能文库

  7. :param sender:Address of the SenderreB哈希力量 | 通用人工智能文库

  8. :param recipient:Address of the RecipientreB哈希力量 | 通用人工智能文库

  9. :param amount:AmountreB哈希力量 | 通用人工智能文库

  10. :return:The index of the Block that will hold this transactionreB哈希力量 | 通用人工智能文库

  11. """reB哈希力量 | 通用人工智能文库


  12. reB哈希力量 | 通用人工智能文库

  13. self.current_transactions.append({reB哈希力量 | 通用人工智能文库

  14. 'sender': sender,reB哈希力量 | 通用人工智能文库

  15. 'recipient': recipient,reB哈希力量 | 通用人工智能文库

  16. 'amount': amount,reB哈希力量 | 通用人工智能文库

  17. })reB哈希力量 | 通用人工智能文库


  18. reB哈希力量 | 通用人工智能文库

  19. return self.last_block['index'] + 1reB哈希力量 | 通用人工智能文库

new_transaction() 方法向列表中添加一个交易记录,并返回该记录将被添加到的区块——下一个待挖掘的区块——的索引,稍后在用户提交交易时会有用。reB哈希力量 | 通用人工智能文库

当 Blockchain 实例化后,我们需要创建一个初始的区块(创世块),并且给它预设一个工作量证明。reB哈希力量 | 通用人工智能文库

除了添加创世块的代码,我们还需要补充 newblock(), newtransaction() 和 hash() 方法:reB哈希力量 | 通用人工智能文库

  1. import hashlibreB哈希力量 | 通用人工智能文库

  2. import jsonreB哈希力量 | 通用人工智能文库

  3. from time import timereB哈希力量 | 通用人工智能文库


  4. reB哈希力量 | 通用人工智能文库

  5. class Blockchain(object):reB哈希力量 | 通用人工智能文库

  6. def __init__(self):reB哈希力量 | 通用人工智能文库

  7. self.current_transactions = []reB哈希力量 | 通用人工智能文库

  8. self.chain = []reB哈希力量 | 通用人工智能文库


  9. reB哈希力量 | 通用人工智能文库

  10. # Create the genesis blockreB哈希力量 | 通用人工智能文库

  11. self.new_block(previous_hash=1, proof=100)reB哈希力量 | 通用人工智能文库


  12. reB哈希力量 | 通用人工智能文库

  13. def new_block(self, proof, previous_hash=None):reB哈希力量 | 通用人工智能文库

  14. block = {reB哈希力量 | 通用人工智能文库

  15. 'index': len(self.chain) + 1,reB哈希力量 | 通用人工智能文库

  16. 'timestamp': time(),reB哈希力量 | 通用人工智能文库

  17. 'transactions': self.current_transactions,reB哈希力量 | 通用人工智能文库

  18. 'proof': proof,reB哈希力量 | 通用人工智能文库

  19. 'previous_hash': previous_hash or self.hash(self.chain[-1]),reB哈希力量 | 通用人工智能文库

  20. }reB哈希力量 | 通用人工智能文库


  21. reB哈希力量 | 通用人工智能文库

  22. # Reset the current list of transactionsreB哈希力量 | 通用人工智能文库

  23. self.current_transactions = []reB哈希力量 | 通用人工智能文库


  24. reB哈希力量 | 通用人工智能文库

  25. self.chain.append(block)reB哈希力量 | 通用人工智能文库

  26. return blockreB哈希力量 | 通用人工智能文库


  27. reB哈希力量 | 通用人工智能文库

  28. def new_transaction(self, sender, recipient, amount):reB哈希力量 | 通用人工智能文库

  29. self.current_transactions.append({reB哈希力量 | 通用人工智能文库

  30. 'sender': sender,reB哈希力量 | 通用人工智能文库

  31. 'recipient': recipient,reB哈希力量 | 通用人工智能文库

  32. 'amount': amount,reB哈希力量 | 通用人工智能文库

  33. })reB哈希力量 | 通用人工智能文库


  34. reB哈希力量 | 通用人工智能文库

  35. return self.last_block['index'] + 1reB哈希力量 | 通用人工智能文库


  36. reB哈希力量 | 通用人工智能文库

  37. @propertyreB哈希力量 | 通用人工智能文库

  38. def last_block(self):reB哈希力量 | 通用人工智能文库

  39. return self.chain[-1]reB哈希力量 | 通用人工智能文库


  40. reB哈希力量 | 通用人工智能文库

  41. @staticmethodreB哈希力量 | 通用人工智能文库

  42. def hash(block):reB哈希力量 | 通用人工智能文库

  43. block_string = json.dumps(block, sort_keys=True).encode()reB哈希力量 | 通用人工智能文库

  44. return hashlib.sha256(block_string).hexdigest()reB哈希力量 | 通用人工智能文库

上面的代码应该很直观,我们基本上有了区块链的雏形。但此时你肯定很想知道一个区块究竟是怎样被创建或挖掘出来的。reB哈希力量 | 通用人工智能文库

新的区块来自工作量证明(PoW)算法。PoW 的目标是计算出一个符合特定条件的数字,这个数字对于所有人而言必须在计算上非常困难,但易于验证。这就是工作量证明的核心思想。reB哈希力量 | 通用人工智能文库

举个例子:reB哈希力量 | 通用人工智能文库

假设一个整数 x 乘以另一个整数 y 的积的 Hash 值必须以 0 结尾,即 hash(x * y) = ac23dc...0。设 x = 5,求 y?reB哈希力量 | 通用人工智能文库

  1. from hashlib import sha256reB哈希力量 | 通用人工智能文库

  2. x = 5reB哈希力量 | 通用人工智能文库

  3. y = 0 # We don't know what y should be yet...reB哈希力量 | 通用人工智能文库

  4. while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "0":reB哈希力量 | 通用人工智能文库

  5. y += 1reB哈希力量 | 通用人工智能文库

  6. print(f'The solution is y = {y}')reB哈希力量 | 通用人工智能文库

结果是 y = 21 // hash(5 * 21) = 1253e9373e...5e3600155e860reB哈希力量 | 通用人工智能文库

在比特币中,工作量证明算法被称为 Hashcash,它和上面的问题很相似,只不过计算难度非常大。这就是矿工们为了争夺创建区块的权利而争相计算的问题。通常,计算难度与目标字符串需要满足的特定字符的数量成正比,矿工算出结果后,就会获得一定数量的比特币奖励(通过交易)。reB哈希力量 | 通用人工智能文库

网络要验证结果,当然非常容易。reB哈希力量 | 通用人工智能文库

让我们来实现一个 PoW 算法,和上面的例子非常相似,规则是:寻找一个数 p,使得它与前一个区块的 proof 拼接成的字符串的 Hash 值以 4 个零开头。reB哈希力量 | 通用人工智能文库

  1. import hashlibreB哈希力量 | 通用人工智能文库

  2. import jsonreB哈希力量 | 通用人工智能文库

  3. from time import timereB哈希力量 | 通用人工智能文库

  4. from uuid import uuid4reB哈希力量 | 通用人工智能文库


  5. reB哈希力量 | 通用人工智能文库

  6. class Blockchain(object):reB哈希力量 | 通用人工智能文库

  7. ...reB哈希力量 | 通用人工智能文库


  8. reB哈希力量 | 通用人工智能文库

  9. def proof_of_work(self, last_proof):reB哈希力量 | 通用人工智能文库

  10. proof = 0reB哈希力量 | 通用人工智能文库

  11. while self.valid_proof(last_proof, proof) is False:reB哈希力量 | 通用人工智能文库

  12. proof += 1reB哈希力量 | 通用人工智能文库


  13. reB哈希力量 | 通用人工智能文库

  14. return proofreB哈希力量 | 通用人工智能文库


  15. reB哈希力量 | 通用人工智能文库

  16. @staticmethodreB哈希力量 | 通用人工智能文库

  17. def valid_proof(last_proof, proof):reB哈希力量 | 通用人工智能文库

  18. guess = f'{last_proof}{proof}'.encode()reB哈希力量 | 通用人工智能文库

  19. guess_hash = hashlib.sha256(guess).hexdigest()reB哈希力量 | 通用人工智能文库

  20. return guess_hash[:4] == "0000"reB哈希力量 | 通用人工智能文库

衡量算法复杂度的办法是修改零的个数。4 个零足够用于演示了,你会发现哪怕多一个零都会大大增加计算出结果所需的时间。reB哈希力量 | 通用人工智能文库

我们的 Blockchain 基本已经完成了,接下来我们将使用 HTTP requests 来与之交互。reB哈希力量 | 通用人工智能文库

第二步:作为 API 的 BlockchainreB哈希力量 | 通用人工智能文库

我们将使用 Flask 框架,它十分轻量并且很容易将网络请求映射到 Python 函数。reB哈希力量 | 通用人工智能文库

我们将创建三个接口:reB哈希力量 | 通用人工智能文库

  1. /transactions/new 创建一个交易并添加到区块reB哈希力量 | 通用人工智能文库


  2. reB哈希力量 | 通用人工智能文库

  3. /mine 告诉服务器去挖掘新的区块reB哈希力量 | 通用人工智能文库


  4. reB哈希力量 | 通用人工智能文库

  5. /chain 返回整个区块链reB哈希力量 | 通用人工智能文库

我们的服务器将扮演区块链网络中的一个节点。我们先添加一些常规代码:reB哈希力量 | 通用人工智能文库

  1. import hashlibreB哈希力量 | 通用人工智能文库

  2. import jsonreB哈希力量 | 通用人工智能文库

  3. from textwrap import dedentreB哈希力量 | 通用人工智能文库

  4. from time import timereB哈希力量 | 通用人工智能文库

  5. from uuid import uuid4reB哈希力量 | 通用人工智能文库

  6. from flask import Flask, jsonify, requestreB哈希力量 | 通用人工智能文库


  7. reB哈希力量 | 通用人工智能文库

  8. class Blockchain(object):reB哈希力量 | 通用人工智能文库

  9. ...reB哈希力量 | 通用人工智能文库


  10. reB哈希力量 | 通用人工智能文库

  11. # Instantiate our NodereB哈希力量 | 通用人工智能文库

  12. app = Flask(__name__)reB哈希力量 | 通用人工智能文库


  13. reB哈希力量 | 通用人工智能文库

  14. # Generate a globally unique address for this nodereB哈希力量 | 通用人工智能文库

  15. node_identifier = str(uuid4()).replace('-', '')reB哈希力量 | 通用人工智能文库


  16. reB哈希力量 | 通用人工智能文库

  17. # Instantiate the BlockchainreB哈希力量 | 通用人工智能文库

  18. blockchain = Blockchain()reB哈希力量 | 通用人工智能文库


  19. reB哈希力量 | 通用人工智能文库

  20. @app.route('/mine', methods=['GET'])reB哈希力量 | 通用人工智能文库

  21. def mine():reB哈希力量 | 通用人工智能文库

  22. return "We'll mine a new Block"reB哈希力量 | 通用人工智能文库


  23. reB哈希力量 | 通用人工智能文库

  24. @app.route('/transactions/new', methods=['POST'])reB哈希力量 | 通用人工智能文库

  25. def new_transaction():reB哈希力量 | 通用人工智能文库

  26. return "We'll add a new transaction"reB哈希力量 | 通用人工智能文库


  27. reB哈希力量 | 通用人工智能文库

  28. @app.route('/chain', methods=['GET'])reB哈希力量 | 通用人工智能文库

  29. def full_chain():reB哈希力量 | 通用人工智能文库

  30. response = {reB哈希力量 | 通用人工智能文库

  31. 'chain': blockchain.chain,reB哈希力量 | 通用人工智能文库

  32. 'length': len(blockchain.chain),reB哈希力量 | 通用人工智能文库

  33. }reB哈希力量 | 通用人工智能文库

  34. return jsonify(response), 200reB哈希力量 | 通用人工智能文库


  35. reB哈希力量 | 通用人工智能文库

  36. if __name__ == '__main__':reB哈希力量 | 通用人工智能文库

  37. app.run(host='127.0.0.1', port=5000)reB哈希力量 | 通用人工智能文库

这是用户发起交易时发送到服务器的请求:reB哈希力量 | 通用人工智能文库

  1. {reB哈希力量 | 通用人工智能文库

  2. "sender": "my address",reB哈希力量 | 通用人工智能文库

  3. "recipient": "someone else's address",reB哈希力量 | 通用人工智能文库

  4. "amount": 5reB哈希力量 | 通用人工智能文库

  5. }reB哈希力量 | 通用人工智能文库

我们已经有了向区块添加交易的方法,因此剩下的部分就很简单了:reB哈希力量 | 通用人工智能文库

  1. @app.route('/transactions/new', methods=['POST'])reB哈希力量 | 通用人工智能文库

  2. def new_transaction():reB哈希力量 | 通用人工智能文库

  3. values = request.get_json()reB哈希力量 | 通用人工智能文库


  4. reB哈希力量 | 通用人工智能文库

  5. # Check that the required fields are in the POST'ed datareB哈希力量 | 通用人工智能文库

  6. required = ['sender', 'recipient', 'amount']reB哈希力量 | 通用人工智能文库

  7. if not all(k in values for k in required):reB哈希力量 | 通用人工智能文库

  8. return 'Missing values', 400reB哈希力量 | 通用人工智能文库


  9. reB哈希力量 | 通用人工智能文库

  10. # Create a new TransactionreB哈希力量 | 通用人工智能文库

  11. index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])reB哈希力量 | 通用人工智能文库


  12. reB哈希力量 | 通用人工智能文库

  13. response = {'message': f'Transaction will be added to Block {index}'}reB哈希力量 | 通用人工智能文库

  14. return jsonify(response), 201reB哈希力量 | 通用人工智能文库

挖掘端正是奇迹发生的地方,它只做三件事:计算 PoW;通过新增一个交易授予矿工一定数量的比特币;构造新的区块并将其添加到区块链中。reB哈希力量 | 通用人工智能文库

  1. @app.route('/mine', methods=['GET'])reB哈希力量 | 通用人工智能文库

  2. def mine():reB哈希力量 | 通用人工智能文库

  3. # We run the proof of work algorithm to get the next proof...reB哈希力量 | 通用人工智能文库

  4. last_block = blockchain.last_blockreB哈希力量 | 通用人工智能文库

  5. last_proof = last_block['proof']reB哈希力量 | 通用人工智能文库

  6. proof = blockchain.proof_of_work(last_proof)reB哈希力量 | 通用人工智能文库


  7. reB哈希力量 | 通用人工智能文库

  8. # We must receive a reward for finding the proof.reB哈希力量 | 通用人工智能文库

  9. # The sender is "0" to signify that this node has mined a new coin.reB哈希力量 | 通用人工智能文库

  10. blockchain.new_transaction(reB哈希力量 | 通用人工智能文库

  11. sender="0",reB哈希力量 | 通用人工智能文库

  12. recipient=node_identifier,reB哈希力量 | 通用人工智能文库

  13. amount=1,reB哈希力量 | 通用人工智能文库

  14. )reB哈希力量 | 通用人工智能文库


  15. reB哈希力量 | 通用人工智能文库

  16. # Forge the new Block by adding it to the chainreB哈希力量 | 通用人工智能文库

  17. block = blockchain.new_block(proof)reB哈希力量 | 通用人工智能文库


  18. reB哈希力量 | 通用人工智能文库

  19. response = {reB哈希力量 | 通用人工智能文库

  20. 'message': "New Block Forged",reB哈希力量 | 通用人工智能文库

  21. 'index': block['index'],reB哈希力量 | 通用人工智能文库

  22. 'transactions': block['transactions'],reB哈希力量 | 通用人工智能文库

  23. 'proof': block['proof'],reB哈希力量 | 通用人工智能文库

  24. 'previous_hash': block['previous_hash'],reB哈希力量 | 通用人工智能文库

  25. }reB哈希力量 | 通用人工智能文库

  26. return jsonify(response), 200reB哈希力量 | 通用人工智能文库

需注意交易的接收者是我们自己的服务器节点,目前我们做的大部分事情都只是围绕 Blockchain 类进行交互。到此,我们的区块链就算完成了。reB哈希力量 | 通用人工智能文库

第三步:交互演示reB哈希力量 | 通用人工智能文库

使用 Postman 演示,略。reB哈希力量 | 通用人工智能文库

第四步:一致性reB哈希力量 | 通用人工智能文库

这真的很棒,我们已经有了一个基本的区块链可以添加交易和挖矿。但是,整个区块链系统必须是分布式的。既然是分布式的,那么我们究竟拿什么保证所有节点运行在同一条链上呢?这就是一致性问题,我们要想在网络中添加新的节点,就必须实现保证一致性的算法。reB哈希力量 | 通用人工智能文库

在实现一致性算法之前,我们需要找到一种方式让一个节点知道它相邻的节点。每个节点都需要保存一份包含网络中其它节点的记录。让我们新增几个接口:reB哈希力量 | 通用人工智能文库

  1. 1. /nodes/register 接收以 URL 的形式表示的新节点的列表reB哈希力量 | 通用人工智能文库


  2. reB哈希力量 | 通用人工智能文库

  3. 2. /nodes/resolve 用于执行一致性算法,用于解决任何冲突,确保节点拥有正确的链reB哈希力量 | 通用人工智能文库


  4. reB哈希力量 | 通用人工智能文库


  5. reB哈希力量 | 通用人工智能文库

  6. ...reB哈希力量 | 通用人工智能文库

  7. from urllib.parse import urlparsereB哈希力量 | 通用人工智能文库

  8. ...reB哈希力量 | 通用人工智能文库


  9. reB哈希力量 | 通用人工智能文库

  10. class Blockchain(object):reB哈希力量 | 通用人工智能文库

  11. def __init__(self):reB哈希力量 | 通用人工智能文库

  12. ...reB哈希力量 | 通用人工智能文库

  13. self.nodes = set()reB哈希力量 | 通用人工智能文库

  14. ...reB哈希力量 | 通用人工智能文库


  15. reB哈希力量 | 通用人工智能文库

  16. def register_node(self, address):reB哈希力量 | 通用人工智能文库

  17. parsed_url = urlparse(address)reB哈希力量 | 通用人工智能文库

  18. self.nodes.add(parsed_url.netloc)reB哈希力量 | 通用人工智能文库

注意到我们用 set 来储存节点,这是一种避免重复添加节点的简便方法。reB哈希力量 | 通用人工智能文库

前面提到的冲突是指不同的节点拥有的链存在差异,要解决这个问题,我们规定最长的合规的链就是最有效的链,换句话说,只有最长且合规的链才是实际存在的链。reB哈希力量 | 通用人工智能文库

让我们再添加两个方法,一个用于添加相邻节点,另一个用于解决冲突。reB哈希力量 | 通用人工智能文库

  1. ...reB哈希力量 | 通用人工智能文库

  2. import requestsreB哈希力量 | 通用人工智能文库


  3. reB哈希力量 | 通用人工智能文库

  4. class Blockchain(object)reB哈希力量 | 通用人工智能文库

  5. ...reB哈希力量 | 通用人工智能文库


  6. reB哈希力量 | 通用人工智能文库

  7. def valid_chain(self, chain):reB哈希力量 | 通用人工智能文库

  8. last_block = chain[0]reB哈希力量 | 通用人工智能文库

  9. current_index = 1reB哈希力量 | 通用人工智能文库


  10. reB哈希力量 | 通用人工智能文库

  11. while current_index < len(chain):reB哈希力量 | 通用人工智能文库

  12. block = chain[current_index]reB哈希力量 | 通用人工智能文库

  13. print(f'{last_block}')reB哈希力量 | 通用人工智能文库

  14. print(f'{block}')reB哈希力量 | 通用人工智能文库

  15. print("-----------")reB哈希力量 | 通用人工智能文库

  16. # Check that the hash of the block is correctreB哈希力量 | 通用人工智能文库

  17. if block['previous_hash'] != self.hash(last_block):reB哈希力量 | 通用人工智能文库

  18. return FalsereB哈希力量 | 通用人工智能文库


  19. reB哈希力量 | 通用人工智能文库

  20. # Check that the Proof of Work is correctreB哈希力量 | 通用人工智能文库

  21. if not self.valid_proof(last_block['proof'], block['proof']):reB哈希力量 | 通用人工智能文库

  22. return FalsereB哈希力量 | 通用人工智能文库


  23. reB哈希力量 | 通用人工智能文库

  24. last_block = blockreB哈希力量 | 通用人工智能文库

  25. current_index += 1reB哈希力量 | 通用人工智能文库


  26. reB哈希力量 | 通用人工智能文库

  27. return TruereB哈希力量 | 通用人工智能文库


  28. reB哈希力量 | 通用人工智能文库

  29. def resolve_conflicts(self):reB哈希力量 | 通用人工智能文库

  30. neighbours = self.nodesreB哈希力量 | 通用人工智能文库

  31. new_chain = NonereB哈希力量 | 通用人工智能文库


  32. reB哈希力量 | 通用人工智能文库

  33. # We're only looking for chains longer than oursreB哈希力量 | 通用人工智能文库

  34. max_length = len(self.chain)reB哈希力量 | 通用人工智能文库


  35. reB哈希力量 | 通用人工智能文库

  36. # Grab and verify the chains from all the nodes in our networkreB哈希力量 | 通用人工智能文库

  37. for node in neighbours:reB哈希力量 | 通用人工智能文库

  38. response = requests.get(f'http://{node}/chain')reB哈希力量 | 通用人工智能文库


  39. reB哈希力量 | 通用人工智能文库

  40. if response.status_code == 200:reB哈希力量 | 通用人工智能文库

  41. length = response.json()['length']reB哈希力量 | 通用人工智能文库

  42. chain = response.json()['chain']reB哈希力量 | 通用人工智能文库


  43. reB哈希力量 | 通用人工智能文库

  44. # Check if the length is longer and the chain is validreB哈希力量 | 通用人工智能文库

  45. if length > max_length and self.valid_chain(chain):reB哈希力量 | 通用人工智能文库

  46. max_length = lengthreB哈希力量 | 通用人工智能文库

  47. new_chain = chainreB哈希力量 | 通用人工智能文库


  48. reB哈希力量 | 通用人工智能文库

  49. # Replace our chain if we discovered a new, valid chain longer than oursreB哈希力量 | 通用人工智能文库

  50. if new_chain:reB哈希力量 | 通用人工智能文库

  51. self.chain = new_chainreB哈希力量 | 通用人工智能文库

  52. return TruereB哈希力量 | 通用人工智能文库


  53. reB哈希力量 | 通用人工智能文库

  54. return FalsereB哈希力量 | 通用人工智能文库

现在你可以新开一台机器,或者在本机上开启不同的网络接口来模拟多节点的网络,或者邀请一些朋友一起来测试你的区块链。reB哈希力量 | 通用人工智能文库

我希望本文能激励你创造更多新东西。我之所以对数字货币入迷,是因为我相信区块链会很快改变我们看待事物的方式,包括经济、政府、档案管理等。reB哈希力量 | 通用人工智能文库

  • 译者:kidney,略有删改reB哈希力量 | 通用人工智能文库

  • 原文地址:https://hackernoon.com/learn-blockchains-by-building-one-117428612f46reB哈希力量 | 通用人工智能文库

  • Python开发整理发布,转载请联系作者获得授权reB哈希力量 | 通用人工智能文库



收录来源链接或附上。内容并不代表投资建议。


本文收录后固定可引用URL链接
    http://www.haxililiang.com/jishu/jinjie/27976.html


☉ 文库同一主题内容智能推荐 ☉
哈希力量 ☉ 通用人工智能文库