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.

198 lines
5.2 KiB

7 years ago
7 years ago
  1. package rpcclient
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "reflect"
  11. "strings"
  12. "github.com/pkg/errors"
  13. types "github.com/tendermint/tendermint/rpc/lib/types"
  14. )
  15. // HTTPClient is a common interface for JSONRPCClient and URIClient.
  16. type HTTPClient interface {
  17. Call(method string, params map[string]interface{}, result interface{}) (interface{}, error)
  18. }
  19. // TODO: Deprecate support for IP:PORT or /path/to/socket
  20. func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, error)) {
  21. parts := strings.SplitN(remoteAddr, "://", 2)
  22. var protocol, address string
  23. if len(parts) == 1 {
  24. // default to tcp if nothing specified
  25. protocol, address = "tcp", remoteAddr
  26. } else if len(parts) == 2 {
  27. protocol, address = parts[0], parts[1]
  28. } else {
  29. // return a invalid message
  30. msg := fmt.Sprintf("Invalid addr: %s", remoteAddr)
  31. return msg, func(_ string, _ string) (net.Conn, error) {
  32. return nil, errors.New(msg)
  33. }
  34. }
  35. // accept http as an alias for tcp
  36. if protocol == "http" {
  37. protocol = "tcp"
  38. }
  39. // replace / with . for http requests (dummy domain)
  40. trimmedAddress := strings.Replace(address, "/", ".", -1)
  41. return trimmedAddress, func(proto, addr string) (net.Conn, error) {
  42. return net.Dial(protocol, address)
  43. }
  44. }
  45. // We overwrite the http.Client.Dial so we can do http over tcp or unix.
  46. // remoteAddr should be fully featured (eg. with tcp:// or unix://)
  47. func makeHTTPClient(remoteAddr string) (string, *http.Client) {
  48. address, dialer := makeHTTPDialer(remoteAddr)
  49. return "http://" + address, &http.Client{
  50. Transport: &http.Transport{
  51. Dial: dialer,
  52. },
  53. }
  54. }
  55. //------------------------------------------------------------------------------------
  56. // JSONRPCClient takes params as a slice
  57. type JSONRPCClient struct {
  58. address string
  59. client *http.Client
  60. }
  61. // NewJSONRPCClient returns a JSONRPCClient pointed at the given address.
  62. func NewJSONRPCClient(remote string) *JSONRPCClient {
  63. address, client := makeHTTPClient(remote)
  64. return &JSONRPCClient{
  65. address: address,
  66. client: client,
  67. }
  68. }
  69. func (c *JSONRPCClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  70. request, err := types.MapToRequest("jsonrpc-client", method, params)
  71. if err != nil {
  72. return nil, err
  73. }
  74. requestBytes, err := json.Marshal(request)
  75. if err != nil {
  76. return nil, err
  77. }
  78. // log.Info(string(requestBytes))
  79. requestBuf := bytes.NewBuffer(requestBytes)
  80. // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes)))
  81. httpResponse, err := c.client.Post(c.address, "text/json", requestBuf)
  82. if err != nil {
  83. return nil, err
  84. }
  85. defer httpResponse.Body.Close() // nolint: errcheck
  86. responseBytes, err := ioutil.ReadAll(httpResponse.Body)
  87. if err != nil {
  88. return nil, err
  89. }
  90. // log.Info(Fmt("RPC response: %v", string(responseBytes)))
  91. return unmarshalResponseBytes(responseBytes, result)
  92. }
  93. //-------------------------------------------------------------
  94. // URI takes params as a map
  95. type URIClient struct {
  96. address string
  97. client *http.Client
  98. }
  99. func NewURIClient(remote string) *URIClient {
  100. address, client := makeHTTPClient(remote)
  101. return &URIClient{
  102. address: address,
  103. client: client,
  104. }
  105. }
  106. func (c *URIClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  107. values, err := argsToURLValues(params)
  108. if err != nil {
  109. return nil, err
  110. }
  111. // log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values))
  112. resp, err := c.client.PostForm(c.address+"/"+method, values)
  113. if err != nil {
  114. return nil, err
  115. }
  116. defer resp.Body.Close() // nolint: errcheck
  117. responseBytes, err := ioutil.ReadAll(resp.Body)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return unmarshalResponseBytes(responseBytes, result)
  122. }
  123. //------------------------------------------------
  124. func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface{}, error) {
  125. // read response
  126. // if rpc/core/types is imported, the result will unmarshal
  127. // into the correct type
  128. // log.Notice("response", "response", string(responseBytes))
  129. var err error
  130. response := &types.RPCResponse{}
  131. err = json.Unmarshal(responseBytes, response)
  132. if err != nil {
  133. return nil, errors.Errorf("Error unmarshalling rpc response: %v", err)
  134. }
  135. if response.Error != nil {
  136. return nil, errors.Errorf("Response error: %v", response.Error)
  137. }
  138. // unmarshal the RawMessage into the result
  139. err = json.Unmarshal(response.Result, result)
  140. if err != nil {
  141. return nil, errors.Errorf("Error unmarshalling rpc response result: %v", err)
  142. }
  143. return result, nil
  144. }
  145. func argsToURLValues(args map[string]interface{}) (url.Values, error) {
  146. values := make(url.Values)
  147. if len(args) == 0 {
  148. return values, nil
  149. }
  150. err := argsToJson(args)
  151. if err != nil {
  152. return nil, err
  153. }
  154. for key, val := range args {
  155. values.Set(key, val.(string))
  156. }
  157. return values, nil
  158. }
  159. func argsToJson(args map[string]interface{}) error {
  160. for k, v := range args {
  161. rt := reflect.TypeOf(v)
  162. isByteSlice := rt.Kind() == reflect.Slice && rt.Elem().Kind() == reflect.Uint8
  163. if isByteSlice {
  164. bytes := reflect.ValueOf(v).Bytes()
  165. args[k] = fmt.Sprintf("0x%X", bytes)
  166. continue
  167. }
  168. // Pass everything else to go-wire
  169. data, err := json.Marshal(v)
  170. if err != nil {
  171. return err
  172. }
  173. args[k] = string(data)
  174. }
  175. return nil
  176. }