Skip to content

Instantly share code, notes, and snippets.

@bertomartin
Created April 13, 2014 04:43
Show Gist options
  • Save bertomartin/10569553 to your computer and use it in GitHub Desktop.
Save bertomartin/10569553 to your computer and use it in GitHub Desktop.
require 'json'
require 'net/http'
require 'bigdecimal'
require 'bigdecimal/util'
class BitcoinClient
def initialize(config_file = File.expand_path("~/.bitcoin/bitcoin.conf"), host = '127.0.0.1', port = 8332)
raise "missing config file" if !File.exist?(config_file)
config = File.read(config_file).each_line.inject({}) do |hash, line|
key, value = line.chomp.split(/=/, 2)
hash[key] = value
hash
end
@username = config['rpcuser']
raise "missing username from configuration" if @username.nil?
@password = config['rpcpassword']
raise "missing password from configuration" if @password.nil?
@host = host
@port = port
@command_id = 1
end
def balance
request('getbalance').to_d
end
def set_passphrase(passphrase, timeout = 10)
request('walletpassphrase', passphrase, timeout)
end
def send_amount(address, amount)
request('sendtoaddress', address, amount.to_f)
end
def list_transactions(account = "", count = 10, from = 0)
request('listtransactions', account, count, from)
end
def request(method, *args)
out = {}
req = Net::HTTP::Post.new("/", {"Content-Type" => "application/json"})
req.basic_auth(@username, @password)
params = { 'method' => method, 'params' => args, 'id' => @command_id }
Net::HTTP.start(@host, @port) do |conn|
res = conn.request(req, params.to_json)
out = JSON.parse(res.body)
end
if error = out["error"]
raise error["message"]
end
if out["id"] != @command_id
raise "id mismatch, expected #{@command_id.inspect}, got #{result["id"].inspect}"
end
@command_id += 1
out['result']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment