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.

195 lines
5.2 KiB

  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) != 2 {
  24. log.Warn("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix")
  25. protocol = types.SocketType(remoteAddr)
  26. address = remoteAddr
  27. } else {
  28. protocol, address = parts[0], parts[1]
  29. }
  30. trimmedAddress := strings.Replace(address, "/", ".", -1) // replace / with . for http requests (dummy domain)
  31. return trimmedAddress, func(proto, addr string) (net.Conn, error) {
  32. return net.Dial(protocol, address)
  33. }
  34. }
  35. // We overwrite the http.Client.Dial so we can do http over tcp or unix.
  36. // remoteAddr should be fully featured (eg. with tcp:// or unix://)
  37. func makeHTTPClient(remoteAddr string) (string, *http.Client) {
  38. address, dialer := makeHTTPDialer(remoteAddr)
  39. return "http://" + address, &http.Client{
  40. Transport: &http.Transport{
  41. Dial: dialer,
  42. },
  43. }
  44. }
  45. //------------------------------------------------------------------------------------
  46. // JSON rpc takes params as a slice
  47. type JSONRPCClient struct {
  48. address string
  49. client *http.Client
  50. }
  51. func NewJSONRPCClient(remote string) *JSONRPCClient {
  52. address, client := makeHTTPClient(remote)
  53. return &JSONRPCClient{
  54. address: address,
  55. client: client,
  56. }
  57. }
  58. func (c *JSONRPCClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  59. // we need this step because we attempt to decode values using `go-wire`
  60. // (handlers.go:176) on the server side
  61. // encodedParams := make(map[string]interface{})
  62. // for k, v := range params {
  63. // bytes := json.RawMessage(wire.JSONBytes(v))
  64. // encodedParams[k] = &bytes
  65. // }
  66. request := types.RPCRequest{
  67. JSONRPC: "2.0",
  68. Method: method,
  69. Params: params,
  70. ID: "",
  71. }
  72. requestBytes, err := json.Marshal(request)
  73. if err != nil {
  74. return nil, err
  75. }
  76. // log.Info(string(requestBytes))
  77. requestBuf := bytes.NewBuffer(requestBytes)
  78. // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes)))
  79. httpResponse, err := c.client.Post(c.address, "text/json", requestBuf)
  80. if err != nil {
  81. return nil, err
  82. }
  83. defer httpResponse.Body.Close()
  84. responseBytes, err := ioutil.ReadAll(httpResponse.Body)
  85. if err != nil {
  86. return nil, err
  87. }
  88. // log.Info(Fmt("RPC response: %v", string(responseBytes)))
  89. return unmarshalResponseBytes(responseBytes, result)
  90. }
  91. //-------------------------------------------------------------
  92. // URI takes params as a map
  93. type URIClient struct {
  94. address string
  95. client *http.Client
  96. }
  97. func NewURIClient(remote string) *URIClient {
  98. address, client := makeHTTPClient(remote)
  99. return &URIClient{
  100. address: address,
  101. client: client,
  102. }
  103. }
  104. func (c *URIClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  105. values, err := argsToURLValues(params)
  106. if err != nil {
  107. return nil, err
  108. }
  109. // log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values))
  110. resp, err := c.client.PostForm(c.address+"/"+method, values)
  111. if err != nil {
  112. return nil, err
  113. }
  114. defer resp.Body.Close()
  115. responseBytes, err := ioutil.ReadAll(resp.Body)
  116. if err != nil {
  117. return nil, err
  118. }
  119. return unmarshalResponseBytes(responseBytes, result)
  120. }
  121. //------------------------------------------------
  122. func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface{}, error) {
  123. // read response
  124. // if rpc/core/types is imported, the result will unmarshal
  125. // into the correct type
  126. // log.Notice("response", "response", string(responseBytes))
  127. var err error
  128. response := &types.RPCResponse{}
  129. err = json.Unmarshal(responseBytes, response)
  130. if err != nil {
  131. return nil, errors.Errorf("Error unmarshalling rpc response: %v", err)
  132. }
  133. errorStr := response.Error
  134. if errorStr != "" {
  135. return nil, errors.Errorf("Response error: %v", errorStr)
  136. }
  137. // unmarshal the RawMessage into the result
  138. err = json.Unmarshal(*response.Result, result)
  139. if err != nil {
  140. return nil, errors.Errorf("Error unmarshalling rpc response result: %v", err)
  141. }
  142. return result, nil
  143. }
  144. func argsToURLValues(args map[string]interface{}) (url.Values, error) {
  145. values := make(url.Values)
  146. if len(args) == 0 {
  147. return values, nil
  148. }
  149. err := argsToJson(args)
  150. if err != nil {
  151. return nil, err
  152. }
  153. for key, val := range args {
  154. values.Set(key, val.(string))
  155. }
  156. return values, nil
  157. }
  158. func argsToJson(args map[string]interface{}) error {
  159. for k, v := range args {
  160. rt := reflect.TypeOf(v)
  161. isByteSlice := rt.Kind() == reflect.Slice && rt.Elem().Kind() == reflect.Uint8
  162. if isByteSlice {
  163. bytes := reflect.ValueOf(v).Bytes()
  164. args[k] = fmt.Sprintf("0x%X", bytes)
  165. continue
  166. }
  167. // Pass everything else to go-wire
  168. data, err := json.Marshal(v)
  169. if err != nil {
  170. return err
  171. }
  172. args[k] = string(data)
  173. }
  174. return nil
  175. }