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.

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