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