API reference (JSON-RPC)
Contents
Controlling Bitcoin Core
Run bitcoind or bitcoin-qt -server. You can control it via the command-line bitcoin-cli utility or by HTTP JSON-RPC commands.
You must create a bitcoin.conf configuration file setting an rpcuser and rpcpassword; see Running Bitcoin for details.
If you are learning the API, it is a very good idea to use the test network (run bitcoind -testnet and bitcoin-cli -testnet).
JSON-RPC
Running Bitcoin with the -server argument (or running bitcoind) tells it to function as a HTTP JSON-RPC server, but Basic access authentication must be used when communicating with it, and, for security, by default, the server only accepts connections from other processes on the same machine. If your HTTP or JSON library requires you to specify which ‘realm’ is authenticated, use ‘jsonrpc’.
Bitcoin supports SSL (https) JSON-RPC connections beginning with version 0.3.14. See the rpcssl wiki page for setup instructions and a list of all bitcoin.conf configuration options.
Allowing arbitrary machines to access the JSON-RPC port (using the rpcallowip configuration option) is dangerous and strongly discouraged— access should be strictly limited to trusted machines.
To access the server you should find a suitable library for your language.
Proper money handling
See the proper money handling page for notes on avoiding rounding errors when handling bitcoin values.
Languages
Python
python-jsonrpc is the official JSON-RPC implementation for Python. It automatically generates Python methods for RPC calls. However, due to its design for supporting old versions of Python, it is also rather inefficient. jgarzik has forked it as Python-BitcoinRPC and optimized it for current versions. Generally, this version is recommended.
While BitcoinRPC lacks a few obscure features from jsonrpc, software using only the ServiceProxy class can be written the same to work with either version the user might choose to install:
The latest version of python-bitcoinrpc has a new syntax.
Erlang
Get the rebar dependency from https://github.com/edescourtis/ebitcoind . By default the client will use the configuration in $HOME/.bitcoin/bitcoin.conf or you can instead specify a URI like this:
Here is a usage example:
The JSON-RPC PHP library also makes it very easy to connect to Bitcoin. For example:
Note: The jsonRPCClient library uses fopen() and will throw an exception saying «Unable to connect» if it receives a 404 or 500 error from bitcoind. This prevents you from being able to see error messages generated by bitcoind (as they are sent with status 404 or 500). The EasyBitcoin-PHP library is similar in function to JSON-RPC PHP but does not have this issue.
The easiest way to tell Java to use HTTP Basic authentication is to set a default Authenticator:
Once that is done, any JSON-RPC library for Java (or ordinary URL POSTs) may be used to communicate with the Bitcoin server.
Instead of writing your own implementation, consider using one of the existing wrappers like BitcoindClient4J, btcd-cli4j or Bitcoin-JSON-RPC-Client instead.
The JSON::RPC package from CPAN can be used to communicate with Bitcoin. You must set the client’s credentials; for example:
The btcrpcclient package can be used to communicate with Bitcoin. You must provide credentials to match the client you are communicating with.
.NET (C#)
The communication with the RPC service can be achieved using the standard http request/response objects. A library for serializing and deserializing Json will make your life a lot easier:
Json.NET ( http://james.newtonking.com/json ) is a high performance JSON package for .NET. It is also available via NuGet from the package manager console ( Install-Package Newtonsoft.Json ).
The following example uses Json.NET:
There is also a wrapper for Json.NET called Bitnet (https://sourceforge.net/projects/bitnet) implementing Bitcoin API in more convenient way:
A more complete library and wrapper for Bitcoin is BitcoinLib (https://github.com/GeorgeKimionis/BitcoinLib) which is also available via NuGet from the package manager console (Install-Package BitcoinLib).
Querying the daemon with BitcoinLib is as simple as:
Node.js
Example using bitcoin-core:
gentle_rpc is a typescript JSON-RPC library for Deno, it works perfectly with lowercase function names.
Example using gentle_rpc:
Command line (cURL)
You can also send commands and see results using cURL or some other command-line HTTP-fetching utility; for example:
You will be prompted for your rpcpassword, and then will see something like:
Command line (jsonrpc-cli)
jsonrpc-cli provides simple json queries from the command-line with highlighted json results (colors) and the ability to view/debug raw http requests and responses.
Clojure
clj-btc is a Clojure wrapper for the bitcoin API.
The C API for processing JSON is Jansson. C applications like libblkmaker use cURL for making the calls and Jansson for interpreting the JSON that cURL fetches.
For example basic usage (which can be easily modified for Bitcoin RPC), see the Jansson example github_commits.c and the associated tutorial.
The following does with libcurl what the cURL example above does:
QJsonRpc is a Qt/C++ implementation of the JSON-RPC protocol. It integrates nicely with Qt, leveraging Qt’s meta object system in order to provide services over the JSON-RPC protocol. QJsonRpc is licensed under the LGPLv2.1.
Multi-wallet RPC calls
Bitcoin Knots 0.13.1 added support for loading multiple, separate wallets. Multi-wallet can be enabled by using more than one -wallet argument when starting Bitcoin, either on the command line or in the Bitcoin config file. This was also included in Bitcoin Core 0.15.
Wallet-level RPC calls (like importaddress or listtransactions ) can specify which wallet file will be accessed. This is done by setting the HTTP endpoint in the JSON-RPC request in the format : /wallet/ , for example https://127.0.0.1:8332/wallet/wallet1.dat .
The command line utility bitcoin-cli can specify the wallet file using the -rpcwallet flag, for example bitcoin-cli -rpcwallet=wallet1.dat getbalance
Alternatively (but not available in Bitcoin Core at this time), an additional parameter can be specified to -rpcauth naming a default wallet for JSON-RPC accesses to the normal endpoint.
Источник
Bitcoin rpc how to
Simple Bitcoin JSON-RPC client based on GuzzleHttp
Run php composer.phar require denpa/php-bitcoinrpc in your project directory or add following lines to composer.json
and run php composer.phar install .
PHP 7.1 or higher
For PHP 5.6 and 7.0 use php-bitcoinrpc v2.0.x.
Create new object with url as parameter
or use array to define your bitcoind settings
Then call methods defined in Bitcoin Core API Documentation with magic:
To send asynchronous request, add Async to method name:
You can also send requests using request method:
or requestAsync method for asynchronous calls:
You can use wallet($name) function to do a Multi-Wallet RPC call:
- Denpa\Bitcoin\Exceptions\BadConfigurationException — thrown on bad client configuration.
- Denpa\Bitcoin\Exceptions\BadRemoteCallException — thrown on getting error message from daemon.
- Denpa\Bitcoin\Exceptions\ConnectionException — thrown on daemon connection errors (e. g. timeouts)
Package provides following helpers to assist with value handling.
Converts value in satoshi to bitcoin.
Converts value in bitcoin to satoshi.
Converts value in bitcoin to ubtc/bits.
Converts value in bitcoin to mbtc.
Trims float value to precision without rounding.
This product is distributed under MIT license.
If you like this project, please consider donating:
BTC: 3L6dqSBNgdpZan78KJtzoXEk9DN3sgEQJu
Bech32: bc1qyj8v6l70c4mjgq7hujywlg6le09kx09nq8d350
❤ Thanks for your support! ❤
About
Fully unit-tested Bitcoin JSON-RPC client based on GuzzleHttp.
Источник
Bitcoin rpc how to
The headless daemon bitcoind has the JSON-RPC API enabled by default, the GUI bitcoin-qt has it disabled by default. This can be changed with the -server option. In the GUI it is possible to execute RPC methods in the Debug Console Dialog.
The RPC interface might change from one major version of Bitcoin Core to the next. This makes the RPC interface implicitly versioned on the major version. The version tuple can be retrieved by e.g. the getnetworkinfo RPC in version .
Usually deprecated features can be re-enabled during the grace-period of one major version via the -deprecatedrpc= command line option. The release notes of a new major release come with detailed instructions on what RPC features were deprecated and how to re-enable them temporarily.
The RPC interface allows other programs to control Bitcoin Core, including the ability to spend funds from your wallets, affect consensus verification, read private data, and otherwise perform operations that can cause loss of money, data, or privacy. This section suggests how you should use and configure Bitcoin Core to reduce the risk that its RPC interface will be abused.
Securing the executable: Anyone with physical or remote access to the computer, container, or virtual machine running Bitcoin Core can compromise either the whole program or just the RPC interface. This includes being able to record any passphrases you enter for unlocking your encrypted wallets or changing settings so that your Bitcoin Core program tells you that certain transactions have multiple confirmations even when they aren’t part of the best block chain. For this reason, you should not use Bitcoin Core for security sensitive operations on systems you do not exclusively control, such as shared computers or virtual private servers.
Securing local network access: By default, the RPC interface can only be accessed by a client running on the same computer and only after the client provides a valid authentication credential (username and passphrase). Any program on your computer with access to the file system and local network can obtain this level of access. Additionally, other programs on your computer can attempt to provide an RPC interface on the same port as used by Bitcoin Core in order to trick you into revealing your authentication credentials. For this reason, it is important to only use Bitcoin Core for security-sensitive operations on a computer whose other programs you trust.
Securing remote network access: You may optionally allow other computers to remotely control Bitcoin Core by setting the rpcallowip and rpcbind configuration parameters. These settings are only meant for enabling connections over secure private networks or connections that have been otherwise secured (e.g. using a VPN or port forwarding with SSH or stunnel). Do not enable RPC connections over the public Internet. Although Bitcoin Core’s RPC interface does use authentication, it does not use encryption, so your login credentials are sent as clear text that can be read by anyone on your network path. Additionally, the RPC interface has not been hardened to withstand arbitrary Internet traffic, so changing the above settings to expose it to the Internet (even using something like a Tor onion service) could expose you to unconsidered vulnerabilities. See bitcoind -help for more information about these settings and other settings described in this document.
Related, if you use Bitcoin Core inside a Docker container, you may need to expose the RPC port to the host system. The default way to do this in Docker also exposes the port to the public Internet. Instead, expose it only on the host system’s localhost, for example: -p 127.0.0.1:8332:8332
Secure authentication: By default, Bitcoin Core generates unique login credentials each time it restarts and puts them into a file readable only by the user that started Bitcoin Core, allowing any of that user’s RPC clients with read access to the file to login automatically. The file is .cookie in the Bitcoin Core configuration directory, and using these credentials is the preferred RPC authentication method. If you need to generate static login credentials for your programs, you can use the script in the share/rpcauth directory in the Bitcoin Core source tree. As a final fallback, you can directly use manually-chosen rpcuser and rpcpassword configuration parameters—but you must ensure that you choose a strong and unique passphrase (and still don’t use insecure networks, as mentioned above).
Secure string handling: The RPC interface does not guarantee any escaping of data beyond what’s necessary to encode it as JSON, although it does usually provide serialized data using a hex representation of the bytes. If you use RPC data in your programs or provide its data to other programs, you must ensure any problem strings are properly escaped. For example, the createwallet RPC accepts arguments such as wallet_name which is a string and could be used for a path traversal attack without application level checks. Multiple websites have been manipulated because they displayed decoded hex strings that included HTML tags. For this reason, and others, it is recommended to display all serialized data in hex form only.
RPC consistency guarantees
State that can be queried via RPCs is guaranteed to be at least up-to-date with the chain state immediately prior to the call’s execution. However, the state returned by RPCs that reflect the mempool may not be up-to-date with the current mempool state.
The mempool state returned via an RPC is consistent with itself and with the chain state at the time of the call. Thus, the mempool state only encompasses transactions that are considered mine-able by the node at the time of the RPC.
The mempool state returned via an RPC reflects all effects of mempool and chain state related RPCs that returned prior to this call.
The wallet state returned via an RPC is consistent with itself and with the chain state at the time of the call.
Wallet RPCs will return the latest chain state consistent with prior non-wallet RPCs. The effects of all blocks (and transactions in blocks) at the time of the call is reflected in the state of all wallet transactions. For example, if a block contains transactions that conflicted with mempool transactions, the wallet would reflect the removal of these mempool transactions in the state.
However, the wallet may not be up-to-date with the current state of the mempool or the state of the mempool by an RPC that returned before this RPC. For example, a wallet transaction that was BIP-125-replaced in the mempool prior to this RPC may not yet be reflected as such in this RPC response.
There is a known issue in the JSON-RPC interface that can cause a node to crash if too many http connections are being opened at the same time because the system runs out of available file descriptors. To prevent this from happening you might want to increase the number of maximum allowed file descriptors in your system and try to prevent opening too many connections to your JSON-RPC interface at the same time if this is under your control. It is hard to give general advice since this depends on your system but if you make several hundred requests at once you are definitely at risk of encountering this issue.
Источник