1 回复
我来给你写一个最简单的区块链实现,核心就是区块的链式结构和哈希验证。
import hashlib
import json
import time
from datetime import datetime
class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
def calculate_hash(self):
block_string = f"{self.index}{self.timestamp}{self.data}{self.previous_hash}"
return hashlib.sha256(block_string.encode()).hexdigest()
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
def create_genesis_block(self):
# 创世区块
return Block(0, datetime.now(), "Genesis Block", "0")
def get_latest_block(self):
return self.chain[-1]
def add_block(self, new_data):
latest_block = self.get_latest_block()
new_block = Block(
index=len(self.chain),
timestamp=datetime.now(),
data=new_data,
previous_hash=latest_block.hash
)
self.chain.append(new_block)
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
return True
# 使用示例
if __name__ == "__main__":
# 创建区块链
my_blockchain = Blockchain()
# 添加一些区块
print("添加区块...")
my_blockchain.add_block("第一笔交易: Alice给Bob转了10个币")
my_blockchain.add_block("第二笔交易: Bob给Charlie转了5个币")
my_blockchain.add_block("第三笔交易: Charlie给David转了3个币")
# 打印区块链
print("\n区块链内容:")
for block in my_blockchain.chain:
print(f"区块 #{block.index}")
print(f"时间戳: {block.timestamp}")
print(f"数据: {block.data}")
print(f"前一个哈希: {block.previous_hash}")
print(f"当前哈希: {block.hash}")
print("-" * 50)
# 验证区块链
print(f"\n区块链是否有效: {my_blockchain.is_chain_valid()}")
# 尝试篡改数据
print("\n尝试篡改第二个区块的数据...")
my_blockchain.chain[1].data = "篡改的数据"
print(f"篡改后区块链是否有效: {my_blockchain.is_chain_valid()}")
这个实现包含了区块链的核心概念:
- 区块结构:每个区块包含索引、时间戳、数据、前一个区块的哈希和当前哈希
- 哈希计算:使用SHA-256算法确保数据完整性
- 链式连接:每个区块都包含前一个区块的哈希,形成不可篡改的链
- 创世区块:区块链的第一个特殊区块
- 验证机制:可以检查整个链的完整性
运行这个代码,你会看到区块链如何工作,以及为什么一旦数据被写入就很难被篡改——因为修改任何一个区块都会导致后续所有区块的哈希不匹配。
总结:区块链的核心就是哈希链加上时间戳。

