0

I am getting the following error while trying RPC call from ruby. bitcoind server is running. I am using bitcoin-ruby library .

Code Tried in irb to test:

require 'bitcoin'
=> true
irb(main):002:0> txid= "611b40973fe68cc42b70ae5af365a449af458d76086415c6fa6c45364c36278e"
=> "611b40973fe68cc42b70ae5af365a449af458d76086415c6fa6c45364c36278e"
irb(main):003:0> rtx= bitcoinRPC('getrawtransaction',[txid])

Error :

NoMethodError: undefined method `bitcoinRPC' for main:Object
    from (irb):3
    from /usr/bin/irb:11:in `<main>'

Any suggetion will be highly appreciated.

Thanks in advance,

R

1 Answer 1

0

Use the following method to call BitcoinRPC using Ruby:

Create ruby file test.rb as

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://username:[email protected]:8332')
  txid= "611b40973fe68cc42b70ae5af365a449af458d76086415c6fa6c45364c36278e"
  p h.getrawtransaction(txid)
end

NOTE: username and password are from your bitcoin.conf file.

1
  • mark this as answer if you run successful.
    – m2pathan
    Commented Feb 27, 2018 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.