1. 安装geth
从官方下载页面获取适合你操作系统的版本。
对于Ubuntu/Debian:
sudo add-apt-repository -y ppa:ethereum/ethereum sudo apt-get update sudo apt-get install ethereum
连接以太坊区块链并进行开发
Geth(Go Ethereum)是以太坊区块链的官方Go语言实现,它允许用户:
在Python中,我们通过web3.py库与geth节点进行交互。
从官方下载页面获取适合你操作系统的版本。
对于Ubuntu/Debian:
sudo add-apt-repository -y ppa:ethereum/ethereum sudo apt-get update sudo apt-get install ethereum
使用以下命令启动一个测试网络的节点:
# 启动测试网络节点 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在Python环境中安装web3.py库:
pip install web3
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}")
A: 通常是因为gas价格设置过低。尝试提高gas价格或检查节点同步状态。
A: 可以使用Goerli水龙头:https://goerlifaucet.com/
A: 完整同步可能需要几小时到几天,取决于网络状态和硬件。使用--syncmode light可以加快同步速度。
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}")
本文由GanKunRuan于2025-07-27发表在吾爱品聚,如有疑问,请联系我们。
本文链接:http://521pj.cn/20256606.html
发表评论