api.go 9.6 KB

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