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.

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