You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

187 lines
5.0 KiB

  1. package rpcclient
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. . "github.com/tendermint/go-common"
  12. "github.com/tendermint/go-rpc/types"
  13. "github.com/tendermint/go-wire"
  14. )
  15. // TODO: Deprecate support for IP:PORT or /path/to/socket
  16. func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, error)) {
  17. parts := strings.SplitN(remoteAddr, "://", 2)
  18. var protocol, address string
  19. if len(parts) != 2 {
  20. log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix")
  21. protocol = rpctypes.SocketType(remoteAddr)
  22. address = remoteAddr
  23. } else {
  24. protocol, address = parts[0], parts[1]
  25. }
  26. trimmedAddress := strings.Replace(address, "/", ".", -1) // replace / with . for http requests (dummy domain)
  27. return trimmedAddress, func(proto, addr string) (net.Conn, error) {
  28. return net.Dial(protocol, address)
  29. }
  30. }
  31. // We overwrite the http.Client.Dial so we can do http over tcp or unix.
  32. // remoteAddr should be fully featured (eg. with tcp:// or unix://)
  33. func makeHTTPClient(remoteAddr string) (string, *http.Client) {
  34. address, dialer := makeHTTPDialer(remoteAddr)
  35. return "http://" + address, &http.Client{
  36. Transport: &http.Transport{
  37. Dial: dialer,
  38. },
  39. }
  40. }
  41. //------------------------------------------------------------------------------------
  42. type Client interface {
  43. }
  44. //------------------------------------------------------------------------------------
  45. // JSON rpc takes params as a slice
  46. type ClientJSONRPC struct {
  47. address string
  48. client *http.Client
  49. }
  50. func NewClientJSONRPC(remote string) *ClientJSONRPC {
  51. address, client := makeHTTPClient(remote)
  52. return &ClientJSONRPC{
  53. address: address,
  54. client: client,
  55. }
  56. }
  57. func (c *ClientJSONRPC) Call(method string, params []interface{}, result interface{}) (interface{}, error) {
  58. return c.call(method, params, result)
  59. }
  60. func (c *ClientJSONRPC) call(method string, params []interface{}, result interface{}) (interface{}, error) {
  61. // Make request and get responseBytes
  62. request := rpctypes.RPCRequest{
  63. JSONRPC: "2.0",
  64. Method: method,
  65. Params: params,
  66. ID: "",
  67. }
  68. requestBytes := wire.JSONBytes(request)
  69. requestBuf := bytes.NewBuffer(requestBytes)
  70. // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes)))
  71. httpResponse, err := c.client.Post(c.address, "text/json", requestBuf)
  72. if err != nil {
  73. return nil, err
  74. }
  75. defer httpResponse.Body.Close()
  76. responseBytes, err := ioutil.ReadAll(httpResponse.Body)
  77. if err != nil {
  78. return nil, err
  79. }
  80. // log.Info(Fmt("RPC response: %v", string(responseBytes)))
  81. return unmarshalResponseBytes(responseBytes, result)
  82. }
  83. //-------------------------------------------------------------
  84. // URI takes params as a map
  85. type ClientURI struct {
  86. address string
  87. client *http.Client
  88. }
  89. func NewClientURI(remote string) *ClientURI {
  90. address, client := makeHTTPClient(remote)
  91. return &ClientURI{
  92. address: address,
  93. client: client,
  94. }
  95. }
  96. func (c *ClientURI) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  97. return c.call(method, params, result)
  98. }
  99. func (c *ClientURI) call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  100. values, err := argsToURLValues(params)
  101. if err != nil {
  102. return nil, err
  103. }
  104. //log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values))
  105. resp, err := c.client.PostForm(c.address+"/"+method, values)
  106. if err != nil {
  107. return nil, err
  108. }
  109. defer resp.Body.Close()
  110. responseBytes, err := ioutil.ReadAll(resp.Body)
  111. if err != nil {
  112. return nil, err
  113. }
  114. return unmarshalResponseBytes(responseBytes, result)
  115. }
  116. //------------------------------------------------
  117. func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface{}, error) {
  118. // read response
  119. // if rpc/core/types is imported, the result will unmarshal
  120. // into the correct type
  121. // log.Notice("response", "response", string(responseBytes))
  122. var err error
  123. response := &rpctypes.RPCResponse{}
  124. err = json.Unmarshal(responseBytes, response)
  125. if err != nil {
  126. return nil, errors.New(Fmt("Error unmarshalling rpc response: %v", err))
  127. }
  128. errorStr := response.Error
  129. if errorStr != "" {
  130. return nil, errors.New(Fmt("Response error: %v", errorStr))
  131. }
  132. // unmarshal the RawMessage into the result
  133. result = wire.ReadJSONPtr(result, *response.Result, &err)
  134. if err != nil {
  135. return nil, errors.New(Fmt("Error unmarshalling rpc response result: %v", err))
  136. }
  137. return result, nil
  138. }
  139. func argsToURLValues(args map[string]interface{}) (url.Values, error) {
  140. values := make(url.Values)
  141. if len(args) == 0 {
  142. return values, nil
  143. }
  144. err := argsToJson(args)
  145. if err != nil {
  146. return nil, err
  147. }
  148. for key, val := range args {
  149. values.Set(key, val.(string))
  150. }
  151. return values, nil
  152. }
  153. func argsToJson(args map[string]interface{}) error {
  154. var n int
  155. var err error
  156. for k, v := range args {
  157. buf := new(bytes.Buffer)
  158. wire.WriteJSON(v, buf, &n, &err)
  159. if err != nil {
  160. return err
  161. }
  162. args[k] = buf.String()
  163. }
  164. return nil
  165. }