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 = index self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.hash = self.calculate_hash() def calculate_hash(self): import hashlib sha = 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}")
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, SimpleStorage def 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_storage def 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) public returns (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 json def deploy_and_mint(): account = get_account() my_nft = MyNFT.deploy({"from": account}) # 上传元数据到IPFS token_uri = upload_to_ipfs("nft_metadata.json") # 铸造NFT tx = 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 Web3 w3 = 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()
安全最佳实践
智能合约安全检测
python
复制
下载
from slither import Slither from slither.detectors import all_detectors def 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开发的重要工具,将持续发挥关键作用。保持学习,你将成为这一变革的引领者!