API reference (JSON-RPC): Difference between revisions

From Bitcoin Wiki
Jump to navigation Jump to search
Genjix (talk | contribs)
Genjix (talk | contribs)
Line 107: Line 107:
         # remove the dot from the string
         # remove the dot from the string
         $significand = substr($numstr, 0, $dotpos);
         $significand = substr($numstr, 0, $dotpos);
        $decimals = substr($numstr, $dotpos + 1, $slen);
      # returns a string!
# GMP cannot use strings, so be careful when using the value
# optionally use numstr_to_internal(gmp_div_dec(...)) to convert the output of this function
# into an internal int64 type number (as you should be doing).
function gmp_div_dec($quot, $divis, $precision=2)
{
    # precision = number of decimals
    $shift = gmp_pow("10", $precision);
    $quot = gmp_mul($quot, $shift);
 
    $res = gmp_div_q($quot, $divis);
    $repr = gmp_strval($res);
    $dotpos = strlen($repr) - $precision;
    $repr = substr($repr, 0, $dotpos) . "." . substr($repr, $dotpos);
    return $repr;
}
 
$a = gmp_init("100");
$b = gmp_init("3");
echo "<p>".gmp_div_dec($a, $b)."</p>";
$decimals = substr($numstr, $dotpos + 1, $slen);
         $num_decimals = strlen($decimals);
         $num_decimals = strlen($decimals);
         if ($num_decimals > 8) {
         if ($num_decimals > 8) {
Line 146: Line 166:
If you need to do a decimal division in GMP, then GMP only supports integer division + a remainder. The work-around for this, is to multiply the quotient by 10^precision, do the division and then insert the decimal point:
If you need to do a decimal division in GMP, then GMP only supports integer division + a remainder. The work-around for this, is to multiply the quotient by 10^precision, do the division and then insert the decimal point:
<source lang="php">
<source lang="php">
$quot = gmp_init("5");
# returns a string!
$divis = gmp_init("2");
# GMP cannot use strings, so be careful when using the value
# number of decimals
# optionally use numstr_to_internal(gmp_div_dec(...)) to convert the output of this function
$precision = 2;
# into an internal int64 type number (as you should be doing).
function gmp_div_dec($quot, $divis, $precision=2)
{
    # precision = number of decimals
    $shift = gmp_pow("10", $precision);
    $quot = gmp_mul($quot, $shift);


$shift = gmp_pow("10", $precision);
    $res = gmp_div_q($quot, $divis);
$quot = gmp_mul($quot, $shift);
    $repr = gmp_strval($res);
 
    $dotpos = strlen($repr) - $precision;
$res = gmp_div_q($quot, $divis);
    $repr = substr($repr, 0, $dotpos) . "." . substr($repr, $dotpos);
$repr = gmp_strval($res);
    return $repr;
$dotpos = strlen($repr) - $precision;
}
$repr = substr($repr, 0, $dotpos) . "." . substr($repr, $dotpos);


echo "Number is $repr";
$a = gmp_init("100");
$res = gmp_init($repr);
$b = gmp_init("3");
echo "<p>".gmp_div_dec($a, $b)."</p>";
</source>
</source>



Revision as of 13:52, 12 March 2011

Controlling Bitcoin

Run bitcoind or bitcoin -server. You can control it via the command-line 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
 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.

Proper money handling

See the proper money handling page for notes on avoiding rounding errors when handling bitcoin values.

Python

Save the following file as jsonrpc.py.

import urllib
import decimal
import json

class JSONRPCException(Exception):
    def __init__(self, rpcError):
        Exception.__init__(self)
        self.error = rpcError
        
class ServiceProxy(object):
    def __init__(self, serviceURL, serviceName=None):
        self.__serviceURL = serviceURL
        self.__serviceName = serviceName

    def __getattr__(self, name):
        if self.__serviceName != None:
            name = "%s.%s" % (self.__serviceName, name)
        return ServiceProxy(self.__serviceURL, name)

    def __call__(self, *args):
         postdata = json.dumps({"method": self.__serviceName, 'params': args, 'id':'jsonrpc'})
         respdata = urllib.urlopen(self.__serviceURL, postdata).read()
         resp = json.loads(respdata, parse_float=decimal.Decimal)
         if resp['error'] != None:
             raise JSONRPCException(resp['error'])
         else:
             return resp['result']

Python-jsonrpc automatically generates Python methods corresponding to the functions above.

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

Precision

Because PHP has no option to JSON decode to accurate decimal class, you should internally use GMP. Treat each number like a large int with 8 decimal places (this can be trimmed for display).

You will need to get a saner branch and compile it. This treats every monetary value int64 8 decimal strings. So 1 BTC will be "100000000". Use PHP's GMP functions to manipulate these values accurately.

For converting between internal GMP numbers and display/user input, you can use these functions:

function numstr_to_internal($numstr)
{
    $slen = strlen($numstr);
    $dotpos = strrpos($numstr, '.');
    if ($dotpos === false) {
        $num = gmp_init($numstr);
        $num = gmp_mul($numstr, pow(10, 8));
    }
    else {
        # remove the dot from the string
        $significand = substr($numstr, 0, $dotpos);
       # returns a string!
# GMP cannot use strings, so be careful when using the value
# optionally use numstr_to_internal(gmp_div_dec(...)) to convert the output of this function
# into an internal int64 type number (as you should be doing).
function gmp_div_dec($quot, $divis, $precision=2)
{
    # precision = number of decimals
    $shift = gmp_pow("10", $precision);
    $quot = gmp_mul($quot, $shift);

    $res = gmp_div_q($quot, $divis);
    $repr = gmp_strval($res);
    $dotpos = strlen($repr) - $precision;
    $repr = substr($repr, 0, $dotpos) . "." . substr($repr, $dotpos);
    return $repr;
}

$a = gmp_init("100");
$b = gmp_init("3");
echo "<p>".gmp_div_dec($a, $b)."</p>";
 $decimals = substr($numstr, $dotpos + 1, $slen);
        $num_decimals = strlen($decimals);
        if ($num_decimals > 8) {
            $decimals = substr($decimals, 0, 8);
            $num_decimals = strlen($decimals);
        }        
        $numstr = $significand . $decimals;
        # GMP doesn't like leading 0s
        $numstr = ltrim($numstr, '0');
        $num = gmp_init($numstr);
        $num = gmp_mul($numstr, pow(10, 8 - $num_decimals));
    }
    return $num;
}

function internal_to_numstr($internal)
{
    $inrepr = gmp_strval($internal);
    $inrlen = strlen($inrepr);
    if (gmp_cmp($internal, pow(10, 8)) < 0) {
        $numstr = '0.' . str_repeat('0', 8 - $inrlen) . $inrepr;
        $numstr = rtrim($numstr, '0');
    }
    else {
        $dotpos = $inrlen - 8;
        $decimals = substr($inrepr, $dotpos, 8);
        $decimals = rtrim($decimals, '0');
        $significand = substr($inrepr, 0, $dotpos);
        $numstr = $significand . '.' . $decimals;
    }
    # if there's no 0's after the . then it will clip it
    # otherwise the decimal remains
    $numstr = rtrim($numstr, '.');
    return $numstr;
}

If you need to do a decimal division in GMP, then GMP only supports integer division + a remainder. The work-around for this, is to multiply the quotient by 10^precision, do the division and then insert the decimal point:

# returns a string!
# GMP cannot use strings, so be careful when using the value
# optionally use numstr_to_internal(gmp_div_dec(...)) to convert the output of this function
# into an internal int64 type number (as you should be doing).
function gmp_div_dec($quot, $divis, $precision=2)
{
    # precision = number of decimals
    $shift = gmp_pow("10", $precision);
    $quot = gmp_mul($quot, $shift);

    $res = gmp_div_q($quot, $divis);
    $repr = gmp_strval($res);
    $dotpos = strlen($repr) - $precision;
    $repr = substr($repr, 0, $dotpos) . "." . substr($repr, $dotpos);
    return $repr;
}

$a = gmp_init("100");
$b = gmp_init("3");
echo "<p>".gmp_div_dec($a, $b)."</p>";

You can put this in a function named gmp_div_dec($a, $b, $precision=2).

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:

  • JayRock for .NET 4.0
  • 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"}