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