Tự làm Blockchain đơn giản bằng Python
Bắt đầu hành trình tự xây dựng một blockchain đơn giản bằng Python nhé. Đây là một cách tuyệt vời để hiểu cách hoạt động cốt lõi của blockchain, đặc biệt nếu bạn mới bắt đầu.
🧠 Mục tiêu#
Xây dựng một blockchain đơn giản có thể:
Tạo các block
Thêm block mới
Kiểm tra tính hợp lệ của chuỗi
Không cần kết nối mạng, không dùng database, chạy hoàn toàn cục bộ
📦 Cấu trúc khối (Block)#
Mỗi block sẽ chứa:
index: Số thứ tự của khốitimestamp: Thời gian tạo khốidata: Dữ liệu (giao dịch hoặc thông tin tùy ý)previous_hash: Mã băm của khối trước đóhash: Mã băm của chính khối nàynonce: Số dùng để giải bài toán (Proof of Work)
✅ Bước 1: Tạo file Python simple_blockchain.py#
` import hashlib import time
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):
value = str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash) + str(self.nonce)
return hashlib.sha256(value.encode('utf-8')).hexdigest()
def mine_block(self, difficulty):
print(f"⛏️ Mining block {self.index}...")
while self.hash[:difficulty] != '0' * difficulty:
self.nonce += 1
self.hash = self.calculate_hash()
print(f"✅ Block mined: {self.hash}")
`
✅ Bước 2: Tạo lớp Blockchain#
` class Blockchain: def init(self): self.chain = [self.create_genesis_block()] self.difficulty = 4 # Số chữ số 0 đầu của hash
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]
prev = self.chain[i - 1]
if current.hash != current.calculate_hash():
print("❌ Hash không hợp lệ")
return False
if current.previous_hash != prev.hash:
print("❌ Liên kết với khối trước sai")
return False
return True
`
✅ Bước 3: Kiểm tra chương trình#
` if name == 'main': my_chain = Blockchain()
my_chain.add_block(Block(1, time.time(), {"amount": 100}))
my_chain.add_block(Block(2, time.time(), {"amount": 200}))
for block in my_chain.chain:
print("\nBlock #", block.index)
print("Hash:", block.hash)
print("Previous Hash:", block.previous_hash)
print("Data:", block.data)
print("Nonce:", block.nonce)
print("\n⛓️ Blockchain hợp lệ?", my_chain.is_chain_valid())
`
🧪 Chạy thử#
python simple_blockchain.py
Kết quả sẽ hiển thị:
Các block được tạo
Mã băm của từng khối
Việc "khai thác" (mine) block mới
Kiểm tra chuỗi hợp lệ
🎓 Bạn học được gì?#
Blockchain không cần server hoặc database.
Hash giúp bảo mật và liên kết các khối.
Proof of Work là quá trình tìm
noncesao cho hash có tiền tố0000….
🧩 Bước tiếp theo bạn có thể làm:#
Thêm hệ thống giao dịch (transaction pool)
Cho phép nhiều node giao tiếp với nhau (dùng Flask/Python socket)
Tạo REST API để gửi dữ liệu lên blockchain
Xây giao diện frontend
Bài liên quan trong #Python
-
Xây dựng website tích hợp blockchain
minhu · 💬 1 -
Các bước để bạn tự xây dựng 1 sàn giao dịch tiền điện tủ
minhdev · 💬 2 -
Code Python sử dụng FastAPI để tạo một API khởi chạy container Docker
minhdev -
Đánh Giá Hiệu Năng Code Python với Công Cụ Timeit
minhdev · 💬 2 -
Herond Browser: Trình Duyệt Web3 Tốc Độ Cao với Ví Crypto Tích Hợp
minhu · 💬 1