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.

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