api.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. )
  28. // PrivateAdminAPI is the collection of administrative API methods exposed only
  29. // over a secure RPC channel.
  30. type PrivateAdminAPI struct {
  31. node *Node // Node interfaced by this API
  32. }
  33. // NewPrivateAdminAPI creates a new API definition for the private admin methods
  34. // of the node itself.
  35. func NewPrivateAdminAPI(node *Node) *PrivateAdminAPI {
  36. return &PrivateAdminAPI{node: node}
  37. }
  38. // AddPeer requests connecting to a remote node, and also maintaining the new
  39. // connection at all times, even reconnecting if it is lost.
  40. func (api *PrivateAdminAPI) AddPeer(url string) (bool, error) {
  41. // Make sure the server is running, fail otherwise
  42. server := api.node.Server()
  43. if server == nil {
  44. return false, ErrNodeStopped
  45. }
  46. // Try to add the url as a static peer and return
  47. node, err := discover.ParseNode(url)
  48. if err != nil {
  49. return false, fmt.Errorf("invalid enode: %v", err)
  50. }
  51. server.AddPeer(node)
  52. return true, nil
  53. }
  54. // StartRPC starts the HTTP RPC API server.
  55. func (api *PrivateAdminAPI) StartRPC(host *string, port *rpc.HexNumber, cors *string, apis *string) (bool, error) {
  56. api.node.lock.Lock()
  57. defer api.node.lock.Unlock()
  58. if api.node.httpHandler != nil {
  59. return false, fmt.Errorf("HTTP RPC already running on %s", api.node.httpEndpoint)
  60. }
  61. if host == nil {
  62. host = &api.node.httpHost
  63. }
  64. if port == nil {
  65. port = rpc.NewHexNumber(api.node.httpPort)
  66. }
  67. if cors == nil {
  68. cors = &api.node.httpCors
  69. }
  70. modules := api.node.httpWhitelist
  71. if apis != nil {
  72. modules = nil
  73. for _, m := range strings.Split(*apis, ",") {
  74. modules = append(modules, strings.TrimSpace(m))
  75. }
  76. }
  77. if err := api.node.startHTTP(fmt.Sprintf("%s:%d", *host, port.Int()), api.node.rpcAPIs, modules, *cors); err != nil {
  78. return false, err
  79. }
  80. return true, nil
  81. }
  82. // StopRPC terminates an already running HTTP RPC API endpoint.
  83. func (api *PrivateAdminAPI) StopRPC() (bool, error) {
  84. api.node.lock.Lock()
  85. defer api.node.lock.Unlock()
  86. if api.node.httpHandler == nil {
  87. return false, fmt.Errorf("HTTP RPC not running")
  88. }
  89. api.node.stopHTTP()
  90. return true, nil
  91. }
  92. // StartWS starts the websocket RPC API server.
  93. func (api *PrivateAdminAPI) StartWS(host *string, port *rpc.HexNumber, allowedOrigins *string, apis *string) (bool, error) {
  94. api.node.lock.Lock()
  95. defer api.node.lock.Unlock()
  96. if api.node.wsHandler != nil {
  97. return false, fmt.Errorf("WebSocket RPC already running on %s", api.node.wsEndpoint)
  98. }
  99. if host == nil {
  100. host = &api.node.wsHost
  101. }
  102. if port == nil {
  103. port = rpc.NewHexNumber(api.node.wsPort)
  104. }
  105. if allowedOrigins == nil {
  106. allowedOrigins = &api.node.wsOrigins
  107. }
  108. modules := api.node.wsWhitelist
  109. if apis != nil {
  110. modules = nil
  111. for _, m := range strings.Split(*apis, ",") {
  112. modules = append(modules, strings.TrimSpace(m))
  113. }
  114. }
  115. if err := api.node.startWS(fmt.Sprintf("%s:%d", *host, port.Int()), api.node.rpcAPIs, modules, *allowedOrigins); err != nil {
  116. return false, err
  117. }
  118. return true, nil
  119. }
  120. // StopRPC terminates an already running websocket RPC API endpoint.
  121. func (api *PrivateAdminAPI) StopWS() (bool, error) {
  122. api.node.lock.Lock()
  123. defer api.node.lock.Unlock()
  124. if api.node.wsHandler == nil {
  125. return false, fmt.Errorf("WebSocket RPC not running")
  126. }
  127. api.node.stopWS()
  128. return true, nil
  129. }
  130. // PublicAdminAPI is the collection of administrative API methods exposed over
  131. // both secure and unsecure RPC channels.
  132. type PublicAdminAPI struct {
  133. node *Node // Node interfaced by this API
  134. }
  135. // NewPublicAdminAPI creates a new API definition for the public admin methods
  136. // of the node itself.
  137. func NewPublicAdminAPI(node *Node) *PublicAdminAPI {
  138. return &PublicAdminAPI{node: node}
  139. }
  140. // Peers retrieves all the information we know about each individual peer at the
  141. // protocol granularity.
  142. func (api *PublicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
  143. server := api.node.Server()
  144. if server == nil {
  145. return nil, ErrNodeStopped
  146. }
  147. return server.PeersInfo(), nil
  148. }
  149. // NodeInfo retrieves all the information we know about the host node at the
  150. // protocol granularity.
  151. func (api *PublicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) {
  152. server := api.node.Server()
  153. if server == nil {
  154. return nil, ErrNodeStopped
  155. }
  156. return server.NodeInfo(), nil
  157. }
  158. // Datadir retrieves the current data directory the node is using.
  159. func (api *PublicAdminAPI) Datadir() string {
  160. return api.node.DataDir()
  161. }
  162. // PublicDebugAPI is the collection of debugging related API methods exposed over
  163. // both secure and unsecure RPC channels.
  164. type PublicDebugAPI struct {
  165. node *Node // Node interfaced by this API
  166. }
  167. // NewPublicDebugAPI creates a new API definition for the public debug methods
  168. // of the node itself.
  169. func NewPublicDebugAPI(node *Node) *PublicDebugAPI {
  170. return &PublicDebugAPI{node: node}
  171. }
  172. // Metrics retrieves all the known system metric collected by the node.
  173. func (api *PublicDebugAPI) Metrics(raw bool) (map[string]interface{}, error) {
  174. // Create a rate formatter
  175. units := []string{"", "K", "M", "G", "T", "E", "P"}
  176. round := func(value float64, prec int) string {
  177. unit := 0
  178. for value >= 1000 {
  179. unit, value, prec = unit+1, value/1000, 2
  180. }
  181. return fmt.Sprintf(fmt.Sprintf("%%.%df%s", prec, units[unit]), value)
  182. }
  183. format := func(total float64, rate float64) string {
  184. return fmt.Sprintf("%s (%s/s)", round(total, 0), round(rate, 2))
  185. }
  186. // Iterate over all the metrics, and just dump for now
  187. counters := make(map[string]interface{})
  188. metrics.DefaultRegistry.Each(func(name string, metric interface{}) {
  189. // Create or retrieve the counter hierarchy for this metric
  190. root, parts := counters, strings.Split(name, "/")
  191. for _, part := range parts[:len(parts)-1] {
  192. if _, ok := root[part]; !ok {
  193. root[part] = make(map[string]interface{})
  194. }
  195. root = root[part].(map[string]interface{})
  196. }
  197. name = parts[len(parts)-1]
  198. // Fill the counter with the metric details, formatting if requested
  199. if raw {
  200. switch metric := metric.(type) {
  201. case metrics.Meter:
  202. root[name] = map[string]interface{}{
  203. "AvgRate01Min": metric.Rate1(),
  204. "AvgRate05Min": metric.Rate5(),
  205. "AvgRate15Min": metric.Rate15(),
  206. "MeanRate": metric.RateMean(),
  207. "Overall": float64(metric.Count()),
  208. }
  209. case metrics.Timer:
  210. root[name] = map[string]interface{}{
  211. "AvgRate01Min": metric.Rate1(),
  212. "AvgRate05Min": metric.Rate5(),
  213. "AvgRate15Min": metric.Rate15(),
  214. "MeanRate": metric.RateMean(),
  215. "Overall": float64(metric.Count()),
  216. "Percentiles": map[string]interface{}{
  217. "5": metric.Percentile(0.05),
  218. "20": metric.Percentile(0.2),
  219. "50": metric.Percentile(0.5),
  220. "80": metric.Percentile(0.8),
  221. "95": metric.Percentile(0.95),
  222. },
  223. }
  224. default:
  225. root[name] = "Unknown metric type"
  226. }
  227. } else {
  228. switch metric := metric.(type) {
  229. case metrics.Meter:
  230. root[name] = map[string]interface{}{
  231. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  232. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  233. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  234. "Overall": format(float64(metric.Count()), metric.RateMean()),
  235. }
  236. case metrics.Timer:
  237. root[name] = map[string]interface{}{
  238. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  239. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  240. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  241. "Overall": format(float64(metric.Count()), metric.RateMean()),
  242. "Maximum": time.Duration(metric.Max()).String(),
  243. "Minimum": time.Duration(metric.Min()).String(),
  244. "Percentiles": map[string]interface{}{
  245. "5": time.Duration(metric.Percentile(0.05)).String(),
  246. "20": time.Duration(metric.Percentile(0.2)).String(),
  247. "50": time.Duration(metric.Percentile(0.5)).String(),
  248. "80": time.Duration(metric.Percentile(0.8)).String(),
  249. "95": time.Duration(metric.Percentile(0.95)).String(),
  250. },
  251. }
  252. default:
  253. root[name] = "Unknown metric type"
  254. }
  255. }
  256. })
  257. return counters, nil
  258. }
  259. // PublicWeb3API offers helper utils
  260. type PublicWeb3API struct {
  261. stack *Node
  262. }
  263. // NewPublicWeb3API creates a new Web3Service instance
  264. func NewPublicWeb3API(stack *Node) *PublicWeb3API {
  265. return &PublicWeb3API{stack}
  266. }
  267. // ClientVersion returns the node name
  268. func (s *PublicWeb3API) ClientVersion() string {
  269. return s.stack.Server().Name
  270. }
  271. // Sha3 applies the ethereum sha3 implementation on the input.
  272. // It assumes the input is hex encoded.
  273. func (s *PublicWeb3API) Sha3(input string) string {
  274. return common.ToHex(crypto.Keccak256(common.FromHex(input)))
  275. }