分页: 1 / 1

第一个区块链演示程序python

发表于 : 2026-01-26 18:51
rungod

代码: 全选

import hashlib
import time
from typing import List, Dict, Any

class Block:
    """区块类,包含基础属性和哈希计算"""
    def __init__(self, index: int, timestamp: float, data: Dict[str, Any], previous_hash: str):
        self.index = index
        self.timestamp = timestamp
        self.data = data  # 存储交易或其他信息
        self.previous_hash = previous_hash
        self.nonce = 0  # 用于工作量证明
        self.hash = self.calculate_hash()

    def calculate_hash(self) -> str:
        """计算当前区块的SHA-256哈希值"""
        block_string = f"{self.index}{self.timestamp}{self.data}{self.previous_hash}{self.nonce}"
        return hashlib.sha256(block_string.encode()).hexdigest()

    def mine_block(self, difficulty: int) -> None:
        """工作量证明挖矿(简单实现)"""
        while self.hash[:difficulty] != '0' * difficulty:
            self.nonce += 1
            self.hash = self.calculate_hash()

class Blockchain:
    """区块链类,管理区块的创建和验证"""
    def __init__(self):
        self.chain: List[Block] = []
        self.difficulty = 2  # 控制挖矿难度
        self.create_genesis_block()

    def create_genesis_block(self) -> None:
        """创建创世区块(第一个区块)"""
        genesis_block = Block(0, time.time(), {"message": "Genesis Block"}, "0")
        self.chain.append(genesis_block)

    def add_block(self, data: Dict[str, Any]) -> None:
        """添加新区块到链上"""
        last_block = self.chain[-1]
        new_block = Block(
            index=len(self.chain),
            timestamp=time.time(),
            data=data,
            previous_hash=last_block.hash
        )
        new_block.mine_block(self.difficulty)
        self.chain.append(new_block)

    def is_chain_valid(self) -> bool:
        """验证区块链完整性"""
        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("正在挖矿第1个区块...")
    my_blockchain.add_block({"sender": "Alice", "receiver": "Bob", "amount": 5})

    print("正在挖矿第2个区块...")
    my_blockchain.add_block({"sender": "Bob", "receiver": "Charlie", "amount": 3})

    # 打印区块链
    for block in my_blockchain.chain:
        print(f"\n区块 #{block.index}")
        print(f"时间戳: {block.timestamp}")
        print(f"数据: {block.data}")
        print(f"前哈希: {block.previous_hash}")
        print(f"当前哈希: {block.hash}")

    # 验证链
    print("\n区块链是否有效?", "是" if my_blockchain.is_chain_valid() else "否")
屏幕截图 2026-01-26 184837.png