區塊鏈是在電腦網路的節點之間共享資料的分類帳(分散式資料庫)。作為資料庫,區塊鏈以電子格式儲存資訊。區塊鏈的創新之處在於它保證了資料記錄的安全性和真實性,可信賴性(不需要沒有可信任的第三方)。
區塊鏈和典型資料庫的差異是資料結構。區塊鏈以block
的方式收集資訊。
block
是一種能永久記錄加密貨幣交易資料(或其他用途)的一種資料結構。類似於鍊錶。一個block
記錄了一些火所有尚未被驗證的最新交易。驗證資料後,block
將關閉,之後會建立一個新的block
來輸入和驗證新的交易。因此,一旦寫入,永久不能更改和刪除。
block
是區塊鏈中儲存和加密資訊的地方
##block由長數字標識,其中包括先前加密區塊的加密交易資訊和新的交易資訊
block以及其中的資訊必須由網路驗證
block = { 'index': 1, 'timestamp': 1506057125.900785, 'transactions': [ { 'sender': "8527147fe1f5426f9dd545de4b27ee00", 'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f", 'amount': 5, } ], 'proof': 324984774000, 'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" }
BlockChain類,建構函式建立一個空列表來儲存區塊鏈,再創建一個空列表來儲存交易。創建
block_chain.py
# block_chain.py class Blockchain: def __init__(self) -> None: self.chain = [] self.current_transactions = [] def new_block(self): # Creates a new Block and adds it to the chain pass def new_transaction(self): # Adds a new transaction to the list of transactions pass @staticmethod def hash(block): # Hashes a Block pass @property def last_block(self): # Returns the last Block in the chain pass
new_transaction負責這個
class Blockchain(object): ... def new_transaction(self, sender, recipient, amount) -> int: self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1
new_transaction# 將交易加入到清單後,它傳回交易將會被加入的區塊的索引——下一個要挖掘的塊。這將在以後對提交交易的用戶有用。
import hashlib import json from time import time class Blockchain: def __init__(self) -> None: self.chain = [] self.current_transactions = [] # Create the genesis block self.new_block(previous_hash=1, proof=100) def new_block(self, proof, previous_hash=None) -> dict: block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1]), } self.current_transactions = [] self.chain.append(block) return block def new_transaction(self, sender, recipient, amount) -> int: self.current_transactions.append( { 'sender': sender, 'recipient': recipient, 'amount': amount, } ) return self.last_block['index'] + 1 @property def last_block(self) -> dict: # Returns the last Block in the chain return self.chain[-1] @staticmethod def hash(block) -> str: block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest()
class Blockchain(object): def proof_of_work(self, last_proof) -> int: proof = 0 while self.valid_proof(last_proof, proof) is False: proof += 1 return proof @staticmethod def valid_proof(last_proof, proof) -> bool: guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:4] == '0000'
Flask框架。
flask
pip install flask我們的伺服器將在我們的區塊鏈網路中形成單一節點,在同級目錄下建立一個
app.py:
from uuid import uuid4 from time import time from textwrap import dedent from flask import Flask, jsonify, request from block_chain import Blockchain # 实例化应用 app = Flask(__name__) # 创建随机节点名称 node_identifier = str(uuid4()).replace('_', '') # 实例化block_chain类 block_chain = Blockchain() # 创建/mine端点 @app.route('/mine', methods=['GET']) def mine(): block_chain.new_transaction( sender="0", recipient=node_identifier, amount=1, ) last_block = block_chain.last_block last_proof = last_block['proof'] proof = block_chain.proof_of_work(last_proof) previous_hash = block_chain.hash(last_block) block = block_chain.new_block(proof, previous_hash) response = { 'message': "New Block Forged", 'index': block['index'], 'transactions': block['transactions'], 'proof': block['proof'], 'previous_hash': block['previous_hash'], } return jsonify(response), 200 @app.route('/transactions/new', methods=['POST']) def new_transaction(): return "We'll add a new transaction" @app.route('/chain', methods=['GET']) def full_chain(): response = { 'chain': block_chain.chain, 'length': len(block_chain.chain), } return jsonify(response), 200 # 修改端口号 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
flask run ##透過api軟體(本次使用的是api fox)來傳送請求:
註冊新節點
... from urllib.parse import urlparse ... class Blockchain: def __init__(self) -> None: ... self.nodes = set() ... def register_node(self, address) -> None: parsed_url = urlparse(address) self.nodes.add(parsed_url.netloc)
衝突
... import requests class Blockchain: ... def valid_chain(self, chain): last_block = chain[0] current_index = 1 while current_index < len(chain): block = chain[current_index] print(f'{last_block}') print(f'{block}') print("\n-----------\n") # Check that the hash of the block is correct if block['previous_hash'] != self.hash(last_block): return False # Check that the Proof of Work is correct if not self.valid_proof(last_block['proof'], block['proof']): return False last_block = block current_index += 1 return True def resolve_conflicts(self): """ This is our Consensus Algorithm, it resolves conflicts by replacing our chain with the longest one in the network. :return: <bool> True if our chain was replaced, False if not """ neighbours = self.nodes new_chain = None # We're only looking for chains longer than ours max_length = len(self.chain) # Grab and verify the chains from all the nodes in our network for node in neighbours: response = requests.get(f'http://{node}/chain') if response.status_code == 200: length = response.json()['length'] chain = response.json()['chain'] # Check if the length is longer and the chain is valid if length > max_length and self.valid_chain(chain): max_length = length new_chain = chain # Replace our chain if we discovered a new, valid chain longer than ours if new_chain: self.chain = new_chain return True return False
第一个方法 valid_chain() 负责通过遍历每个块并验证哈希和证明来检查链是否有效。resolve_conflicts() 是一种循环遍历我们所有相邻节点、下载它们的链并使用上述方法验证它们的方法。如果找到一个有效的链,其长度大于我们的,我们将替换我们的。
让我们将两个端点注册到我们的 API,一个用于添加相邻节点,另一个用于解决冲突:
@app.route('/nodes/register', methods=['POST']) def register_nodes(): values = request.get_json() nodes = values.get('nodes') if nodes is None: return "Error: Please supply a valid list of nodes", 400 for node in nodes: blockchain.register_node(node) response = { 'message': 'New nodes have been added', 'total_nodes': list(blockchain.nodes), } return jsonify(response), 201 @app.route('/nodes/resolve', methods=['GET']) def consensus(): replaced = blockchain.resolve_conflicts() if replaced: response = { 'message': 'Our chain was replaced', 'new_chain': blockchain.chain } else: response = { 'message': 'Our chain is authoritative', 'chain': blockchain.chain } return jsonify(response), 200
在这一点上,如果你愿意,你可以拿一台不同的机器,并在你的网络上启动不同的节点。或者在同一台机器上使用不同的端口启动进程。比如创建两个端口5000和6000来进行尝试。
以上是Python如何建構區塊鏈的詳細內容。更多資訊請關注PHP中文網其他相關文章!