lib/bitcoin/network/command_client.rb in bitcoin-ruby-0.0.5 vs lib/bitcoin/network/command_client.rb in bitcoin-ruby-0.0.6

- old
+ new

@@ -17,10 +17,12 @@ @callbacks = {} @block = block instance_eval &block if block @buffer = BufferedTokenizer.new("\x00") @connection_attempts = 0 + @requests = {} + @i = 0 end def log; @log ||= Bitcoin::Logger.create(:client) end @@ -30,11 +32,11 @@ end # call +connected+ callback def post_init log.debug { "Connected" } - callback :connected + request(:connected) { callback(:connected) } end # call +disconnected+ callback and try to reconnect def unbind log.debug { "Disconnected." } @@ -45,25 +47,33 @@ post_init end end # request command +cmd+ with +args+ from the server - def request cmd, *args + def request cmd, params = nil, &block + id = @i += 1 + @requests[id] = block if block log.debug { "request: #{cmd} #{args.inspect}" } - register_monitor_callbacks if cmd.to_sym == :monitor - send_data([cmd, args].to_json + "\x00") + register_monitor_callbacks(params) if cmd.to_sym == :monitor + request = { id: id, method: cmd } + request[:params] = params if params + send_data(request.to_json + "\x00") end # receive response from server def receive_data data @connection_attempts = 0 @buffer.extract(data).each do |packet| - cmd, *data = *JSON.load(packet) - log.debug { d = data.inspect - "response: #{cmd} #{d[0...50]}#{d.size > 50 ? '...' : ''}" } - callback(:response, cmd, *data) - callback(cmd.to_sym, *data) + response = JSON.parse(packet) + log.debug { d = response['result'].inspect + "response: #{response['method']} #{d[0...50]}#{d.size > 50 ? '...' : ''}" } + if cb = @requests[response['id']] + cb.call(response['result']) + else + callback(:response, response['method'], response['result']) + callback(response['method'].to_sym, response['result']) + end end end # call the callback specified by +name+ passing in +args+ def callback name, *args @@ -82,13 +92,13 @@ super(name, *args) end end # register callbacks for monitor - def register_monitor_callbacks - on_monitor do |type, data| - type, *params = type.split("_") - callback(type, *((data || []) + (params || []))) + def register_monitor_callbacks params + on_monitor do |data| + next if data.is_a?(Hash) && data.keys == ["id"] + callback(params["channel"], data) end end end