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.

186 lines
5.0 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. request, err := types.MapToRequest("", method, params)
  60. if err != nil {
  61. return nil, err
  62. }
  63. requestBytes, err := json.Marshal(request)
  64. if err != nil {
  65. return nil, err
  66. }
  67. // log.Info(string(requestBytes))
  68. requestBuf := bytes.NewBuffer(requestBytes)
  69. // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes)))
  70. httpResponse, err := c.client.Post(c.address, "text/json", requestBuf)
  71. if err != nil {
  72. return nil, err
  73. }
  74. defer httpResponse.Body.Close()
  75. responseBytes, err := ioutil.ReadAll(httpResponse.Body)
  76. if err != nil {
  77. return nil, err
  78. }
  79. // log.Info(Fmt("RPC response: %v", string(responseBytes)))
  80. return unmarshalResponseBytes(responseBytes, result)
  81. }
  82. //-------------------------------------------------------------
  83. // URI takes params as a map
  84. type URIClient struct {
  85. address string
  86. client *http.Client
  87. }
  88. func NewURIClient(remote string) *URIClient {
  89. address, client := makeHTTPClient(remote)
  90. return &URIClient{
  91. address: address,
  92. client: client,
  93. }
  94. }
  95. func (c *URIClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  96. values, err := argsToURLValues(params)
  97. if err != nil {
  98. return nil, err
  99. }
  100. // log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values))
  101. resp, err := c.client.PostForm(c.address+"/"+method, values)
  102. if err != nil {
  103. return nil, err
  104. }
  105. defer resp.Body.Close()
  106. responseBytes, err := ioutil.ReadAll(resp.Body)
  107. if err != nil {
  108. return nil, err
  109. }
  110. return unmarshalResponseBytes(responseBytes, result)
  111. }
  112. //------------------------------------------------
  113. func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface{}, error) {
  114. // read response
  115. // if rpc/core/types is imported, the result will unmarshal
  116. // into the correct type
  117. // log.Notice("response", "response", string(responseBytes))
  118. var err error
  119. response := &types.RPCResponse{}
  120. err = json.Unmarshal(responseBytes, response)
  121. if err != nil {
  122. return nil, errors.Errorf("Error unmarshalling rpc response: %v", err)
  123. }
  124. errorStr := response.Error
  125. if errorStr != "" {
  126. return nil, errors.Errorf("Response error: %v", errorStr)
  127. }
  128. // unmarshal the RawMessage into the result
  129. err = json.Unmarshal(*response.Result, result)
  130. if err != nil {
  131. return nil, errors.Errorf("Error unmarshalling rpc response result: %v", err)
  132. }
  133. return result, nil
  134. }
  135. func argsToURLValues(args map[string]interface{}) (url.Values, error) {
  136. values := make(url.Values)
  137. if len(args) == 0 {
  138. return values, nil
  139. }
  140. err := argsToJson(args)
  141. if err != nil {
  142. return nil, err
  143. }
  144. for key, val := range args {
  145. values.Set(key, val.(string))
  146. }
  147. return values, nil
  148. }
  149. func argsToJson(args map[string]interface{}) error {
  150. for k, v := range args {
  151. rt := reflect.TypeOf(v)
  152. isByteSlice := rt.Kind() == reflect.Slice && rt.Elem().Kind() == reflect.Uint8
  153. if isByteSlice {
  154. bytes := reflect.ValueOf(v).Bytes()
  155. args[k] = fmt.Sprintf("0x%X", bytes)
  156. continue
  157. }
  158. // Pass everything else to go-wire
  159. data, err := json.Marshal(v)
  160. if err != nil {
  161. return err
  162. }
  163. args[k] = string(data)
  164. }
  165. return nil
  166. }