API reference (JSON-RPC)

来自Bitcoin Wiki
Simapple讨论 | 贡献2011年5月28日 (六) 14:23的版本 (以内容“== 操控 bitcoin 软件 == 运行 ''bitcoind'' 或 ''bitcoin -server''. 你可以通过命令行或[http://json-rpc.org/wiki/specification| HTTP JSON-RPC] 命令来...”创建新页面)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航搜索

操控 bitcoin 软件

运行 bitcoindbitcoin -server. 你可以通过命令行或HTTP JSON-RPC 命令来操控它.



 $ ./bitcoind
 bitcoin server starting
 $ ./bitcoind help
 # shows the help text


 $ ./bitcoind getbalance


运行'bitcoin -server'或'bitcoind' 将使bitcoin以HTTP JSON-RPC服务器模式运行,但与其通信时必须使用[1],安全起见,默认情况下服务器只接受同一机器上其他进程的连接。如果你的HTTP或JSON库需要你指定已认证的'realm',请使用'jsonrpc'。

0.3.14版之后版本的Bitcoin支持SSL (https) JSON-RPC连接。配置详情请参考本页面


Proper money handling

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


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 (at least Python 2.6+, though not 3.x). 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@")
  #access.sendtoaddress("11yEmxiMso2RsFVfBcCa616npBvGgxiBX", 10)


Make sure to do:
    gem install rest-client

    h = ServiceProxy.new('http://user:password@')
    puts h.getinfo.call
    puts h.getbalance.call 'accname'
require 'json'
require 'rest_client'

class JSONRPCException < RuntimeError
    def initialize()

class ServiceProxy
    def initialize(service_url, service_name=nil)
        @service_url = service_url
        @service_name = service_name

    def method_missing(name, *args, &block)
        if @service_name != nil
            name = "%s.%s" % [@service_name, name]
        return ServiceProxy.new(@service_url, name)

    def respond_to?(sym)

    def call(*args)
        postdata = {"method" => @service_name, "params" => args, "id" => "jsonrpc"}.to_json
        respdata = RestClient.post @service_url, postdata
        resp = JSON.parse respdata
        if resp["error"] != nil
            raise JSONRPCException.new, resp['error']
        return resp['result']


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


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.


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;
     '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()));
     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);
     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;'

You will be prompted for your rpcpassword, and then will see something like:


See Also