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

Python中使用geth的完整指南 - 连接以太坊区块链

Python中使用geth的完整指南

连接以太坊区块链并进行开发

什么是geth?

Geth(Go Ethereum)是以太坊区块链的官方Go语言实现,它允许用户:

  • 运行以太坊节点
  • 挖掘以太币
  • 创建和管理账户
  • 部署和交互智能合约
  • 在以太坊网络上发送交易

在Python中,我们通过web3.py库与geth节点进行交互。

安装和设置

1. 安装geth

官方下载页面获取适合你操作系统的版本。

对于Ubuntu/Debian:

sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum

2. 启动geth节点

使用以下命令启动一个测试网络的节点:

# 启动测试网络节点
geth --goerli --syncmode light --http --http.api eth,net,web3,personal

# 或者启动私有开发网络
geth --dev --http --http.api eth,net,web3,personal

参数说明:

  • --goerli:连接到Goerli测试网络
  • --dev:启动私有开发网络
  • --http:启用HTTP-RPC服务器
  • --http.api:启用指定的API

3. 安装web3.py

在Python环境中安装web3.py库:

pip install web3

Python与geth交互示例

连接到geth节点

from web3 import Web3

# 连接到本地geth节点
w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))

if w3.isConnected():
    print("成功连接到geth节点")
    print(f"当前区块号: {w3.eth.block_number}")
else:
    print("连接失败")

账户管理

# 创建新账户
account = w3.eth.account.create()
private_key = account.key.hex()
address = account.address

print(f"新账户地址: {address}")
print(f"私钥: {private_key}")

# 获取账户余额
balance = w3.eth.get_balance(address)
print(f"余额: {w3.fromWei(balance, 'ether')} ETH")

发送交易

# 发送以太币交易
def send_eth(sender, receiver, amount_eth, private_key):
    # 设置交易参数
    nonce = w3.eth.get_transaction_count(sender)
    amount_wei = w3.toWei(amount_eth, 'ether')
    
    tx = {
        'nonce': nonce,
        'to': receiver,
        'value': amount_wei,
        'gas': 21000,
        'gasPrice': w3.toWei('50', 'gwei'),
        'chainId': 5  # Goerli测试网ID
    }
    
    # 签名交易
    signed_tx = w3.eth.account.sign_transaction(tx, private_key)
    
    # 发送交易
    tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
    
    # 等待交易确认
    receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
    return receipt

# 使用示例
sender_address = "0xYourSenderAddress"
receiver_address = "0xReceiverAddress"
sender_private_key = "YourPrivateKey"

receipt = send_eth(sender_address, receiver_address, 0.01, sender_private_key)
print(f"交易成功!哈希: {receipt.transactionHash.hex()}")

与智能合约交互

# 示例:与ERC-20代币合约交互
contract_address = "0xContractAddress"
contract_abi = [...]  # 合约ABI

contract = w3.eth.contract(address=contract_address, abi=contract_abi)

# 读取合约数据
token_name = contract.functions.name().call()
token_symbol = contract.functions.symbol().call()
print(f"代币名称: {token_name} ({token_symbol})")

# 获取账户余额
account_balance = contract.functions.balanceOf(address).call()
print(f"代币余额: {account_balance}")

# 发送代币交易
def transfer_tokens(receiver, amount):
    nonce = w3.eth.get_transaction_count(sender_address)
    
    tx = contract.functions.transfer(receiver, amount).buildTransaction({
        'chainId': 5,
        'gas': 100000,
        'gasPrice': w3.toWei('50', 'gwei'),
        'nonce': nonce
    })
    
    signed_tx = w3.eth.account.sign_transaction(tx, sender_private_key)
    tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
    return tx_hash.hex()

# 转账示例
tx_hash = transfer_tokens(receiver_address, 100)
print(f"代币转账交易哈希: {tx_hash}")

最佳实践与安全提示

  • 开发时使用测试网络(如Goerli)或私有链
  • 永远不要将私钥硬编码在代码中 - 使用环境变量或安全存储
  • 为生产环境配置适当的geth同步模式(light/full/archive)
  • 合理设置gas价格和gas限制以避免交易失败
  • 处理交易失败和重试逻辑
  • 使用Infura等节点服务作为备用连接
  • 定期备份你的keystore文件

常见问题解答

Q: 为什么我的交易一直处于pending状态?

A: 通常是因为gas价格设置过低。尝试提高gas价格或检查节点同步状态。

Q: geth同步需要多长时间?

A: 完整同步可能需要几小时到几天,取决于网络状态和硬件。使用--syncmode light可以加快同步速度。

Q: 如何监听新区块或事件?

A: 使用web3.py的过滤器功能:

# 监听新区块
new_block_filter = w3.eth.filter('latest')
while True:
    for block_hash in new_block_filter.get_new_entries():
        block = w3.eth.get_block(block_hash)
        print(f"新区块 #{block.number}")

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

发表评论