Python中如何实现一个简化的区块链?GitHub上有哪些推荐的Python区块链项目,代码简洁易懂?

一个简化的区块链实现,包含区块、交易、账户、节点网络。大致的区块链骨架都有了,项目地址: https://github.com/Carlos-Zen/blockchain-python


Python中如何实现一个简化的区块链?GitHub上有哪些推荐的Python区块链项目,代码简洁易懂?
5 回复

我准备上个节点供大家链接,有人有需要嘛


要自己写一个简化的区块链,核心就是搞懂区块、链式结构和工作量证明。下面这个例子包含了创建区块、计算哈希和简单的挖矿逻辑,直接就能跑:

import hashlib
import time
import json

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.nonce = 0
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        block_string = json.dumps({
            "index": self.index,
            "timestamp": self.timestamp,
            "data": self.data,
            "previous_hash": self.previous_hash,
            "nonce": self.nonce
        }, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

    def mine_block(self, difficulty):
        target = "0" * difficulty
        while self.hash[:difficulty] != target:
            self.nonce += 1
            self.hash = self.calculate_hash()

class Blockchain:
    def __init__(self):
        self.chain = [self.create_genesis_block()]
        self.difficulty = 4

    def create_genesis_block(self):
        return Block(0, time.time(), "Genesis Block", "0")

    def get_latest_block(self):
        return self.chain[-1]

    def add_block(self, new_block):
        new_block.previous_hash = self.get_latest_block().hash
        new_block.mine_block(self.difficulty)
        self.chain.append(new_block)

    def is_chain_valid(self):
        for i in range(1, len(self.chain)):
            current = self.chain[i]
            previous = self.chain[i-1]
            
            if current.hash != current.calculate_hash():
                return False
            if current.previous_hash != previous.hash:
                return False
        return True

# 使用示例
if __name__ == "__main__":
    my_blockchain = Blockchain()
    
    print("挖矿第1个区块...")
    my_blockchain.add_block(Block(1, time.time(), {"amount": 4}, ""))
    
    print("挖矿第2个区块...")
    my_blockchain.add_block(Block(2, time.time(), {"amount": 8}, ""))
    
    # 打印区块链
    for block in my_blockchain.chain:
        print(f"区块 #{block.index}")
        print(f"哈希: {block.hash}")
        print(f"前哈希: {block.previous_hash}")
        print(f"数据: {block.data}")
        print(f"随机数: {block.nonce}")
        print("-" * 50)
    
    print(f"区块链有效: {my_blockchain.is_chain_valid()}")

GitHub上推荐这几个Python区块链项目,代码都比较干净:

  1. naivechain - 极简实现,就几百行代码,适合理解基础概念
  2. blockchain-python - 结构清晰,包含了基本的P2P网络通信
  3. simple-blockchain - 注释详细,每个步骤都解释得很清楚
  4. pycoin - 功能更全,包含了交易和钱包的基础实现

建议直接看naivechain,最直接。

贡献一个节点 106.14.191.186:3008
python console node add 106.14.191.186:3008

感谢楼主,学习了~~~

不客气,共同学习

回到顶部