零基础用python开发区块链(五web3进阶)

简介

web3.py 是一个功能强大的 Python 库,用于与以太坊区块链进行交互。它提供了一系列功能,使得开发者可以轻松地与以太坊网络进行交易、查询数据、调用智能合约、管理账户、监听事件等。下面是 web3.py 支持的主要功能列表:

1. 连接以太坊节点

web3.py 支持连接多种以太坊节点,包括:

  • HTTPProvider:通过 HTTP 连接节点,例如 Infura 或本地节点。
  • WebsocketProvider:通过 WebSocket 连接节点,适合监听事件。
  • IPCProvider:通过 IPC(进程间通信)与本地节点交互。

示例:

from web3 import Web3

# 一Infura的HTTP URL
infura_url = 'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'

# 创建 Web3 实例并连接到 Infura 节点
w3 = Web3(Web3.HTTPProvider(infura_url))

# 检查连接状态
if w3.isConnected():
    print("Connected to Ethereum node via HTTP")
else:
    print("Failed to connect")


from web3 import Web3


# 二Infura的WebSocket URL
infura_ws_url = 'wss://mainnet.infura.io/ws/v3/YOUR_INFURA_PROJECT_ID'

# 创建 Web3 实例并通过 WebSocket 连接到 Infura 节点
w3 = Web3(Web3.WebsocketProvider(infura_ws_url))

# 检查连接状态
if w3.isConnected():
    print("Connected to Ethereum node via WebSocket")
else:
    print("Failed to connect")


from web3 import Web3

# 三 IPC 文件路径(本地Geth节点的默认路径)
ipc_path = '/path/to/geth.ipc'

# 创建 Web3 实例并通过 IPC 连接到本地节点
w3 = Web3(Web3.IPCProvider(ipc_path))

# 检查连接状态
if w3.isConnected():
    print("Connected to Ethereum node via IPC")
else:
    print("Failed to connect")


from web3 import Web3

#四 Alchemy的HTTP URL或本地Geth节点的HTTP URL
alchemy_url = 'https://eth-mainnet.alchemyapi.io/v2/YOUR_ALCHEMY_API_KEY'
# 或者使用本地 Geth 节点的 URL
# local_url = 'http://127.0.0.1:8545'

# 创建 Web3 实例并通过 HTTP 连接到 Alchemy 或本地节点
w3 = Web3(Web3.HTTPProvider(alchemy_url))

# 检查连接状态
if w3.isConnected():
    print("Connected to Ethereum node via HTTP (Alchemy or Local Node)")
else:
    print("Failed to connect")


from web3 import Web3, HTTPProvider

#五 自定义 HTTP 请求头
custom_http_provider = HTTPProvider('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID', {'timeout': 60})

# 创建 Web3 实例并使用自定义 Provider
w3 = Web3(custom_http_provider)

# 检查连接状态
if w3.isConnected():
    print("Connected to Ethereum node via custom HTTP provider")
else:
    print("Failed to connect")

  • HTTPProvider:适用于大多数场景,特别是在使用远程节点(如 Infura 或 Alchemy)时。
  • WebsocketProvider:适用于需要实时监听事件的场景,适合需要高频率数据更新的应用。
  • IPCProvider:用于本地节点连接,通常适用于开发和调试环境。

2. 账户管理

web3.py 提供了账户创建、管理和交易签名功能,支持私钥的导入导出、地址生成等。

  • 生成新账户

    from web3 import Web3
    account = w3.eth.account.create()
    print(f"Address: {account.address}")
    print(f"Private Key: {account.privateKey.hex()}")
    

    从私钥导入账户

    private_key = 'your_private_key'
    account = w3.eth.account.from_key(private_key)
    print(f"Address: {account.address}")
    

    3. 查询区块链数据

    web3.py 允许查询以太坊区块链上的各种数据,如区块、交易、账户余额、Gas 价格等。

  • 查询账户余额

    balance = w3.eth.get_balance('0xYourAddress')
    ether_balance = w3.fromWei(balance, 'ether')
    print(f"Account balance: {ether_balance} ETH")
    

    查询最新区块

    latest_block = w3.eth.get_block('latest')
    print(latest_block)
    

    查询交易

    tx_hash = '0xTransactionHash'
    transaction = w3.eth.get_transaction(tx_hash)
    print(transaction)
    

    查询 Gas 价格

    gas_price = w3.eth.gas_price
    print(f"Gas Price: {w3.fromWei(gas_price, 'gwei')} Gwei")
    

    4. 交易管理

    web3.py 支持生成、签署、发送和跟踪交易。

  • 发送 ETH 转账

    tx = {
        'nonce': w3.eth.getTransactionCount('0xYourAddress'),
        'to': '0xRecipientAddress',
        'value': w3.toWei(0.01, 'ether'),
        'gas': 2000000,
        'gasPrice': w3.toWei('50', 'gwei'),
        'chainId': 1  # 主网 ID 为 1
    }
    signed_tx = w3.eth.account.sign_transaction(tx, 'your_private_key')
    tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
    print(f"Transaction hash: {w3.toHex(tx_hash)}")
    

    查询交易状态

    receipt = w3.eth.getTransactionReceipt(tx_hash)
    print(f"Transaction status: {receipt['status']}")
    

    5. 智能合约交互

    web3.py 提供了与智能合约交互的完整支持,包括调用函数、事件监听和合约部署。

  • 加载智能合约

    contract = w3.eth.contract(address='0xContractAddress', abi=contract_abi)
    

    调用智能合约的读方法

    balance = contract.functions.balanceOf('0xSomeAddress').call()
    print(f"Balance: {balance}")
    

    调用智能合约的写方法

    tx = contract.functions.transfer('0xRecipientAddress', 1000).buildTransaction({
        'from': '0xYourAddress',
        'nonce': w3.eth.getTransactionCount('0xYourAddress'),
        'gas': 2000000,
        'gasPrice': w3.toWei('50', 'gwei')
    })
    signed_tx = w3.eth.account.sign_transaction(tx, 'your_private_key')
    tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
    print(f"Transaction hash: {w3.toHex(tx_hash)}")
    

    6. 事件监听

    web3.py 支持监听智能合约的事件,适合实时跟踪合约中发生的动作。

  • 监听智能合约事件
    event_filter = contract.events.Transfer.createFilter(fromBlock='latest')
    
    while True:
        for event in event_filter.get_new_entries():
            print(f"New Transfer event: {event}")
    

    7. 签名消息和验证

    web3.py 提供了消息签名和验证的功能,允许用户使用账户的私钥签署消息,并且可以使用公钥验证签名。

  • 签名消息

    message = "Hello, Ethereum!"
    signed_message = w3.eth.account.sign_message(Web3.keccak(text=message), 'your_private_key')
    print(signed_message)
    

    验证签名

    recovered_address = w3.eth.account.recover_message(Web3.keccak(text=message), signature=signed_message.signature)
    print(f"Recovered address: {recovered_address}")
    

    8. 管理 ENS(以太坊名称服务)

    web3.py 支持以太坊名称服务(ENS),可以将 ENS 名称解析为以太坊地址,简化转账流程。

  • 解析 ENS 名称
    address = w3.ens.address('vitalik.eth')
    print(f"Address: {address}")
    

    9. 支持 PoA 网络

    在某些使用权威证明(PoA)共识机制的网络(如 Rinkeby 测试网或 Binance Smart Chain)中,需要添加 geth_poa_middleware 以正确处理区块。

  • 添加 PoA 支持
    from web3.middleware import geth_poa_middleware
    
    w3.middleware_onion.inject(geth_poa_middleware, layer=0)
    

    10. IPFS 交互

    虽然 web3.py 不直接支持 IPFS,但它可以通过与以太坊智能合约结合使用来存储和引用 IPFS 哈希。

    11. 其他功能

  • 多签交易:支持多签名交易和账户管理。
  • ENS 注册和管理:管理以太坊域名。
  • 区块事件和日志过滤:过滤区块日志并监听特定事件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值