Skip to content

ARMR JSON RPC API Documentation

Godlove Damian edited this page Jun 12, 2019 · 1 revision

== Starting ARMR Server ==

Run ''./ARMRd'' -daemon''. You can control it via the command-line utility.

You must create a ARMR.conf configuration file setting an rpcuser and rpcpassword; see Setup ARMR Node for details.

Now run:

$ ./ARMRd -daemon ARMR server starting

$ ./ARMRd help

# shows the help text

A full list of ARMR JSON-RPC API Calls list will be shown.

$ ./ARMRd getbalance 2000.00000

If you are learning the API, it is a very good idea to use the test network (run ARMRd -testnet -daemon).

== JSON-RPC ==

Running ARMR with the -daemon argument (ARMRd -daemon) tells it to function as a server, but 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'.

Allowing arbitrary machines to access the JSON-RPC port (using the rpcallowip) is dangerous and '''strongly discouraged'''-- access should be strictly limited to trusted machines.

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

== Proper money handling ==

See the Proper Money Handling page for notes on avoiding rounding errors when handling ARMR values.

== Languages ==

=== Ruby ===

require 'net/http' require 'uri' require 'json'

class ARMRRPC 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 = ARMRRPC.new('http://user:password@127.0.0.1:17570') p h.getbalance p h.getinfo p h.getnewaddress p h.dumpprivkey( h.getnewaddress ) end

=== PHP ===

The [http://jsonrpcphp.org/ JSON-RPC PHP] library also makes it very easy to connect to ARMR. For example:

require_once 'jsonRPCClient.php';

$ARMR = new jsonRPCClient('http://user:password@127.0.0.1:17570/');

echo "

\n";
print_r($ARMR->getinfo()); echo "\n";
echo "Received: ".$ARMR->getreceivedbylabel("Your Address")."\n";
echo "
";

'''Note:''' The jsonRPCClient library uses fopen() and will throw an exception saying "Unable to connect" if it receives a 404 or 500 error from ARMRd. This prevents you from being able to see error messages generated by ARMRd (as they are sent with status 404 or 500).

=== 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, [http://json-rpc.org/wiki/implementations any JSON-RPC library for Java] (or ordinary URL POSTs) may be used to communicate with the ARMR server.

=== Perl ===

The JSON::RPC package from CPAN can be used to communicate with ARMR. 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:17570', 'jsonrpc', 'user' => 'password' # REPLACE WITH YOUR ARMR.conf rpcuser/rpcpassword );

my $uri = 'http://localhost:17570/'; 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 the RPC service can be achieved using the standard http request/response objects. A library for serializing and deserializing Json will make your life a lot easier:

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 ).

The following example uses Json.NET:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost.:17570"); 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

=== Node.js ===

Example using ARMR-core:

const Client = require('ARMR-core'); const client = new Client({ network: 'regtest', username: 'user', password: 'pass', port: 18443 });

client.getBlockchainInfo().then((help) => console.log(help));

=== Command line (cURL) ===

You can also send commands and see results using [http://curl.haxx.se/ 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:17570/

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

=== C ===

The C API for processing JSON is [https://jansson.readthedocs.org/en/latest/ Jansson].

#include

#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:17570/");

curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(data));
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);

curl_easy_setopt(curl, CURLOPT_USERPWD,
		 "ARMRrpcUSERNAME:ARMRrpcPASSWORD");

curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);

curl_easy_perform(curl);
}
return 0;

}

This output can be parsed with Jansson, ''à la'' the Jansson tutorial linked to above.

=== Qt/C++ ===

[https://bitbucket.org/devonit/qjsonrpc/overview 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 * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include #include #include #include

#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 = "ARMRrpc"; 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] "; return -1; }

HttpClient client("http://127.0.0.1:17570");
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();

}

Clone this wiki locally