api.go 10.0 KB

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