Bitcoin Forum

Bitcoin => Development & Technical Discussion => Topic started by: jesmurf on December 24, 2010, 07:40:38 AM



Title: JSON-RPC library for Ruby and Rails
Post by: jesmurf on December 24, 2010, 07:40:38 AM
Hi everybody,

I'm new to Bitcoin, although I'm very exited about it. If I goof up posting this please correct me gently.  :)

I've released a JSON-RPC library for Ruby/Rails. The Wiki had nothing for Ruby:
http://www.bitcoin.org/wiki/doku.php?id=api

And I wrestled to get any JSON-RPC library to work. Everything was too old, circa 2005-2007. Here's a fresh implementation.

https://github.com/jjeffus/rpcjson

To control bitcoind you would do the following.

1. First install the rubygem.

Code:
gem install rpcjson

2. Next set up bitcoin.conf like the Wiki says.
3. Start bitcoind or bitcoin -server.

Then in a ruby script:

Code:
require 'rubygems'
require 'rpcjson'

bc = RPC::JSON::Client.new 'http://username:password@127.0.0.1:8332', 1.1
puts bc.getinfo

Please let me know if it's useful, or you find any bugs.

- Jonathan


Title: Re: JSON-RPC library for Ruby and Rails
Post by: davout on December 24, 2010, 01:13:26 PM
Nice work, haven't tried it myself, here is what I use so far in a Rails app.
Can't be bothered packaging it into a gem right now though.

Bitcoin client, autostrips underscores for more pretty code
Code:
module Bitcoin
  class Client
    def initialize
      config_file = File.open(File.join(Rails.root, "config", "bitcoin.yml"))
      config = YAML::load(config_file)[Rails.env].symbolize_keys

      @client = JsonWrapper.new(config[:url],
        config[:username],
        config[:password]
      )
    end

    def method_missing(method, *args)
      @client.request({
          :method => method.to_s.gsub(/\_/, ""),
          :params => args
        }
      )
    end
  end
end

Code:
module Bitcoin
  module Util
    def self.valid_bitcoin_address?(address)
      # We don't want leading/trailing spaces to pollute addresses
      (address == address.strip) and Bitcoin::Client.new.validate_address(address)['isvalid']
    end

    def self.my_bitcoin_address?(address)
      Bitcoin::Client.new.validate_address(address)['ismine']
    end

    def self.get_account(address)
      Bitcoin::Client.new.get_account(address)
    end
  end
end

my JSON wrapper
Code:
require 'net/http'
require 'addressable/uri'
require 'json'

module Bitcoin
  class JsonWrapper
    def initialize(url, username, password)
      @address = Addressable::URI.parse(url)
      @username = username
      @password = password
    end

    def request(params)
      result = nil

      full_params = params.merge({
          :jsonrpc => "2.0",
          :id => (rand * 10 ** 12).to_i.to_s
        })

      request_body = full_params.to_json

      Net::HTTP.start(@address.host, @address.port) do |connection|
        post = Net::HTTP::Post.new(@address.path)
        post.body = request_body
        post.basic_auth(@username, @password)
        result = connection.request(post)
        result = JSON.parse(result.body)
      end

      if error = result["error"]
        raise "#{error["message"]}, request was #{request_body}"
      end

      result = result["result"]
      result
    end
  end
end

A validator for proper bitcoin addresses (validate :foo, :bitcoin_address => true)
Code:
class BitcoinAddressValidator < ActiveModel::EachValidator
  def validate_each(record, field, value)
    unless (value.blank? or Bitcoin::Util.valid_bitcoin_address?(value))
      record.errors[field] << "is invalid"
    end
  end
end


Title: Re: JSON-RPC library for Ruby and Rails
Post by: jesmurf on December 24, 2010, 04:33:54 PM
Thanks davout!

I'm trying to incorporate Bitcoin in a couple of my Rails projects, this will help out a LOT. At the moment I'm working on incorporating Bitcoin into Shopify as a payment method. I'll post results on the forum if I get anything good.

- Jonathan
 


Title: Re: JSON-RPC library for Ruby and Rails
Post by: alowm on January 06, 2011, 08:40:39 AM
Nice code, gentlemen.  8)

davout, I like your approach, but the absence of a test suite for it would make me uncomfortable using it on a production system.


Title: Re: JSON-RPC library for Ruby and Rails
Post by: davout on January 06, 2011, 09:55:09 AM
Nice code, gentlemen.  8)

davout, I like your approach, but the absence of a test suite for it would make me uncomfortable using it on a production system.
A test suite would be pretty useless because you'd pretty much be testing either :
 - the bitcoin client (and that would tie you to a version to some extent)
 - one of the http, addressable and json libs which would be pretty useless too...

Anyway, that's what's being used in production in bitcoin-central.net, flawless so far.
I have some tests for the address validation but these are pretty obsolete, they were made when I checked for address validity myself and didn't rely on the client to do it, guess I should remove them :)


Title: Re: JSON-RPC library for Ruby and Rails
Post by: Nefario on January 06, 2011, 10:13:36 AM
I think I'll be making use of this very soon ,thanks very much.


Title: Re: JSON-RPC library for Ruby and Rails
Post by: dholowiski on May 20, 2011, 01:48:08 PM
Hi, I'm using this in my rails project but I'm getting the error - 401 Unauthorized. Any ideas?


Title: Re: JSON-RPC library for Ruby and Rails
Post by: Nefario on May 20, 2011, 02:42:09 PM
Hi, I'm using this in my rails project but I'm getting the error - 401 Unauthorized. Any ideas?

Before you startup bitcoind you need to have rpcpassword & username set in the config file otherwise rpc wont work.


Title: Re: JSON-RPC library for Ruby and Rails
Post by: davout on May 20, 2011, 02:55:27 PM
Hi, I'm using this in my rails project but I'm getting the error - 401 Unauthorized. Any ideas?

Before you startup bitcoind you need to have rpcpassword & username set in the config file otherwise rpc wont work.
+1


Title: Re: JSON-RPC library for Ruby and Rails
Post by: Nefario on May 20, 2011, 03:15:59 PM
Hi, I'm using this in my rails project but I'm getting the error - 401 Unauthorized. Any ideas?

Before you startup bitcoind you need to have rpcpassword & username set in the config file otherwise rpc wont work.
+1

Where did you dissapear to?


Title: Re: JSON-RPC library for Ruby and Rails
Post by: davout on May 20, 2011, 03:22:39 PM
Where did you dissapear to?
Had to deal with going abroad for work with little to no internet connection, and no family for a bunch of months.
Can't say I aren't happy about having family and bitcoin community back :D

Big big kudos to what you've done with the GLBSE !


Title: Re: JSON-RPC library for Ruby and Rails
Post by: Nefario on May 20, 2011, 05:02:51 PM
Where did you dissapear to?
Had to deal with going abroad for work with little to no internet connection, and no family for a bunch of months.
Can't say I aren't happy about having family and bitcoin community back :D

Big big kudos to what you've done with the GLBSE !

Much thanks, I understand what it's like without family or internet for a long time. You must have had the shakes without your daily dose (of net that is).