[Python] Blockchain 區塊鏈實作

程式語言:Python3.6+
Package:
requests
flask
json
time
uuid
urllib
程式碼皆是來自於 Learn Blockchains by Building One,感謝作者的無私貢獻

功能:簡單實現區塊鏈

簡單來說
  • 區塊鏈就是由無數的區塊(帳本)所組成的,而區塊(帳本)中有著一定數目的交易
  • 區塊(帳本)之間則是由 hash 所串連起來
    每一個區塊(帳本)都會記錄著前一個區塊(帳本)的 hash 值,並依此產生該區塊(帳本)的 hash 值
  • hash 值有指定格式,俗稱挖礦
    例如:再加上某個值後,hash 的前四位需為零,也就是 0000...,隨著 0 的數量上升,所需的計算量會大增
  • 最正確的區塊鏈則是最長的那個,因為耗費的計算力最大 
因以上特性,當偷改了一個區塊(帳本)等同要把之後所有的區塊(帳本)包含未來的都需更改
這幾乎是不可能的,除非計算力超過整體網路的 50%,但與其這麼辛苦倒不如乖乖的挖礦獲利

使用方法
建立節點
# 可看到相關參數
python web.py -h

# 建立指令
python web.py
python web.py -P 5000
python web.py -H 127.0.0.1 -P 5000

目前的區塊鏈
http://127.0.0.1:5000/chain

新增交易(POST),在此用 curl 實現 POST
curl http://127.0.0.1:5000/transactions/new -X POST -H "Content-Type: application/json" -d '{"sender": "d4ee26eee15148ee92c6cd394edd974e", "recipient": "someone-other-address", "amount": 5}'

# windows 需改為
curl http://127.0.0.1:5000/transactions/new -X POST -H "Content-Type: application/json" -d "{\"sender\": \"d4ee26eee15148ee92c6cd394edd974e\", \"recipient\": \"someone-other-address\", \"amount\": 5}"

新增區塊
http://127.0.0.1:5000/mine

註冊節點(POST),在此用 curl 實現 POST
curl http://127.0.0.1:5000/nodes/register -X POST -H "Content-Type: application/json" -d '{"nodes": ["http://127.0.0.1:5001"]}'

# windows 需改為
curl http://127.0.0.1:5000/nodes/register -X POST -H "Content-Type: application/json" -d "{\"nodes\": [\"http://127.0.0.1:5001\"]}"

同步區塊鏈
# 先建立新的節點
python web.py -H 127.0.0.1 -P 5001
# 觀看目前的狀況
http://127.0.0.1:5001/chain
# 註冊已存在節點
curl http://127.0.0.1:5001/nodes/register -X POST -H "Content-Type: application/json" -d "{\"nodes\": [\"http://127.0.0.1:5000\"]}"
# 同步
http://127.0.0.1:5001/nodes/resolve
程式碼

web.py

  1. from flask import Flask, jsonify, request
  2. from uuid import uuid4
  3.  
  4. from blockchain import Blockchain
  5.  
  6. # Instantiate our Node
  7. app = Flask(__name__)
  8.  
  9. # Generate a globally unique address for this node
  10. node_identifier = str(uuid4()).replace('-', '')
  11.  
  12. # Instantiate the Blockchain
  13. blockchain = Blockchain()
  14.  
  15.  
  16. @app.route('/chain', methods=['GET'])
  17. def full_chain():
  18. """
  19. 目前的區塊鏈
  20. """
  21. response = {
  22. 'chain': blockchain.chain,
  23. 'length': len(blockchain.chain),
  24. }
  25. return jsonify(response), 200
  26.  
  27.  
  28. @app.route('/transactions/new', methods=['POST'])
  29. def new_transaction():
  30. """
  31. 新增交易
  32. """
  33. values = request.get_json()
  34.  
  35. # Check that the required fields are in the POST'ed data
  36. required = ['sender', 'recipient', 'amount']
  37. if not all(k in values for k in required):
  38. return 'Missing values', 400
  39.  
  40. # Create a new Transaction
  41. index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
  42.  
  43. response = {'message': f'Transaction will be added to Block {index}'}
  44. return jsonify(response), 201
  45.  
  46.  
  47. @app.route('/mine', methods=['GET'])
  48. def mine():
  49. """
  50. 產生新的 block
  51. """
  52. # We run the proof of work algorithm to get the next proof...
  53. last_block = blockchain.last_block
  54. last_proof = last_block['proof']
  55. proof = blockchain.proof_of_work(last_proof)
  56.  
  57. # We must receive a reward for finding the proof.
  58. # The sender is "0" to signify that this node has mined a new coin.
  59. blockchain.new_transaction(
  60. sender="0",
  61. recipient=node_identifier,
  62. amount=1,
  63. )
  64.  
  65. # Forge the new Block by adding it to the chain
  66. previous_hash = blockchain.hash(last_block)
  67. block = blockchain.new_block(proof, previous_hash)
  68.  
  69. response = {
  70. 'message': "New Block Forged",
  71. 'index': block['index'],
  72. 'transactions': block['transactions'],
  73. 'proof': block['proof'],
  74. 'previous_hash': block['previous_hash'],
  75. }
  76. return jsonify(response), 200
  77.  
  78.  
  79. @app.route('/nodes/register', methods=['POST'])
  80. def register_nodes():
  81. """
  82. 註冊節點,別註冊到自己的
  83. """
  84. values = request.get_json()
  85.  
  86. nodes = values.get('nodes')
  87. if nodes is None:
  88. return "Error: Please supply a valid list of nodes", 400
  89.  
  90. for node in nodes:
  91. blockchain.register_node(node)
  92.  
  93. response = {
  94. 'message': 'New nodes have been added',
  95. 'total_nodes': list(blockchain.nodes),
  96. }
  97. return jsonify(response), 201
  98.  
  99.  
  100. @app.route('/nodes/resolve', methods=['GET'])
  101. def consensus():
  102. """
  103. 更新成最長的區塊鏈
  104. """
  105. replaced = blockchain.resolve_conflicts()
  106.  
  107. if replaced:
  108. response = {
  109. 'message': 'Our chain was replaced',
  110. 'new_chain': blockchain.chain
  111. }
  112. else:
  113. response = {
  114. 'message': 'Our chain is authoritative',
  115. 'chain': blockchain.chain
  116. }
  117.  
  118. return jsonify(response), 200
  119.  
  120.  
  121. if __name__ == '__main__':
  122. from argparse import ArgumentParser
  123.  
  124. parser = ArgumentParser()
  125. parser.add_argument('-P', '--port', default=5000, type=int, help='port to listen on')
  126. parser.add_argument('-H', '--host', default='127.0.0.1', type=str, help='host to listen on')
  127. args = parser.parse_args()
  128. port = args.port
  129. host = args.host
  130. app.run(host=host, port=port)

blockchain.py

  1. import hashlib
  2. import json
  3. from time import time
  4.  
  5. import requests
  6. from urllib.parse import urlparse
  7.  
  8.  
  9. class Blockchain(object):
  10. def __init__(self):
  11. self.current_transactions = []
  12. self.chain = []
  13. self.nodes = set()
  14.  
  15. # Create the genesis block
  16. self.new_block(previous_hash=1, proof=100)
  17.  
  18. def new_block(self, proof, previous_hash=None):
  19. """
  20. Create a new Block in the Blockchain
  21. :param proof: <int> The proof given by the Proof of Work algorithm
  22. :param previous_hash: (Optional) <str> Hash of previous Block
  23. :return: <dict> New Block
  24. """
  25.  
  26. block = {
  27. 'index': len(self.chain) + 1,
  28. 'timestamp': time(),
  29. 'transactions': self.current_transactions,
  30. 'proof': proof,
  31. 'previous_hash': previous_hash or self.hash(self.chain[-1]),
  32. }
  33.  
  34. # Reset the current list of transactions
  35. self.current_transactions = []
  36.  
  37. self.chain.append(block)
  38. return block
  39.  
  40. def new_transaction(self, sender, recipient, amount):
  41. """
  42. Creates a new transaction to go into the next mined Block
  43. :param sender: <str> Address of the Sender
  44. :param recipient: <str> Address of the Recipient
  45. :param amount: <int> Amount
  46. :return: <int> The index of the Block that will hold this transaction
  47. """
  48. self.current_transactions.append({
  49. 'sender': sender,
  50. 'recipient': recipient,
  51. 'amount': amount,
  52. })
  53.  
  54. return self.last_block['index'] + 1
  55.  
  56. @property
  57. def last_block(self):
  58. return self.chain[-1]
  59.  
  60. @staticmethod
  61. def hash(block):
  62. """
  63. Creates a SHA-256 hash of a Block
  64. :param block: <dict> Block
  65. :return: <str>
  66. """
  67.  
  68. # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
  69. block_string = json.dumps(block, sort_keys=True).encode()
  70. return hashlib.sha256(block_string).hexdigest()
  71.  
  72. def proof_of_work(self, last_proof):
  73. """
  74. Simple Proof of Work Algorithm:
  75. - Find a number p' such that hash(pp') contains leading 4 zeroes
  76. - p is the previous proof, and p' is the new proof
  77. :param last_proof: <int>
  78. :return: <int>
  79. """
  80.  
  81. proof = 0
  82. while self.valid_proof(last_proof, proof) is False:
  83. proof += 1
  84.  
  85. return proof
  86.  
  87. @staticmethod
  88. def valid_proof(last_proof, proof):
  89. """
  90. Validates the Proof: Does hash(last_proof, proof) contain 4 leading zeroes?
  91. :param last_proof: <int> Previous Proof
  92. :param proof: <int> Current Proof
  93. :return: <bool> True if correct, False if not.
  94. """
  95.  
  96. guess = f'{last_proof}{proof}'.encode()
  97. guess_hash = hashlib.sha256(guess).hexdigest()
  98. return guess_hash[:4] == "0000"
  99.  
  100. def register_node(self, address):
  101. """
  102. Add a new node to the list of nodes
  103. :param address: <str> Address of node. Eg. 'http://192.168.0.5:5000'
  104. :return: None
  105. """
  106.  
  107. parsed_url = urlparse(address)
  108. self.nodes.add(parsed_url.netloc)
  109.  
  110. def valid_chain(self, chain):
  111. """
  112. Determine if a given blockchain is valid
  113. :param chain: <list> A blockchain
  114. :return: <bool> True if valid, False if not
  115. """
  116.  
  117. last_block = chain[0]
  118. current_index = 1
  119.  
  120. while current_index < len(chain):
  121. block = chain[current_index]
  122. print(f'{last_block}')
  123. print(f'{block}')
  124. print("\n-----------\n")
  125. # Check that the hash of the block is correct
  126. if block['previous_hash'] != self.hash(last_block):
  127. return False
  128.  
  129. # Check that the Proof of Work is correct
  130. if not self.valid_proof(last_block['proof'], block['proof']):
  131. return False
  132.  
  133. last_block = block
  134. current_index += 1
  135.  
  136. return True
  137.  
  138. def resolve_conflicts(self):
  139. """
  140. This is our Consensus Algorithm, it resolves conflicts
  141. by replacing our chain with the longest one in the network.
  142. :return: <bool> True if our chain was replaced, False if not
  143. """
  144.  
  145. neighbours = self.nodes
  146. new_chain = None
  147.  
  148. # We're only looking for chains longer than ours
  149. max_length = len(self.chain)
  150.  
  151. # Grab and verify the chains from all the nodes in our network
  152. for node in neighbours:
  153. response = requests.get(f'http://{node}/chain')
  154.  
  155. if response.status_code == 200:
  156. length = response.json()['length']
  157. chain = response.json()['chain']
  158.  
  159. # Check if the length is longer and the chain is valid
  160. if length > max_length and self.valid_chain(chain):
  161. max_length = length
  162. new_chain = chain
  163.  
  164. # Replace our chain if we discovered a new, valid chain longer than ours
  165. if new_chain:
  166. self.chain = new_chain
  167. return True
  168.  
  169. return False

參考

gochain

留言