Class: Silkroad::Client
- Inherits:
-
Object
- Object
- Silkroad::Client
- Defined in:
- lib/silkroad/client.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- DEFAULT_RPC_PORT =
8332- TESTNET_RPC_PORT =
18332- JSONRPC_VERSION =
'2.0'
Instance Method Summary collapse
- #batch(requests = nil, &block) ⇒ Object
-
#initialize(user, pass, opts = {}) ⇒ Client
constructor
A new instance of Client.
- #inspect ⇒ Object
- #rpc(meth, *params) ⇒ Object
- #send(formdata) ⇒ Object
Constructor Details
#initialize(user, pass, opts = {}) ⇒ Client
Returns a new instance of Client.
9 10 11 12 13 14 15 16 |
# File 'lib/silkroad/client.rb', line 9 def initialize(user, pass, opts={}) @user = user @opts = opts @uri = URI.parse @opts[:url] || "http://localhost:#{DEFAULT_RPC_PORT}" @uri.port = DEFAULT_RPC_PORT if @opts[:url].nil? || !@opts[:url].match(/:80/) @user = user @pass = pass end |
Instance Method Details
#batch(requests = nil, &block) ⇒ Object
18 19 20 21 22 |
# File 'lib/silkroad/client.rb', line 18 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 |
#inspect ⇒ Object
55 56 57 |
# File 'lib/silkroad/client.rb', line 55 def inspect "#<#{self.class} user=\"#{@user}\" @uri=\"#{@uri.to_s}\">" end |
#rpc(meth, *params) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/silkroad/client.rb', line 24 def rpc(meth, *params) response = send jsonrpc: JSONRPC_VERSION, method: meth, params: params if response.code != '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(formdata) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/silkroad/client.rb', line 39 def send(formdata) resp = Net::HTTP.start(@uri.host, @uri.port) do |http| req = Net::HTTP::Post.new '/' req.basic_auth @user, @pass req.add_field 'Content-Type', 'application/json' req.use_ssl = true if @uri.scheme == 'https' req.body = formdata.to_json http.request req end if resp.code == '403' && resp.body.empty? raise Error, '403 Forbidden - check your user/pass and/or uri, and ensure IP is whitelisted for remote connections' end resp end |