https://tests.bitcoin.it/w/api.php?action=feedcontributions&user=Edescourtis&feedformat=atom
Bitcoin Wiki - User contributions [en]
2024-03-28T17:06:23Z
User contributions
MediaWiki 1.30.0
https://tests.bitcoin.it/w/index.php?title=API_reference_(JSON-RPC)&diff=53683
API reference (JSON-RPC)
2015-01-05T01:45:55Z
<p>Edescourtis: /* Erlang */</p>
<hr />
<div>== Controlling Bitcoin ==<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 />
== 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.getinfo()<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.getinfo<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:getinfo(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->getinfo()); 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 to write your wrapper you can use [[Bitcoin-JSON-RPC-Client|this implementation]] or [https://github.com/johannbarbie/BitcoindClient4J this one] .<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 => 'getinfo',<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/conformal/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/conformal/btcnet"<br />
"github.com/conformal/btcrpcclient"<br />
"github.com/conformal/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", &btcnet.MainNetParams)<br />
if err != nil {<br />
log.Fatalf("address receiver1 seems to be invalid: %v", err)<br />
}<br />
receiver2, err := btcutil.DecodeAddress("1anotherAddressThatsPrettyReal", &btcnet.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 serialising 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.GetInfo();<br />
Console.WriteLine("Balance:" + inf["balance"]);<br />
</source><br />
<br />
A more complete library and wrapper for Bitcoin (also for Litecoin and all Bitcoin clones) 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 />
double networkDifficulty = bitcoinService.GetDifficulty();<br />
decimal myBalance = bitcoinService.GetBalance();<br />
</source><br />
<br />
== Node.js ==<br />
<br />
* [https://github.com/freewil/node-bitcoin node-bitcoin] (npm: bitcoin) <br />
<br />
Example using node-bitcoin:<br />
<br />
<source lang="javascript"><br />
var bitcoin = require('bitcoin');<br />
var client = new bitcoin.Client({<br />
host: 'localhost',<br />
port: 8332,<br />
user: 'user',<br />
pass: 'pass'<br />
});<br />
<br />
client.getDifficulty(function(err, difficulty) {<br />
if (err) {<br />
return console.error(err);<br />
}<br />
<br />
console.log('Difficulty: ' + difficulty);<br />
});<br />
</source><br />
<br />
Example using Kapitalize:<br />
<br />
<source lang='javascript'><br />
var client = require('kapitalize')()<br />
<br />
client.auth('user', 'password')<br />
<br />
client<br />
.getInfo()<br />
.getDifficulty(function(err, difficulty) {<br />
console.log('Dificulty: ', difficulty)<br />
})<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": "getinfo", "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 />
== 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/getinfo)<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 />
== See Also==<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)]]</div>
Edescourtis
https://tests.bitcoin.it/w/index.php?title=API_reference_(JSON-RPC)&diff=53682
API reference (JSON-RPC)
2015-01-05T01:33:17Z
<p>Edescourtis: Erlang</p>
<hr />
<div>== Controlling Bitcoin ==<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 />
== 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.getinfo()<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.getinfo<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>). 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:getinfo(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 />
#{<<"data">> => <<"01000000015072ea92bb330a3ef04bcf170c244bea7e"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 1000,<br />
<<"hash">> => <<"32528460a50ae4eb40c53b9f4cdd4e64"...>>,<br />
<<"sigops">> => 1},<br />
#{<<"data">> => <<"010000000432c35cd9be53c27f39e96d5af23617"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 0,<br />
<<"hash">> => <<"6bd3f1d8e67ae101341c9f66074a"...>>,<br />
<<"sigops">> => 2},<br />
#{<<"data">> => <<"01000000020e1d51c50de8e34844d733ad4c"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 20000,<br />
<<"hash">> => <<"23fcb2f2b52ed1f79c211b3b"...>>,<br />
<<"sigops">> => 1},<br />
#{<<"data">> => <<"010000000584e494f0c0f22eeffd8b60"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 0,<br />
<<"hash">> => <<"4a3e8526daff8e04568f"...>>,<br />
<<"sigops">> => 1},<br />
#{<<"data">> => <<"0100000002a8545d91579925ef12"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 20000,<br />
<<"hash">> => <<"f6dce7acf65f04ea"...>>,<br />
<<"sigops">> => 2},<br />
#{<<"data">> => <<"01000000130439f489e8e9c2"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 30000,<br />
<<"hash">> => <<"9fc0ab68f4a6"...>>,<br />
<<"sigops">> => 2},<br />
#{<<"data">> => <<"01000000013fdbac949b"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 20000,<br />
<<"hash">> => <<"b773a227"...>>,<br />
<<"sigo"...>> => 2},<br />
#{<<"data">> => <<"0100000004ae4fbc"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 10000,<br />
<<"hash">> => <<"f9e3"...>>,<br />
<<...>> => 2},<br />
#{<<"data">> => <<"010000000896"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 20000,<br />
<<...>> => <<...>>,...},<br />
#{<<"data">> => <<"01000000"...>>,<br />
<<"depe"...>> => [],<br />
<<...>> => 10000,...},<br />
#{<<"data">> => <<"0100"...>>,<<...>> => [],...},<br />
#{<<...>> => <<...>>,...},<br />
#{...}|...],<br />
<<"version">> => 2}}<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->getinfo()); 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 to write your wrapper you can use [[Bitcoin-JSON-RPC-Client|this implementation]] or [https://github.com/johannbarbie/BitcoindClient4J this one] .<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 => 'getinfo',<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/conformal/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/conformal/btcnet"<br />
"github.com/conformal/btcrpcclient"<br />
"github.com/conformal/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", &btcnet.MainNetParams)<br />
if err != nil {<br />
log.Fatalf("address receiver1 seems to be invalid: %v", err)<br />
}<br />
receiver2, err := btcutil.DecodeAddress("1anotherAddressThatsPrettyReal", &btcnet.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 serialising 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.GetInfo();<br />
Console.WriteLine("Balance:" + inf["balance"]);<br />
</source><br />
<br />
A more complete library and wrapper for Bitcoin (also for Litecoin and all Bitcoin clones) 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 />
double networkDifficulty = bitcoinService.GetDifficulty();<br />
decimal myBalance = bitcoinService.GetBalance();<br />
</source><br />
<br />
== Node.js ==<br />
<br />
* [https://github.com/freewil/node-bitcoin node-bitcoin] (npm: bitcoin) <br />
<br />
Example using node-bitcoin:<br />
<br />
<source lang="javascript"><br />
var bitcoin = require('bitcoin');<br />
var client = new bitcoin.Client({<br />
host: 'localhost',<br />
port: 8332,<br />
user: 'user',<br />
pass: 'pass'<br />
});<br />
<br />
client.getDifficulty(function(err, difficulty) {<br />
if (err) {<br />
return console.error(err);<br />
}<br />
<br />
console.log('Difficulty: ' + difficulty);<br />
});<br />
</source><br />
<br />
Example using Kapitalize:<br />
<br />
<source lang='javascript'><br />
var client = require('kapitalize')()<br />
<br />
client.auth('user', 'password')<br />
<br />
client<br />
.getInfo()<br />
.getDifficulty(function(err, difficulty) {<br />
console.log('Dificulty: ', difficulty)<br />
})<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": "getinfo", "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 />
== 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/getinfo)<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 />
== See Also==<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)]]</div>
Edescourtis