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 Attribute Summary collapse
-
#uri ⇒ Object
readonly
Returns the value of attribute uri.
Instance Method Summary collapse
- #batch(requests = nil, &block) ⇒ Object
-
#initialize(uri, opts = {}) ⇒ Client
constructor
A new instance of Client.
- #inspect ⇒ Object
- #rpc(meth, *params) ⇒ Object
- #send(formdata) ⇒ Object
Constructor Details
#initialize(uri, opts = {}) ⇒ Client
Returns a new instance of Client.
10 11 12 13 14 15 |
# File 'lib/silkroad/client.rb', line 10 def initialize(uri, opts={}) @opts = opts @uri = URI uri raise Error, 'user and password required' unless @uri.user && @uri.password @uri.port = DEFAULT_RPC_PORT if @uri.port.nil? || (@uri.port == 80 && !uri.match(/:80/)) end |
Instance Attribute Details
#uri ⇒ Object (readonly)
Returns the value of attribute uri.
4 5 6 |
# File 'lib/silkroad/client.rb', line 4 def uri @uri 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 |
#inspect ⇒ Object
56 57 58 |
# File 'lib/silkroad/client.rb', line 56 def inspect "#<#{self.class} user=\"#{@user}\" @uri=\"#{@uri.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, id: 1 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
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/silkroad/client.rb', line 38 def send(formdata) http = Net::HTTP.new(@uri.host, @uri.port) http.use_ssl = true if @uri.scheme == 'https' resp = http.start do req = Net::HTTP::Post.new '/' req.basic_auth @uri.user, @uri.password req.add_field 'Content-Type', 'application/json' 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 |