https://www.python.org/static/community_logos/python-logo-master-v3-TM.png
區塊鏈基礎概念
區塊鏈核心特性
python
復制
下載
class Block:def __init__(self, index, timestamp, data, previous_hash):self.index = indexself.timestamp = timestampself.data = dataself.previous_hash = previous_hashself.hash = self.calculate_hash()def calculate_hash(self):import hashlibsha = hashlib.sha256()sha.update(f"{self.index}{self.timestamp}{self.data}{self.previous_hash}".encode('utf-8'))return sha.hexdigest()# 創建創世區塊 genesis_block = Block(0, "2023-01-01", "Genesis Block", "0") print(f"創世區塊哈希: {genesis_block.hash}")
https://www.researchgate.net/publication/336707000/figure/fig1/AS:817393838129153@1572173939816/The-structure-of-a-blockchain-The-blockchain-is-a-linked-list-containing-blocks-of-data.png
Web3.py 入門
連接以太坊網絡
python
復制
下載
from web3 import Web3# 連接Infura節點 infura_url = "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID" w3 = Web3(Web3.HTTPProvider(infura_url))# 檢查連接 print(f"是否已連接: {w3.isConnected()}") print(f"最新區塊號: {w3.eth.block_number}")# 獲取賬戶余額 address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e" # 示例地址 balance = w3.eth.get_balance(address) print(f"余額: {w3.fromWei(balance, 'ether')} ETH")
智能合約交互
python
復制
下載
# 合約ABI示例 contract_abi = ''' [{"inputs": [],"name": "get","outputs": [{"name": "","type": "uint256"}],"stateMutability": "view","type": "function"},{"inputs": [{"name": "x","type": "uint256"}],"name": "set","outputs": [],"stateMutability": "nonpayable","type": "function"} ] '''# 合約地址 contract_address = "0x1234567890123456789012345678901234567890"# 創建合約實例 contract = w3.eth.contract(address=contract_address, abi=contract_abi)# 調用只讀函數 current_value = contract.functions.get().call() print(f"當前值: {current_value}")# 發送交易(需要賬戶和私鑰) ''' account = "0xYourAccountAddress" private_key = "YourPrivateKey" nonce = w3.eth.get_transaction_count(account) tx = contract.functions.set(42).buildTransaction({'chainId': 1,'gas': 200000,'gasPrice': w3.toWei('50', 'gwei'),'nonce': nonce }) signed_tx = w3.eth.account.sign_transaction(tx, private_key) tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f"交易哈希: {tx_hash.hex()}") '''
智能合約開發
Solidity基礎合約
solidity
復制
下載
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0;contract SimpleStorage {uint256 private value;event ValueChanged(uint256 newValue);function get() public view returns (uint256) {return value;}function set(uint256 newValue) public {value = newValue;emit ValueChanged(newValue);} }
使用Brownie部署合約
python
復制
下載
from brownie import accounts, SimpleStoragedef deploy_simple_storage():# 加載賬戶account = accounts[0]# 部署合約simple_storage = SimpleStorage.deploy({"from": account})# 初始值initial_value = simple_storage.get()print(f"初始值: {initial_value}")# 更新值transaction = simple_storage.set(42, {"from": account})transaction.wait(1) # 等待1個區塊確認# 新值updated_value = simple_storage.get()print(f"更新后的值: {updated_value}")return simple_storagedef main():deploy_simple_storage()
https://ethereum.org/static/8ea7775026b7fac7b16188a50a60f70d/302a4/developers.png
NFT開發實戰
ERC721合約示例
solidity
復制
下載
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0;import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol";contract MyNFT is ERC721 {using Counters for Counters.Counter;Counters.Counter private _tokenIds;constructor() ERC721("MyNFT", "MNFT") {}function mintNFT(address recipient, string memory tokenURI)publicreturns (uint256){_tokenIds.increment();uint256 newItemId = _tokenIds.current();_mint(recipient, newItemId);_setTokenURI(newItemId, tokenURI);return newItemId;} }
使用Python鑄造NFT
python
復制
下載
from brownie import accounts, network, config, MyNFT from scripts.helpful_scripts import get_account from pathlib import Path import requests import jsondef deploy_and_mint():account = get_account()my_nft = MyNFT.deploy({"from": account})# 上傳元數據到IPFStoken_uri = upload_to_ipfs("nft_metadata.json")# 鑄造NFTtx = my_nft.mintNFT(account, token_uri, {"from": account})tx.wait(1)print(f"NFT鑄造成功!查看地址: {my_nft.address}")def upload_to_ipfs(filepath):with Path(filepath).open("rb") as fp:file_binary = fp.read()ipfs_url = "http://127.0.0.1:5001"endpoint = "/api/v0/add"response = requests.post(ipfs_url + endpoint, files={"file": file_binary})ipfs_hash = response.json()["Hash"]return f"ipfs://{ipfs_hash}"def main():deploy_and_mint()
https://miro.medium.com/max/1400/1*8NgGYtqkYOwesVQdI3VQYw.png
DeFi應用開發
代幣合約(ERC20)
solidity
復制
下載
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0;import "@openzeppelin/contracts/token/ERC20/ERC20.sol";contract MyToken is ERC20 {constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {_mint(msg.sender, initialSupply);} }
查詢代幣余額
python
復制
下載
from web3 import Web3# 連接節點 w3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/YOUR_PROJECT_ID"))# ERC20 ABI片段 erc20_abi = ''' [{"constant": true,"inputs": [{"name": "_owner", "type": "address"}],"name": "balanceOf","outputs": [{"name": "balance", "type": "uint256"}],"type": "function"} ] '''# 代幣合約地址 token_address = "0x6B175474E89094C44Da98b954EedeAC495271d0F" # DAI合約 user_address = "0xYourWalletAddress"# 創建合約實例 contract = w3.eth.contract(address=token_address, abi=erc20_abi)# 查詢余額 balance = contract.functions.balanceOf(user_address).call() print(f"代幣余額: {balance / 10**18}") # 假設代幣有18位小數
區塊鏈數據分析
分析交易數據
python
復制
下載
import pandas as pd from web3 import Web3w3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/YOUR_PROJECT_ID"))def get_block_data(block_number):block = w3.eth.get_block(block_number, full_transactions=True)return {"block_number": block.number,"timestamp": block.timestamp,"miner": block.miner,"gas_used": block.gasUsed,"gas_limit": block.gasLimit,"transaction_count": len(block.transactions)}# 獲取最近10個區塊數據 blocks_data = [get_block_data(w3.eth.block_number - i) for i in range(10)] df = pd.DataFrame(blocks_data)# 數據分析 print(df.describe()) print("\nGas使用率:") df['gas_usage'] = df['gas_used'] / df['gas_limit'] print(df[['block_number', 'gas_usage']])
可視化交易趨勢
python
復制
下載
import matplotlib.pyplot as plt# 準備數據 df['datetime'] = pd.to_datetime(df['timestamp'], unit='s')# 創建圖表 plt.figure(figsize=(12, 6)) plt.plot(df['datetime'], df['gas_usage'], marker='o') plt.title('區塊Gas使用率趨勢') plt.xlabel('時間') plt.ylabel('Gas使用率') plt.grid(True) plt.savefig('gas_usage_trend.png') plt.show()
https://www.researchgate.net/publication/338442131/figure/fig1/AS:842381179748352@1577724938245/Blockchain-data-analysis-process.png
安全最佳實踐
智能合約安全檢測
python
復制
下載
from slither import Slither from slither.detectors import all_detectorsdef analyze_contract(contract_path):# 加載合約slither = Slither(contract_path)# 運行所有檢測器detectors = [getattr(all_detectors, d) for d in all_detectors.__all__]print(f"分析合約: {contract_path}")print("=" * 50)for detector in detectors:detector = detector(slither)detector_results = detector.detect()if detector_results:print(f"\n{detector.ARGUMENT}:")for result in detector_results:print(f"- {result['description']}")print(f" 位置: {result['source_mapping']}")# 分析合約 analyze_contract("SimpleStorage.sol")
常見漏洞防護
-
重入攻擊防護:
solidity
復制
下載
// 使用OpenZeppelin的ReentrancyGuard import "@openzeppelin/contracts/security/ReentrancyGuard.sol";contract SecureContract is ReentrancyGuard {function safeWithdraw() public nonReentrant {// 提款邏輯} }
-
整數溢出防護:
solidity
復制
下載
// 使用SafeMath(0.8.0+版本已內置) import "@openzeppelin/contracts/utils/math/SafeMath.sol";contract SafeMathExample {using SafeMath for uint256;function safeAdd(uint256 a, uint256 b) public pure returns (uint256) {return a.add(b);} }
Web3開發工具鏈
工具名稱 | 用途 | 適用場景 |
---|---|---|
Web3.py | 以太坊交互庫 | 后端服務、腳本 |
Brownie | 開發框架 | 合約測試、部署 |
Hardhat | 開發環境 | 專業合約開發 |
Ganache | 本地測試鏈 | 開發測試 |
Infura/Alchemy | 節點服務 | 生產環境連接 |
OpenZeppelin | 合約庫 | 安全合約開發 |
IPFS | 去中心化存儲 | NFT元數據存儲 |
去中心化應用(DApp)架構
text
復制
下載
dapp_project/ ├── client/ # 前端代碼 │ ├── public/ # 靜態文件 │ └── src/ # React/Vue代碼 ├── contracts/ # 智能合約 │ ├── contracts/ # Solidity代碼 │ ├── tests/ # 合約測試 │ └── scripts/ # 部署腳本 ├── backend/ # 后端服務(可選) │ ├── api/ # API路由 │ └── services/ # 業務邏輯 └── docs/ # 項目文檔
前端集成示例
javascript
復制
下載
import { ethers } from "ethers"; import ABI from "./contractABI.json";async function connectWallet() {if (window.ethereum) {try {// 請求賬戶訪問const accounts = await window.ethereum.request({ method: "eth_requestAccounts" });const provider = new ethers.providers.Web3Provider(window.ethereum);const signer = provider.getSigner();// 合約實例const contractAddress = "0x123...";const contract = new ethers.Contract(contractAddress, ABI, signer);// 調用合約const value = await contract.get();console.log("當前值:", value.toString());} catch (error) {console.error("用戶拒絕訪問:", error);}} else {alert("請安裝MetaMask!");} }
結語與學習路徑
https://ethereum.org/static/4d030a6f9c1e4a919e775cf12a8dd192/302a4/learn.png
通過這八篇系列教程,你已經掌握了:
-
區塊鏈基礎原理與Python實現
-
Web3.py與以太坊交互
-
智能合約開發與部署
-
NFT與DeFi應用開發
-
區塊鏈數據分析
-
安全最佳實踐
-
完整DApp架構
下一步學習建議:
-
深入協議層:
-
學習以太坊EVM原理
-
研究零知識證明(ZKP)技術
-
探索Layer2解決方案
-
-
參與生態:
-
貢獻開源Web3項目
-
參加黑客松活動
-
加入DAO組織
-
-
專業領域:
-
DeFi協議開發
-
NFT平臺架構
-
區塊鏈安全審計
-
-
擴展知識:
-
IPFS與去中心化存儲
-
Oracles與鏈外數據
-
跨鏈技術
-
區塊鏈技術正在重塑互聯網未來,Python作為Web3開發的重要工具,將持續發揮關鍵作用。保持學習,你將成為這一變革的引領者!