javascript
探索比特币源码4-JSON-RPC接口的其他调用方法
探索比特幣源碼4-JSON-RPC接口的其他調用方法
上一文探索比特幣源碼3-熟悉RPC接口中練習了使用bitcoin-cli客戶端調用JSON-RPC接口的方法。
本文探索JSON-RPC接口的其他調用方法,包括:
curl(命令行HTTP客戶端)
其他語言的封裝的API庫(以python為例)
使用命令行HTTP客戶端curl調用RPC接口
之前從未接觸過curl,所以這部分僅作簡單了解和練習。
curl是一種命令行工具,作用是發出網絡請求,然后得到和提取數據,顯示在”標準輸出”(stdout)上面
如下是兩個不錯的資料:
curl網站開發指南
curl命令介紹
當我們使用bitcoin-cli獲取某個具體RPC命令的幫助時,它會提供一個使用curl調用接口的示例:
$ bitcoin-cli help getblockhash getblockhash heightReturns hash of block in best-block-chain at height provided.Arguments: 1. height (numeric, required) The height indexResult: "hash" (string) The block hashExamples: > bitcoin-cli getblockhash 1000 > curl --user myusername --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getblockhash", "params": [1000] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/按照提示,我們使用curl來完成一次簡單的JSON-RPC調用:
$ curl --user myusername --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getblockhash", "params": [1000] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/其中 myusername 是bitcoin.conf配置文件中所填的用戶名
我在調用時,訪問失敗了,應該是科學上網的原因,我沒有再深入研究。
現在讓我們來進入下面更重要的部分,使用其他編程語言的封裝庫來訪問JSON-RPC接口。
使用python-bitcoinlib庫調用RPC接口
我們平時可能會產生一些需求,需要我們批量的調用JSON-RPC來對比特幣區塊鏈的數據進行一些分析。
這時候,使用編程的方式調用封裝好的RPC接口是相當方便的。
大多數語言都提供了對于比特幣核心JSON-RPC接口的封裝,這里嘗試了精通比特幣第三章介紹的python-bitcoinlib庫
安裝python-bitcoinlib
首先安裝依賴庫:
$ sudo apt-get install libssl-dev然后安裝python-bitcoinlib庫
$ sudo pip install python-bitcoinlib調用練習
我們先創建一個rpc調用練習文件rpc_example.py:
from bitcoin.rpc import RawProxy #Create a connection to local Bitcoin Core node p = RawProxy() #Run the getblockchaininfo command, store the resulting data in info info = p.getblockchaininfo() # Retrieve the 'blocks' element from the info print(info['blocks'])運行python腳本
$ python rpc_example.py 384204表明我的比特幣節點目前同步了384204個區塊
由于我的全節點區塊鏈同步出了問題,這里僅做一個簡單的測試,后面爭取在這個小節補充更多的示例。
總結
以上是生活随笔為你收集整理的探索比特币源码4-JSON-RPC接口的其他调用方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 协议簇:TCP 解析: Sequence
- 下一篇: 比特币中的密码学知识汇总