api.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package node
  17. import (
  18. "fmt"
  19. "strings"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/p2p"
  24. "github.com/ethereum/go-ethereum/p2p/discover"
  25. "github.com/ethereum/go-ethereum/rpc"
  26. "github.com/rcrowley/go-metrics"
  27. "gopkg.in/fatih/set.v0"
  28. )
  29. // PrivateAdminAPI is the collection of administrative API methods exposed only
  30. // over a secure RPC channel.
  31. type PrivateAdminAPI struct {
  32. node *Node // Node interfaced by this API
  33. }
  34. // NewPrivateAdminAPI creates a new API definition for the private admin methods
  35. // of the node itself.
  36. func NewPrivateAdminAPI(node *Node) *PrivateAdminAPI {
  37. return &PrivateAdminAPI{node: node}
  38. }
  39. // AddPeer requests connecting to a remote node, and also maintaining the new
  40. // connection at all times, even reconnecting if it is lost.
  41. func (api *PrivateAdminAPI) AddPeer(url string) (bool, error) {
  42. // Make sure the server is running, fail otherwise
  43. server := api.node.Server()
  44. if server == nil {
  45. return false, ErrNodeStopped
  46. }
  47. // Try to add the url as a static peer and return
  48. node, err := discover.ParseNode(url)
  49. if err != nil {
  50. return false, fmt.Errorf("invalid enode: %v", err)
  51. }
  52. server.AddPeer(node)
  53. return true, nil
  54. }
  55. // StartRPC starts the HTTP RPC API server.
  56. func (api *PrivateAdminAPI) StartRPC(host string, port int, cors string, apis string) (bool, error) {
  57. api.node.lock.Lock()
  58. defer api.node.lock.Unlock()
  59. if api.node.httpHandler != nil {
  60. return false, fmt.Errorf("HTTP RPC already running on %s", api.node.httpEndpoint)
  61. }
  62. if err := api.node.startHTTP(fmt.Sprintf("%s:%d", host, port), api.node.rpcAPIs, strings.Split(apis, ","), cors); err != nil {
  63. return false, err
  64. }
  65. return true, nil
  66. }
  67. // StopRPC terminates an already running HTTP RPC API endpoint.
  68. func (api *PrivateAdminAPI) StopRPC() (bool, error) {
  69. api.node.lock.Lock()
  70. defer api.node.lock.Unlock()
  71. if api.node.httpHandler == nil {
  72. return false, fmt.Errorf("HTTP RPC not running")
  73. }
  74. api.node.stopHTTP()
  75. return true, nil
  76. }
  77. // StartWS starts the websocket RPC API server.
  78. func (api *PrivateAdminAPI) StartWS(address string, port int, cors string, apis string) (bool, error) {
  79. var offeredAPIs []rpc.API
  80. if len(apis) > 0 {
  81. namespaces := set.New()
  82. for _, a := range strings.Split(apis, ",") {
  83. namespaces.Add(strings.TrimSpace(a))
  84. }
  85. for _, api := range api.node.APIs() {
  86. if namespaces.Has(api.Namespace) {
  87. offeredAPIs = append(offeredAPIs, api)
  88. }
  89. }
  90. } else {
  91. // use by default all public API's
  92. for _, api := range api.node.APIs() {
  93. if api.Public {
  94. offeredAPIs = append(offeredAPIs, api)
  95. }
  96. }
  97. }
  98. if address == "" {
  99. address = "127.0.0.1"
  100. }
  101. if port == 0 {
  102. port = 8546
  103. }
  104. corsDomains := strings.Split(cors, " ")
  105. err := rpc.StartWS(address, port, corsDomains, offeredAPIs)
  106. return err == nil, err
  107. }
  108. // StopRPC terminates an already running websocket RPC API endpoint.
  109. func (api *PrivateAdminAPI) StopWS() (bool, error) {
  110. err := rpc.StopWS()
  111. return err == nil, err
  112. }
  113. // PublicAdminAPI is the collection of administrative API methods exposed over
  114. // both secure and unsecure RPC channels.
  115. type PublicAdminAPI struct {
  116. node *Node // Node interfaced by this API
  117. }
  118. // NewPublicAdminAPI creates a new API definition for the public admin methods
  119. // of the node itself.
  120. func NewPublicAdminAPI(node *Node) *PublicAdminAPI {
  121. return &PublicAdminAPI{node: node}
  122. }
  123. // Peers retrieves all the information we know about each individual peer at the
  124. // protocol granularity.
  125. func (api *PublicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
  126. server := api.node.Server()
  127. if server == nil {
  128. return nil, ErrNodeStopped
  129. }
  130. return server.PeersInfo(), nil
  131. }
  132. // NodeInfo retrieves all the information we know about the host node at the
  133. // protocol granularity.
  134. func (api *PublicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) {
  135. server := api.node.Server()
  136. if server == nil {
  137. return nil, ErrNodeStopped
  138. }
  139. return server.NodeInfo(), nil
  140. }
  141. // Datadir retrieves the current data directory the node is using.
  142. func (api *PublicAdminAPI) Datadir() string {
  143. return api.node.DataDir()
  144. }
  145. // PublicDebugAPI is the collection of debugging related API methods exposed over
  146. // both secure and unsecure RPC channels.
  147. type PublicDebugAPI struct {
  148. node *Node // Node interfaced by this API
  149. }
  150. // NewPublicDebugAPI creates a new API definition for the public debug methods
  151. // of the node itself.
  152. func NewPublicDebugAPI(node *Node) *PublicDebugAPI {
  153. return &PublicDebugAPI{node: node}
  154. }
  155. // Metrics retrieves all the known system metric collected by the node.
  156. func (api *PublicDebugAPI) Metrics(raw bool) (map[string]interface{}, error) {
  157. // Create a rate formatter
  158. units := []string{"", "K", "M", "G", "T", "E", "P"}
  159. round := func(value float64, prec int) string {
  160. unit := 0
  161. for value >= 1000 {
  162. unit, value, prec = unit+1, value/1000, 2
  163. }
  164. return fmt.Sprintf(fmt.Sprintf("%%.%df%s", prec, units[unit]), value)
  165. }
  166. format := func(total float64, rate float64) string {
  167. return fmt.Sprintf("%s (%s/s)", round(total, 0), round(rate, 2))
  168. }
  169. // Iterate over all the metrics, and just dump for now
  170. counters := make(map[string]interface{})
  171. metrics.DefaultRegistry.Each(func(name string, metric interface{}) {
  172. // Create or retrieve the counter hierarchy for this metric
  173. root, parts := counters, strings.Split(name, "/")
  174. for _, part := range parts[:len(parts)-1] {
  175. if _, ok := root[part]; !ok {
  176. root[part] = make(map[string]interface{})
  177. }
  178. root = root[part].(map[string]interface{})
  179. }
  180. name = parts[len(parts)-1]
  181. // Fill the counter with the metric details, formatting if requested
  182. if raw {
  183. switch metric := metric.(type) {
  184. case metrics.Meter:
  185. root[name] = map[string]interface{}{
  186. "AvgRate01Min": metric.Rate1(),
  187. "AvgRate05Min": metric.Rate5(),
  188. "AvgRate15Min": metric.Rate15(),
  189. "MeanRate": metric.RateMean(),
  190. "Overall": float64(metric.Count()),
  191. }
  192. case metrics.Timer:
  193. root[name] = map[string]interface{}{
  194. "AvgRate01Min": metric.Rate1(),
  195. "AvgRate05Min": metric.Rate5(),
  196. "AvgRate15Min": metric.Rate15(),
  197. "MeanRate": metric.RateMean(),
  198. "Overall": float64(metric.Count()),
  199. "Percentiles": map[string]interface{}{
  200. "5": metric.Percentile(0.05),
  201. "20": metric.Percentile(0.2),
  202. "50": metric.Percentile(0.5),
  203. "80": metric.Percentile(0.8),
  204. "95": metric.Percentile(0.95),
  205. },
  206. }
  207. default:
  208. root[name] = "Unknown metric type"
  209. }
  210. } else {
  211. switch metric := metric.(type) {
  212. case metrics.Meter:
  213. root[name] = map[string]interface{}{
  214. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  215. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  216. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  217. "Overall": format(float64(metric.Count()), metric.RateMean()),
  218. }
  219. case metrics.Timer:
  220. root[name] = map[string]interface{}{
  221. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  222. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  223. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  224. "Overall": format(float64(metric.Count()), metric.RateMean()),
  225. "Maximum": time.Duration(metric.Max()).String(),
  226. "Minimum": time.Duration(metric.Min()).String(),
  227. "Percentiles": map[string]interface{}{
  228. "5": time.Duration(metric.Percentile(0.05)).String(),
  229. "20": time.Duration(metric.Percentile(0.2)).String(),
  230. "50": time.Duration(metric.Percentile(0.5)).String(),
  231. "80": time.Duration(metric.Percentile(0.8)).String(),
  232. "95": time.Duration(metric.Percentile(0.95)).String(),
  233. },
  234. }
  235. default:
  236. root[name] = "Unknown metric type"
  237. }
  238. }
  239. })
  240. return counters, nil
  241. }
  242. // PublicWeb3API offers helper utils
  243. type PublicWeb3API struct {
  244. stack *Node
  245. }
  246. // NewPublicWeb3API creates a new Web3Service instance
  247. func NewPublicWeb3API(stack *Node) *PublicWeb3API {
  248. return &PublicWeb3API{stack}
  249. }
  250. // ClientVersion returns the node name
  251. func (s *PublicWeb3API) ClientVersion() string {
  252. return s.stack.Server().Name
  253. }
  254. // Sha3 applies the ethereum sha3 implementation on the input.
  255. // It assumes the input is hex encoded.
  256. func (s *PublicWeb3API) Sha3(input string) string {
  257. return common.ToHex(crypto.Sha3(common.FromHex(input)))
  258. }