api.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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/p2p"
  25. "github.com/ethereum/go-ethereum/p2p/discover"
  26. "github.com/ethereum/go-ethereum/rpc"
  27. "github.com/rcrowley/go-metrics"
  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) (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. modules := api.node.httpWhitelist
  128. if apis != nil {
  129. modules = nil
  130. for _, m := range strings.Split(*apis, ",") {
  131. modules = append(modules, strings.TrimSpace(m))
  132. }
  133. }
  134. if err := api.node.startHTTP(fmt.Sprintf("%s:%d", *host, *port), api.node.rpcAPIs, modules, allowedOrigins); err != nil {
  135. return false, err
  136. }
  137. return true, nil
  138. }
  139. // StopRPC terminates an already running HTTP RPC API endpoint.
  140. func (api *PrivateAdminAPI) StopRPC() (bool, error) {
  141. api.node.lock.Lock()
  142. defer api.node.lock.Unlock()
  143. if api.node.httpHandler == nil {
  144. return false, fmt.Errorf("HTTP RPC not running")
  145. }
  146. api.node.stopHTTP()
  147. return true, nil
  148. }
  149. // StartWS starts the websocket RPC API server.
  150. func (api *PrivateAdminAPI) StartWS(host *string, port *int, allowedOrigins *string, apis *string) (bool, error) {
  151. api.node.lock.Lock()
  152. defer api.node.lock.Unlock()
  153. if api.node.wsHandler != nil {
  154. return false, fmt.Errorf("WebSocket RPC already running on %s", api.node.wsEndpoint)
  155. }
  156. if host == nil {
  157. h := DefaultWSHost
  158. if api.node.config.WSHost != "" {
  159. h = api.node.config.WSHost
  160. }
  161. host = &h
  162. }
  163. if port == nil {
  164. port = &api.node.config.WSPort
  165. }
  166. origins := api.node.config.WSOrigins
  167. if allowedOrigins != nil {
  168. origins = nil
  169. for _, origin := range strings.Split(*allowedOrigins, ",") {
  170. origins = append(origins, strings.TrimSpace(origin))
  171. }
  172. }
  173. modules := api.node.config.WSModules
  174. if apis != nil {
  175. modules = nil
  176. for _, m := range strings.Split(*apis, ",") {
  177. modules = append(modules, strings.TrimSpace(m))
  178. }
  179. }
  180. if err := api.node.startWS(fmt.Sprintf("%s:%d", *host, *port), api.node.rpcAPIs, modules, origins, api.node.config.WSExposeAll); err != nil {
  181. return false, err
  182. }
  183. return true, nil
  184. }
  185. // StopRPC terminates an already running websocket RPC API endpoint.
  186. func (api *PrivateAdminAPI) StopWS() (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 not running")
  191. }
  192. api.node.stopWS()
  193. return true, nil
  194. }
  195. // PublicAdminAPI is the collection of administrative API methods exposed over
  196. // both secure and unsecure RPC channels.
  197. type PublicAdminAPI struct {
  198. node *Node // Node interfaced by this API
  199. }
  200. // NewPublicAdminAPI creates a new API definition for the public admin methods
  201. // of the node itself.
  202. func NewPublicAdminAPI(node *Node) *PublicAdminAPI {
  203. return &PublicAdminAPI{node: node}
  204. }
  205. // Peers retrieves all the information we know about each individual peer at the
  206. // protocol granularity.
  207. func (api *PublicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
  208. server := api.node.Server()
  209. if server == nil {
  210. return nil, ErrNodeStopped
  211. }
  212. return server.PeersInfo(), nil
  213. }
  214. // NodeInfo retrieves all the information we know about the host node at the
  215. // protocol granularity.
  216. func (api *PublicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) {
  217. server := api.node.Server()
  218. if server == nil {
  219. return nil, ErrNodeStopped
  220. }
  221. return server.NodeInfo(), nil
  222. }
  223. // Datadir retrieves the current data directory the node is using.
  224. func (api *PublicAdminAPI) Datadir() string {
  225. return api.node.DataDir()
  226. }
  227. // PublicDebugAPI is the collection of debugging related API methods exposed over
  228. // both secure and unsecure RPC channels.
  229. type PublicDebugAPI struct {
  230. node *Node // Node interfaced by this API
  231. }
  232. // NewPublicDebugAPI creates a new API definition for the public debug methods
  233. // of the node itself.
  234. func NewPublicDebugAPI(node *Node) *PublicDebugAPI {
  235. return &PublicDebugAPI{node: node}
  236. }
  237. // Metrics retrieves all the known system metric collected by the node.
  238. func (api *PublicDebugAPI) Metrics(raw bool) (map[string]interface{}, error) {
  239. // Create a rate formatter
  240. units := []string{"", "K", "M", "G", "T", "E", "P"}
  241. round := func(value float64, prec int) string {
  242. unit := 0
  243. for value >= 1000 {
  244. unit, value, prec = unit+1, value/1000, 2
  245. }
  246. return fmt.Sprintf(fmt.Sprintf("%%.%df%s", prec, units[unit]), value)
  247. }
  248. format := func(total float64, rate float64) string {
  249. return fmt.Sprintf("%s (%s/s)", round(total, 0), round(rate, 2))
  250. }
  251. // Iterate over all the metrics, and just dump for now
  252. counters := make(map[string]interface{})
  253. metrics.DefaultRegistry.Each(func(name string, metric interface{}) {
  254. // Create or retrieve the counter hierarchy for this metric
  255. root, parts := counters, strings.Split(name, "/")
  256. for _, part := range parts[:len(parts)-1] {
  257. if _, ok := root[part]; !ok {
  258. root[part] = make(map[string]interface{})
  259. }
  260. root = root[part].(map[string]interface{})
  261. }
  262. name = parts[len(parts)-1]
  263. // Fill the counter with the metric details, formatting if requested
  264. if raw {
  265. switch metric := metric.(type) {
  266. case metrics.Meter:
  267. root[name] = map[string]interface{}{
  268. "AvgRate01Min": metric.Rate1(),
  269. "AvgRate05Min": metric.Rate5(),
  270. "AvgRate15Min": metric.Rate15(),
  271. "MeanRate": metric.RateMean(),
  272. "Overall": float64(metric.Count()),
  273. }
  274. case metrics.Timer:
  275. root[name] = map[string]interface{}{
  276. "AvgRate01Min": metric.Rate1(),
  277. "AvgRate05Min": metric.Rate5(),
  278. "AvgRate15Min": metric.Rate15(),
  279. "MeanRate": metric.RateMean(),
  280. "Overall": float64(metric.Count()),
  281. "Percentiles": map[string]interface{}{
  282. "5": metric.Percentile(0.05),
  283. "20": metric.Percentile(0.2),
  284. "50": metric.Percentile(0.5),
  285. "80": metric.Percentile(0.8),
  286. "95": metric.Percentile(0.95),
  287. },
  288. }
  289. default:
  290. root[name] = "Unknown metric type"
  291. }
  292. } else {
  293. switch metric := metric.(type) {
  294. case metrics.Meter:
  295. root[name] = map[string]interface{}{
  296. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  297. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  298. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  299. "Overall": format(float64(metric.Count()), metric.RateMean()),
  300. }
  301. case metrics.Timer:
  302. root[name] = map[string]interface{}{
  303. "Avg01Min": format(metric.Rate1()*60, metric.Rate1()),
  304. "Avg05Min": format(metric.Rate5()*300, metric.Rate5()),
  305. "Avg15Min": format(metric.Rate15()*900, metric.Rate15()),
  306. "Overall": format(float64(metric.Count()), metric.RateMean()),
  307. "Maximum": time.Duration(metric.Max()).String(),
  308. "Minimum": time.Duration(metric.Min()).String(),
  309. "Percentiles": map[string]interface{}{
  310. "5": time.Duration(metric.Percentile(0.05)).String(),
  311. "20": time.Duration(metric.Percentile(0.2)).String(),
  312. "50": time.Duration(metric.Percentile(0.5)).String(),
  313. "80": time.Duration(metric.Percentile(0.8)).String(),
  314. "95": time.Duration(metric.Percentile(0.95)).String(),
  315. },
  316. }
  317. default:
  318. root[name] = "Unknown metric type"
  319. }
  320. }
  321. })
  322. return counters, nil
  323. }
  324. // PublicWeb3API offers helper utils
  325. type PublicWeb3API struct {
  326. stack *Node
  327. }
  328. // NewPublicWeb3API creates a new Web3Service instance
  329. func NewPublicWeb3API(stack *Node) *PublicWeb3API {
  330. return &PublicWeb3API{stack}
  331. }
  332. // ClientVersion returns the node name
  333. func (s *PublicWeb3API) ClientVersion() string {
  334. return s.stack.Server().Name
  335. }
  336. // Sha3 applies the ethereum sha3 implementation on the input.
  337. // It assumes the input is hex encoded.
  338. func (s *PublicWeb3API) Sha3(input hexutil.Bytes) hexutil.Bytes {
  339. return crypto.Keccak256(input)
  340. }