python-rpcのインストール

> pip install python-bitcoinrpc

bitcoindの起動

ここを参考にしてください。

前回に続いてregtestで試してみます。

> bitcoind -regtest

RPC接続

//source_001.py
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException

rpc_user="username"
rpc_password="password"

rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:8332"%(rpc_user, rpc_password))

blhash = rpc_connection.getblockhash(0)
bl = rpc_connection.getblock(blhash)
print(bl)

rpc_userrpc_passwordbitcoin.conf内の値を使ってください。

実行結果

> python source_001.py
{'hash': '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206', 'confirmations': 107, 'strippedsize': 285, 'size': 285, 'weight': 1140, 'height': 0, 'version': 1, 'versionHex': '00000001', 'merkleroot': '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b', 'tx': ['4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b'], 'time': 1296688602, 'mediantime': 1296688602, 'nonce': 2, 'bits': '207fffff', 'difficulty': Decimal('4.656542373906925E-10'), 'chainwork': '0000000000000000000000000000000000000000000000000000000000000002', 'nextblockhash': '60943d938696f7b00966add8bc04f62a4ffaf184fc81c9a43a527280f09da72f'}

ブロック0の情報を取得し、
0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206というハッシュが得られました。
このソースコードはbitcoin-cliで以下のようなことをしているのと等価です。

> bitcoin-cli getblockhash 0
0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206
> bitcoin-cli getblock 0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206
{
  "hash": "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206",
  "confirmations": 107,
  "strippedsize": 285,
  "size": 285,
  "weight": 1140,
  "height": 0,
  "version": 1,
  "versionHex": "00000001",
  "merkleroot": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
  "tx": [
    "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
  ],
  "time": 1296688602,
  "mediantime": 1296688602,
  "nonce": 2,
  "bits": "207fffff",
  "difficulty": 4.656542373906925e-010,
  "chainwork": "0000000000000000000000000000000000000000000000000000000000000002",
  "nextblockhash": "60943d938696f7b00966add8bc04f62a4ffaf184fc81c9a43a527280f09da72f"
}