# 一个区块的基本结构 # { # "index": 0, # "timestamp": "", # "transactions" : [ # { # "sender": "", # "recipient": "", # "amount": 5 # } # ], # "proof": "", # "previous_hash": "" # } import hashlib import json from time import time from uuid import uuid4 from flask import Flask, request from flask.json import jsonify class Blockchain: def __init__(self): # 定义一个区块链 self.chain = [] # 定义一个交易信息 self.current_transactions = [] # 定义一个创世区块 self.new_block(proof=100, previous_hash=1) # 新建一个区块 def new_block(self, proof, previous_hash=None): block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.last_block) } 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 # 计算区块的哈希值 @staticmethod def hash(block): block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string) # 获取区块链里面最后一个块 @property def last_block(self): return self.chain[-1] # 工作量证明 def proof_of_work(self, last_proof: int) -> int: proof = 0 while self.valid_proof(last_proof, proof) is False: proof += 1 print(proof) return proof # 挖矿动作 @staticmethod def valid_proof(last_proof: int, proof: int) -> bool: guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() print(guess_hash) return guess_hash[0:4] == "0000" # 节点之间的通讯 app = Flask(__name__) blockchain = Blockchain() # 生成一个uuid给自己做交易名称 node_identifier = str(uuid4()).replace('-', '') # 测试通讯 @app.route('/index', methods=['GET']) def index(): return 'Hello BlockChain' # 接收交易信息请求 @app.route('/transactions/new', methods=['POST']) def new_transactions(): values = request.get_json() required = ['sender', 'recipient', 'amount'] if values is None: return 'Missing values', 400 if not all(k in values for k in required): return 'Missing values', 400 index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = { 'message': f'Transaction will be added to block {index}' } return jsonify(response), 201 # 打包交易 -> 挖矿 @app.route('/mine', methods=['GET']) def mine(): last_block = blockchain.last_block last_proof = last_block['proof'] # 挖矿,并添加工作量证明 proof = blockchain.proof_of_work(last_proof) # 给自己一个交易信息 blockchain.new_transaction(sender='0', recipient=node_identifier, amount=1) block = blockchain.new_block(proof, None) response = { 'message': 'New Block Forged', 'block': block['index'], 'transactions': block['transactions'], 'proof': block['proof'], 'previous_hash': block['previous_hash'] } return jsonify(response), 200 # 返回整个区块链信息 @app.route('/chain', methods=['GET']) def full_chain(): response = { 'chain': blockchain.chain, 'length': len(blockchain.chain) } return jsonify(response), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)