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.

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