▼点击下方卡片关注我
▲点击上方卡片关注我
区块结构设计
1
import hashlib
2
import time
3
import json
4
from typing import List, Dict
6
class Block:
7
def __init__(self, index: int, transactions: List[Dict], timestamp: float, previous_hash: str):
8
self.index = index # 区块索引
9
self.transactions = transactions # 交易数据
10
self.timestamp = timestamp # 时间戳
11
self.previous_hash = previous_hash # 前一个区块的哈希值
12
self.nonce = 0 # 用于工作量证明
13
self.hash = self.calculate_hash() # 当前区块的哈希值
15
def calculate_hash(self) -> str:
16
# 计算区块的哈希值
17
block_string = json.dumps(self.__dict__, sort_keys=True)
18
return hashlib.sha256(block_string.encode()).hexdigest()
区块的哈希值包含了区块的所有信息,任何数据的改变都会导致哈希值变化 timestamp用float类型存储,精确到毫秒级别 序列化时必须用sort_keys=True,确保生成稳定的哈希值
区块链核心实现
1
class Blockchain:
2
def __init__(self):
3
self.chain = [self._create_genesis_block()]
4
self.difficulty = 4 # 工作量证明难度
5
self.pending_transactions = []
6
self.mining_reward = 10 # 挖矿奖励
8
def _create_genesis_block(self) -> Block:
9
# 创建创世区块
10
return Block(0, [], time.time(), “0”)
12
def mine_pending_transactions(self, miner_address: str):
13
# 打包pending的交易,挖出新区块
14
block = Block(len(self.chain), self.pending_transactions, time.time(),
15
self.chain[-1].hash)
17
self._proof_of_work(block)
18
print(f“区块已被挖出!花费时间: {time.time() - block.timestamp}秒”)
20
self.chain.append(block)
21
self.pending_transactions = [
22
{“from”: “network”, “to”: miner_address, “amount”: self.mining_reward}
23
]
工作量证明机制
1
def _proof_of_work(self, block: Block):
2
while block.hash[:self.difficulty] != “0” * self.difficulty:
3
block.nonce += 1
4
block.hash = block.calculate_hash()
⚠️ 小贴士:
difficulty越大,挖矿难度越高,4代表哈希值前4位必须都是0 nonce不断递增直到找到满足条件的哈希值 实际项目中difficulty会动态调整,保证出块时间相对稳定
交易与余额查询
1
def add_transaction(self, sender: str, recipient: str, amount: float):
2
self.pending_transactions.append({
3
“from”: sender,
4
“to”: recipient,
5
“amount”: amount
6
})
8
def get_balance(self, address: str) -> float:
9
balance = 0
10
for block in self.chain:
11
for transaction in block.transactions:
12
if transaction[“from”] == address:
13
balance -= transaction[“amount”]
14
if transaction[“to”] == address:
15
balance += transaction[“amount”]
16
return balance
1
# 创建区块链
2
coin = Blockchain()
4
# 发起几笔交易
5
coin.add_transaction(“小明”, “小红”, 50)
6
coin.add_transaction(“小红”, “小张”, 30)
8
# 挖矿打包交易
9
coin.mine_pending_transactions(“矿工小王”)
11
# 查询余额
12
print(f“小明的余额: {coin.get_balance('小明')}”)
13
print(f“小红的余额: {coin.get_balance('小红')}”)
14
print(f“矿工小王的余额: {coin.get_balance('矿工小王')}”)
实际区块链还需要考虑双花攻击、分叉处理等安全问题 交易签名验证也是必不可少的,这里为了简化省略了 生产环境要用更安全的随机数生成器,别直接用time模块
推 荐 阅 读
点赞分享
让钱和爱流向你