通過命令列在Python中測試以太坊RPC客戶端
在這個筆記中,我將使用Python命令列測試以太坊的RPC客戶端,準備好狂敲鍵盤吧。過程中有關JSON RPC的更多資訊,可以參閱ofollow,noindex">JSON RPC 。
輸入:
from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all"
import sys sys.version
輸出:
準備環境
為以太坊安裝Python RPC客戶端 ,輸入:
jitsejan@jjvps:~$ pip install ethereum-rpc-client
啟動區塊鏈以確保啟用RPC。
輸入:
jitsejan@jjvps:~$ geth --networkid 23 --nodiscover --maxpeers 0--port 30333 --rpc
驗證geth是否正在執行並且列出了該帳戶。
輸入:
!geth account list
輸出:
Account #0: {8cf9deda0712f2291fb16739f8759e4a0a575854} keystore:///home/jitsejan/.ethereum/keystore/UTC--2017-05-01T14-58-43.532247863Z--8cf9deda0712f2291fb16739f8759e4a0a575854
連結到RPC客戶端
輸入:
from eth_rpc_client import Client client = Client(host="127.0.0.1", port="8545")
檢查客戶端
輸入:
import pdir pdir(client)
輸出:
abstract class: __subclasshook__ attribute access: __delattr__, __dir__, __getattribute__, __setattr__ class customization: __init_subclass__ object customization: __format__, __hash__, __init__, __new__, __repr__, __sizeof__, __str__ other: _coinbase_cache, _coinbase_cache_til, _nonce, async_timeout, host, is_async, port, request_queue, request_thread, results, session pickle: __reduce__, __reduce_ex__ rich comparison: __eq__, __ge__, __gt__, __le__, __lt__, __ne__ special attribute: __class__, __dict__, __doc__, __module__, __weakref__ descriptor: default_from_address: @property with getter, Cache the coinbase address so that we don't make two requests for every function: _make_request: call: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call construct_json_request: get_accounts: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_accounts get_balance: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getbalance get_block_by_hash: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbyhash get_block_by_number: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbynumber get_block_number: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_blocknumber<F37> get_code: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode get_coinbase: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_coinbase get_filter_changes: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getfilterchanges get_filter_logs: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getfilterlogs get_gas_price: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gasprice get_logs: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getlogs get_max_gas: get_nonce: get_transaction_by_hash: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyhash get_transaction_receipt: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionreceipt make_request: new_block_filter: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newblockfilter new_filter: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter new_pending_transaction_filter: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newpendingtransactionfilter process_requests: Loop that runs in a thread to process requests synchronously. send_transaction: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction uninstall_filter: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_uninstallfilter wait_for_block: wait_for_transaction:
獲取區塊鏈的coinbase
輸入:
address = client.get_coinbase() address
輸出:
0x8cf9deda0712f2291fb16739f8759e4a0a575854
查詢主地址的餘額
輸入:
client.get_balance(address)
輸出:
135000419895999999940
設定其他兩臺機器的地址
輸入:
address_vps_one = "0xc257beaea430afb3a09640ce7f020c906331f805" address_vps_two = "0xe86ee31b7d32b743907fa7438c422a1803717deb" client.get_balance(address_vps_one) client.get_balance(address_vps_two)
輸出:
交易
讓我們從主機發送12個乙太網到VPS,1 GWEI=0.000000001 Ether。
輸入:
amount = 12 # Ether sending_address = address receiving_address = address_vps_one
獲取密碼以解鎖傳送帳戶
輸入:
from getpass import getpass pw = getpass(prompt='Enter the password for the sender: ')
通過命令列解鎖帳戶
輸入:
command = r'geth --exec "personal.unlockAccount(\"%s\", \"%s\");" attach ' % (sending_address, pw) result = !$command if result[0] != 'true': print('Fail: %s' % result[0]) else: print('Account is unlocked!')
輸出:
Account is unlocked!
傳送交易
tx_hash = client.send_transaction(to=receiving_address, _from=sending_address, value=amount * 10**9)
檢查交易明細
client.get_transaction_by_hash(tx_hash)
輸出:
{'blockHash': '0x0000000000000000000000000000000000000000000000000000000000000000', 'blockNumber': None, 'from': '0x8cf9deda0712f2291fb16739f8759e4a0a575854', 'gas': '0x15f90', 'gasPrice': '0x4a817c800', 'hash': '0x3d1a193ccfccc4e9ab2a411044069deeec2feef31a594bbf73726b463e8e90b4', 'input': '0x', 'nonce': '0xb', 'r': '0xe8698846a461938e800698fcc34570e0c4e9a3425f0bc441bf3e0716dab7b3e0', 's': '0x4fcd9bda8a1e98a7b0e8d953dec0cc733238c383d97393aa15c43963551f8daf', 'to': '0xc257beaea430afb3a09640ce7f020c906331f805', 'transactionIndex': '0x0', 'v': '0x42', 'value': '0x2cb417800'}
執行一個挖掘步驟
執行礦工以驗證交易。
輸入:
prev_balance_sen = client.get_balance(sending_address) prev_balance_rec = client.get_balance(receiving_address)
result = !geth --exec "miner.start();admin.sleepBlocks(1);miner.stop();" attach if result[0] != 'true': print('Fail: %s' % result[0]) else: print("Mining finished!")
輸出挖礦完成:
Mining finished!
檢查是否已收到乙太網
輸入:
print("Received %d"% (client.get_balance(receiving_address)-prev_balance_rec))
輸出收到金額:
Received 12000000000
檢查Ether是否已傳送
首先檢查餘額的差異,輸入:
print("Difference of the sender %d"% (client.get_balance(sending_address)-prev_balance_sen))
輸出:
Difference of the sender 4999999988000000000
對於採礦來說,礦工將獲得採礦獎金。
輸入:
mining_bonus = 5000000000000000000
要獲得乙太網傳送的數量,我們需要減去採礦獎金。
輸入:
print("Amount difference: %d" % int(client.get_balance(sending_address)-prev_balance_sen - mining_bonus))
輸出金額差異:
Amount difference: -12000000000
。
======================================================================
分享一些以太坊、EOS、比特幣等區塊鏈相關的互動式線上程式設計實戰教程:
- python以太坊,主要是針對python工程師使用web3.py進行區塊鏈以太坊開發的詳解。
- java以太坊開發教程,主要是針對java和android程式員進行區塊鏈以太坊開發的web3j詳解。
- php以太坊,主要是介紹使用php進行智慧合約開發互動,進行賬號建立、交易、轉賬、代幣開發以及過濾器和交易等內容。
- 以太坊入門教程,主要介紹智慧合約與dapp應用開發,適合入門。
- 以太坊開發進階教程,主要是介紹使用node.js、mongodb、區塊鏈、ipfs實現去中心化電商DApp實戰,適合進階。
- C#以太坊,主要講解如何使用C#開發基於.Net的以太坊應用,包括賬戶管理、狀態與交易、智慧合約開發與互動、過濾器和交易等。
- EOS教程,本課程幫助你快速入門EOS區塊鏈去中心化應用的開發,內容涵蓋EOS工具鏈、賬戶與錢包、發行代幣、智慧合約開發與部署、使用程式碼與智慧合約互動等核心知識點,最後綜合運用各知識點完成一個便籤DApp的開發。
- java比特幣開發教程,本課程面向初學者,內容即涵蓋比特幣的核心概念,例如區塊鏈儲存、去中心化共識機制、金鑰與指令碼、交易與UTXO等,同時也詳細講解如何在Java程式碼中整合比特幣支援功能,例如建立地址、管理錢包、構造裸交易等,是Java工程師不可多得的比特幣開發學習課程。
- php比特幣開發教程,本課程面向初學者,內容即涵蓋比特幣的核心概念,例如區塊鏈儲存、去中心化共識機制、金鑰與指令碼、交易與UTXO等,同時也詳細講解如何在Php程式碼中整合比特幣支援功能,例如建立地址、管理錢包、構造裸交易等,是Php工程師不可多得的比特幣開發學習課程。
- tendermint區塊鏈開發詳解 ,本課程適合希望使用tendermint進行區塊鏈開發的工程師,課程內容即包括tendermint應用開發模型中的核心概念,例如ABCI介面、默克爾樹、多版本狀態庫等,也包括代幣發行等豐富的實操程式碼,是go語言工程師快速入門區塊鏈開發的最佳選擇。
匯智網原創翻譯,轉載請標明出處。這裡是原文在Python中使用以太坊RPC客戶端