classBlockchain(object): def__init__(self): self.chain = [] self.current_transactions = [] defnew_block(self): # Creates a new Block and adds it to the chain pass defnew_transaction(self): # Adds a new transaction to the list of transactions pass @staticmethod defhash(block): # Hashes a Block pass
@property deflast_block(self): # Returns the last Block in the chain pass
classBlockchain(object): ... defnew_transaction(self, sender, recipient, amount): """ 生成新交易信息,信息将加入到下一个待挖的区块中 :param sender: Address of the Sender :param recipient: Address of the Recipient :param amount: Amount :return: The index of the Block that will hold this transaction """
# Create the genesis block self.new_block(previous_hash=1, proof=100)
defnew_block(self, proof, previous_hash=None): """ 生成新块 :param proof: The proof given by the Proof of Work algorithm :param previous_hash: (Optional) Hash of previous Block :return: New Block """
# Reset the current list of transactions self.current_transactions = []
self.chain.append(block) return block
defnew_transaction(self, sender, recipient, amount): """ 生成新交易信息,信息将加入到下一个待挖的区块中 :param sender: Address of the Sender :param recipient: Address of the Recipient :param amount: Amount :return: The index of the Block that will hold this transaction """ self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, })
# We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest()
import hashlib import json from textwrap import dedent from time import time from uuid import uuid4
from
flask import Flask
classBlockchain(object): ...
# Instantiate our Node app = Flask(__name__)
# Generate a globally unique address for this node node_identifier = str(uuid4()).replace('-', '')
# Instantiate the Blockchain blockchain = Blockchain()
@app.route('/mine', methods=['GET']) defmine(): return"We'll mine a new Block" @app.route('/transactions/new', methods=['POST']) defnew_transaction(): return"We'll add a new transaction"
# Check that the required fields are in the POST'ed data required = ['sender', 'recipient', 'amount'] ifnot all(k in values for k in required): return'Missing values', 400
# Create a new Transaction 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']) defmine(): # We run the proof of work algorithm to get the next proof... last_block = blockchain.last_block last_proof = last_block['proof'
] proof = blockchain.proof_of_work(last_proof)
class
Blockchain(object): def__init__(self): ... self.nodes = set() ...
defregister_node(self, address): """ Add a new node to the list of nodes :param address: Address of node. Eg. 'http://192.168.0.5:5000' :return: None """
classBlockchain(object) ... defvalid_chain(self, chain): """ Determine if a given blockchain is valid :param chain: A blockchain :return: True if valid, False if not """
last_block = chain[0] current_index = 1
while current_index < len(chain): block = chain[current_index] print(f'{last_block}') print(f'{block}') print("-----------") # Check that the hash of the block is correct if block['previous_hash'] != self.hash(last_block): returnFalse
# Check that the Proof of Work is correct ifnot self.valid_proof(last_block['proof'], block['proof']): returnFalse