Class: Bitcoin::RPC::HttpServer

Inherits:
EM::Connection
  • Object
show all
Includes:
RequestHandler, EM::HttpServer
Defined in:
lib/bitcoin/rpc/http_server.rb

Overview

Bitcoinrb RPC server.

Constant Summary collapse

SUPPORTED_COMMANDS =
%w[
  getblockchaininfo
  stop
  getblockheader
  getpeerinfo
  sendrawtransaction
  decoderawtransaction
  decodescript
  createwallet
  listwallets
  getwalletinfo
  listaccounts
  encryptwallet
  getnewaddress
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RequestHandler

#createwallet, #decoderawtransaction, #decodescript, #encryptwallet, #getblockchaininfo, #getblockheader, #getnewaddress, #getpeerinfo, #getwalletinfo, #listaccounts, #listwallets, #sendrawtransaction, #stop

Constructor Details

#initialize(node) ⇒ HttpServer

Returns a new instance of HttpServer.



31
32
33
34
# File 'lib/bitcoin/rpc/http_server.rb', line 31

def initialize(node)
  @node = node
  @logger = Bitcoin::Logger.create(:debug)
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



29
30
31
# File 'lib/bitcoin/rpc/http_server.rb', line 29

def logger
  @logger
end

#nodeObject (readonly)

Returns the value of attribute node.



28
29
30
# File 'lib/bitcoin/rpc/http_server.rb', line 28

def node
  @node
end

Class Method Details

.run(node, port = 8332) ⇒ Object



41
42
43
# File 'lib/bitcoin/rpc/http_server.rb', line 41

def self.run(node, port = 8332)
  EM.start_server('0.0.0.0', port, HttpServer, node)
end

Instance Method Details

#parse_json_paramsArray

parse request parameter.

Returns:

  • (Array)

    the array of command and args



76
77
78
79
# File 'lib/bitcoin/rpc/http_server.rb', line 76

def parse_json_params
  params = JSON.parse(@http_post_content)
  [params['method'], params['params']]
end

#post_initObject



36
37
38
39
# File 'lib/bitcoin/rpc/http_server.rb', line 36

def post_init
  super
  logger.debug 'start http server.'
end

#process_http_requestObject

process http request.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/bitcoin/rpc/http_server.rb', line 46

def process_http_request
  operation = proc {
    command, args = parse_json_params
    logger.debug("process http request. command = #{command}")
    unless SUPPORTED_COMMANDS.include?(command)
      raise ArgumentError, "Unsupported method: #{command}"
    end
    begin
      send(command, *args).to_json
    rescue Exception => e
      e
    end
  }
  callback = proc{ |result|
    response = EM::DelegatedHttpResponse.new(self)
    if result.is_a?(Exception)
      response.status = 500
      response.content = result.message
    else
      response.status = 200
      response.content = result
    end
    response.content_type 'application/json'
    response.send_response
  }
  EM.defer(operation, callback)
end