api.go 13 KB

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