超简单版区块链实现教程
1. 地址生成
地址是比特币系统中用于接收和发送比特币的标识符。地址生成过程涉及多个加密步骤:
1.1 哈希函数
我们使用以下哈希函数: - SHA-256:将任意长度数据转换为256位哈希值 - RIPEMD-160:将SHA-256结果进一步压缩为160位 - Hash160:SHA-256后接RIPEMD-160的组合
def sha256(data: bytes) -> bytes:
return hashlib.sha256(data).digest()
def ripemd160(data: bytes) -> bytes:
ripemd = hashlib.new("ripemd160")
ripemd.update(data)
return ripemd.digest()
def hash160(data: bytes) -> bytes:
return ripemd160(sha256(data))
1.2 Base58编码
Base58是比特币地址使用的编码方式,去除了容易混淆的字符(0,O,I,l)。
BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def base58_encode(data: bytes) -> str:
num = int.from_bytes(data, "big")
encoded = ""
while num > 0:
num, mod = divmod(num, 58)
encoded = BASE58_ALPHABET[mod] + encoded
leading_zeroes = len(data) - len(data.lstrip(b'\x00'))
return "1" * leading_zeroes + encoded
1.3 地址生成流程
获取公钥(通常来自椭圆曲线加密)
计算Hash160(公钥)
添加版本号(主网为0x00)
计算校验和(双SHA-256)
Base58Check编码
def public_key_to_address(public_key_hex: str) -> str:
public_key_bytes = bytes.fromhex(public_key_hex)
pubkey_hash = hash160(public_key_bytes)
versioned_payload = b'\x00' + pubkey_hash
return base58check_encode(versioned_payload)
1.4 地址验证
通过校验和验证地址的有效性:
def is_valid_address(address: str) -> bool:
try:
decoded = base58_decode(address)
payload, checksum = decoded[:-4], decoded[-4:]
return sha256(sha256(payload))[:4] == checksum
except Exception:
return False
2. 交易结构与签名
比特币交易是比特币系统的核心,记录了比特币的转移过程。我们的实现包含以下关键组件:
2.1 交易数据结构
class Transaction:
def init(self, from_address: str, to_address: str, value: int, comment: str = ""):
self.from_address = from_address
self.to_address = to_address
self.value = value
self.comment = comment
2.2 交易签名
使用椭圆曲线数字签名算法(ECDSA)对交易进行签名:
def sign_transaction(transaction: Transaction, private_key_hex: str) -> str:
private_key_bytes = bytes.fromhex(private_key_hex)
signing_key = SigningKey.from_string(private_key_bytes, curve=SECP256k1)
tx_copy = transaction.serialize()
signature = signing_key.sign(tx_copy)
return signature.hex()
2.3 交易验证
验证交易签名是否有效:
def is_valid(self):
public_key = SigningKey.from_string(
bytes.fromhex(self.transaction.from_address),
curve=SECP256k1
).verifying_key
try:
public_key.verify(
bytes.fromhex(self.signature),
self.transaction.serialize()
)
return True
except:
return False
2.4 创币交易
每个区块的第一个交易是创币交易,用于奖励矿工:
def coinbase_transaction(miner_address, reward):
return Transaction(
from_address="network",
to_address=miner_address,
value=reward,
comment="coinbase transaction"
)
3. 区块结构与挖矿
区块是区块链的基本组成单元,包含交易数据和元数据。我们的实现包含以下关键组件:
3.1 区块数据结构
class Block:
def init(self, index, previous_hash, transactions, difficulty, timestamp=None, nonce=0):
self.index = index
self.previous_hash = previous_hash
self.transactions = transactions
self.difficulty = difficulty
self.timestamp = timestamp or time.time()
self.nonce = nonce
3.2 工作量证明
通过调整nonce值来寻找满足难度要求的哈希值:
def proof_of_work(self, difficulty):
prefix_str = '0' * difficulty
while not self.compute_hash_bin().startswith(prefix_str):
self.nonce += 1
return self.compute_hash()
3.3 区块验证
验证区块的有效性,包括: 1. 交易有效性 2. 哈希值正确性 3. 前一个区块哈希匹配
def is_valid(self):
coinbase_transaction = self.transactions[0]
return (is_coinbase_transaction(coinbase_transaction) and
all([t.is_valid() for t in self.transactions[1:]]))
3.4 创世区块
区块链的第一个区块,手动创建:
def create_genesis_block(self):
genesis_block = Block(0, "0", [], 1, time.time())
genesis_block.hash = genesis_block.proof_of_work(genesis_block.difficulty).hex()
self.chain.append(genesis_block)
3.5 挖矿过程
创建创币交易
调整难度
执行工作量证明
添加新区块
def mine(self, miner_address):
coinbase_tx = coinbase_transaction(miner_address, self.mining_reward)
top_block = self.chain[-1]
difficulty = top_block.difficulty
if top_block.index>0 and top_block.index % self.difficulty_ajustment_interval == 0:
total_time = top_block.timestamp - self.chain[-self.difficulty_ajustment_interval].timestamp
difficulty = self.ajust_difficulty(difficulty, total_time, self.interval)
new_block = Block(len(self.chain), top_block.hash, [coinbase_tx], difficulty, time.time())
self.add_block(new_block)
return new_block
4. 区块链结构与验证
区块链是由多个区块组成的链式结构,我们的实现包含以下关键功能:
4.1 区块链初始化
class Blockchain:
def init(self, difficulty_ajustment_interval=5, interval=60, mining_reward=50):
self.chain = []
self.difficulty_ajustment_interval = difficulty_ajustment_interval
self.interval = interval
self.mining_reward = mining_reward
self.create_genesis_block()
4.2 链验证
验证整个区块链的有效性: 1. 检查每个区块的哈希值 2. 验证前一个区块哈希的连续性 3. 检查工作量证明 4. 验证所有交易
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.compute_hash().hex():
return False
if current.previous_hash != previous.hash:
return False
if not self.is_valid_proof(current, current.hash):
return False
if not current.is_valid():
return False
return True
4.3 难度调整
根据区块生成时间动态调整挖矿难度:
def ajust_difficulty(self, difficulty, total_time, interval):
if total_time < interval * self.difficulty_ajustment_interval:
difficulty += 1
else:
difficulty -= 1
return difficulty
4.4 添加新区块
将验证通过的区块添加到链中:
def add_block(self, block):
block.previous_hash = self.chain[-1].hash
block.hash = block.proof_of_work(block.difficulty).hex()
self.chain.append(block)
4.5 区块链演示
创建区块链并演示挖矿过程:
if name == "__main__":
blockchain = Blockchain(3, 2, 50)
print("Genesis Block:", blockchain.chain[0])
# 创建并挖矿新区块
for i in range(33):
blockchain.mine("miner1")
# 打印区块链
for block in blockchain.chain:
print(block)
# 验证区块链
print("Is blockchain valid?", blockchain.is_chain_valid())
本教程实现了一个简化的比特币区块链系统,包含以下核心功能: 1. 比特币地址生成与验证 2. 交易创建与签名验证 3. 区块结构与挖矿机制 4. 区块链结构与验证
这个实现虽然简化了比特币的许多复杂特性(如UTXO模型、脚本系统等),但涵盖了区块链的核心概念,是学习区块链技术的良好起点。