lib/sibit.rb in sibit-0.7.8 vs lib/sibit.rb in sibit-0.8.0
- old
+ new
@@ -22,10 +22,11 @@
require 'net/http'
require 'uri'
require 'bitcoin'
require 'json'
+require 'cgi'
# Sibit main class.
#
# It works through the Blockchain API at the moment:
# https://www.blockchain.com/api/blockchain_api
@@ -66,18 +67,34 @@
def get_json(_uri)
{}
end
end
+ # This HTTP client will be used by default.
+ def self.default_http
+ http = Net::HTTP.new('blockchain.info', 443)
+ http.use_ssl = true
+ http
+ end
+
+ # This HTTP client with proxy.
+ def self.proxy_http(addr)
+ host, port = addr.split(':')
+ http = Net::HTTP.new('blockchain.info', 443, host, port.to_i)
+ http.use_ssl = true
+ http
+ end
+
# Constructor.
#
# You may provide the log you want to see the messages in. If you don't
# provide anything, the console will be used. The object you provide
# has to respond to the method +info+ or +puts+ in order to receive logging
# messages.
- def initialize(log: STDOUT)
+ def initialize(log: STDOUT, http: Sibit.default_http)
@log = log
+ @http = http
end
# Current price of 1 BTC.
def price(cur = 'USD')
h = get_json('/ticker')[cur.upcase]
@@ -179,11 +196,16 @@
# Send GET request to the Blockchain API and return JSON response.
# This method will also log the process and will validate the
# response for correctness.
def get_json(uri)
start = Time.now
- res = Net::HTTP.get_response(URI('https://blockchain.info' + uri))
+ res = @http.get(
+ uri,
+ 'Accept' => 'text/plain',
+ 'User-Agent' => user_agent,
+ 'Accept-Encoding' => ''
+ )
raise Error, "Failed to retrieve #{uri} (#{res.code}): #{res.body}" unless res.code == '200'
info("GET #{uri}: #{res.code}/#{res.body.length}b in #{age(start)}")
JSON.parse(res.body)
end
@@ -222,19 +244,30 @@
"#{((Time.now - start) * 1000).round}ms"
end
def post_tx(body)
start = Time.now
- uri = URI('https://blockchain.info/pushtx')
- res = Net::HTTP.post_form(uri, tx: body)
+ uri = '/pushtx'
+ res = @http.post(
+ '/pushtx',
+ "tx=#{CGI.escape(body)}",
+ 'Accept' => 'text/plain',
+ 'User-Agent' => user_agent,
+ 'Accept-Encoding' => '',
+ 'Content-Type' => 'application/x-www-form-urlencoded'
+ )
raise Error, "Failed to post tx to #{uri}: #{res.code}\n#{res.body}" unless res.code == '200'
info("POST #{uri}: #{res.code} in #{age(start)}")
end
def info(msg)
if @log.respond_to?(:info)
@log.info(msg)
elsif @log.respond_to?(:puts)
@log.puts(msg)
end
+ end
+
+ def user_agent
+ "Anonymous/#{Sibit::VERSION}"
end
end