看完此文再不懂区块链算我输,用Python从零开始创建区块链("轻松掌握区块链:Python零基础构建实战教程,包你一看就懂!")
原创
一、区块链简介
区块链是一种分布式数据库技术,其最首要的特点是去中心化、平安性高、透明性强。区块链技术被广泛应用于数字货币、供应链管理、智能合约等领域。本文将带您从零起始,用Python构建一个单纯的区块链原型。
二、环境准备
在起始之前,请确保您的计算机已安装Python环境。本文以Python 3为例,若您使用的是Python 2,部分代码大概需要调整。
三、构建区块链的基本组成
一个单纯的区块链首要由以下几个部分组成:
- 区块(Block)
- 链(Chain)
- 工作量证明(Proof of Work,PoW)
四、创建区块
区块是区块链的基本单元,每个区块包含一些交易记录以及前一个区块的哈希值。下面我们使用Python创建一个单纯的区块类:
import hashlib
import json
from time import time
class Block:
def __init__(self, index, transactions, timestamp, previous_hash):
self.index = index
self.transactions = transactions
self.timestamp = timestamp
self.previous_hash = previous_hash
self.hash = self.compute_hash()
def compute_hash(self):
block_string = json.dumps(self.__dict__, sort_keys=True)
return hashlib.sha256(block_string.encode()).hexdigest()
五、创建区块链
接下来,我们创建一个区块链类,该类包含一个区块列表,并提供一些方法来添加区块和验证区块链的有效性:
class Blockchain:
def __init__(self):
self.unconfirmed_transactions = [] # 存储未确认的交易
self.chain = []
self.create_genesis_block()
def create_genesis_block(self):
genesis_block = Block(0, [], time(), "0")
genesis_block.hash = genesis_block.compute_hash()
self.chain.append(genesis_block)
def add_new_transaction(self, transaction):
self.unconfirmed_transactions.append(transaction)
def mine(self):
if not self.unconfirmed_transactions:
return False
last_block = self.chain[-1]
new_block = Block(index=last_block.index + 1,
transactions=self.unconfirmed_transactions,
timestamp=time(),
previous_hash=last_block.hash)
new_block.hash = new_block.compute_hash()
self.chain.append(new_block)
self.unconfirmed_transactions = []
return new_block.index
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():
return False
if current.previous_hash != previous.hash:
return False
return True
六、工作量证明(Proof of Work,PoW)
为了增多区块链的平安性,我们引入工作量证明机制。这里我们使用一个单纯的PoW算法,即找到一个数,促使区块哈希值的前四个字符为"0000":
class ProofOfWork:
def __init__(self, block):
self.block = block
self.target = 1000000
def run(self):
nonce = 0
while True:
hash = self.block.compute_hash()
if hash[:4] == "0000":
return nonce
nonce += 1
七、测试区块链
现在,我们可以创建一个区块链实例,并添加一些交易,然后挖矿生成新的区块:
blockchain = Blockchain()
blockchain.add_new_transaction({"from": "Alice", "to": "Bob", "amount": 10})
blockchain.add_new_transaction({"from": "Bob", "to": "Charlie", "amount": 5})
proof_of_work = ProofOfWork(blockchain.chain[-1])
nonce = proof_of_work.run()
blockchain.mine()
print("区块链是否有效:", blockchain.is_chain_valid())
print("最新区块:", blockchain.chain[-1].__dict__)
八、总结
本文从零起始,使用Python构建了一个单纯的区块链原型。我们介绍了区块链的基本组成,实现了区块和区块链类,并引入了工作量证明机制。通过测试,我们可以看到区块链的有效性。当然,这只是一个非常基础的示例,实际的区块链系统要繁复得多。期待本文能帮助您更好地领会区块链的原理和实现。