Class: Silkroad::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/silkroad/client.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

DEFAULT_PORT =
8332
JSONRPC_VERSION =
'2.0'

Instance Method Summary collapse

Constructor Details

#initialize(user, pass, opts = {}) ⇒ Client

Returns a new instance of Client.



7
8
9
10
11
12
13
14
15
# File 'lib/silkroad/client.rb', line 7

def initialize(user, pass, opts={})
  @user        = user
  @opts        = opts
  @url         = Addressable::URI.parse @opts[:url] || "http://localhost:#{DEFAULT_PORT}"
  @url.port    = DEFAULT_PORT if @url.port.nil?

  @http_client = HTTPClient.new
  @http_client.set_auth @url.to_s, user, pass
end

Instance Method Details

#batch(requests = nil, &block) ⇒ Object



17
18
19
20
21
# File 'lib/silkroad/client.rb', line 17

def batch(requests=nil, &block)
  requests ||= Batch.new(&block).requests
  requests.each {|r| r[:jsonrpc] = JSONRPC_VERSION unless r[:jsonrpc]}
  JSON.parse send(requests).body
end

#inspectObject



42
43
44
# File 'lib/silkroad/client.rb', line 42

def inspect
  "#<#{self.class} user=\"#{@user}\" @url=\"#{@url.to_s}\">"
end

#rpc(meth, *params) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/silkroad/client.rb', line 23

def rpc(meth, *params)
  response = send jsonrpc: JSONRPC_VERSION, method: meth, params: params

  if response.status != 200
    if response.body.nil?
      raise Error.new "bitcoind returned HTTP status #{response.status} with no body: #{response.http_header.reason_phrase}"
    else
      response_obj = JSON.parse response.body
      raise Error.new "bitcoind returned error code #{response_obj['error']['code']}: #{response_obj['error']['message']}"
    end
  else
    JSON.parse(response.body)['result']
  end
end

#send(request) ⇒ Object



38
39
40
# File 'lib/silkroad/client.rb', line 38

def send(request)
  @http_client.post @url, request.to_json, {'Content-Type' => 'application/json'}
end