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.

197 lines
5.2 KiB

  1. package rpcclient
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "reflect"
  12. "strings"
  13. . "github.com/tendermint/go-common"
  14. "github.com/tendermint/go-rpc/types"
  15. "github.com/tendermint/go-wire"
  16. )
  17. // TODO: Deprecate support for IP:PORT or /path/to/socket
  18. func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, error)) {
  19. parts := strings.SplitN(remoteAddr, "://", 2)
  20. var protocol, address string
  21. if len(parts) != 2 {
  22. log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix")
  23. protocol = rpctypes.SocketType(remoteAddr)
  24. address = remoteAddr
  25. } else {
  26. protocol, address = parts[0], parts[1]
  27. }
  28. trimmedAddress := strings.Replace(address, "/", ".", -1) // replace / with . for http requests (dummy domain)
  29. return trimmedAddress, func(proto, addr string) (net.Conn, error) {
  30. return net.Dial(protocol, address)
  31. }
  32. }
  33. // We overwrite the http.Client.Dial so we can do http over tcp or unix.
  34. // remoteAddr should be fully featured (eg. with tcp:// or unix://)
  35. func makeHTTPClient(remoteAddr string) (string, *http.Client) {
  36. address, dialer := makeHTTPDialer(remoteAddr)
  37. return "http://" + address, &http.Client{
  38. Transport: &http.Transport{
  39. Dial: dialer,
  40. },
  41. }
  42. }
  43. //------------------------------------------------------------------------------------
  44. type Client interface {
  45. }
  46. //------------------------------------------------------------------------------------
  47. // JSON rpc takes params as a slice
  48. type ClientJSONRPC struct {
  49. address string
  50. client *http.Client
  51. }
  52. func NewClientJSONRPC(remote string) *ClientJSONRPC {
  53. address, client := makeHTTPClient(remote)
  54. return &ClientJSONRPC{
  55. address: address,
  56. client: client,
  57. }
  58. }
  59. func (c *ClientJSONRPC) Call(method string, params []interface{}, result interface{}) (interface{}, error) {
  60. return c.call(method, params, result)
  61. }
  62. func (c *ClientJSONRPC) call(method string, params []interface{}, result interface{}) (interface{}, error) {
  63. // Make request and get responseBytes
  64. request := rpctypes.RPCRequest{
  65. JSONRPC: "2.0",
  66. Method: method,
  67. Params: params,
  68. ID: "",
  69. }
  70. requestBytes := wire.JSONBytes(request)
  71. requestBuf := bytes.NewBuffer(requestBytes)
  72. // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes)))
  73. httpResponse, err := c.client.Post(c.address, "text/json", requestBuf)
  74. if err != nil {
  75. return nil, err
  76. }
  77. defer httpResponse.Body.Close()
  78. responseBytes, err := ioutil.ReadAll(httpResponse.Body)
  79. if err != nil {
  80. return nil, err
  81. }
  82. // log.Info(Fmt("RPC response: %v", string(responseBytes)))
  83. return unmarshalResponseBytes(responseBytes, result)
  84. }
  85. //-------------------------------------------------------------
  86. // URI takes params as a map
  87. type ClientURI struct {
  88. address string
  89. client *http.Client
  90. }
  91. func NewClientURI(remote string) *ClientURI {
  92. address, client := makeHTTPClient(remote)
  93. return &ClientURI{
  94. address: address,
  95. client: client,
  96. }
  97. }
  98. func (c *ClientURI) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  99. return c.call(method, params, result)
  100. }
  101. func (c *ClientURI) call(method string, params map[string]interface{}, result interface{}) (interface{}, error) {
  102. values, err := argsToURLValues(params)
  103. if err != nil {
  104. return nil, err
  105. }
  106. // log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values))
  107. resp, err := c.client.PostForm(c.address+"/"+method, values)
  108. if err != nil {
  109. return nil, err
  110. }
  111. defer resp.Body.Close()
  112. responseBytes, err := ioutil.ReadAll(resp.Body)
  113. if err != nil {
  114. return nil, err
  115. }
  116. return unmarshalResponseBytes(responseBytes, result)
  117. }
  118. //------------------------------------------------
  119. func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface{}, error) {
  120. // read response
  121. // if rpc/core/types is imported, the result will unmarshal
  122. // into the correct type
  123. // log.Notice("response", "response", string(responseBytes))
  124. var err error
  125. response := &rpctypes.RPCResponse{}
  126. err = json.Unmarshal(responseBytes, response)
  127. if err != nil {
  128. return nil, errors.New(Fmt("Error unmarshalling rpc response: %v", err))
  129. }
  130. errorStr := response.Error
  131. if errorStr != "" {
  132. return nil, errors.New(Fmt("Response error: %v", errorStr))
  133. }
  134. // unmarshal the RawMessage into the result
  135. result = wire.ReadJSONPtr(result, *response.Result, &err)
  136. if err != nil {
  137. return nil, errors.New(Fmt("Error unmarshalling rpc response result: %v", err))
  138. }
  139. return result, nil
  140. }
  141. func argsToURLValues(args map[string]interface{}) (url.Values, error) {
  142. values := make(url.Values)
  143. if len(args) == 0 {
  144. return values, nil
  145. }
  146. err := argsToJson(args)
  147. if err != nil {
  148. return nil, err
  149. }
  150. for key, val := range args {
  151. values.Set(key, val.(string))
  152. }
  153. return values, nil
  154. }
  155. func argsToJson(args map[string]interface{}) error {
  156. var n int
  157. var err error
  158. for k, v := range args {
  159. // Convert byte slices to "0x"-prefixed hex
  160. byteSlice, isByteSlice := reflect.ValueOf(v).Interface().([]byte)
  161. if isByteSlice {
  162. args[k] = fmt.Sprintf("0x%X", byteSlice)
  163. continue
  164. }
  165. // Pass everything else to go-wire
  166. buf := new(bytes.Buffer)
  167. wire.WriteJSON(v, buf, &n, &err)
  168. if err != nil {
  169. return err
  170. }
  171. args[k] = buf.String()
  172. }
  173. return nil
  174. }