接口列表参考官方文档:https://developer.bitcoin.org/reference/rpc/index.html
为了方便,使用一个第三方python工具:bitcoinrpc
可以直接使用pip安装
pip install bitcoinrpc
然后就可以直接在python代码中使用:
from bitcoinrpc.authproxy import AuthServiceProxy
# 创建一个连接到 Bitcoin Core RPC 服务的代理对象
rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:8332" % ('fx', '0000'))
highestBlockNumber = rpc_connection.getblockcount()
print(highestBlockNumber)
常用接口
1. getbestblockhash()
返回工作量最大的完全验证链中最佳(tip)块的哈希值。
2.getblockcount()
返回工作量最大的完全验证链的高度(创世区块的高度为0)。
3. getblockhash()
返回最佳块链中所提供的块的哈希值。
参数1:height 类型:numeric, required 区块高度索引。
4. getblock()
参数1:blockhash 类型:string, required 区块哈希。
参数2:verbosity 类型:numeric, optional 默认为1,结果返回一个json对象;若为0,则返回一个十六进制编码的数据。
运行试试:
highestBlock_number = rpc_connection.getblockcount()
print("最大区块高度:" + str(highestBlock_number))
highestBlockHhash = rpc_connection.getblockhash(highestBlock_number)
print("最大区块哈希:" + str(highestBlock_number))
highestBlock = rpc_connection.getblock(highestBlockHhash)
print(highestBlock)
输出:
其中,最后面的 'tx' 就是这个区块中每一笔交易的交易id;'time'是区块时间,一个区块内的交易时间都是同一个时间戳。
5. getrawtransaction()
参数1:txid 类型:string, required 交易id。
参数2:verbose 类型:boolean, optional 默认为0,返回一个string;若为1,则返回一个json对象。
参数3:blockhash 类型:string, optional 查询的交易所在区块的区块哈希。
Note:若是不想要使用参数3,只通过txid查询交易,需要建立txid的索引。方法是:在启动节点的时候,添加参数-txindex=1,可以添加在快捷方式的 “属性”-“目标” 的后面,然后重启节点。重启节点后,需要等待它大概几个小时的时间来构建索引。
试试运行一下(我这里是已经构建过了txid的索引):
txid = '8f6494671a989920f402e460e8765dd88db3cb4ab0ed44011bd3b63e11b17899'
tx = rpc_connection.getrawtransaction(txid, 1)
print(tx)
输出: