一、区块链与区块链结构
# Block.py
import hashlib
from datetime import datetime
class Block:
"""
区块链结构:
prev_hash: 父区块哈希值
data: 区块内容
timestamp: 区块创建时间
hash: 区块哈希值
"""
def __init__(self, data, prev_hash):
# 将传入的父区块哈希值和数据保存到变量中
self.prev_hash = prev_hash
self.data = data
# 获得当前的时间
self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 计算区块哈希值
# 获取哈希对象
message = hashlib.sha256()
# 先将数据内容转为字符串并进行编码,再将它们哈希
# 注意:update() 方法现在只接受 bytes 类型的数据,不接收 str 类型
message.update(str(self.prev_hash).encode('utf-8'))
message.update(str(self.prev_hash).encode('utf-8'))
message.update(str(self.prev_hash).encode('utf-8'))
# update() 更新 hash 对象,连续的调用该方法相当于连续的追加更新
# 返回字符串类型的消息摘要
self.hash = message.hexdigest()
# BlockChain.py
from Block import Block
class BlockChain:
"""
区块链结构体
blocks: 包含区块的列表
"""
def __init__(self):
self.blocks = []
def add_block(self, block):
"""
添加区块
:param block:
:return:
"""
self.blocks.append(block)
# 新建区块
genesis_block = Block(data="创世区块", prev_hash="")
new_block1 = Block(data="张三转给李四一个比特币", prev_hash=genesis_block.hash)
new_block2 = Block(data="张三转给王五三个比特币", prev_hash=genesis_block.hash)
# 新建一个区块链对象
blockChain = BlockChain()
# 将刚才新建的区块加入区块链
blockChain.add_block(genesis_block)
blockChain.add_block(new_block1)
blockChain.add_block(new_block2)
# 打印区块链信息
print("区块链包含区块个数为:%d\n" % len(blockChain.blocks))
blockHeight = 0
for block in blockChain.blocks:
print(f"本区块高度为:{blockHeight}")
print(f"父区块哈希:{block.prev_hash}")
print(f"区块内容:{block.data}")
print(f"区块哈希:{block.hash}")
print()
blockHeight += 1
二、加入工作量证明(POW)
# Block.py
import hashlib
from datetime import datetime
from time import time
class Block:
"""
区块链结构:
prev_hash: 父区块哈希值
data: 区块内容
timestamp: 区块创建时间
hash: 区块哈希值
nonce: 随机数
"""
def __init__(self, data, prev_hash):
# 将传入的父区块哈希值和数据保存到变量中
self.prev_hash = prev_hash
self.data = data
# 获得当前的时间
self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 设置随机数、哈希初始值为 None
self.nonce = None
self.hash = None
# 类的 __repr__() 方法定义了实例化对象的输出信息
def __repr__(self):
return f"区块内容:{self.data}\n区块哈希值:{self.hash}"
class ProofOfWork:
"""
工作量证明:
block: 区块