classBlockchain(object):def__init__(self):
self.chain =[]
self.current_transactions =[]defnew_block(self):# Creates a new Block and adds it to the chainpassdefnew_transaction(self):# Adds a new transaction to the list of transactionspass
@staticmethoddefhash(block):# Hashes a Blockpass
@propertydeflast_block(self):# Returns the last Block in the chainpass
2.2. 在区块中添加交易信息
classBlockchain(object):...defnew_transaction(self, sender, recipient, amount):"""
Creates a new transaction to go into the next mined Block
:param sender: <str> Address of the Sender
:param recipient: <str> Address of the Recipient
:param amount: <int> Amount
:return: <int> The index of the Block that will hold this transaction
"""
self.current_transactions.append({'sender': sender,'recipient': recipient,'amount': amount,})return self.last_block['index']+1
注意,在列表中添加新交易之后,会返回该交易被加到的区块的索引,也就是指向下一个要挖的区块。
2.3. 创世区块和工作量证明
实例化Blockchain类之后,还需要新建一个创始区块。此外还要加入证明。
import hashlib
import json
from time import time
classBlockchain(object):def__init__(self):
self.current_transactions =[]
self.chain =[]# Create the genesis block
self.new_block(previous_hash=1, proof=100)defnew_block(self, proof, previous_hash=None):"""
Create a new Block in the Blockchain
:param proof: <int> The proof given by the Proof of Work algorithm
:param previous_hash: (Optional) <str> Hash of previous Block
:return: <dict> New Block
"""
block ={'index':len(self.chain)+1,'timestamp': time(),'transactions': self.current_transactions,'proof': proof,'previous_hash': previous_hash or self.hash(self.chain[-1]),}# Reset the current list of transactions
self.current_transactions =[]
self.chain.append(block)return block
defnew_transaction(self, sender, recipient, amount):"""
Creates a new transaction to go into the next mined Block
:param sender: <str> Address of the Sender
:param recipient: <str> Address of the Recipient
:param amount: <int> Amount
:return: <int> The index of the Block that will hold this transaction
"""
self.current_transactions.append({'sender': sender,'recipient': recipient,'amount': amount,})return self.last_block['index']+1
@propertydeflast_block(self):return self.chain[-1]
@staticmethoddefhash(block):"""
Creates a SHA-256 hash of a Block
:param block: <dict> Block
:return: <str>
"""# 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()
2.4. 完成工作量证明的书写
import hashlib
import json
from time import time
from uuid import uuid4
classBlockchain(object):...defproof_of_work(self, last_proof):"""
Simple Proof of Work Algorithm:
- Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p'
- p is the previous proof, and p' is the new proof
:param last_proof: <int>
:return: <int>
"""
proof =0while self.valid_proof(last_proof, proof)isFalse:
proof +=1return proof
@staticmethoddefvalid_proof(last_proof, proof):"""
Validates the Proof: Does hash(last_proof, proof) contain 4 leading zeroes?
:param last_proof: <int> Previous Proof
:param proof: <int> Current Proof
:return: <bool> True if correct, False if not.
"""
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()return guess_hash[:4]=="0000"