如何用python写一个有字数上限的文字区块链?
我们想要创建一个简单的区块链,其中每个块包含一些文本数据,并且有字数上限。
假设每个块的最大字数限制为100字。如果超过,我们需要进行截断或者其他处理(这里我们选择截断)。
我们还将实现基本的区块链结构,包括前一个块的哈希、当前块的数据和哈希,以及时间戳。
我们将使用SHA-256哈希算法。
步骤:
-
定义块(Block)的结构。
-
创建区块链(Blockchain)类。
-
在添加新区块时,检查文本数据的字数,如果超过100字,则截断(保留前100字)。
-
每个块包含以下信息:索引、时间戳、数据、前一个块的哈希和当前块的哈希。
注意:我们不考虑挖矿难度,所以我们的区块链是一个简单的版本。
让我们开始编写代码。
使用Python实现有字数上限的文字区块链
下面是一个简单的基于Python的文字区块链实现,其中每个区块都有字数限制。
import hashlib
import json
import time
from typing import List, Dict, Any
class TextBlock:
"""文字区块类"""
def __init__(self, index: int, text: str, previous_hash: str, max_text_length: int = 100):
"""
初始化区块
Args:
index: 区块索引
text: 区块文字内容
previous_hash: 前一个区块的哈希值
max_text_length: 文字内容的最大长度
"""
self.index = index
self.timestamp = time.time()
self.text = text[:max_text_length] # 确保文字不超过限制
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
self.max_text_length = max_text_length
def calculate_hash(self) -> str:
"""计算当前区块的哈希值"""
block_string = json.dumps({
"index": self.index,
"timestamp": self.timestamp,
"text": self.text,
"previous_hash": self.previous_hash
}, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
def is_valid(self) -> bool:
"""验证区块的有效性"""
# 检查文字长度是否超过限制
if len(self.text) > self.max_text_length:
return False
# 检查哈希值是否正确
if self.hash != self.calculate_hash():
return False
return True
def to_dict(self) -> Dict[str, Any]:
"""将区块转换为字典"""
return {
"index": self.index,
"timestamp": self.timestamp,
"text": self.text,
"previous_hash": self.previous_hash,
"hash": self.hash,
"max_text_length": self.max_text_length
}
class TextBlockchain:
"""文字区块链类"""
def __init__(self, max_text_length: int = 100):
"""
初始化区块链
Args:
max_text_length: 每个区块文字内容的最大长度
"""
self.chain: List[TextBlock] = []
self.max_text_length = max_text_length
self.create_genesis_block()
def create_genesis_block(self):
"""创建创世区块"""
genesis_block = TextBlock(
index=0,
text="Genesis Block",
previous_hash="0",
max_text_length=self.max_text_length
)
self.chain.append(genesis_block)
def get_latest_block(self) -> TextBlock:
"""获取最新的区块"""
return self.chain[-1]
def add_block(self, text: str) -> bool:
"""
添加新的区块到链上
Args:
text: 要添加的文字内容
Returns:
添加是否成功
"""
# 检查文字长度
if len(text) > self.max_text_length:
print(f"文字长度超过限制: {len(text)} > {self.max_text_length}")
return False
previous_block = self.get_latest_block()
new_block = TextBlock(
index=len(self.chain),
text=text,
previous_hash=previous_block.hash,
max_text_length=self.max_text_length
)
# 验证新区块
if not new_block.is_valid():
print("新区块无效")
return False
self.chain.append(new_block)
return True
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():
print(f"区块 {current_block.index} 的哈希值无效")
return False
# 检查当前区块是否指向正确的前一个区块
if current_block.previous_hash != previous_block.hash:
print(f"区块 {current_block.index} 的前一个哈希值无效")
return False
# 检查区块内容是否有效
if not current_block.is_valid():
print(f"区块 {current_block.index} 的内容无效")
return False
return True
def display_chain(self):
"""显示整个区块链"""
for block in self.chain:
print(f"区块 #{block.index}")
print(f"时间戳: {block.timestamp}")
print(f"文字内容: {block.text}")
print(f"前一个哈希: {block.previous_hash}")
print(f"当前哈希: {block.hash}")
print("-" * 50)
# 示例使用
if __name__ == "__main__":
# 创建区块链,设置最大文字长度为50个字符
blockchain = TextBlockchain(max_text_length=50)
# 添加一些区块
texts = [
"这是第一个区块的文字内容",
"这是第二个区块的文字,稍微长一些但仍然在限制范围内",
"这个文字内容太长了,应该会被截断或者拒绝添加,让我们看看会发生什么" * 2, # 这个会超过限制
"这是第四个区块"
]
for text in texts:
success = blockchain.add_block(text)
if success:
print(f"成功添加区块: {text[:30]}...")
else:
print(f"添加区块失败: {text[:30]}...")
# 验证区块链
print(f"\n区块链是否有效: {blockchain.is_chain_valid()}")
# 显示区块链
print("\n区块链内容:")
blockchain.display_chain()
功能说明
-
TextBlock类:
-
表示单个区块
-
包含索引、时间戳、文字内容、前一个区块哈希和当前哈希
-
自动计算哈希值
-
验证区块有效性
-
-
TextBlockchain类:
-
管理整个区块链
-
创建创世区块
-
添加新区块(检查字数限制)
-
验证整个区块链的完整性
-
-
主要特性:
-
字数限制检查
-
哈希链式结构
-
区块链完整性验证
-
易于扩展
-
扩展建议
-
可以添加工作量证明(PoW)机制
-
可以实现分布式网络
-
可以添加交易验证机制
-
可以增加数据持久化功能
这个实现提供了一个基础框架,您可以根据具体需求进行修改和扩展