```python
# 比特币代码示例
class Blockchain:
def __init__(self):
self.chain = []
self.current_transactions = []
# 创建创世块
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None):
"""
生成新块
:param proof:
通过工作证明算法得到的证明
:param previous_hash: (Optional) 前一个块的哈希值
:return: 新块
"""
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):
"""
生成新交易信息,信息将加入到下一个待挖的区块中
:param sender: 发送者的地址
:param recipient: 接收者的地址
:param amount: 金额
:return: 保存该交易的块的索引
"""
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return self.last_block['index'] 1
@staticmethod
def hash(block):
"""
生成块的 SHA-256 值
:param block: Block
:return:
"""
# 必须确保字典是有序的,否则会有不一致性
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
@property
def last_block(self):
# 返回链中的最后一个块
return self.chain[-1]
def proof_of_work(self, last_proof):
"""
简单的工作量证明算法:
- 查找一个 p' 使得 hash(pp') 以4个零开头
- p 是上一个块的证明, p' 是当前的证明
:param last_proof:
:return:
"""
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof = 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
"""
验证证明: 是否hash(last_proof, proof)以4个0开头?
:param last_proof: 上一个块的证明
:param proof: 当前的证明
:return: 有效为True,否则为False
"""
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
# 示例用法
blockchain = Blockchain()
blockchain.new_transaction("Alice", "Bob", 5)
blockchain.new_transaction("Bob", "Charlie", 3)
blockchain.new_block(proof=12345)
```