LoginSignup
5
7

More than 5 years have passed since last update.

pythonからbitcoindにアクセスする

Last updated at Posted at 2017-06-30

この記事では、Mac OS Sierra 10.12.4を使っています。
bitcoindにpythonからアクセスする環境を構築した時の情報をまとめました。

bitcoindをインストールしていることを前提とします。
参考:bitcoindをdockerで環境構築する

python-rpcのインストール

python-bitcoinrpcを利用します。

pip install python-bitcoinrpc

rpc接続の確立

bitcoinで利用されるrpc(リモートプロシージャコール)の接続を確立します。
quick_startに従って始めます。

from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
rpc_user="bitcoinrpc"
rpc_password='passwordxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:8332"%(rpc_user, rpc_password))

rpc_user,rpc_passwordはbitcoindの環境構築時に設定したものを使います。
わからなければ、bitcoin.confを確認すれば書かれているはずです。
なお、2017/6/24時点、AuthServiceProxyにおいて、パスワードに「/」が入っているとエラーになります。
(urllibでrpc_user,rpc_passwordを分解する際の区切りがうまく識別できないため)
/が混じらないpasswordにするなど工夫が必要です。

rpc接続の確認

rpc_connectionを定義したら、ブロックをとってみましょう

blhash = rpc_connection.getblockhash(0) #blhashはブロックのhash文字列
bl = rpc_connection.getblock(blhash) #blはブロック情報

結果確認

bl
{'bits': '1d00ffff',
 'chainwork': '0000000000000000000000000000000000000000000000000000000100010001',
 'confirmations': 1,
 'difficulty': 1,
 'hash': '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f',
 'height': 0,
 'mediantime': 1231006505,
 'merkleroot': '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b',
 'nonce': 2083236893,
 'size': 285,
 'strippedsize': 285,
 'time': 1231006505,
 'tx': ['4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b'],
 'version': 1,
 'versionHex': '00000001',
 'weight': 1140}

genesisブロック情報が取れています。

次回はブロック内のトランザクション情報を取得するコードを作成します。

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7