Loading...
Vietnam Geography App
Loading...
Vietnam Geography App
Tìm hiểu công nghệ blockchain từ cơ bản đến nâng cao, bao gồm Bitcoin, Ethereum và các ứng dụng thực tế.
Tạo blockchain cơ bản để hiểu cách block được tạo và liên kết
Blockchain đơn giản có thể add blocks và validate chain integrity
# Simple Blockchain Implementation
import hashlib
import json
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):
block_string = json.dumps({
"index": self.index,
"timestamp": self.timestamp,
"data": self.data,
"previous_hash": self.previous_hash,
"nonce": self.nonce
}, sort_keys=True)
return hashlib.sha256(block_string.encode()).hexdigest()
def mine_block(self, difficulty):
target = "0" * difficulty
while self.hash[:difficulty] != target:
self.nonce += 1
self.hash = self.calculate_hash()
print(f"Block mined: {self.hash}")
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
self.difficulty = 2
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_block = self.chain[i]
previous_block = self.chain[i-1]
if current_block.hash != current_block.calculate_hash():
return False
if current_block.previous_hash != previous_block.hash:
return False
return True
# Test blockchain
my_blockchain = Blockchain()
my_blockchain.add_block(Block(1, time.time(), "Transaction 1", ""))
my_blockchain.add_block(Block(2, time.time(), "Transaction 2", ""))
print("Blockchain valid:", my_blockchain.is_chain_valid())Walmart + IBM Food Trust
Tracking contaminated food sources takes weeks
Blockchain-based supply chain tracing system
Reduced tracing time from weeks to seconds