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.

237 lines
6.3 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
  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. amino "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. // Set to true to prevent GZIP-bomb DoS attacks
  68. DisableCompression: true,
  69. Dial: dialer,
  70. },
  71. }
  72. }
  73. //------------------------------------------------------------------------------------
  74. // JSONRPCClient takes params as a slice
  75. type JSONRPCClient struct {
  76. address string
  77. client *http.Client
  78. cdc *amino.Codec
  79. }
  80. // NewJSONRPCClient returns a JSONRPCClient pointed at the given address.
  81. func NewJSONRPCClient(remote string) *JSONRPCClient {
  82. address, client := makeHTTPClient(remote)
  83. return &JSONRPCClient{
  84. address: address,
  85. client: client,
  86. cdc: amino.NewCodec(),
  87. }
  88. }
  89. func (c *JSONRPCClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  90. request, err := types.MapToRequest(c.cdc, types.JSONRPCStringID("jsonrpc-client"), method, params)
  91. if err != nil {
  92. return nil, err
  93. }
  94. requestBytes, err := json.Marshal(request)
  95. if err != nil {
  96. return nil, err
  97. }
  98. // log.Info(string(requestBytes))
  99. requestBuf := bytes.NewBuffer(requestBytes)
  100. // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes)))
  101. httpResponse, err := c.client.Post(c.address, "text/json", requestBuf)
  102. if err != nil {
  103. return nil, err
  104. }
  105. defer httpResponse.Body.Close() // nolint: errcheck
  106. responseBytes, err := ioutil.ReadAll(httpResponse.Body)
  107. if err != nil {
  108. return nil, err
  109. }
  110. // log.Info(Fmt("RPC response: %v", string(responseBytes)))
  111. return unmarshalResponseBytes(c.cdc, responseBytes, result)
  112. }
  113. func (c *JSONRPCClient) Codec() *amino.Codec {
  114. return c.cdc
  115. }
  116. func (c *JSONRPCClient) SetCodec(cdc *amino.Codec) {
  117. c.cdc = cdc
  118. }
  119. //-------------------------------------------------------------
  120. // URI takes params as a map
  121. type URIClient struct {
  122. address string
  123. client *http.Client
  124. cdc *amino.Codec
  125. }
  126. func NewURIClient(remote string) *URIClient {
  127. address, client := makeHTTPClient(remote)
  128. return &URIClient{
  129. address: address,
  130. client: client,
  131. cdc: amino.NewCodec(),
  132. }
  133. }
  134. func (c *URIClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  135. values, err := argsToURLValues(c.cdc, params)
  136. if err != nil {
  137. return nil, err
  138. }
  139. // log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values))
  140. resp, err := c.client.PostForm(c.address+"/"+method, values)
  141. if err != nil {
  142. return nil, err
  143. }
  144. defer resp.Body.Close() // nolint: errcheck
  145. responseBytes, err := ioutil.ReadAll(resp.Body)
  146. if err != nil {
  147. return nil, err
  148. }
  149. return unmarshalResponseBytes(c.cdc, responseBytes, result)
  150. }
  151. func (c *URIClient) Codec() *amino.Codec {
  152. return c.cdc
  153. }
  154. func (c *URIClient) SetCodec(cdc *amino.Codec) {
  155. c.cdc = cdc
  156. }
  157. //------------------------------------------------
  158. func unmarshalResponseBytes(cdc *amino.Codec, responseBytes []byte, result interface{}) (interface{}, error) {
  159. // Read response. If rpc/core/types is imported, the result will unmarshal
  160. // into the correct type.
  161. // log.Notice("response", "response", string(responseBytes))
  162. var err error
  163. response := &types.RPCResponse{}
  164. err = json.Unmarshal(responseBytes, response)
  165. if err != nil {
  166. return nil, errors.Errorf("Error unmarshalling rpc response: %v", err)
  167. }
  168. if response.Error != nil {
  169. return nil, errors.Errorf("Response error: %v", response.Error)
  170. }
  171. // Unmarshal the RawMessage into the result.
  172. err = cdc.UnmarshalJSON(response.Result, result)
  173. if err != nil {
  174. return nil, errors.Errorf("Error unmarshalling rpc response result: %v", err)
  175. }
  176. return result, nil
  177. }
  178. func argsToURLValues(cdc *amino.Codec, args map[string]interface{}) (url.Values, error) {
  179. values := make(url.Values)
  180. if len(args) == 0 {
  181. return values, nil
  182. }
  183. err := argsToJSON(cdc, args)
  184. if err != nil {
  185. return nil, err
  186. }
  187. for key, val := range args {
  188. values.Set(key, val.(string))
  189. }
  190. return values, nil
  191. }
  192. func argsToJSON(cdc *amino.Codec, args map[string]interface{}) error {
  193. for k, v := range args {
  194. rt := reflect.TypeOf(v)
  195. isByteSlice := rt.Kind() == reflect.Slice && rt.Elem().Kind() == reflect.Uint8
  196. if isByteSlice {
  197. bytes := reflect.ValueOf(v).Bytes()
  198. args[k] = fmt.Sprintf("0x%X", bytes)
  199. continue
  200. }
  201. data, err := cdc.MarshalJSON(v)
  202. if err != nil {
  203. return err
  204. }
  205. args[k] = string(data)
  206. }
  207. return nil
  208. }