当前位置: 首页 > ops >正文

Python 区块链与Web3开发指南

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")

常见漏洞防护

  1. 重入攻击防护:

solidity

复制

下载

// 使用OpenZeppelin的ReentrancyGuard
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";contract SecureContract is ReentrancyGuard {function safeWithdraw() public nonReentrant {// 提款逻辑}
}
  1. 整数溢出防护:

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

通过这八篇系列教程,你已经掌握了:

  1. 区块链基础原理与Python实现

  2. Web3.py与以太坊交互

  3. 智能合约开发与部署

  4. NFT与DeFi应用开发

  5. 区块链数据分析

  6. 安全最佳实践

  7. 完整DApp架构

下一步学习建议

  1. 深入协议层

    • 学习以太坊EVM原理

    • 研究零知识证明(ZKP)技术

    • 探索Layer2解决方案

  2. 参与生态

    • 贡献开源Web3项目

    • 参加黑客松活动

    • 加入DAO组织

  3. 专业领域

    • DeFi协议开发

    • NFT平台架构

    • 区块链安全审计

  4. 扩展知识

    • IPFS与去中心化存储

    • Oracles与链外数据

    • 跨链技术

区块链技术正在重塑互联网未来,Python作为Web3开发的重要工具,将持续发挥关键作用。保持学习,你将成为这一变革的引领者!

http://www.xdnf.cn/news/14497.html

相关文章:

  • 实战指南:用DataHub管理Hive元数据
  • 断言(Assertion)中常用的正则表达式
  • 最大公约数
  • 详细讲解Redis为什么被设计成单线程
  • 前端开发面试题总结-vue2框架篇(四)
  • Controller Area Network (CAN) 通信机制简介
  • 解决Matplotlib三维图无法旋转的问题
  • springboot入门之路(一)
  • Spring MVC 处理静态资源请求 - ResourceHandler
  • [Jenkins在线安装]
  • 为什么会出现 make 工程管理器?它到底能做什么?
  • Arduino入门教程:10、屏幕显示
  • python大学校园旧物捐赠系统
  • Linux操作系统之进程(六):进程的控制(上)
  • 分治算法之归并排序
  • Day04_C语言基础数据结构重点复习笔记20250618
  • 反转链表二--LeetCode
  • Neo4j 入门到精通(Cypher语言详解)
  • 前端部署更新后,如何优雅地通知用户刷新页面?
  • OpenCV——图像形态学
  • Arrays.asList() 的不可变陷阱:问题、原理与解决方案
  • 秋招是开发算法一起准备,还是只准备一个
  • 技能系统详解(1)——技能
  • mysql 学习
  • 45-Oracle 索引的新建与重建
  • 6-16阿里前端面试记录
  • RAG 架构地基工程-Retrieval 模块的系统设计分享
  • 学习STC51单片机41(芯片为STC89C52RCRC)智能小车8(测速显示到OLED显示屏)
  • git最常用命令
  • RISC-V向量扩展与GPU协处理:开源加速器设计新范式——对比NVDLA与香山架构的指令集融合方案