api.go 10 KB

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