API reference (JSON-RPC): Difference between revisions
Add an alternative bitcoin java json-rpc client library |
Edescourtis (talk | contribs) Erlang |
||
Line 96: | Line 96: | ||
# also see: https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list | # also see: https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list | ||
end | end | ||
</source> | |||
== Erlang == | |||
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>). Here is a usage example: | |||
<source lang="erlang"> | |||
1> {ok,Pid} = ebitcoind:start_link(). | |||
{ok,<0.177.0>} | |||
2> ebitcoind:getbalance(Pid). | |||
8437.02478294 | |||
3> ebitcoind:getinfo(Pid). | |||
{ok, #{<<"balance">> => 8437.02478294, | |||
<<"blocks">> => 260404, | |||
<<"connections">> => 8, | |||
<<"difficulty">> => 148819199.80509263, | |||
<<"errors">> => <<>>, | |||
<<"keypoololdest">> => 1420307921, | |||
<<"keypoolsize">> => 102, | |||
<<"paytxfee">> => 0.0, | |||
<<"protocolversion">> => 70002, | |||
<<"proxy">> => <<>>, | |||
<<"relayfee">> => 1.0e-5, | |||
<<"testnet">> => false, | |||
<<"timeoffset">> => -3, | |||
<<"version">> => 90300, | |||
<<"walletversion">> => 60000}} | |||
4> ebitcoind:setgenerate(Pid,true). | |||
{ok, null} | |||
5> ebitcoind:getblocktemplate(Pid, #{}). | |||
{ok,#{<<"bits">> => <<"181b0dca">>, | |||
<<"coinbaseaux">> => #{<<"flags">> => <<"062f503253482f">>}, | |||
<<"coinbasevalue">> => 2518690558, | |||
<<"curtime">> => 1420421249, | |||
<<"height">> => 337533, | |||
<<"mintime">> => 1420416332, | |||
<<"mutable">> => [<<"time">>,<<"transactions">>,<<"prevblock">>], | |||
<<"noncerange">> => <<"00000000ffffffff">>, | |||
<<"previousblockhash">> => <<"000000000000000017ce0a0d328bf84cc597785844393e899e9a971a81679a5f">>, | |||
<<"sigoplimit">> => 20000, | |||
<<"sizelimit">> => 1000000, | |||
<<"target">> => <<"00000000000000001b0dca00000000000000000000000000000000000000"...>>, | |||
<<"transactions">> => [#{<<"data">> => <<"01000000049b47ce225d29bff7c18b7df7d7df4693523a52"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 0, | |||
<<"hash">> => <<"6d0d76e1f27b3a6f7325923710dcdb4107c9"...>>, | |||
<<"sigops">> => 1}, | |||
#{<<"data">> => <<"01000000015072ea92bb330a3ef04bcf170c244bea7e"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 1000, | |||
<<"hash">> => <<"32528460a50ae4eb40c53b9f4cdd4e64"...>>, | |||
<<"sigops">> => 1}, | |||
#{<<"data">> => <<"010000000432c35cd9be53c27f39e96d5af23617"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 0, | |||
<<"hash">> => <<"6bd3f1d8e67ae101341c9f66074a"...>>, | |||
<<"sigops">> => 2}, | |||
#{<<"data">> => <<"01000000020e1d51c50de8e34844d733ad4c"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 20000, | |||
<<"hash">> => <<"23fcb2f2b52ed1f79c211b3b"...>>, | |||
<<"sigops">> => 1}, | |||
#{<<"data">> => <<"010000000584e494f0c0f22eeffd8b60"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 0, | |||
<<"hash">> => <<"4a3e8526daff8e04568f"...>>, | |||
<<"sigops">> => 1}, | |||
#{<<"data">> => <<"0100000002a8545d91579925ef12"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 20000, | |||
<<"hash">> => <<"f6dce7acf65f04ea"...>>, | |||
<<"sigops">> => 2}, | |||
#{<<"data">> => <<"01000000130439f489e8e9c2"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 30000, | |||
<<"hash">> => <<"9fc0ab68f4a6"...>>, | |||
<<"sigops">> => 2}, | |||
#{<<"data">> => <<"01000000013fdbac949b"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 20000, | |||
<<"hash">> => <<"b773a227"...>>, | |||
<<"sigo"...>> => 2}, | |||
#{<<"data">> => <<"0100000004ae4fbc"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 10000, | |||
<<"hash">> => <<"f9e3"...>>, | |||
<<...>> => 2}, | |||
#{<<"data">> => <<"010000000896"...>>, | |||
<<"depends">> => [], | |||
<<"fee">> => 20000, | |||
<<...>> => <<...>>,...}, | |||
#{<<"data">> => <<"01000000"...>>, | |||
<<"depe"...>> => [], | |||
<<...>> => 10000,...}, | |||
#{<<"data">> => <<"0100"...>>,<<...>> => [],...}, | |||
#{<<...>> => <<...>>,...}, | |||
#{...}|...], | |||
<<"version">> => 2}} | |||
</source> | </source> | ||
Revision as of 01:33, 5 January 2015
Controlling Bitcoin
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.
Now run:
$ ./bitcoind -daemon bitcoin server starting $ ./bitcoin-cli -rpcwait help # shows the help text
A list of RPC calls will be shown.
$ ./bitcoin-cli getbalance 2000.00000
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.
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:
from jsonrpc import ServiceProxy
access = ServiceProxy("http://user:password@127.0.0.1:8332")
access.getinfo()
access.listreceivedbyaddress(6)
#access.sendtoaddress("11yEmxiMso2RsFVfBcCa616npBvGgxiBX", 10)
The latest version of python-bitcoinrpc has a new syntax.
from bitcoinrpc.authproxy import AuthServiceProxy
Ruby
require 'net/http'
require 'uri'
require 'json'
class BitcoinRPC
def initialize(service_url)
@uri = URI.parse(service_url)
end
def method_missing(name, *args)
post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
resp = JSON.parse( http_post_request(post_body) )
raise JSONRPCError, resp['error'] if resp['error']
resp['result']
end
def http_post_request(post_body)
http = Net::HTTP.new(@uri.host, @uri.port)
request = Net::HTTP::Post.new(@uri.request_uri)
request.basic_auth @uri.user, @uri.password
request.content_type = 'application/json'
request.body = post_body
http.request(request).body
end
class JSONRPCError < RuntimeError; end
end
if $0 == __FILE__
h = BitcoinRPC.new('http://user:password@127.0.0.1:8332')
p h.getbalance
p h.getinfo
p h.getnewaddress
p h.dumpprivkey( h.getnewaddress )
# also see: https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list
end
Erlang
Get the rebar dependency from https://github.com/edescourtis/ebitcoind (By default the client will use the configuration in $HOME/.bitcoin/bitcoin.conf
). Here is a usage example:
1> {ok,Pid} = ebitcoind:start_link().
{ok,<0.177.0>}
2> ebitcoind:getbalance(Pid).
8437.02478294
3> ebitcoind:getinfo(Pid).
{ok, #{<<"balance">> => 8437.02478294,
<<"blocks">> => 260404,
<<"connections">> => 8,
<<"difficulty">> => 148819199.80509263,
<<"errors">> => <<>>,
<<"keypoololdest">> => 1420307921,
<<"keypoolsize">> => 102,
<<"paytxfee">> => 0.0,
<<"protocolversion">> => 70002,
<<"proxy">> => <<>>,
<<"relayfee">> => 1.0e-5,
<<"testnet">> => false,
<<"timeoffset">> => -3,
<<"version">> => 90300,
<<"walletversion">> => 60000}}
4> ebitcoind:setgenerate(Pid,true).
{ok, null}
5> ebitcoind:getblocktemplate(Pid, #{}).
{ok,#{<<"bits">> => <<"181b0dca">>,
<<"coinbaseaux">> => #{<<"flags">> => <<"062f503253482f">>},
<<"coinbasevalue">> => 2518690558,
<<"curtime">> => 1420421249,
<<"height">> => 337533,
<<"mintime">> => 1420416332,
<<"mutable">> => [<<"time">>,<<"transactions">>,<<"prevblock">>],
<<"noncerange">> => <<"00000000ffffffff">>,
<<"previousblockhash">> => <<"000000000000000017ce0a0d328bf84cc597785844393e899e9a971a81679a5f">>,
<<"sigoplimit">> => 20000,
<<"sizelimit">> => 1000000,
<<"target">> => <<"00000000000000001b0dca00000000000000000000000000000000000000"...>>,
<<"transactions">> => [#{<<"data">> => <<"01000000049b47ce225d29bff7c18b7df7d7df4693523a52"...>>,
<<"depends">> => [],
<<"fee">> => 0,
<<"hash">> => <<"6d0d76e1f27b3a6f7325923710dcdb4107c9"...>>,
<<"sigops">> => 1},
#{<<"data">> => <<"01000000015072ea92bb330a3ef04bcf170c244bea7e"...>>,
<<"depends">> => [],
<<"fee">> => 1000,
<<"hash">> => <<"32528460a50ae4eb40c53b9f4cdd4e64"...>>,
<<"sigops">> => 1},
#{<<"data">> => <<"010000000432c35cd9be53c27f39e96d5af23617"...>>,
<<"depends">> => [],
<<"fee">> => 0,
<<"hash">> => <<"6bd3f1d8e67ae101341c9f66074a"...>>,
<<"sigops">> => 2},
#{<<"data">> => <<"01000000020e1d51c50de8e34844d733ad4c"...>>,
<<"depends">> => [],
<<"fee">> => 20000,
<<"hash">> => <<"23fcb2f2b52ed1f79c211b3b"...>>,
<<"sigops">> => 1},
#{<<"data">> => <<"010000000584e494f0c0f22eeffd8b60"...>>,
<<"depends">> => [],
<<"fee">> => 0,
<<"hash">> => <<"4a3e8526daff8e04568f"...>>,
<<"sigops">> => 1},
#{<<"data">> => <<"0100000002a8545d91579925ef12"...>>,
<<"depends">> => [],
<<"fee">> => 20000,
<<"hash">> => <<"f6dce7acf65f04ea"...>>,
<<"sigops">> => 2},
#{<<"data">> => <<"01000000130439f489e8e9c2"...>>,
<<"depends">> => [],
<<"fee">> => 30000,
<<"hash">> => <<"9fc0ab68f4a6"...>>,
<<"sigops">> => 2},
#{<<"data">> => <<"01000000013fdbac949b"...>>,
<<"depends">> => [],
<<"fee">> => 20000,
<<"hash">> => <<"b773a227"...>>,
<<"sigo"...>> => 2},
#{<<"data">> => <<"0100000004ae4fbc"...>>,
<<"depends">> => [],
<<"fee">> => 10000,
<<"hash">> => <<"f9e3"...>>,
<<...>> => 2},
#{<<"data">> => <<"010000000896"...>>,
<<"depends">> => [],
<<"fee">> => 20000,
<<...>> => <<...>>,...},
#{<<"data">> => <<"01000000"...>>,
<<"depe"...>> => [],
<<...>> => 10000,...},
#{<<"data">> => <<"0100"...>>,<<...>> => [],...},
#{<<...>> => <<...>>,...},
#{...}|...],
<<"version">> => 2}}
PHP
The JSON-RPC PHP library also makes it very easy to connect to Bitcoin. For example:
require_once 'jsonRPCClient.php';
$bitcoin = new jsonRPCClient('http://user:password@127.0.0.1:8332/');
echo "<pre>\n";
print_r($bitcoin->getinfo()); echo "\n";
echo "Received: ".$bitcoin->getreceivedbylabel("Your Address")."\n";
echo "</pre>";
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.
Java
The easiest way to tell Java to use HTTP Basic authentication is to set a default Authenticator:
final String rpcuser ="...";
final String rpcpassword ="...";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray());
}
});
Once that is done, any JSON-RPC library for Java (or ordinary URL POSTs) may be used to communicate with the Bitcoin server.
Instead to write your wrapper you can use this implementation or this one .
Perl
The JSON::RPC package from CPAN can be used to communicate with Bitcoin. You must set the client's credentials; for example:
use JSON::RPC::Client;
use Data::Dumper;
my $client = new JSON::RPC::Client;
$client->ua->credentials(
'localhost:8332', 'jsonrpc', 'user' => 'password' # REPLACE WITH YOUR bitcoin.conf rpcuser/rpcpassword
);
my $uri = 'http://localhost:8332/';
my $obj = {
method => 'getinfo',
params => [],
};
my $res = $client->call( $uri, $obj );
if ($res){
if ($res->is_error) { print "Error : ", $res->error_message; }
else { print Dumper($res->result); }
} else {
print $client->status_line;
}
Go
The btcrpcclient package can be used to communicate with Bitcoin. You must provide credentials to match the client you are communicating with.
package main
import (
"github.com/conformal/btcnet"
"github.com/conformal/btcrpcclient"
"github.com/conformal/btcutil"
"log"
)
func main() {
// create new client instance
client, err := btcrpcclient.New(&btcrpcclient.ConnConfig{
HttpPostMode: true,
DisableTLS: true,
Host: "127.0.0.1:8332",
User: "rpcUsername",
Pass: "rpcPassword",
}, nil)
if err != nil {
log.Fatalf("error creating new btc client: %v", err)
}
// list accounts
accounts, err := client.ListAccounts()
if err != nil {
log.Fatalf("error listing accounts: %v", err)
}
// iterate over accounts (map[string]btcutil.Amount) and write to stdout
for label, amount := range accounts {
log.Printf("%s: %s", label, amount)
}
// prepare a sendMany transaction
receiver1, err := btcutil.DecodeAddress("1someAddressThatIsActuallyReal", &btcnet.MainNetParams)
if err != nil {
log.Fatalf("address receiver1 seems to be invalid: %v", err)
}
receiver2, err := btcutil.DecodeAddress("1anotherAddressThatsPrettyReal", &btcnet.MainNetParams)
if err != nil {
log.Fatalf("address receiver2 seems to be invalid: %v", err)
}
receivers := map[btcutil.Address]btcutil.Amount{
receiver1: 42, // 42 satoshi
receiver2: 100, // 100 satoshi
}
// create and send the sendMany tx
txSha, err := client.SendMany("some-account-label-from-which-to-send", receivers)
if err != nil {
log.Fatalf("error sendMany: %v", err)
}
log.Printf("sendMany completed! tx sha is: %s", txSha.String())
}
.NET (C#)
The communication with the RPC service can be achieved using the standard http request/response objects. A library for serialising 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:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost.:8332");
webRequest.Credentials = new NetworkCredential("user", "pwd");
/// important, otherwise the service can't desirialse your request properly
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
JObject joe = new JObject();
joe.Add(new JProperty("jsonrpc", "1.0"));
joe.Add(new JProperty("id", "1"));
joe.Add(new JProperty("method", Method));
// params is a collection values which the method requires..
if (Params.Keys.Count == 0)
{
joe.Add(new JProperty("params", new JArray()));
}
else
{
JArray props = new JArray();
// add the props in the reverse order!
for (int i = Params.Keys.Count - 1; i >= 0; i--)
{
.... // add the params
}
joe.Add(new JProperty("params", props));
}
// serialize json for the request
string s = JsonConvert.SerializeObject(joe);
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse webResponse = webRequest.GetResponse();
... // deserialze the response
There is also a wrapper for Json.NET called Bitnet (https://sourceforge.net/projects/bitnet) implementing Bitcoin API in more convenient way:
BitnetClient bc = new BitnetClient("http://127.0.0.1:8332");
bc.Credentials = new NetworkCredential("user", "pass");
var p = bc.GetDifficulty();
Console.WriteLine("Difficulty:" + p.ToString());
var inf = bc.GetInfo();
Console.WriteLine("Balance:" + inf["balance"]);
A more complete library and wrapper for Bitcoin (also for Litecoin and all Bitcoin clones) 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:
IBitcoinService bitcoinService = new BitcoinService();
double networkDifficulty = bitcoinService.GetDifficulty();
decimal myBalance = bitcoinService.GetBalance();
Node.js
- node-bitcoin (npm: bitcoin)
Example using node-bitcoin:
var bitcoin = require('bitcoin');
var client = new bitcoin.Client({
host: 'localhost',
port: 8332,
user: 'user',
pass: 'pass'
});
client.getDifficulty(function(err, difficulty) {
if (err) {
return console.error(err);
}
console.log('Difficulty: ' + difficulty);
});
Example using Kapitalize:
var client = require('kapitalize')()
client.auth('user', 'password')
client
.getInfo()
.getDifficulty(function(err, difficulty) {
console.log('Dificulty: ', difficulty)
})
Command line (cURL)
You can also send commands and see results using cURL or some other command-line HTTP-fetching utility; for example:
curl --user user --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getinfo", "params": [] }'
-H 'content-type: text/plain;' http://127.0.0.1:8332/
You will be prompted for your rpcpassword, and then will see something like:
{"result":{"balance":0.000000000000000,"blocks":59952,"connections":48,"proxy":"","generate":false,
"genproclimit":-1,"difficulty":16.61907875185736,"error":null,"id":"curltest"}
Clojure
clj-btc is a Clojure wrapper for the bitcoin API.
user=> (require '[clj-btc.core :as btc])
nil
user=> (btc/getinfo)
{"timeoffset" 0, "protocolversion" 70001, "blocks" 111908, "errors" "",
"testnet" true, "proxy" "", "connections" 4, "version" 80500,
"keypoololdest" 1380388750, "paytxfee" 0E-8M,
"difficulty" 4642.44443532M, "keypoolsize" 101, "balance" 0E-8M,
"walletversion" 60000}