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.

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