python源码实例
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash
def calculate_hash(index, previous_hash, timestamp, data):
value = str(index) + str(previous_hash) + str(timestamp) + str(data)
return hashlib.sha256(value.encode('utf-8')).hexdigest()
def create_genesis_block():
return Block(0, "0", int(time.time()), "Genesis Block", calculate_hash(0, "0", int(time.time()), "Genesis Block"))
def create_new_block(previous_block, data):
index = previous_block.index + 1
timestamp = int(time.time())
hash = calculate_hash(index, previous_block.previous_hash, timestamp, data)
return Block(index, previous_block.previous_hash, timestamp, data, hash)
def is_chain_valid(blockchain):
for i in range(1, len(blockchain)):
current_block = blockchain[i]
previous_block = blockchain[i - 1]
if current_block.hash != calculate_hash(current_block.index, current_block.previous_hash, current_block.timestamp, current_block.data):
return False
if current_block.previous_hash != previous_block.hash:
return False
return True
# 区块链初始化
blockchain = [create_genesis_block()]
previous_block = blockchain[0]
# 添加新区块到区块链中
for i in range(1, 10): # 添加10个新区块到区块链中作为示例
blockchain.append(create_new_block(previous_block, f"Block #{i}"))
previous_block = blockchain[-1] # 更新previous_block为最新添加的区块
这个代码示例定义了一个Block
类,用于表示区块链中的每个区块。每个区块包含一个索引、前一个区块的哈希值、时间戳、数据和自己的哈希值。此外,代码中还定义了几个辅助函数来帮助创建新的区块、验证区块链的完整性等。