目录
Python实例题
题目
基于区块链的供应链管理系统
问题描述
开发一个基于区块链的供应链管理系统,包含以下功能:
- 供应链网络:连接供应商、制造商、物流商和零售商
- 智能合约:自动化执行供应链中的业务规则
- 产品溯源:记录和查询产品的全生命周期信息
- 资产追踪:实时追踪货物和资产的位置和状态
- 权限管理:控制不同参与者的访问权限
解题思路
- 使用 Hyperledger Fabric 或 Ethereum 搭建联盟链网络
- 开发智能合约实现供应链业务逻辑
- 设计区块链数据模型存储产品和交易信息
- 构建 Web 应用提供用户界面和 API 接口
- 集成物联网设备获取实时资产数据
关键代码框架
javascript
// 智能合约示例 (Solidity - 基于Ethereum)
pragma solidity ^0.8.0;
contract SupplyChain {
// 参与者角色
enum Role { Manufacturer, Supplier, Distributor, Retailer, Consumer }
// 参与者结构
struct Participant {
address walletAddress;
string companyName;
Role role;
bool approved;
uint256 registrationDate;
}
// 产品结构
struct Product {
string productId;
string name;
string description;
address manufacturer;
uint256 manufacturingDate;
uint256[] batchNumbers;
bool isActive;
}
// 批次结构
struct Batch {
uint256 batchNumber;
string productId;
uint256 quantity;
address currentHolder;
string currentLocation;
uint256[] transactionIds;
bool isSealed;
}
// 交易结构
struct Transaction {
uint256 transactionId;
uint256 batchNumber;
address sender;
address receiver;
string location;
uint256 timestamp;
string transactionType; // "SHIPMENT", "RECEIPT", "INSPECTION", etc.
string notes;
bytes32[] signatures;
}
// 数据存储
mapping(address => Participant) public participants;
mapping(string => Product) public products;
mapping(uint256 => Batch) public batches;
mapping(uint256 => Transaction) public transactions;
// 计数器
uint256 public transactionCounter = 0;
uint256 public batchCounter = 0;
// 事件
event ParticipantRegistered(address indexed participantAddress, string companyName, Role role);
event ProductCreated(string indexed productId, string name, address manufacturer);
event BatchCreated(uint256 indexed batchNumber, string productId, uint256 quantity);
event TransactionRecorded(uint256 indexed transactionId, uint256 batchNumber, address sender, address receiver);
// 管理员地址
address public admin;
// 构造函数
constructor() {
admin = msg.sender;
participants[admin] = Participant(admin, "SystemAdmin", Role.Manufacturer, true, block.timestamp);
}
// 修饰器:仅已批准的参与者
modifier onlyApprovedParticipant() {
require(participants[msg.sender].approved, "未批准的参与者");
_;
}
// 注册新参与者
function registerParticipant(address walletAddress, string memory companyName, Role role) external onlyApprovedParticipant {
require(!participants[walletAddress].approved, "参与者已注册");
participants[walletAddress] = Participant(
walletAddress,
companyName,
role,
false, // 初始状态为未批准
block.timestamp
);
emit ParticipantRegistered(walletAddress, companyName, role);
}
// 批准参与者
function approveParticipant(address participantAddress) external {
require(msg.sender == admin, "只有管理员可以批准参与者");
require(participants[participantAddress].walletAddress != address(0), "参与者不存在");
participants[participantAddress].approved = true;
}
// 创建新产品
function createProduct(string memory productId, string memory name, string memory description) external onlyApprovedParticipant {
require(participants[msg.sender].role == Role.Manufacturer, "只有制造商可以创建产品");
require(products[productId].manufacturer == address(0), "产品已存在");
products[productId] = Product(
productId,
name,
description,
msg.sender,
block.timestamp,
new uint256[](0),
true
);
emit ProductCreated(productId, name, msg.sender);
}
// 创建新产品批次
function createBatch(string memory productId, uint256 quantity) external onlyApprovedParticipant {
require(products[productId].manufacturer != address(0), "产品不存在");
require(participants[msg.sender].role == Role.Manufacturer, "只有制造商可以创建批次");
batchCounter++;
uint256 newBatchNumber = batchCounter;
batches[newBatchNumber] = Batch(
newBatchNumber,
productId,
quantity,
msg.sender,
"Manufacturer Facility",
new uint256[](0),
true
);
// 将批次添加到产品的批次列表
products[productId].batchNumbers.push(newBatchNumber);
emit BatchCreated(newBatchNumber, productId, quantity);
}
// 记录交易
function recordTransaction(uint256 batchNumber, address receiver, string memory location, string memory transactionType, string memory notes) external onlyApprovedParticipant {
require(batches[batchNumber].batchNumber != 0, "批次不存在");
require(batches[batchNumber].currentHolder == msg.sender, "只有当前持有者可以发起交易");
require(participants[receiver].approved, "接收方未被批准");
transactionCounter++;
uint256 newTransactionId = transactionCounter;
transactions[newTransactionId] = Transaction(
newTransactionId,
batchNumber,
msg.sender,
receiver,
location,
block.timestamp,
transactionType,
notes,
new bytes32[](0)
);
// 将交易添加到批次的交易列表
batches[batchNumber].transactionIds.push(newTransactionId);
// 更新批次的当前持有者和位置
batches[batchNumber].currentHolder = receiver;
batches[batchNumber].currentLocation = location;
emit TransactionRecorded(newTransactionId, batchNumber, msg.sender, receiver);
}
// 获取产品的所有批次
function getProductBatches(string memory productId) external view returns (uint256[] memory) {
return products[productId].batchNumbers;
}
// 获取批次的所有交易
function getBatchTransactions(uint256 batchNumber) external view returns (uint256[] memory) {
return batches[batchNumber].transactionIds;
}
// 获取产品的完整历史记录
function getProductHistory(string memory productId) external view returns (Transaction[] memory) {
uint256[] memory batchNumbers = products[productId].batchNumbers;
uint256 totalTransactions = 0;
// 计算总交易数
for (uint256 i = 0; i < batchNumbers.length; i++) {
totalTransactions += batches[batchNumbers[i]].transactionIds.length;
}
Transaction[] memory history = new Transaction[](totalTransactions);
uint256 index = 0;
// 收集所有交易
for (uint256 i = 0; i < batchNumbers.length; i++) {
uint256[] memory transactionIds = batches[batchNumbers[i]].transactionIds;
for (uint256 j = 0; j < transactionIds.length; j++) {
history[index] = transactions[transactionIds[j]];
index++;
}
}
return history;
}
}
python
# Python后端API示例 (与区块链交互)
from flask import Flask, request, jsonify
from web3 import Web3
import json
import os
from dotenv import load_dotenv
# 加载环境变量
load_dotenv()
# 初始化Flask应用
app = Flask(__name__)
# 连接到以太坊节点
w3 = Web3(Web3.HTTPProvider(os.getenv('ETHEREUM_NODE_URL')))
assert w3.is_connected(), "无法连接到以太坊节点"
# 加载智能合约ABI和地址
with open('SupplyChain.abi') as f:
contract_abi = json.load(f)
contract_address = os.getenv('CONTRACT_ADDRESS')
contract = w3.eth.contract(address=contract_address, abi=contract_abi)
# 账户配置
private_key = os.getenv('PRIVATE_KEY')
account = w3.eth.account.from_key(private_key)
w3.eth.default_account = account.address
# 辅助函数:发送交易
def send_transaction(function, args=None, gas=500000):
if args is None:
args = []
# 构建交易
transaction = function(*args).build_transaction({
'chainId': int(os.getenv('CHAIN_ID')),
'gas': gas,
'maxFeePerGas': w3.to_wei('2', 'gwei'),
'maxPriorityFeePerGas': w3.to_wei('1', 'gwei'),
'nonce': w3.eth.get_transaction_count(account.address),
})
# 签署交易
signed_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)
# 发送交易
tx_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
# 等待交易确认
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
return tx_receipt
# API路由
@app.route('/api/participants', methods=['POST'])
def register_participant():
"""注册新参与者"""
data = request.json
wallet_address = data.get('wallet_address')
company_name = data.get('company_name')
role = data.get('role')
# 角色映射 (0: Manufacturer, 1: Supplier, 2: Distributor, 3: Retailer, 4: Consumer)
role_mapping = {
'manufacturer': 0,
'supplier': 1,
'distributor': 2,
'retailer': 3,
'consumer': 4
}
role_id = role_mapping.get(role.lower(), 0)
try:
# 调用智能合约方法
receipt = send_transaction(
contract.functions.registerParticipant,
[wallet_address, company_name, role_id]
)
return jsonify({
'status': 'success',
'transaction_hash': receipt.transactionHash.hex(),
'message': '参与者注册成功'
}), 201
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/products', methods=['POST'])
def create_product():
"""创建新产品"""
data = request.json
product_id = data.get('product_id')
name = data.get('name')
description = data.get('description')
try:
# 调用智能合约方法
receipt = send_transaction(
contract.functions.createProduct,
[product_id, name, description]
)
return jsonify({
'status': 'success',
'transaction_hash': receipt.transactionHash.hex(),
'message': '产品创建成功'
}), 201
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/batches', methods=['POST'])
def create_batch():
"""创建新批次"""
data = request.json
product_id = data.get('product_id')
quantity = data.get('quantity')
try:
# 调用智能合约方法
receipt = send_transaction(
contract.functions.createBatch,
[product_id, quantity]
)
return jsonify({
'status': 'success',
'transaction_hash': receipt.transactionHash.hex(),
'message': '批次创建成功'
}), 201
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/transactions', methods=['POST'])
def record_transaction():
"""记录交易"""
data = request.json
batch_number = data.get('batch_number')
receiver = data.get('receiver')
location = data.get('location')
transaction_type = data.get('transaction_type')
notes = data.get('notes')
try:
# 调用智能合约方法
receipt = send_transaction(
contract.functions.recordTransaction,
[batch_number, receiver, location, transaction_type, notes]
)
return jsonify({
'status': 'success',
'transaction_hash': receipt.transactionHash.hex(),
'message': '交易记录成功'
}), 201
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/products/<product_id>/history', methods=['GET'])
def get_product_history(product_id):
"""获取产品历史记录"""
try:
# 调用智能合约方法
history = contract.functions.getProductHistory(product_id).call()
# 格式化交易数据
formatted_history = []
for tx in history:
formatted_tx = {
'transaction_id': tx[0],
'batch_number': tx[1],
'sender': tx[2],
'receiver': tx[3],
'location': tx[4],
'timestamp': tx[5],
'transaction_type': tx[6],
'notes': tx[7],
'signatures': [sig.hex() for sig in tx[8]]
}
formatted_history.append(formatted_tx)
return jsonify({
'status': 'success',
'history': formatted_history
}), 200
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
if __name__ == '__main__':
app.run(debug=True)
难点分析
- 区块链网络搭建:配置和管理联盟链网络
- 智能合约开发:设计安全、高效的智能合约
- 数据隐私保护:在共享账本上保护敏感信息
- 性能优化:提高区块链系统的吞吐量
- 跨链集成:与其他区块链或传统系统集成
扩展方向
- 添加物联网设备集成实现实时资产追踪
- 开发移动端应用方便现场操作
- 实现智能合约升级机制
- 添加高级数据分析和预测功能
- 集成金融服务实现供应链融资