Ruby bitcoind JSON RPCCall

0

I am trying the JSON-RPC call from https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)#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://rpcuser:rpcpassword@127.0.0.1:8332')
  p h.getbalance
  p h.getinfo
  p h.getnewaddress
  p h.dumpprivkey( h.getnewaddress )
end

But when I try running the file, I get a RPC.rb: end of file reached (EOFError)

I have the bitcoind running, I can run various commands, but I an not seem to get this script running.

Bryan Singh

Posted 2017-06-02T06:35:03.363

Reputation: 1

Answers

1

The code is free of syntax errors, but it looks like you need to replace the rpcuser and rpcpassword in this line:

h = BitcoinRPC.new('http://rpcuser:rpcpassword@127.0.0.1:8332')

To the actual rpcuser and rpcpassword values that are set in your bitcoin.conf file.

If that doesn't work, I'd suggest doing some debugging by opening an irb session and running this code to see the result of the HTTP request to the RPC service:

require 'net/http'
require 'json'

post_body = { method: 'getblockchaininfo', params: [], id: 'jsonrpc' }.to_json

uri = URI.parse "http://rpcuser:rpcpassword@127.0.0.1:8332"

def http_post_request(uri, 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

http_post_request(uri, post_body)

Eric Allam

Posted 2017-06-02T06:35:03.363

Reputation: 708

0

I don't really know Ruby but these two lines looks off to me.

  class JSONRPCError < RuntimeError; end
end

Two ends?

m1xolyd1an

Posted 2017-06-02T06:35:03.363

Reputation: 3 356