Bitcoin Core client is composed of a daemon, bitcoind, a GUI oriented client, bitcoin-qt and a CLI oriented client, bitcoin-cli. bitcoind offerts an JSON-RPC interface over a HTTP socket to perform functions on the wallet, transactions, mempool, etc.
In this post, I’ll quickly show how to access this interface using python and no extra library.
Firstly, you need to set RPC cookie authentification (it is also possible to set a login/password authentification, but this method will soon become obsolete as I’m writing this.). By default, no cookie is defined so one is created randomly at each bitcoind start, and is usable by bitcoin-cli. To be able to use ours, there is a script in Bitcoin Core’s github repository to allow creating login credentials for a JSON-RPC user. This script is named rpcauth.py. Let’s try it:
You’ll have to add in bitcoin.conf said line, and restart (start) bitcoind:
Please note that I’m using testnet on my examples.
You can test authentification using bitcoin-cli, using -rpcuser and -rpcpassword flags:
We are done for this part! Still have to write some python code to connect & send commands. There is a lot of other ways to reach the API, but in this example I’ll just use raw python with only requests module.
This code is pretty much straightforward: We are just doing a http query with authentification headers, and returning the result. Nothing more is required.
Let’s test it:
There is a lot of api calls available. They go from wallet management, to stats, transaction creation, etc. More things can be done through the API than bitcoin-qt. Recently, I’ve sent some custom raw data messages on the testnet blockchain, creating my own custom transaction, in just a few lines of code using that API. I’ll come back later on another article.
This API is also used for mining. Miners like bfgminer can connect to that API as well (if you don’t use a pool/stratum server). Finally, there is some interesting examples in the developers examples wiki page.