摘要:def __init__(self, index, Timestamp, data, previous_hash, nonce=0):
以下是一个使用 Python 实现的简单区块链核心功能示例:
python
import Hashlib
import time
class Block:
def __init__(self, index, Timestamp, data, previous_hash, nonce=0):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.nonce = nonce
self.hash = self.calculate_hash
def calculate_hash(self):
"""计算当前区块的哈希值"""
block_string = f"{self.index}{self.timestamp}{self.data}{self.previous_hash}{self.nonce}"
return hashlib.SHA256(block_string.encode).hexdigest
class blockchain:
def __init__(self):
self.chain =
self.create_genesis_block
def create_genesis_block(self):
"""创建创世区块(第一个区块)"""
genesis_block = Block(0, time.time, "Genesis Block", "0")
self.chain.append(genesis_block)
def add_block(self, data):
"""添加新区块到链上"""
previous_block = self.chain[-1]
new_index = previous_block.index + 1
new_timestamp = time.time
previous_hash = previous_block.hash
# 工作量证明获取有效 Nonce
nonce = self.proof_of_work(new_index, new_timestamp, data, previous_hash)
# 创建新区块
new_block = Block(new_index, new_timestamp, data, previous_hash, nonce)
self.chain.append(new_block)
def proof_of_work(self, index, timestamp, data, previous_hash, difficulty=4):
"""工作量证明算法,找到满足条件的 Nonce"""
nonce = 0
arget = '0' * difficulty # 定义难度目标(例如:前导 4 个零)
while True:
block_string = f"{index}{timestamp}{data}{previous_hash}{nonce}"
hash_attempt = hashlib.sha256(block_string.encode).hexdigest
if hash_attempt.startswith(target):
print(f"Valid Nonce found: {nonce} | Hash: {hash_attempt}")
return nonce
nonce += 1
def is_chain_valid(self):
"""验证区块链的完整性"""
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i-1]
# 检查哈希值是否正确
if current_block.hash != current_block.calculate_hash:
return False
# 检查前一个哈希是否匹配
if current_block.previous_hash != previous_block.hash:
return False
# 检查工作量证明是否有效(哈希是否满足难度要求)
if not current_block.hash.startswith('0' * 4):
return False
return True
# 测试区块链
if __name__ == "__main__":
blockchain = Blockchain
# 添加两个新区块
print("Mining Block 1...")
blockchain.add_block("First Block Data")
print("Mining Block 2...")
blockchain.add_block("Second Block Data")
# 打印区块链信息
print("\nBlockchain Info:")
for block in blockchain.chain:
print(f"""
Index: {block.index}
Timestamp: {block.timestamp}
Data: {block.data}
Previous Hash: {block.previous_hash}
Nonce: {block.nonce}
Hash: {block.hash}
""")
# 验证区块链是否有效
print("Is blockchain valid?", blockchain.is_chain_valid)
关键功能说明:
区块结构 (Block 类)Ø 包含 index(区块高度)、timestamp(时间戳)、data(交易数据)、previous_hash(前一区块哈希)、nonce(随机数)和 hash(当前区块哈希)。
Ø 通过 calculate_hash 方法计算 SHA-256 哈希值。
区块链结构 (Blockchain 类)Ø create_genesis_block:初始化创世区块。
Ø add_block(data):添加新区块时执行工作量证明。
Ø proof_of_work:通过调整 Nonce 寻找满足难度要求的哈希值。
Ø is_chain_valid:验证区块链的完整性和有效性。
工作量证明 (PoW)Ø 要求哈希值以指定数量的前导零开头(例如:0000)。
Ø 通过暴力枚举 Nonce 值找到有效哈希。
创建区块链并添加两个新区块。打印每个区块的详细信息。验证区块链是否有效。难度调整:可通过修改 difficulty 参数(如 difficulty=2)降低计算复杂度。性能优化:实际应用中需使用更高效的 PoW 实现(如多线程/矿池)。数据扩展:可将 data 字段扩展为交易列表,并加入梅克尔树结构。来源:老客数据一点号