API reference (JSON-RPC)
目次
Bitcoinの制御[編集]
bitcoind または bitcoin-qt -server を実行してください。
コマンドラインのbitcoin-cliユーティリティまたはHTTP JSON-RPCコマンドで制御できます。
rpcuserとrpcpasswordを設定するbitcoin.conf設定ファイルを作成する必要があります。
詳細は、Bitcoinの実行中を参照してください。
今すぐ実行する:
$ ./bitcoind -daemon ビットクロックサーバーの起動
$ ./bitcoin-cli -rpcwait help #はヘルプテキストを示します
RPC呼び出しの一覧が表示されます。
$ ./bitcoin-cli getbalance 2000.00000
APIを学んでいる場合は、テストネットワーク(ビットコム-testnetとbitcoin-cli -testnetを実行)を使用することをお勧めします。
JSON-RPC[編集]
Bitcoinを-server引数(またはビットコインを実行中)とともに実行すると、HTTP JSON-RPCサーバとして機能するように指示されますが、
基本アクセス認証は、通信するときに使用する必要があります。
セキュリティのために、デフォルトでは、サーバは同じマシン上の他のプロセスからの接続のみを受け入れます。
HTTPまたはJSONライブラリで、認証される 'realm'を指定する必要がある場合は、 'jsonrpc'を使用します。
Bitcoinは、バージョン0.3.14から始まるSSL(https)JSON-RPC接続をサポートしています。
設定方法とすべてのbitcoin.conf設定オプションのリストについては、 rpcssl wikiページを参照してください。
(rpcallowip 設定オプションを使用して)任意のマシンがJSON-RPCポートにアクセスできるようにすることは危険であり、強く推奨されません。アクセスは厳重に信頼できるマシンに制限する必要があります。
サーバーにアクセスするには、ご使用の言語用の適切なライブラリが必要です。
適正な貨幣処理[編集]
ビットコイン値を扱う際の丸め誤差を避けるための注意については、適切なマネー処理ページを参照してください。
Python[編集]
python-jsonrpcは、Pythonの公式JSON-RPC実装です。
RPC呼び出し用のPythonメソッドを自動的に生成します。
しかし、古いバージョンのPythonをサポートするために設計されているため、やはり非効率的です。
jgarzikはそれをPython-BitcoinRPCとしてフォークし、現在のバージョン用に最適化しました。
一般的には、このバージョンをお勧めします。
BitcoinRPCにはjsonrpcからのあいまいな機能がいくつかありますが、ServiceProxyクラスだけを使用するソフトウェアは、どちらのバージョンでもインストールすることができます。
jsonrpcからのインポートServiceProxy
access = ServiceProxy( "http:// user:password@127.0.0.1:8332")
access.getinfo()
access.listreceivedbyaddress(6)
#access.sendtoaddress( "11yEmxiMso2RsFVfBcCa616npBvGgxiBX"、10)
最新バージョンのpython-bitcoinrpcには新しい構文があります。
bitcoinrpc.authproxyからのインポート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[編集]
鉄筋依存をhttps://github.com/edescourtis/ebitcoindから取得します。
デフォルトでは、クライアントは$HOME/.bitcoin/bitcoin.conf
の設定を使用するか、代わりに以下のようなURIを指定することができます:
ebitcoind:start_link(<<"http://user:password@localhost:8332/">>).
使用例を次に示します。
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},
...
PHP[編集]
JSON-RPC PHPライブラリを使用すると、Bitcoinに簡単に接続することもできます。例えば:
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>";
jsonRPCClientライブラリはfopen()を使用し、ビットコインドから404または500のエラーを受け取った場合、「Unable to connect」という例外をスローします。これにより、ビットコインによって生成されたエラーメッセージ(ステータス404または500で送信されるため)が表示されなくなります。 EasyBitcoin-PHP ライブラリは、JSON-RPC PHPと機能は似ていますが、この問題はありません。
Java[編集]
JavaにHTTP基本認証を使用するように指示する最も簡単な方法は、デフォルトの認証者を設定することです。
final String rpcuser ="...";
final String rpcpassword ="...";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray());
}
});
これが完了すると、Java用のJSON-RPCライブラリ(または通常のURL POST)をBitcoinサーバーと通信するために使用できます。
独自の実装を記述するのではなく、[BitcoindClient4J、[btcd-cli4j]
または Bitcoin-JSON-RPC-Clientを使用します。
Perl[編集]
CPANのJSON :: RPCパッケージは、Bitcoinとの通信に使用できます。クライアントの資格情報を設定する必要があります。例えば:
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;
}
移動[編集]
btcrpcclient パッケージは、Bitcoinと通信するために使用できます。
通信しているクライアントと一致するように、資格情報を提供する必要があります。
package main
import (
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcrpcclient"
"github.com/btcsuite/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", &chaincfg.MainNetParams)
if err != nil {
log.Fatalf("address receiver1 seems to be invalid: %v", err)
}
receiver2, err := btcutil.DecodeAddress("1anotherAddressThatsPrettyReal", &chaincfg.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#)[編集]
RPCサービスとの通信は、標準のhttp要求/応答オブジェクトを使用して行うことができます。
Jsonをシリアライズおよびデシリアライズするためのライブラリは、あなたの生活を楽にします:
Json.NET(http://james.newtonking.com/json)は、.NET用の高性能JSONパッケージです。
また、パッケージマネージャコンソール(Install-Package Newtonsoft.Json)からNuGetを介して入手できます。
次の例では、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
Bitnet(https://sourceforge.net/projects/bitnet)と呼ばれるJson.NET用のラッパーもあります。
より便利な方法でBitcoin APIを実装する:
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"]);
Bitcoin用の完全なライブラリとラッパー(LitecoinとすべてのBitcoinクローン用)は、BitcoinLib(https://github.com/GeorgeKimionis/BitcoinLib)です。
NuGetをパッケージマネージャコンソール(Install-Package BitcoinLib)から削除します。
BitcoinLibでデーモンに問い合わせるのは簡単です:
IBitcoinService bitcoinService = new BitcoinService();
var networkDifficulty = bitcoinService.GetDifficulty();
var myBalance = bitcoinService.GetBalance();
Node.js[編集]
- node-bitcoin(npm:bitcoin)
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);
});
Kapitalizeを使用した例:
var client = require('kapitalize')()
client.auth('user', 'password')
client
.getInfo()
.getDifficulty(function(err, difficulty) {
console.log('Dificulty: ', difficulty)
})
コマンドライン(cURL)[編集]
cURLやその他のコマンドラインHTTP取得ユーティリティを使用して、コマンドを送信して結果を表示することもできます。例えば:
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はビットコインAPIのClojureラッパーです。
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}
C[編集]
JSONを処理するためのC APIは、[1]です。
libblkmakerのようなCのアプリケーションでは、呼び出しを行うために
cURLを使用し、cURLが取得するJSONを解釈するためにJanssonを使用します。
基本的な使い方(Bitcoin RPCの場合は簡単に変更できます)については、Janssonの例github_commits.cと[https:// jansson .readthedocs.org / ja / latest / tutorial.html#the-github-repo-commits-api関連のチュートリアル]。
以下はlibcurlの cURLの例が行うことです:#include <stdlib.h>
#include <curl/curl.h>
int main()
{
CURL *curl = curl_easy_init();
struct curl_slist *headers = NULL;
if (curl) {
const char *data =
"{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", \"method\": \"getinfo\", \"params\": [] }";
headers = curl_slist_append(headers, "content-type: text/plain;");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8332/");
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(data));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(curl, CURLOPT_USERPWD,
"bitcoinrpcUSERNAME:bitcoinrpcPASSWORD");
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
curl_easy_perform(curl);
}
return 0;
}
(source: Bitcoin StackExchange)
Qt/C++[編集]
QJsonRpc is a Qt/C++ implementation of the JSON-RPC protocol. It integrates nicely with Qt, leveraging Qt's meta object system in order to provide services over the JSON-RPC protocol. QJsonRpc is licensed under the LGPLv2.1.
/*
* Copyright(C)2012-2013 Matt Broadstone
*お問い合わせ先:http://bitbucket.org/devonit/qjsonrpc
*このファイルはQJsonRpcライブラリの一部です。
*このライブラリはフリーソフトウェアです。あなたはそれを再配布することができます
* GNU Lesser General Publicの条件の下でそれを修正する
*フリーソフトウェア財団が発行したライセンス。どちらか
*バージョン2.1のライセンス、または(オプションで)それ以降のバージョン。
*このライブラリは有用であることを願って配布されていますが、
*ただし、いかなる保証もありません。黙示の保証なしでも
*商品性または特定の目的に対する適合性。 GNUを参照してください
*より一般的な一般公衆利用許諾契約書。
*/
#include <QCoreApplication>
#include <QAuthenticator>
#include <QStringList>
#include <QDebug>
#include "qjsonrpchttpclient.h"
class HttpClient : public QJsonRpcHttpClient
{
Q_OBJECT
public:
HttpClient(const QString &endpoint, QObject *parent = 0)
: QJsonRpcHttpClient(endpoint, parent)
{
// defaults added for my local test server
m_username = "bitcoinrpc";
m_password = "232fb3276bbb7437d265298ea48bdc46";
}
void setUsername(const QString &username) {
m_username = username;
}
void setPassword(const QString &password) {
m_password = password;
}
private Q_SLOTS:
virtual void handleAuthenticationRequired(QNetworkReply *reply, QAuthenticator * authenticator)
{
Q_UNUSED(reply)
authenticator->setUser(m_username);
authenticator->setPassword(m_password);
}
private:
QString m_username;
QString m_password;
};
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
if (app.arguments().size() < 2) {
qDebug() << "usage: " << argv[0] << "[-u username] [-p password] <command> <arguments>";
return -1;
}
HttpClient client("http://127.0.0.1:8332");
if (app.arguments().contains("-u")) {
int idx = app.arguments().indexOf("-u");
app.arguments().removeAt(idx);
if(idx<app.arguments().count())
client.setUsername(app.arguments().takeAt(idx));
else qDebug()<<"-u value not defined";
}
if (app.arguments().contains("-p")) {
int idx = app.arguments().indexOf("-p");
app.arguments().removeAt(idx);
if(idx<app.arguments().count())
client.setPassword(app.arguments().takeAt(idx));
else qDebug()<<"-p value not defined";
}
QJsonRpcMessage message = QJsonRpcMessage::createRequest(app.arguments().at(1));
QJsonRpcMessage response = client.sendMessageBlocking(message);
if (response.type() == QJsonRpcMessage::Error) {
qDebug() << response.errorData();
return -1;
}
qDebug() << response.toJson();
}
関連項目[編集]
- APIコールリスト
- Bitcoinを実行中
- Lazy API
- PHP開発者イントロ
- Raw Transactions API
- GoUrl Bitcoin PHP Payment API
- WebベースのJSON RPCインターフェイス。
Category:技術 Category:開発者 zh-cn:API_reference_(JSON-RPC)]
|