https://tests.bitcoin.it/w/api.php?action=feedcontributions&user=Ethicnology&feedformat=atomBitcoin Wiki - User contributions [en]2024-03-29T08:53:00ZUser contributionsMediaWiki 1.30.0https://tests.bitcoin.it/w/index.php?title=API_reference_(JSON-RPC)&diff=68207API reference (JSON-RPC)2020-09-27T21:29:01Z<p>Ethicnology: gentleRpc -> gentle_rpc (the repository change his naming convention)</p>
<hr />
<div>== Controlling Bitcoin Core ==<br />
<br />
Run ''bitcoind'' or ''bitcoin-qt -server''. You can control it via the command-line bitcoin-cli utility or by [http://json-rpc.org/wiki/specification HTTP JSON-RPC] commands.<br />
<br />
You must create a bitcoin.conf configuration file setting an rpcuser and rpcpassword; see [[Running Bitcoin]] for details.<br />
<br />
Now run:<br />
$ ./bitcoind -daemon<br />
bitcoin server starting<br />
$ ./bitcoin-cli -rpcwait help<br />
# shows the help text<br />
<br />
A [[Original Bitcoin client/API Calls list|list of RPC calls]] will be shown.<br />
<br />
$ ./bitcoin-cli getbalance<br />
2000.00000<br />
<br />
If you are learning the API, it is a very good idea to use the test network (run bitcoind -testnet and bitcoin-cli -testnet).<br />
<br />
== JSON-RPC ==<br />
<br />
Running Bitcoin with the -server argument (or running bitcoind) tells it to function as a [http://json-rpc.org/wiki/specification HTTP JSON-RPC] server, but <br />
[http://en.wikipedia.org/wiki/Basic_access_authentication 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'.<br />
<br />
Bitcoin supports SSL (https) JSON-RPC connections beginning with version 0.3.14. See the [[Enabling SSL on original client daemon|rpcssl wiki page]] for setup instructions and a list of all bitcoin.conf configuration options.<br />
<br />
Allowing arbitrary machines to access the JSON-RPC port (using the rpcallowip [[Running_Bitcoin|configuration option]]) is dangerous and '''strongly discouraged'''-- access should be strictly limited to trusted machines.<br />
<br />
To access the server you should find a [http://json-rpc.org/wiki/implementations suitable library] for your language.<br />
<br />
== Proper money handling ==<br />
<br />
See the [[Proper Money Handling (JSON-RPC)|proper money handling page]] for notes on avoiding rounding errors when handling bitcoin values.<br />
<br />
== Languages ==<br />
<br />
=== Python ===<br />
<br />
[http://json-rpc.org/wiki/python-json-rpc python-jsonrpc] is the official JSON-RPC implementation for Python.<br />
It automatically generates Python methods for RPC calls.<br />
However, due to its design for supporting old versions of Python, it is also rather inefficient.<br />
[[User:jgarzik|jgarzik]] has forked it as [https://github.com/jgarzik/python-bitcoinrpc Python-BitcoinRPC] and optimized it for current versions.<br />
Generally, this version is recommended.<br />
<br />
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:<br />
<br />
<source lang="python"><br />
from jsonrpc import ServiceProxy<br />
<br />
access = ServiceProxy("http://user:password@127.0.0.1:8332")<br />
access.getblockchaininfo()<br />
access.listreceivedbyaddress(6)<br />
#access.sendtoaddress("11yEmxiMso2RsFVfBcCa616npBvGgxiBX", 10)<br />
</source><br />
<br />
The latest version of python-bitcoinrpc has a new syntax.<br />
<source lang="python"><br />
from bitcoinrpc.authproxy import AuthServiceProxy<br />
</source><br />
<br />
=== Ruby ===<br />
<br />
<source lang="ruby"><br />
require 'net/http'<br />
require 'uri'<br />
require 'json'<br />
<br />
class BitcoinRPC<br />
def initialize(service_url)<br />
@uri = URI.parse(service_url)<br />
end<br />
<br />
def method_missing(name, *args)<br />
post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json<br />
resp = JSON.parse( http_post_request(post_body) )<br />
raise JSONRPCError, resp['error'] if resp['error']<br />
resp['result']<br />
end<br />
<br />
def http_post_request(post_body)<br />
http = Net::HTTP.new(@uri.host, @uri.port)<br />
request = Net::HTTP::Post.new(@uri.request_uri)<br />
request.basic_auth @uri.user, @uri.password<br />
request.content_type = 'application/json'<br />
request.body = post_body<br />
http.request(request).body<br />
end<br />
<br />
class JSONRPCError < RuntimeError; end<br />
end<br />
<br />
if $0 == __FILE__<br />
h = BitcoinRPC.new('http://user:password@127.0.0.1:8332')<br />
p h.getbalance<br />
p h.getblockchaininfo<br />
p h.getnewaddress<br />
p h.dumpprivkey( h.getnewaddress )<br />
# also see: https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list<br />
end<br />
</source><br />
<br />
=== Erlang ===<br />
Get the rebar dependency from https://github.com/edescourtis/ebitcoind . By default the client will use the configuration in <code>$HOME/.bitcoin/bitcoin.conf</code> or you can instead specify a URI like this:<br />
<source lang="erlang">ebitcoind:start_link(<<"http://user:password@localhost:8332/">>).</source><br />
<br />
Here is a usage example:<br />
<source lang="erlang"><br />
1> {ok,Pid} = ebitcoind:start_link().<br />
{ok,<0.177.0>}<br />
2> ebitcoind:getbalance(Pid).<br />
8437.02478294<br />
3> ebitcoind:getblockchaininfo(Pid).<br />
{ok, #{<<"balance">> => 8437.02478294,<br />
<<"blocks">> => 260404,<br />
<<"connections">> => 8,<br />
<<"difficulty">> => 148819199.80509263,<br />
<<"errors">> => <<>>,<br />
<<"keypoololdest">> => 1420307921,<br />
<<"keypoolsize">> => 102,<br />
<<"paytxfee">> => 0.0,<br />
<<"protocolversion">> => 70002,<br />
<<"proxy">> => <<>>,<br />
<<"relayfee">> => 1.0e-5,<br />
<<"testnet">> => false,<br />
<<"timeoffset">> => -3,<br />
<<"version">> => 90300,<br />
<<"walletversion">> => 60000}}<br />
4> ebitcoind:setgenerate(Pid,true).<br />
{ok, null}<br />
5> ebitcoind:getblocktemplate(Pid, #{}). <br />
{ok,#{<<"bits">> => <<"181b0dca">>,<br />
<<"coinbaseaux">> => #{<<"flags">> => <<"062f503253482f">>},<br />
<<"coinbasevalue">> => 2518690558,<br />
<<"curtime">> => 1420421249,<br />
<<"height">> => 337533,<br />
<<"mintime">> => 1420416332,<br />
<<"mutable">> => [<<"time">>,<<"transactions">>,<<"prevblock">>],<br />
<<"noncerange">> => <<"00000000ffffffff">>,<br />
<<"previousblockhash">> => <<"000000000000000017ce0a0d328bf84cc597785844393e899e9a971a81679a5f">>,<br />
<<"sigoplimit">> => 20000,<br />
<<"sizelimit">> => 1000000,<br />
<<"target">> => <<"00000000000000001b0dca00000000000000000000000000000000000000"...>>,<br />
<<"transactions">> => [#{<<"data">> => <<"01000000049b47ce225d29bff7c18b7df7d7df4693523a52"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 0,<br />
<<"hash">> => <<"6d0d76e1f27b3a6f7325923710dcdb4107c9"...>>,<br />
<<"sigops">> => 1},<br />
...<br />
</source><br />
<br />
=== PHP ===<br />
<br />
The [http://jsonrpcphp.org/ JSON-RPC PHP] library also makes it very easy to connect to Bitcoin. For example:<br />
<br />
<source lang="php"><br />
require_once 'jsonRPCClient.php';<br />
<br />
$bitcoin = new jsonRPCClient('http://user:password@127.0.0.1:8332/');<br />
<br />
echo "<pre>\n";<br />
print_r($bitcoin->getblockchaininfo()); echo "\n";<br />
echo "Received: ".$bitcoin->getreceivedbylabel("Your Address")."\n";<br />
echo "</pre>";<br />
</source><br />
<br />
'''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 [https://github.com/aceat64/EasyBitcoin-PHP EasyBitcoin-PHP library] is similar in function to JSON-RPC PHP but does not have this issue.<br />
<br />
=== Java ===<br />
<br />
The easiest way to tell Java to use HTTP Basic authentication is to set a default Authenticator:<br />
<br />
<source lang="java"><br />
final String rpcuser ="...";<br />
final String rpcpassword ="...";<br />
<br />
Authenticator.setDefault(new Authenticator() {<br />
protected PasswordAuthentication getPasswordAuthentication() {<br />
return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray());<br />
}<br />
});<br />
</source><br />
<br />
Once that is done, [http://json-rpc.org/wiki/implementations any JSON-RPC library for Java] (or ordinary URL POSTs) may be used to communicate with the Bitcoin server.<br />
<br />
Instead of writing your own implementation, consider using one of the existing wrappers like [https://github.com/johannbarbie/BitcoindClient4J BitcoindClient4J], [https://github.com/priiduneemre/btcd-cli4j btcd-cli4j] or [[Bitcoin-JSON-RPC-Client|Bitcoin-JSON-RPC-Client]] instead.<br />
<br />
=== Perl ===<br />
<br />
The JSON::RPC package from CPAN can be used to communicate with Bitcoin. You must set the client's credentials; for example:<br />
<br />
<source lang="perl"><br />
use JSON::RPC::Client;<br />
use Data::Dumper;<br />
<br />
my $client = new JSON::RPC::Client;<br />
<br />
$client->ua->credentials(<br />
'localhost:8332', 'jsonrpc', 'user' => 'password' # REPLACE WITH YOUR bitcoin.conf rpcuser/rpcpassword<br />
);<br />
<br />
my $uri = 'http://localhost:8332/';<br />
my $obj = {<br />
method => 'getblockchaininfo',<br />
params => [],<br />
};<br />
<br />
my $res = $client->call( $uri, $obj );<br />
<br />
if ($res){<br />
if ($res->is_error) { print "Error : ", $res->error_message; }<br />
else { print Dumper($res->result); }<br />
} else {<br />
print $client->status_line;<br />
}<br />
</source><br />
<br />
=== Go ===<br />
<br />
The [https://github.com/btcsuite/btcrpcclient btcrpcclient package] can be used to communicate with Bitcoin. You must provide credentials to match the client you are communicating with.<br />
<br />
<source lang="go"><br />
package main<br />
<br />
import (<br />
"github.com/btcsuite/btcd/chaincfg"<br />
"github.com/btcsuite/btcrpcclient"<br />
"github.com/btcsuite/btcutil"<br />
"log"<br />
)<br />
<br />
func main() {<br />
// create new client instance<br />
client, err := btcrpcclient.New(&btcrpcclient.ConnConfig{<br />
HTTPPostMode: true,<br />
DisableTLS: true,<br />
Host: "127.0.0.1:8332",<br />
User: "rpcUsername",<br />
Pass: "rpcPassword",<br />
}, nil)<br />
if err != nil {<br />
log.Fatalf("error creating new btc client: %v", err)<br />
}<br />
<br />
// list accounts<br />
accounts, err := client.ListAccounts()<br />
if err != nil {<br />
log.Fatalf("error listing accounts: %v", err)<br />
}<br />
// iterate over accounts (map[string]btcutil.Amount) and write to stdout<br />
for label, amount := range accounts {<br />
log.Printf("%s: %s", label, amount)<br />
}<br />
<br />
// prepare a sendMany transaction<br />
receiver1, err := btcutil.DecodeAddress("1someAddressThatIsActuallyReal", &chaincfg.MainNetParams)<br />
if err != nil {<br />
log.Fatalf("address receiver1 seems to be invalid: %v", err)<br />
}<br />
receiver2, err := btcutil.DecodeAddress("1anotherAddressThatsPrettyReal", &chaincfg.MainNetParams)<br />
if err != nil {<br />
log.Fatalf("address receiver2 seems to be invalid: %v", err)<br />
}<br />
receivers := map[btcutil.Address]btcutil.Amount{<br />
receiver1: 42, // 42 satoshi<br />
receiver2: 100, // 100 satoshi<br />
}<br />
<br />
// create and send the sendMany tx<br />
txSha, err := client.SendMany("some-account-label-from-which-to-send", receivers)<br />
if err != nil {<br />
log.Fatalf("error sendMany: %v", err)<br />
}<br />
log.Printf("sendMany completed! tx sha is: %s", txSha.String())<br />
}<br />
</source><br />
<br />
=== .NET (C#) ===<br />
The communication with the RPC service can be achieved using the standard http request/response objects.<br />
A library for serializing and deserializing Json will make your life a lot easier:<br />
<br />
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 ).<br />
<br />
The following example uses Json.NET:<br />
<br />
<source lang="csharp"><br />
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost.:8332");<br />
webRequest.Credentials = new NetworkCredential("user", "pwd");<br />
/// important, otherwise the service can't desirialse your request properly<br />
webRequest.ContentType = "application/json-rpc";<br />
webRequest.Method = "POST";<br />
<br />
JObject joe = new JObject();<br />
joe.Add(new JProperty("jsonrpc", "1.0"));<br />
joe.Add(new JProperty("id", "1"));<br />
joe.Add(new JProperty("method", Method));<br />
// params is a collection values which the method requires..<br />
if (Params.Keys.Count == 0)<br />
{<br />
joe.Add(new JProperty("params", new JArray()));<br />
}<br />
else<br />
{<br />
JArray props = new JArray();<br />
// add the props in the reverse order!<br />
for (int i = Params.Keys.Count - 1; i >= 0; i--)<br />
{<br />
.... // add the params<br />
}<br />
joe.Add(new JProperty("params", props));<br />
}<br />
<br />
// serialize json for the request<br />
string s = JsonConvert.SerializeObject(joe);<br />
byte[] byteArray = Encoding.UTF8.GetBytes(s);<br />
webRequest.ContentLength = byteArray.Length;<br />
Stream dataStream = webRequest.GetRequestStream();<br />
dataStream.Write(byteArray, 0, byteArray.Length);<br />
dataStream.Close();<br />
<br />
<br />
WebResponse webResponse = webRequest.GetResponse();<br />
<br />
... // deserialze the response<br />
</source><br />
<br />
There is also a wrapper for Json.NET called Bitnet (https://sourceforge.net/projects/bitnet)<br />
implementing Bitcoin API in more convenient way:<br />
<br />
<source lang="csharp"><br />
BitnetClient bc = new BitnetClient("http://127.0.0.1:8332");<br />
bc.Credentials = new NetworkCredential("user", "pass");<br />
<br />
var p = bc.GetDifficulty();<br />
Console.WriteLine("Difficulty:" + p.ToString());<br />
<br />
var inf = bc.GetBlockchainInfo();<br />
Console.WriteLine("Balance:" + inf["balance"]);<br />
</source><br />
<br />
A more complete library and wrapper for Bitcoin is [https://github.com/GeorgeKimionis/BitcoinLib BitcoinLib] (https://github.com/GeorgeKimionis/BitcoinLib) which is also available via [https://www.nuget.org/packages/BitcoinLib/ NuGet] from the package manager console (Install-Package BitcoinLib). <br />
<br />
Querying the daemon with [https://github.com/GeorgeKimionis/BitcoinLib BitcoinLib] is as simple as:<br />
<br />
<source lang="csharp"><br />
IBitcoinService bitcoinService = new BitcoinService();<br />
<br />
var networkDifficulty = bitcoinService.GetDifficulty();<br />
var myBalance = bitcoinService.GetBalance();<br />
</source><br />
<br />
=== Node.js ===<br />
<br />
* [https://github.com/ruimarinho/bitcoin-core bitcoin-core] (npm: [https://www.npmjs.com/package/bitcoin-core bitcoin-core]) <br />
<br />
Example using bitcoin-core:<br />
<br />
<source lang="javascript"><br />
const Client = require('bitcoin-core');<br />
const client = new Client({ <br />
network: 'regtest', <br />
username: 'user', <br />
password: 'pass', <br />
port: 18443 <br />
});<br />
<br />
client.getBlockchainInfo().then((help) => console.log(help));<br />
</source><br />
<br />
=== Deno ===<br />
<br />
* Github: [https://github.com/timonson/gentle_rpc gentle_rpc] or deno.land: [https://deno.land/x/gentle_rpc deno.land] <br />
<br />
gentle_rpc is a typescript JSON-RPC library for Deno, it works perfectly with lowercase function names.<br />
<br />
Example using gentle_rpc:<br />
<br />
<source lang="typescript"><br />
import { createRemote } from "https://deno.land/x/gentle_rpc/rpcClient.ts";<br />
<br />
let Node = new URL("http://127.0.0.1");<br />
Node.port = "18332";<br />
Node.username = "BitcoinUser";<br />
Node.password = "BitcoinPassword";<br />
<br />
const remote = createRemote(Node);<br />
const info = await remote.getblockchaininfo();<br />
console.log(info);<br />
</source><br />
<br />
=== Command line (cURL) ===<br />
<br />
You can also send commands and see results using [http://curl.haxx.se/ cURL] or some other command-line HTTP-fetching utility; for example:<br />
<br />
<source lang="bash"><br />
curl --user user --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getblockchaininfo", "params": [] }' <br />
-H 'content-type: text/plain;' http://127.0.0.1:8332/<br />
</source><br />
<br />
You will be prompted for your rpcpassword, and then will see something like:<br />
<br />
<source lang="javascript"><br />
{"result":{"balance":0.000000000000000,"blocks":59952,"connections":48,"proxy":"","generate":false,<br />
"genproclimit":-1,"difficulty":16.61907875185736},"error":null,"id":"curltest"}<br />
</source><br />
<br />
=== Command line (jsonrpc-cli) ===<br />
<br />
[https://github.com/dan-da/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.<br />
<br />
<source lang="bash"><br />
jsonrpc-cli --user=rpcuser --pass=rpcpassword http://localhost:8332/ getblockchaininfo<br />
</source><br />
<br />
<source lang="javascript"><br />
{<br />
"version": 109900,<br />
"protocolversion": 70002,<br />
"walletversion": 60000,<br />
"balance": 0,<br />
"blocks": 588597,<br />
"timeoffset": -1,<br />
"connections": 9,<br />
"proxy": "127.0.0.1:9050",<br />
"difficulty": 9013786945891.682,<br />
"testnet": false,<br />
"keypoololdest": 1463279619,<br />
"keypoolsize": 101,<br />
"paytxfee": 0,<br />
"relayfee": 1.0e-5,<br />
"errors": null<br />
}<br />
</source><br />
<br />
=== Clojure ===<br />
<br />
[https://github.com/aviad/clj-btc clj-btc] is a Clojure wrapper for the bitcoin API.<br />
<br />
<source lang="clojure"><br />
user=> (require '[clj-btc.core :as btc])<br />
nil<br />
user=> (btc/getblockchaininfo)<br />
{"timeoffset" 0, "protocolversion" 70001, "blocks" 111908, "errors" "",<br />
"testnet" true, "proxy" "", "connections" 4, "version" 80500,<br />
"keypoololdest" 1380388750, "paytxfee" 0E-8M,<br />
"difficulty" 4642.44443532M, "keypoolsize" 101, "balance" 0E-8M,<br />
"walletversion" 60000}<br />
</source><br />
<br />
=== C ===<br />
The C API for processing JSON is [https://jansson.readthedocs.org/en/latest/ Jansson]. C applications like [https://github.com/bitcoin/libblkmaker libblkmaker] use [[API_reference_(JSON-RPC)#Command_line_.28cURL.29|cURL]] for making the calls and Jansson for interpreting the JSON that cURL fetches.<br />
<br />
For example basic usage (which can be easily modified for Bitcoin RPC), see the Jansson example [https://jansson.readthedocs.org/en/latest/_downloads/github_commits.c github_commits.c] and [https://jansson.readthedocs.org/en/latest/tutorial.html#the-github-repo-commits-api the associated tutorial].<br />
<br />
The following does with libcurl what the [[API_reference_(JSON-RPC)#Command_line_.28cURL.29|cURL example above]] does:<source lang="c">#include <stdlib.h><br />
<br />
#include <curl/curl.h><br />
<br />
int main()<br />
{<br />
CURL *curl = curl_easy_init();<br />
struct curl_slist *headers = NULL;<br />
<br />
if (curl) {<br />
const char *data =<br />
"{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", \"method\": \"getblockchaininfo\", \"params\": [] }";<br />
<br />
headers = curl_slist_append(headers, "content-type: text/plain;");<br />
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);<br />
<br />
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8332/");<br />
<br />
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(data));<br />
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);<br />
<br />
curl_easy_setopt(curl, CURLOPT_USERPWD,<br />
"bitcoinrpcUSERNAME:bitcoinrpcPASSWORD");<br />
<br />
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);<br />
<br />
curl_easy_perform(curl);<br />
}<br />
return 0;<br />
}<br />
</source>This output can be parsed with Jansson, ''à la'' the Jansson tutorial linked to above.<br />
<br />
(source: [https://bitcoin.stackexchange.com/a/41158/4334 Bitcoin StackExchange])<br />
<br />
=== Qt/C++ ===<br />
<br />
[https://bitbucket.org/devonit/qjsonrpc/overview 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.<br />
<br />
<source lang="cpp"><br />
/*<br />
* Copyright (C) 2012-2013 Matt Broadstone<br />
* Contact: http://bitbucket.org/devonit/qjsonrpc<br />
*<br />
* This file is part of the QJsonRpc Library.<br />
*<br />
* This library is free software; you can redistribute it and/or<br />
* modify it under the terms of the GNU Lesser General Public<br />
* License as published by the Free Software Foundation; either<br />
* version 2.1 of the License, or (at your option) any later version.<br />
*<br />
* This library is distributed in the hope that it will be useful,<br />
* but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU<br />
* Lesser General Public License for more details.<br />
*/<br />
#include <QCoreApplication><br />
#include <QAuthenticator><br />
#include <QStringList><br />
#include <QDebug><br />
<br />
#include "qjsonrpchttpclient.h"<br />
<br />
class HttpClient : public QJsonRpcHttpClient<br />
{<br />
Q_OBJECT<br />
public:<br />
HttpClient(const QString &endpoint, QObject *parent = 0)<br />
: QJsonRpcHttpClient(endpoint, parent)<br />
{<br />
// defaults added for my local test server<br />
m_username = "bitcoinrpc";<br />
m_password = "232fb3276bbb7437d265298ea48bdc46";<br />
}<br />
<br />
void setUsername(const QString &username) {<br />
m_username = username;<br />
}<br />
<br />
void setPassword(const QString &password) {<br />
m_password = password;<br />
}<br />
<br />
private Q_SLOTS:<br />
virtual void handleAuthenticationRequired(QNetworkReply *reply, QAuthenticator * authenticator)<br />
{<br />
Q_UNUSED(reply)<br />
authenticator->setUser(m_username);<br />
authenticator->setPassword(m_password);<br />
}<br />
<br />
private:<br />
QString m_username;<br />
QString m_password;<br />
<br />
};<br />
<br />
int main(int argc, char **argv)<br />
{<br />
QCoreApplication app(argc, argv);<br />
if (app.arguments().size() < 2) {<br />
qDebug() << "usage: " << argv[0] << "[-u username] [-p password] <command> <arguments>";<br />
return -1;<br />
}<br />
<br />
HttpClient client("http://127.0.0.1:8332");<br />
if (app.arguments().contains("-u")) {<br />
int idx = app.arguments().indexOf("-u");<br />
app.arguments().removeAt(idx);<br />
if(idx<app.arguments().count())<br />
client.setUsername(app.arguments().takeAt(idx));<br />
else qDebug()<<"-u value not defined";<br />
}<br />
<br />
if (app.arguments().contains("-p")) {<br />
int idx = app.arguments().indexOf("-p");<br />
app.arguments().removeAt(idx);<br />
if(idx<app.arguments().count())<br />
client.setPassword(app.arguments().takeAt(idx));<br />
else qDebug()<<"-p value not defined";<br />
}<br />
<br />
QJsonRpcMessage message = QJsonRpcMessage::createRequest(app.arguments().at(1));<br />
QJsonRpcMessage response = client.sendMessageBlocking(message);<br />
if (response.type() == QJsonRpcMessage::Error) {<br />
qDebug() << response.errorData();<br />
return -1;<br />
}<br />
<br />
qDebug() << response.toJson();<br />
}<br />
</source><br />
<br />
== Multi-wallet RPC calls ==<br />
<br />
[[Bitcoin Knots]] 0.13.1 added support for loading multiple, separate wallets.<br />
Multi-wallet can be enabled by using more than one <code>-wallet</code> argument when starting Bitcoin, either on the command line or in the Bitcoin config file.<br />
This was also included in [[Bitcoin Core]] 0.15.<br />
<br />
Wallet-level RPC calls (like <code>importaddress</code> or <code>listtransactions</code>) can specify which wallet file will be accessed. This is done by setting the HTTP endpoint in the JSON-RPC request in the format <code><RPC IP address>:<RPC port>/wallet/<wallet name></code>, for example <code>https://127.0.0.1:8332/wallet/wallet1.dat</code>.<br />
<br />
The command line utility bitcoin-cli can specify the wallet file using the <code>-rpcwallet</code> flag, for example <code>bitcoin-cli -rpcwallet=wallet1.dat getbalance</code><br />
<br />
For more details see the [https://github.com/bitcoin/bitcoin/blob/master/doc/release-notes/release-notes-0.15.0.md#multi-wallet-support Bitcoin Core 0.15 release notes]<br />
<br />
Alternatively (but not available in Bitcoin Core at this time), an additional parameter can be specified to <code>-rpcauth</code> naming a default wallet for JSON-RPC accesses to the normal endpoint.<br />
<br />
== See Also==<br />
<br />
* The Bitcoin Core documentation: https://github.com/bitcoin/bitcoin/blob/master/doc/JSON-RPC-interface.md#json-rpc-interface<br />
* The Bitcoin Core RPC help for each call: https://bitcoincore.org/en/doc/<br />
* The Bitcoin Core RPC error codes: https://github.com/bitcoin/bitcoin/blob/master/src/rpc/protocol.h<br />
* Bitcoin Core RPC API version changes https://masonicboom.github.io/btcrpcapi/<br />
<br />
* [[Original_Bitcoin_client/API_Calls_list|API calls list]]<br />
* [[Running Bitcoin]]<br />
* [[Lazy API]]<br />
* [[PHP developer intro]]<br />
* [[Raw_Transactions|Raw Transactions API]]<br />
* [https://gourl.io/bitcoin-payment-gateway-api.html GoUrl Bitcoin PHP Payment API]<br />
* [http://blockchain.info/api/json_rpc_api Web Based JSON RPC interface.]<br />
<br />
[[Category:Technical]]<br />
[[Category:Developer]]<br />
[[zh-cn:API_reference_(JSON-RPC)]]<br />
<br />
{{Bitcoin Core documentation}}</div>Ethicnologyhttps://tests.bitcoin.it/w/index.php?title=API_reference_(JSON-RPC)&diff=68067API reference (JSON-RPC)2020-07-25T22:43:25Z<p>Ethicnology: Add gentleRpc typescript library for Deno developers</p>
<hr />
<div>== Controlling Bitcoin Core ==<br />
<br />
Run ''bitcoind'' or ''bitcoin-qt -server''. You can control it via the command-line bitcoin-cli utility or by [http://json-rpc.org/wiki/specification HTTP JSON-RPC] commands.<br />
<br />
You must create a bitcoin.conf configuration file setting an rpcuser and rpcpassword; see [[Running Bitcoin]] for details.<br />
<br />
Now run:<br />
$ ./bitcoind -daemon<br />
bitcoin server starting<br />
$ ./bitcoin-cli -rpcwait help<br />
# shows the help text<br />
<br />
A [[Original Bitcoin client/API Calls list|list of RPC calls]] will be shown.<br />
<br />
$ ./bitcoin-cli getbalance<br />
2000.00000<br />
<br />
If you are learning the API, it is a very good idea to use the test network (run bitcoind -testnet and bitcoin-cli -testnet).<br />
<br />
== JSON-RPC ==<br />
<br />
Running Bitcoin with the -server argument (or running bitcoind) tells it to function as a [http://json-rpc.org/wiki/specification HTTP JSON-RPC] server, but <br />
[http://en.wikipedia.org/wiki/Basic_access_authentication 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'.<br />
<br />
Bitcoin supports SSL (https) JSON-RPC connections beginning with version 0.3.14. See the [[Enabling SSL on original client daemon|rpcssl wiki page]] for setup instructions and a list of all bitcoin.conf configuration options.<br />
<br />
Allowing arbitrary machines to access the JSON-RPC port (using the rpcallowip [[Running_Bitcoin|configuration option]]) is dangerous and '''strongly discouraged'''-- access should be strictly limited to trusted machines.<br />
<br />
To access the server you should find a [http://json-rpc.org/wiki/implementations suitable library] for your language.<br />
<br />
== Proper money handling ==<br />
<br />
See the [[Proper Money Handling (JSON-RPC)|proper money handling page]] for notes on avoiding rounding errors when handling bitcoin values.<br />
<br />
== Languages ==<br />
<br />
=== Python ===<br />
<br />
[http://json-rpc.org/wiki/python-json-rpc python-jsonrpc] is the official JSON-RPC implementation for Python.<br />
It automatically generates Python methods for RPC calls.<br />
However, due to its design for supporting old versions of Python, it is also rather inefficient.<br />
[[User:jgarzik|jgarzik]] has forked it as [https://github.com/jgarzik/python-bitcoinrpc Python-BitcoinRPC] and optimized it for current versions.<br />
Generally, this version is recommended.<br />
<br />
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:<br />
<br />
<source lang="python"><br />
from jsonrpc import ServiceProxy<br />
<br />
access = ServiceProxy("http://user:password@127.0.0.1:8332")<br />
access.getblockchaininfo()<br />
access.listreceivedbyaddress(6)<br />
#access.sendtoaddress("11yEmxiMso2RsFVfBcCa616npBvGgxiBX", 10)<br />
</source><br />
<br />
The latest version of python-bitcoinrpc has a new syntax.<br />
<source lang="python"><br />
from bitcoinrpc.authproxy import AuthServiceProxy<br />
</source><br />
<br />
=== Ruby ===<br />
<br />
<source lang="ruby"><br />
require 'net/http'<br />
require 'uri'<br />
require 'json'<br />
<br />
class BitcoinRPC<br />
def initialize(service_url)<br />
@uri = URI.parse(service_url)<br />
end<br />
<br />
def method_missing(name, *args)<br />
post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json<br />
resp = JSON.parse( http_post_request(post_body) )<br />
raise JSONRPCError, resp['error'] if resp['error']<br />
resp['result']<br />
end<br />
<br />
def http_post_request(post_body)<br />
http = Net::HTTP.new(@uri.host, @uri.port)<br />
request = Net::HTTP::Post.new(@uri.request_uri)<br />
request.basic_auth @uri.user, @uri.password<br />
request.content_type = 'application/json'<br />
request.body = post_body<br />
http.request(request).body<br />
end<br />
<br />
class JSONRPCError < RuntimeError; end<br />
end<br />
<br />
if $0 == __FILE__<br />
h = BitcoinRPC.new('http://user:password@127.0.0.1:8332')<br />
p h.getbalance<br />
p h.getblockchaininfo<br />
p h.getnewaddress<br />
p h.dumpprivkey( h.getnewaddress )<br />
# also see: https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list<br />
end<br />
</source><br />
<br />
=== Erlang ===<br />
Get the rebar dependency from https://github.com/edescourtis/ebitcoind . By default the client will use the configuration in <code>$HOME/.bitcoin/bitcoin.conf</code> or you can instead specify a URI like this:<br />
<source lang="erlang">ebitcoind:start_link(<<"http://user:password@localhost:8332/">>).</source><br />
<br />
Here is a usage example:<br />
<source lang="erlang"><br />
1> {ok,Pid} = ebitcoind:start_link().<br />
{ok,<0.177.0>}<br />
2> ebitcoind:getbalance(Pid).<br />
8437.02478294<br />
3> ebitcoind:getblockchaininfo(Pid).<br />
{ok, #{<<"balance">> => 8437.02478294,<br />
<<"blocks">> => 260404,<br />
<<"connections">> => 8,<br />
<<"difficulty">> => 148819199.80509263,<br />
<<"errors">> => <<>>,<br />
<<"keypoololdest">> => 1420307921,<br />
<<"keypoolsize">> => 102,<br />
<<"paytxfee">> => 0.0,<br />
<<"protocolversion">> => 70002,<br />
<<"proxy">> => <<>>,<br />
<<"relayfee">> => 1.0e-5,<br />
<<"testnet">> => false,<br />
<<"timeoffset">> => -3,<br />
<<"version">> => 90300,<br />
<<"walletversion">> => 60000}}<br />
4> ebitcoind:setgenerate(Pid,true).<br />
{ok, null}<br />
5> ebitcoind:getblocktemplate(Pid, #{}). <br />
{ok,#{<<"bits">> => <<"181b0dca">>,<br />
<<"coinbaseaux">> => #{<<"flags">> => <<"062f503253482f">>},<br />
<<"coinbasevalue">> => 2518690558,<br />
<<"curtime">> => 1420421249,<br />
<<"height">> => 337533,<br />
<<"mintime">> => 1420416332,<br />
<<"mutable">> => [<<"time">>,<<"transactions">>,<<"prevblock">>],<br />
<<"noncerange">> => <<"00000000ffffffff">>,<br />
<<"previousblockhash">> => <<"000000000000000017ce0a0d328bf84cc597785844393e899e9a971a81679a5f">>,<br />
<<"sigoplimit">> => 20000,<br />
<<"sizelimit">> => 1000000,<br />
<<"target">> => <<"00000000000000001b0dca00000000000000000000000000000000000000"...>>,<br />
<<"transactions">> => [#{<<"data">> => <<"01000000049b47ce225d29bff7c18b7df7d7df4693523a52"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 0,<br />
<<"hash">> => <<"6d0d76e1f27b3a6f7325923710dcdb4107c9"...>>,<br />
<<"sigops">> => 1},<br />
...<br />
</source><br />
<br />
=== PHP ===<br />
<br />
The [http://jsonrpcphp.org/ JSON-RPC PHP] library also makes it very easy to connect to Bitcoin. For example:<br />
<br />
<source lang="php"><br />
require_once 'jsonRPCClient.php';<br />
<br />
$bitcoin = new jsonRPCClient('http://user:password@127.0.0.1:8332/');<br />
<br />
echo "<pre>\n";<br />
print_r($bitcoin->getblockchaininfo()); echo "\n";<br />
echo "Received: ".$bitcoin->getreceivedbylabel("Your Address")."\n";<br />
echo "</pre>";<br />
</source><br />
<br />
'''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 [https://github.com/aceat64/EasyBitcoin-PHP EasyBitcoin-PHP library] is similar in function to JSON-RPC PHP but does not have this issue.<br />
<br />
=== Java ===<br />
<br />
The easiest way to tell Java to use HTTP Basic authentication is to set a default Authenticator:<br />
<br />
<source lang="java"><br />
final String rpcuser ="...";<br />
final String rpcpassword ="...";<br />
<br />
Authenticator.setDefault(new Authenticator() {<br />
protected PasswordAuthentication getPasswordAuthentication() {<br />
return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray());<br />
}<br />
});<br />
</source><br />
<br />
Once that is done, [http://json-rpc.org/wiki/implementations any JSON-RPC library for Java] (or ordinary URL POSTs) may be used to communicate with the Bitcoin server.<br />
<br />
Instead of writing your own implementation, consider using one of the existing wrappers like [https://github.com/johannbarbie/BitcoindClient4J BitcoindClient4J], [https://github.com/priiduneemre/btcd-cli4j btcd-cli4j] or [[Bitcoin-JSON-RPC-Client|Bitcoin-JSON-RPC-Client]] instead.<br />
<br />
=== Perl ===<br />
<br />
The JSON::RPC package from CPAN can be used to communicate with Bitcoin. You must set the client's credentials; for example:<br />
<br />
<source lang="perl"><br />
use JSON::RPC::Client;<br />
use Data::Dumper;<br />
<br />
my $client = new JSON::RPC::Client;<br />
<br />
$client->ua->credentials(<br />
'localhost:8332', 'jsonrpc', 'user' => 'password' # REPLACE WITH YOUR bitcoin.conf rpcuser/rpcpassword<br />
);<br />
<br />
my $uri = 'http://localhost:8332/';<br />
my $obj = {<br />
method => 'getblockchaininfo',<br />
params => [],<br />
};<br />
<br />
my $res = $client->call( $uri, $obj );<br />
<br />
if ($res){<br />
if ($res->is_error) { print "Error : ", $res->error_message; }<br />
else { print Dumper($res->result); }<br />
} else {<br />
print $client->status_line;<br />
}<br />
</source><br />
<br />
=== Go ===<br />
<br />
The [https://github.com/btcsuite/btcrpcclient btcrpcclient package] can be used to communicate with Bitcoin. You must provide credentials to match the client you are communicating with.<br />
<br />
<source lang="go"><br />
package main<br />
<br />
import (<br />
"github.com/btcsuite/btcd/chaincfg"<br />
"github.com/btcsuite/btcrpcclient"<br />
"github.com/btcsuite/btcutil"<br />
"log"<br />
)<br />
<br />
func main() {<br />
// create new client instance<br />
client, err := btcrpcclient.New(&btcrpcclient.ConnConfig{<br />
HTTPPostMode: true,<br />
DisableTLS: true,<br />
Host: "127.0.0.1:8332",<br />
User: "rpcUsername",<br />
Pass: "rpcPassword",<br />
}, nil)<br />
if err != nil {<br />
log.Fatalf("error creating new btc client: %v", err)<br />
}<br />
<br />
// list accounts<br />
accounts, err := client.ListAccounts()<br />
if err != nil {<br />
log.Fatalf("error listing accounts: %v", err)<br />
}<br />
// iterate over accounts (map[string]btcutil.Amount) and write to stdout<br />
for label, amount := range accounts {<br />
log.Printf("%s: %s", label, amount)<br />
}<br />
<br />
// prepare a sendMany transaction<br />
receiver1, err := btcutil.DecodeAddress("1someAddressThatIsActuallyReal", &chaincfg.MainNetParams)<br />
if err != nil {<br />
log.Fatalf("address receiver1 seems to be invalid: %v", err)<br />
}<br />
receiver2, err := btcutil.DecodeAddress("1anotherAddressThatsPrettyReal", &chaincfg.MainNetParams)<br />
if err != nil {<br />
log.Fatalf("address receiver2 seems to be invalid: %v", err)<br />
}<br />
receivers := map[btcutil.Address]btcutil.Amount{<br />
receiver1: 42, // 42 satoshi<br />
receiver2: 100, // 100 satoshi<br />
}<br />
<br />
// create and send the sendMany tx<br />
txSha, err := client.SendMany("some-account-label-from-which-to-send", receivers)<br />
if err != nil {<br />
log.Fatalf("error sendMany: %v", err)<br />
}<br />
log.Printf("sendMany completed! tx sha is: %s", txSha.String())<br />
}<br />
</source><br />
<br />
=== .NET (C#) ===<br />
The communication with the RPC service can be achieved using the standard http request/response objects.<br />
A library for serializing and deserializing Json will make your life a lot easier:<br />
<br />
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 ).<br />
<br />
The following example uses Json.NET:<br />
<br />
<source lang="csharp"><br />
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost.:8332");<br />
webRequest.Credentials = new NetworkCredential("user", "pwd");<br />
/// important, otherwise the service can't desirialse your request properly<br />
webRequest.ContentType = "application/json-rpc";<br />
webRequest.Method = "POST";<br />
<br />
JObject joe = new JObject();<br />
joe.Add(new JProperty("jsonrpc", "1.0"));<br />
joe.Add(new JProperty("id", "1"));<br />
joe.Add(new JProperty("method", Method));<br />
// params is a collection values which the method requires..<br />
if (Params.Keys.Count == 0)<br />
{<br />
joe.Add(new JProperty("params", new JArray()));<br />
}<br />
else<br />
{<br />
JArray props = new JArray();<br />
// add the props in the reverse order!<br />
for (int i = Params.Keys.Count - 1; i >= 0; i--)<br />
{<br />
.... // add the params<br />
}<br />
joe.Add(new JProperty("params", props));<br />
}<br />
<br />
// serialize json for the request<br />
string s = JsonConvert.SerializeObject(joe);<br />
byte[] byteArray = Encoding.UTF8.GetBytes(s);<br />
webRequest.ContentLength = byteArray.Length;<br />
Stream dataStream = webRequest.GetRequestStream();<br />
dataStream.Write(byteArray, 0, byteArray.Length);<br />
dataStream.Close();<br />
<br />
<br />
WebResponse webResponse = webRequest.GetResponse();<br />
<br />
... // deserialze the response<br />
</source><br />
<br />
There is also a wrapper for Json.NET called Bitnet (https://sourceforge.net/projects/bitnet)<br />
implementing Bitcoin API in more convenient way:<br />
<br />
<source lang="csharp"><br />
BitnetClient bc = new BitnetClient("http://127.0.0.1:8332");<br />
bc.Credentials = new NetworkCredential("user", "pass");<br />
<br />
var p = bc.GetDifficulty();<br />
Console.WriteLine("Difficulty:" + p.ToString());<br />
<br />
var inf = bc.GetBlockchainInfo();<br />
Console.WriteLine("Balance:" + inf["balance"]);<br />
</source><br />
<br />
A more complete library and wrapper for Bitcoin is [https://github.com/GeorgeKimionis/BitcoinLib BitcoinLib] (https://github.com/GeorgeKimionis/BitcoinLib) which is also available via [https://www.nuget.org/packages/BitcoinLib/ NuGet] from the package manager console (Install-Package BitcoinLib). <br />
<br />
Querying the daemon with [https://github.com/GeorgeKimionis/BitcoinLib BitcoinLib] is as simple as:<br />
<br />
<source lang="csharp"><br />
IBitcoinService bitcoinService = new BitcoinService();<br />
<br />
var networkDifficulty = bitcoinService.GetDifficulty();<br />
var myBalance = bitcoinService.GetBalance();<br />
</source><br />
<br />
=== Node.js ===<br />
<br />
* [https://github.com/ruimarinho/bitcoin-core bitcoin-core] (npm: [https://www.npmjs.com/package/bitcoin-core bitcoin-core]) <br />
<br />
Example using bitcoin-core:<br />
<br />
<source lang="javascript"><br />
const Client = require('bitcoin-core');<br />
const client = new Client({ <br />
network: 'regtest', <br />
username: 'user', <br />
password: 'pass', <br />
port: 18443 <br />
});<br />
<br />
client.getBlockchainInfo().then((help) => console.log(help));<br />
</source><br />
<br />
=== Deno ===<br />
<br />
* Github: [https://github.com/timonson/gentleRpc gentleRpc] or deno.land: [https://deno.land/x/gentleRpc gentleRpc] <br />
<br />
gentleRpc is a typescript JSON-RPC library for Deno, it works perfectly with lowercase function names.<br />
<br />
Example using gentleRpc:<br />
<br />
<source lang="typescript"><br />
import { createRemote } from "https://deno.land/x/gentleRpc/rpcClient.ts";<br />
<br />
let Node = new URL("http://127.0.0.1");<br />
Node.port = "18332";<br />
Node.username = "BitcoinUser";<br />
Node.password = "BitcoinPassword";<br />
<br />
const remote = createRemote(Node);<br />
const info = await remote.getblockchaininfo();<br />
console.log(info);<br />
</source><br />
<br />
=== Command line (cURL) ===<br />
<br />
You can also send commands and see results using [http://curl.haxx.se/ cURL] or some other command-line HTTP-fetching utility; for example:<br />
<br />
<source lang="bash"><br />
curl --user user --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getblockchaininfo", "params": [] }' <br />
-H 'content-type: text/plain;' http://127.0.0.1:8332/<br />
</source><br />
<br />
You will be prompted for your rpcpassword, and then will see something like:<br />
<br />
<source lang="javascript"><br />
{"result":{"balance":0.000000000000000,"blocks":59952,"connections":48,"proxy":"","generate":false,<br />
"genproclimit":-1,"difficulty":16.61907875185736},"error":null,"id":"curltest"}<br />
</source><br />
<br />
=== Command line (jsonrpc-cli) ===<br />
<br />
[https://github.com/dan-da/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.<br />
<br />
<source lang="bash"><br />
jsonrpc-cli --user=rpcuser --pass=rpcpassword http://localhost:8332/ getblockchaininfo<br />
</source><br />
<br />
<source lang="javascript"><br />
{<br />
"version": 109900,<br />
"protocolversion": 70002,<br />
"walletversion": 60000,<br />
"balance": 0,<br />
"blocks": 588597,<br />
"timeoffset": -1,<br />
"connections": 9,<br />
"proxy": "127.0.0.1:9050",<br />
"difficulty": 9013786945891.682,<br />
"testnet": false,<br />
"keypoololdest": 1463279619,<br />
"keypoolsize": 101,<br />
"paytxfee": 0,<br />
"relayfee": 1.0e-5,<br />
"errors": null<br />
}<br />
</source><br />
<br />
=== Clojure ===<br />
<br />
[https://github.com/aviad/clj-btc clj-btc] is a Clojure wrapper for the bitcoin API.<br />
<br />
<source lang="clojure"><br />
user=> (require '[clj-btc.core :as btc])<br />
nil<br />
user=> (btc/getblockchaininfo)<br />
{"timeoffset" 0, "protocolversion" 70001, "blocks" 111908, "errors" "",<br />
"testnet" true, "proxy" "", "connections" 4, "version" 80500,<br />
"keypoololdest" 1380388750, "paytxfee" 0E-8M,<br />
"difficulty" 4642.44443532M, "keypoolsize" 101, "balance" 0E-8M,<br />
"walletversion" 60000}<br />
</source><br />
<br />
=== C ===<br />
The C API for processing JSON is [https://jansson.readthedocs.org/en/latest/ Jansson]. C applications like [https://github.com/bitcoin/libblkmaker libblkmaker] use [[API_reference_(JSON-RPC)#Command_line_.28cURL.29|cURL]] for making the calls and Jansson for interpreting the JSON that cURL fetches.<br />
<br />
For example basic usage (which can be easily modified for Bitcoin RPC), see the Jansson example [https://jansson.readthedocs.org/en/latest/_downloads/github_commits.c github_commits.c] and [https://jansson.readthedocs.org/en/latest/tutorial.html#the-github-repo-commits-api the associated tutorial].<br />
<br />
The following does with libcurl what the [[API_reference_(JSON-RPC)#Command_line_.28cURL.29|cURL example above]] does:<source lang="c">#include <stdlib.h><br />
<br />
#include <curl/curl.h><br />
<br />
int main()<br />
{<br />
CURL *curl = curl_easy_init();<br />
struct curl_slist *headers = NULL;<br />
<br />
if (curl) {<br />
const char *data =<br />
"{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", \"method\": \"getblockchaininfo\", \"params\": [] }";<br />
<br />
headers = curl_slist_append(headers, "content-type: text/plain;");<br />
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);<br />
<br />
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8332/");<br />
<br />
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(data));<br />
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);<br />
<br />
curl_easy_setopt(curl, CURLOPT_USERPWD,<br />
"bitcoinrpcUSERNAME:bitcoinrpcPASSWORD");<br />
<br />
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);<br />
<br />
curl_easy_perform(curl);<br />
}<br />
return 0;<br />
}<br />
</source>This output can be parsed with Jansson, ''à la'' the Jansson tutorial linked to above.<br />
<br />
(source: [https://bitcoin.stackexchange.com/a/41158/4334 Bitcoin StackExchange])<br />
<br />
=== Qt/C++ ===<br />
<br />
[https://bitbucket.org/devonit/qjsonrpc/overview 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.<br />
<br />
<source lang="cpp"><br />
/*<br />
* Copyright (C) 2012-2013 Matt Broadstone<br />
* Contact: http://bitbucket.org/devonit/qjsonrpc<br />
*<br />
* This file is part of the QJsonRpc Library.<br />
*<br />
* This library is free software; you can redistribute it and/or<br />
* modify it under the terms of the GNU Lesser General Public<br />
* License as published by the Free Software Foundation; either<br />
* version 2.1 of the License, or (at your option) any later version.<br />
*<br />
* This library is distributed in the hope that it will be useful,<br />
* but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU<br />
* Lesser General Public License for more details.<br />
*/<br />
#include <QCoreApplication><br />
#include <QAuthenticator><br />
#include <QStringList><br />
#include <QDebug><br />
<br />
#include "qjsonrpchttpclient.h"<br />
<br />
class HttpClient : public QJsonRpcHttpClient<br />
{<br />
Q_OBJECT<br />
public:<br />
HttpClient(const QString &endpoint, QObject *parent = 0)<br />
: QJsonRpcHttpClient(endpoint, parent)<br />
{<br />
// defaults added for my local test server<br />
m_username = "bitcoinrpc";<br />
m_password = "232fb3276bbb7437d265298ea48bdc46";<br />
}<br />
<br />
void setUsername(const QString &username) {<br />
m_username = username;<br />
}<br />
<br />
void setPassword(const QString &password) {<br />
m_password = password;<br />
}<br />
<br />
private Q_SLOTS:<br />
virtual void handleAuthenticationRequired(QNetworkReply *reply, QAuthenticator * authenticator)<br />
{<br />
Q_UNUSED(reply)<br />
authenticator->setUser(m_username);<br />
authenticator->setPassword(m_password);<br />
}<br />
<br />
private:<br />
QString m_username;<br />
QString m_password;<br />
<br />
};<br />
<br />
int main(int argc, char **argv)<br />
{<br />
QCoreApplication app(argc, argv);<br />
if (app.arguments().size() < 2) {<br />
qDebug() << "usage: " << argv[0] << "[-u username] [-p password] <command> <arguments>";<br />
return -1;<br />
}<br />
<br />
HttpClient client("http://127.0.0.1:8332");<br />
if (app.arguments().contains("-u")) {<br />
int idx = app.arguments().indexOf("-u");<br />
app.arguments().removeAt(idx);<br />
if(idx<app.arguments().count())<br />
client.setUsername(app.arguments().takeAt(idx));<br />
else qDebug()<<"-u value not defined";<br />
}<br />
<br />
if (app.arguments().contains("-p")) {<br />
int idx = app.arguments().indexOf("-p");<br />
app.arguments().removeAt(idx);<br />
if(idx<app.arguments().count())<br />
client.setPassword(app.arguments().takeAt(idx));<br />
else qDebug()<<"-p value not defined";<br />
}<br />
<br />
QJsonRpcMessage message = QJsonRpcMessage::createRequest(app.arguments().at(1));<br />
QJsonRpcMessage response = client.sendMessageBlocking(message);<br />
if (response.type() == QJsonRpcMessage::Error) {<br />
qDebug() << response.errorData();<br />
return -1;<br />
}<br />
<br />
qDebug() << response.toJson();<br />
}<br />
</source><br />
<br />
== Multi-wallet RPC calls ==<br />
<br />
[[Bitcoin Knots]] 0.13.1 added support for loading multiple, separate wallets.<br />
Multi-wallet can be enabled by using more than one <code>-wallet</code> argument when starting Bitcoin, either on the command line or in the Bitcoin config file.<br />
This was also included in [[Bitcoin Core]] 0.15.<br />
<br />
Wallet-level RPC calls (like <code>importaddress</code> or <code>listtransactions</code>) can specify which wallet file will be accessed. This is done by setting the HTTP endpoint in the JSON-RPC request in the format <code><RPC IP address>:<RPC port>/wallet/<wallet name></code>, for example <code>https://127.0.0.1:8332/wallet/wallet1.dat</code>.<br />
<br />
The command line utility bitcoin-cli can specify the wallet file using the <code>-rpcwallet</code> flag, for example <code>bitcoin-cli -rpcwallet=wallet1.dat getbalance</code><br />
<br />
For more details see the [https://github.com/bitcoin/bitcoin/blob/master/doc/release-notes/release-notes-0.15.0.md#multi-wallet-support Bitcoin Core 0.15 release notes]<br />
<br />
Alternatively (but not available in Bitcoin Core at this time), an additional parameter can be specified to <code>-rpcauth</code> naming a default wallet for JSON-RPC accesses to the normal endpoint.<br />
<br />
== See Also==<br />
<br />
* The Bitcoin Core documentation: https://github.com/bitcoin/bitcoin/blob/master/doc/JSON-RPC-interface.md#json-rpc-interface<br />
* The Bitcoin Core RPC help for each call: https://bitcoincore.org/en/doc/<br />
* The Bitcoin Core RPC error codes: https://github.com/bitcoin/bitcoin/blob/master/src/rpc/protocol.h<br />
* Bitcoin Core RPC API version changes https://masonicboom.github.io/btcrpcapi/<br />
<br />
* [[Original_Bitcoin_client/API_Calls_list|API calls list]]<br />
* [[Running Bitcoin]]<br />
* [[Lazy API]]<br />
* [[PHP developer intro]]<br />
* [[Raw_Transactions|Raw Transactions API]]<br />
* [https://gourl.io/bitcoin-payment-gateway-api.html GoUrl Bitcoin PHP Payment API]<br />
* [http://blockchain.info/api/json_rpc_api Web Based JSON RPC interface.]<br />
<br />
[[Category:Technical]]<br />
[[Category:Developer]]<br />
[[zh-cn:API_reference_(JSON-RPC)]]<br />
<br />
{{Bitcoin Core documentation}}</div>Ethicnology