用Python模拟区块链含注释说明

用Python模拟区块链含注释说明

今天我们用Python来模拟区块链,以下是代码及注释说明:

import hashlib
import datetime

class Block:
    def __init__(self, data, previous_hash):
        self.timestamp = datetime.datetime.now()
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.calc_hash()

    def calc_hash(self):
        sha = hashlib.sha256()
        sha.update(str(self.timestamp).encode('utf-8') +
                   str(self.data).encode('utf-8') +
                   str(self.previous_hash).encode('utf-8'))
        return sha.hexdigest()

class Blockchain:
    def __init__(self):
        self.chain = [Block("Genesis Block", "")]

    def add_block(self, data):
        previous_block = self.chain[-1]
        new_block = Block(data, previous_block.hash)
        self.chain.append(new_block)

    def print_blocks(self):
        for i, block in enumerate(self.chain):
            print("[Block {}]".format(i))
            print("Timestamp: ", block.timestamp)
            print("Data: ", block.data)
            print("SHA256 Hash: ", block.hash)
            print("Previous Hash: ", block.previous_hash)
            print("-" * 20)

# 创建区块链对象
my_blockchain = Blockchain()

# 添加数据块
my_blockchain.add_block("This is the first block.")
my_blockchain.add_block("This is the second block.")
my_blockchain.add_block("This is the third block.")

# 打印区块链
my_blockchain.print_blocks()

代码注释说明:

– 第1行:import hashlib 导入 hashlib 模块,用于计算 SHA256 哈希值。

– 第2行:import datetime 导入 datetime 模块,用于保存和显示时间戳。

– 第4-12行:定义 Block 类,表示区块的数据结构。每个块包括时间戳、数据、前一个块的哈希值和当前块的哈希值。

– 第14-24行:定义 Blockchain 类,表示整个区块链的数据结构。初始时只有一个“创世块”(即第一个区块,其前一个区块的哈希值为“空字符串”)。

– 第26-33行:定义 add_block() 方法,用于向区块链中添加新的块。

– 第35-48行:定义 print_blocks() 方法,用于打印整个区块链中所有的块信息。

– 第51-53行:创建一个 Blockchain 对象 my_blockchain。

– 第56-58行:向区块链中添加3个块,分别包含不同的数据信息。

– 第61行:打印整个区块链的信息。

发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/75211
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!

(0)
股市刺客的头像股市刺客
上一篇 2024 年 7 月 12 日
下一篇 2024 年 7 月 12 日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注