API reference (JSON-RPC)

From Bitcoin Wiki
Revision as of 21:40, 17 December 2010 by Genjix (talk | contribs) (→‎Java)
Jump to navigation Jump to search

Controlling Bitcoin

If you run Bitcoin with the -server argument or bitcoind, you can control it via the command-line or by HTTP-JSON-RPC commands.

Under Linux create ~/.bitcoin/bitcoin.conf. Under Windows create bitcoin.conf in the Bitcoin data directory.

bitcoin.conf:

 rpcuser=myusername
 rpcpassword=secretpassword

Now run:

 $ ./bitcoind
 bitcoin server starting
 $ ./bitcoind help

A list of RPC calls will be shown.

 $ ./bitcoind getbalance
 2000.00000

JSON-RPC

Running Bitcoin with the -server argument (or running bitcoind) tells it to function as a 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.

To access the server you should find a library for your language.

Python

For Python, python-jsonrpc is perfect. Python-jsonrpc auto-magically generates Python methods corresponding to the functions above. For example:

 from jsonrpc import ServiceProxy
 
 access = ServiceProxy("http://user:password@127.0.0.1:8332")
 access.getinfo()
 access.listreceivedbyaddress(6)
 access.sendtoaddress("11yEmxiMso2RsFVfBcCa616npBvGgxiBX", 10)

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:pass@127.0.0.1:8332/'); 
  
 echo "<pre>\n";
 print_r($bitcoin->getinfo()); echo "\n";
 echo "Received: ".$bitcoin->getreceivedbylabel("Your Address")."\n";
 echo "</pre>";

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.

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;

}

.NET (C#)

The communication with rpc service can be achieved using the standard httprequest/response objects. A library for serialising and deserialising Json will make your life a lot easier:

- Use JayRock for .NET 4.0

- Use Json.Net for .NET 2.0 and above

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


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"}