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.

219 lines
5.7 KiB

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