api.go 10 KB

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