api.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. "context"
  19. "fmt"
  20. "strings"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common/hexutil"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/metrics"
  25. "github.com/ethereum/go-ethereum/p2p"
  26. "github.com/ethereum/go-ethereum/p2p/discover"
  27. "github.com/ethereum/go-ethereum/rpc"
  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. // RemovePeer disconnects from a a remote node if the connection exists
  56. func (api *PrivateAdminAPI) RemovePeer(url string) (bool, error) {
  57. // Make sure the server is running, fail otherwise
  58. server := api.node.Server()
  59. if server == nil {
  60. return false, ErrNodeStopped
  61. }
  62. // Try to remove the url as a static peer and return
  63. node, err := discover.ParseNode(url)
  64. if err != nil {
  65. return false, fmt.Errorf("invalid enode: %v", err)
  66. }
  67. server.RemovePeer(node)
  68. return true, nil
  69. }
  70. // PeerEvents creates an RPC subscription which receives peer events from the
  71. // node's p2p.Server
  72. func (api *PrivateAdminAPI) PeerEvents(ctx context.Context) (*rpc.Subscription, error) {
  73. // Make sure the server is running, fail otherwise
  74. server := api.node.Server()
  75. if server == nil {
  76. return nil, ErrNodeStopped
  77. }
  78. // Create the subscription
  79. notifier, supported := rpc.NotifierFromContext(ctx)
  80. if !supported {
  81. return nil, rpc.ErrNotificationsUnsupported
  82. }
  83. rpcSub := notifier.CreateSubscription()
  84. go func() {
  85. events := make(chan *p2p.PeerEvent)
  86. sub := server.SubscribeEvents(events)
  87. defer sub.Unsubscribe()
  88. for {
  89. select {
  90. case event := <-events:
  91. notifier.Notify(rpcSub.ID, event)
  92. case <-sub.Err():
  93. return
  94. case <-rpcSub.Err():
  95. return
  96. case <-notifier.Closed():
  97. return
  98. }
  99. }
  100. }()
  101. return rpcSub, nil
  102. }
  103. // StartRPC starts the HTTP RPC API server.
  104. func (api *PrivateAdminAPI) StartRPC(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) {
  105. api.node.lock.Lock()
  106. defer api.node.lock.Unlock()
  107. if api.node.httpHandler != nil {
  108. return false, fmt.Errorf("HTTP RPC already running on %s", api.node.httpEndpoint)
  109. }
  110. if host == nil {
  111. h := DefaultHTTPHost
  112. if api.node.config.HTTPHost != "" {
  113. h = api.node.config.HTTPHost
  114. }
  115. host = &h
  116. }
  117. if port == nil {
  118. port = &api.node.config.HTTPPort
  119. }
  120. allowedOrigins := api.node.config.HTTPCors
  121. if cors != nil {
  122. allowedOrigins = nil
  123. for _, origin := range strings.Split(*cors, ",") {
  124. allowedOrigins = append(allowedOrigins, strings.TrimSpace(origin))
  125. }
  126. }
  127. allowedVHosts := api.node.config.HTTPVirtualHosts
  128. if vhosts != nil {
  129. allowedVHosts = nil
  130. for _, vhost := range strings.Split(*host, ",") {
  131. allowedVHosts = append(allowedVHosts, strings.TrimSpace(vhost))
  132. }
  133. }
  134. modules := api.node.httpWhitelist
  135. if apis != nil {
  136. modules = nil
  137. for _, m := range strings.Split(*apis, ",") {
  138. modules = append(modules, strings.TrimSpace(m))
  139. }
  140. }
  141. if err := api.node.startHTTP(fmt.Sprintf("%s:%d", *host, *port), api.node.rpcAPIs, modules, allowedOrigins, allowedVHosts); err != nil {
  142. return false, err
  143. }
  144. return true, nil
  145. }
  146. // StopRPC terminates an already running HTTP RPC API endpoint.
  147. func (api *PrivateAdminAPI) StopRPC() (bool, error) {
  148. api.node.lock.Lock()
  149. defer api.node.lock.Unlock()
  150. if api.node.httpHandler == nil {
  151. return false, fmt.Errorf("HTTP RPC not running")
  152. }
  153. api.node.stopHTTP()
  154. return true, nil
  155. }
  156. // StartWS starts the websocket RPC API server.
  157. func (api *PrivateAdminAPI) StartWS(host *string, port *int, allowedOrigins *string, apis *string) (bool, error) {
  158. api.node.lock.Lock()
  159. defer api.node.lock.Unlock()
  160. if api.node.wsHandler != nil {
  161. return false, fmt.Errorf("WebSocket RPC already running on %s", api.node.wsEndpoint)
  162. }
  163. if host == nil {
  164. h := DefaultWSHost
  165. if api.node.config.WSHost != "" {
  166. h = api.node.config.WSHost
  167. }
  168. host = &h
  169. }
  170. if port == nil {
  171. port = &api.node.config.WSPort
  172. }
  173. origins := api.node.config.WSOrigins
  174. if allowedOrigins != nil {
  175. origins = nil
  176. for _, origin := range strings.Split(*allowedOrigins, ",") {
  177. origins = append(origins, strings.TrimSpace(origin))
  178. }
  179. }
  180. modules := api.node.config.WSModules
  181. if apis != nil {
  182. modules = nil
  183. for _, m := range strings.Split(*apis, ",") {
  184. modules = append(modules, strings.TrimSpace(m))
  185. }
  186. }
  187. if err := api.node.startWS(fmt.Sprintf("%s:%d", *host, *port), api.node.rpcAPIs, modules, origins, api.node.config.WSExposeAll); err != nil {
  188. return false, err
  189. }
  190. return true, nil
  191. }
  192. // StopWS terminates an already running websocket RPC API endpoint.
  193. func (api *PrivateAdminAPI) StopWS() (bool, error) {
  194. api.node.lock.Lock()
  195. defer api.node.lock.Unlock()
  196. if api.node.wsHandler == nil {
  197. return false, fmt.Errorf("WebSocket RPC not running")
  198. }
  199. api.node.stopWS()
  200. return true, nil
  201. }
  202. // PublicAdminAPI is the collection of administrative API methods exposed over
  203. // both secure and unsecure RPC channels.
  204. type PublicAdminAPI struct {
  205. node *Node // Node interfaced by this API
  206. }
  207. // NewPublicAdminAPI creates a new API definition for the public admin methods
  208. // of the node itself.
  209. func NewPublicAdminAPI(node *Node) *PublicAdminAPI {
  210. return &PublicAdminAPI{node: node}
  211. }
  212. // Peers retrieves all the information we know about each individual peer at the
  213. // protocol granularity.
  214. func (api *PublicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
  215. server := api.node.Server()
  216. if server == nil {
  217. return nil, ErrNodeStopped
  218. }
  219. return server.PeersInfo(), nil
  220. }
  221. // NodeInfo retrieves all the information we know about the host node at the
  222. // protocol granularity.
  223. func (api *PublicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) {
  224. server := api.node.Server()
  225. if server == nil {
  226. return nil, ErrNodeStopped
  227. }
  228. return server.NodeInfo(), nil
  229. }
  230. // Datadir retrieves the current data directory the node is using.
  231. func (api *PublicAdminAPI) Datadir() string {
  232. return api.node.DataDir()
  233. }
  234. // PublicDebugAPI is the collection of debugging related API methods exposed over
  235. // both secure and unsecure RPC channels.
  236. type PublicDebugAPI struct {
  237. node *Node // Node interfaced by this API
  238. }
  239. // NewPublicDebugAPI creates a new API definition for the public debug methods
  240. // of the node itself.
  241. func NewPublicDebugAPI(node *Node) *PublicDebugAPI {
  242. return &PublicDebugAPI{node: node}
  243. }
  244. // Metrics retrieves all the known system metric collected by the node.
  245. func (api *PublicDebugAPI) Metrics(raw bool) (map[string]interface{}, error) {
  246. // Create a rate formatter
  247. units := []string{"", "K", "M", "G", "T", "E", "P"}
  248. round := func(value float64, prec int) string {
  249. unit := 0
  250. for value >= 1000 {
  251. unit, value, prec = unit+1, value/1000, 2
  252. }
  253. return fmt.Sprintf(fmt.Sprintf("%%.%df%s", prec, units[unit]), value)
  254. }
  255. format := func(total float64, rate float64) string {
  256. return fmt.Sprintf("%s (%s/s)", round(total, 0), round(rate, 2))
  257. }
  258. // Iterate over all the metrics, and just dump for now
  259. counters := make(map[string]interface{})
  260. metrics.DefaultRegistry.Each(func(name string, metric interface{}) {
  261. // Create or retrieve the counter hierarchy for this metric
  262. root, parts := counters, strings.Split(name, "/")
  263. for _, part := range parts[:len(parts)-1] {
  264. if _, ok := root[part]; !ok {
  265. root[part] = make(map[string]interface{})
  266. }
  267. root = root[part].(map[string]interface{})
  268. }
  269. name = parts[len(parts)-1]
  270. // Fill the counter with the metric details, formatting if requested
  271. if raw {
  272. switch metric := metric.(type) {
  273. case metrics.Counter:
  274. root[name] = map[string]interface{}{
  275. "Overall": float64(metric.Count()),
  276. }
  277. case metrics.Meter:
  278. root[name] = map[string]interface{}{
  279. "AvgRate01Min": metric.Rate1(),
  280. "AvgRate05Min": metric.Rate5(),
  281. "AvgRate15Min": metric.Rate15(),
  282. "MeanRate": metric.RateMean(),
  283. "Overall": float64(metric.Count()),
  284. }
  285. case metrics.Timer:
  286. root[name] = map[string]interface{}{
  287. "AvgRate01Min": metric.Rate1(),
  288. "AvgRate05Min": metric.Rate5(),
  289. "AvgRate15Min": metric.Rate15(),
  290. "MeanRate": metric.RateMean(),
  291. "Overall": float64(metric.Count()),
  292. "Percentiles": map[string]interface{}{
  293. "5": metric.Percentile(0.05),
  294. "20": metric.Percentile(0.2),
  295. "50": metric.Percentile(0.5),
  296. "80": metric.Percentile(0.8),
  297. "95": metric.Percentile(0.95),
  298. },
  299. }
  300. case metrics.ResettingTimer:
  301. t := metric.Snapshot()
  302. ps := t.Percentiles([]float64{5, 20, 50, 80, 95})
  303. root[name] = map[string]interface{}{
  304. "Measurements": len(t.Values()),
  305. "Mean": time.Duration(t.Mean()).String(),
  306. "Percentiles": map[string]interface{}{
  307. "5": time.Duration(ps[0]).String(),
  308. "20": time.Duration(ps[1]).String(),
  309. "50": time.Duration(ps[2]).String(),
  310. "80": time.Duration(ps[3]).String(),
  311. "95": time.Duration(ps[4]).String(),
  312. },
  313. }
  314. default:
  315. root[name] = "Unknown metric type"
  316. }
  317. } else {
  318. switch metric := metric.(type) {
  319. case metrics.Counter:
  320. root[name] = map[string]interface{}{
  321. "Overall": float64(metric.Count()),
  322. }
  323. case metrics.Meter:
  324. root[name] = map[string]interface{}{
  325. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  326. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  327. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  328. "Overall": format(float64(metric.Count()), metric.RateMean()),
  329. }
  330. case metrics.Timer:
  331. root[name] = map[string]interface{}{
  332. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  333. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  334. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  335. "Overall": format(float64(metric.Count()), metric.RateMean()),
  336. "Maximum": time.Duration(metric.Max()).String(),
  337. "Minimum": time.Duration(metric.Min()).String(),
  338. "Percentiles": map[string]interface{}{
  339. "5": time.Duration(metric.Percentile(0.05)).String(),
  340. "20": time.Duration(metric.Percentile(0.2)).String(),
  341. "50": time.Duration(metric.Percentile(0.5)).String(),
  342. "80": time.Duration(metric.Percentile(0.8)).String(),
  343. "95": time.Duration(metric.Percentile(0.95)).String(),
  344. },
  345. }
  346. case metrics.ResettingTimer:
  347. t := metric.Snapshot()
  348. ps := t.Percentiles([]float64{5, 20, 50, 80, 95})
  349. root[name] = map[string]interface{}{
  350. "Measurements": len(t.Values()),
  351. "Mean": time.Duration(t.Mean()).String(),
  352. "Percentiles": map[string]interface{}{
  353. "5": time.Duration(ps[0]).String(),
  354. "20": time.Duration(ps[1]).String(),
  355. "50": time.Duration(ps[2]).String(),
  356. "80": time.Duration(ps[3]).String(),
  357. "95": time.Duration(ps[4]).String(),
  358. },
  359. }
  360. default:
  361. root[name] = "Unknown metric type"
  362. }
  363. }
  364. })
  365. return counters, nil
  366. }
  367. // PublicWeb3API offers helper utils
  368. type PublicWeb3API struct {
  369. stack *Node
  370. }
  371. // NewPublicWeb3API creates a new Web3Service instance
  372. func NewPublicWeb3API(stack *Node) *PublicWeb3API {
  373. return &PublicWeb3API{stack}
  374. }
  375. // ClientVersion returns the node name
  376. func (s *PublicWeb3API) ClientVersion() string {
  377. return s.stack.Server().Name
  378. }
  379. // Sha3 applies the ethereum sha3 implementation on the input.
  380. // It assumes the input is hex encoded.
  381. func (s *PublicWeb3API) Sha3(input hexutil.Bytes) hexutil.Bytes {
  382. return crypto.Keccak256(input)
  383. }