api.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. "github.com/ethereum/go-ethereum/common/hexutil"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/internal/debug"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/p2p"
  26. "github.com/ethereum/go-ethereum/p2p/enode"
  27. "github.com/ethereum/go-ethereum/rpc"
  28. )
  29. // apis returns the collection of built-in RPC APIs.
  30. func (n *Node) apis() []rpc.API {
  31. return []rpc.API{
  32. {
  33. Namespace: "admin",
  34. Version: "1.0",
  35. Service: &privateAdminAPI{n},
  36. }, {
  37. Namespace: "admin",
  38. Version: "1.0",
  39. Service: &publicAdminAPI{n},
  40. Public: true,
  41. }, {
  42. Namespace: "debug",
  43. Version: "1.0",
  44. Service: debug.Handler,
  45. }, {
  46. Namespace: "web3",
  47. Version: "1.0",
  48. Service: &publicWeb3API{n},
  49. Public: true,
  50. },
  51. }
  52. }
  53. // privateAdminAPI is the collection of administrative API methods exposed only
  54. // over a secure RPC channel.
  55. type privateAdminAPI struct {
  56. node *Node // Node interfaced by this API
  57. }
  58. // AddPeer requests connecting to a remote node, and also maintaining the new
  59. // connection at all times, even reconnecting if it is lost.
  60. func (api *privateAdminAPI) AddPeer(url string) (bool, error) {
  61. // Make sure the server is running, fail otherwise
  62. server := api.node.Server()
  63. if server == nil {
  64. return false, ErrNodeStopped
  65. }
  66. // Try to add the url as a static peer and return
  67. node, err := enode.Parse(enode.ValidSchemes, url)
  68. if err != nil {
  69. return false, fmt.Errorf("invalid enode: %v", err)
  70. }
  71. server.AddPeer(node)
  72. return true, nil
  73. }
  74. // RemovePeer disconnects from a remote node if the connection exists
  75. func (api *privateAdminAPI) RemovePeer(url string) (bool, error) {
  76. // Make sure the server is running, fail otherwise
  77. server := api.node.Server()
  78. if server == nil {
  79. return false, ErrNodeStopped
  80. }
  81. // Try to remove the url as a static peer and return
  82. node, err := enode.Parse(enode.ValidSchemes, url)
  83. if err != nil {
  84. return false, fmt.Errorf("invalid enode: %v", err)
  85. }
  86. server.RemovePeer(node)
  87. return true, nil
  88. }
  89. // AddTrustedPeer allows a remote node to always connect, even if slots are full
  90. func (api *privateAdminAPI) AddTrustedPeer(url string) (bool, error) {
  91. // Make sure the server is running, fail otherwise
  92. server := api.node.Server()
  93. if server == nil {
  94. return false, ErrNodeStopped
  95. }
  96. node, err := enode.Parse(enode.ValidSchemes, url)
  97. if err != nil {
  98. return false, fmt.Errorf("invalid enode: %v", err)
  99. }
  100. server.AddTrustedPeer(node)
  101. return true, nil
  102. }
  103. // RemoveTrustedPeer removes a remote node from the trusted peer set, but it
  104. // does not disconnect it automatically.
  105. func (api *privateAdminAPI) RemoveTrustedPeer(url string) (bool, error) {
  106. // Make sure the server is running, fail otherwise
  107. server := api.node.Server()
  108. if server == nil {
  109. return false, ErrNodeStopped
  110. }
  111. node, err := enode.Parse(enode.ValidSchemes, url)
  112. if err != nil {
  113. return false, fmt.Errorf("invalid enode: %v", err)
  114. }
  115. server.RemoveTrustedPeer(node)
  116. return true, nil
  117. }
  118. // PeerEvents creates an RPC subscription which receives peer events from the
  119. // node's p2p.Server
  120. func (api *privateAdminAPI) PeerEvents(ctx context.Context) (*rpc.Subscription, error) {
  121. // Make sure the server is running, fail otherwise
  122. server := api.node.Server()
  123. if server == nil {
  124. return nil, ErrNodeStopped
  125. }
  126. // Create the subscription
  127. notifier, supported := rpc.NotifierFromContext(ctx)
  128. if !supported {
  129. return nil, rpc.ErrNotificationsUnsupported
  130. }
  131. rpcSub := notifier.CreateSubscription()
  132. go func() {
  133. events := make(chan *p2p.PeerEvent)
  134. sub := server.SubscribeEvents(events)
  135. defer sub.Unsubscribe()
  136. for {
  137. select {
  138. case event := <-events:
  139. notifier.Notify(rpcSub.ID, event)
  140. case <-sub.Err():
  141. return
  142. case <-rpcSub.Err():
  143. return
  144. case <-notifier.Closed():
  145. return
  146. }
  147. }
  148. }()
  149. return rpcSub, nil
  150. }
  151. // StartHTTP starts the HTTP RPC API server.
  152. func (api *privateAdminAPI) StartHTTP(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) {
  153. api.node.lock.Lock()
  154. defer api.node.lock.Unlock()
  155. // Determine host and port.
  156. if host == nil {
  157. h := DefaultHTTPHost
  158. if api.node.config.HTTPHost != "" {
  159. h = api.node.config.HTTPHost
  160. }
  161. host = &h
  162. }
  163. if port == nil {
  164. port = &api.node.config.HTTPPort
  165. }
  166. // Determine config.
  167. config := httpConfig{
  168. CorsAllowedOrigins: api.node.config.HTTPCors,
  169. Vhosts: api.node.config.HTTPVirtualHosts,
  170. Modules: api.node.config.HTTPModules,
  171. }
  172. if cors != nil {
  173. config.CorsAllowedOrigins = nil
  174. for _, origin := range strings.Split(*cors, ",") {
  175. config.CorsAllowedOrigins = append(config.CorsAllowedOrigins, strings.TrimSpace(origin))
  176. }
  177. }
  178. if vhosts != nil {
  179. config.Vhosts = nil
  180. for _, vhost := range strings.Split(*host, ",") {
  181. config.Vhosts = append(config.Vhosts, strings.TrimSpace(vhost))
  182. }
  183. }
  184. if apis != nil {
  185. config.Modules = nil
  186. for _, m := range strings.Split(*apis, ",") {
  187. config.Modules = append(config.Modules, strings.TrimSpace(m))
  188. }
  189. }
  190. if err := api.node.http.setListenAddr(*host, *port); err != nil {
  191. return false, err
  192. }
  193. if err := api.node.http.enableRPC(api.node.rpcAPIs, config); err != nil {
  194. return false, err
  195. }
  196. if err := api.node.http.start(); err != nil {
  197. return false, err
  198. }
  199. return true, nil
  200. }
  201. // StartRPC starts the HTTP RPC API server.
  202. // This method is deprecated. Use StartHTTP instead.
  203. func (api *privateAdminAPI) StartRPC(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) {
  204. log.Warn("Deprecation warning", "method", "admin.StartRPC", "use-instead", "admin.StartHTTP")
  205. return api.StartHTTP(host, port, cors, apis, vhosts)
  206. }
  207. // StopHTTP shuts down the HTTP server.
  208. func (api *privateAdminAPI) StopHTTP() (bool, error) {
  209. api.node.http.stop()
  210. return true, nil
  211. }
  212. // StopRPC shuts down the HTTP server.
  213. // This method is deprecated. Use StopHTTP instead.
  214. func (api *privateAdminAPI) StopRPC() (bool, error) {
  215. log.Warn("Deprecation warning", "method", "admin.StopRPC", "use-instead", "admin.StopHTTP")
  216. return api.StopHTTP()
  217. }
  218. // StartWS starts the websocket RPC API server.
  219. func (api *privateAdminAPI) StartWS(host *string, port *int, allowedOrigins *string, apis *string) (bool, error) {
  220. api.node.lock.Lock()
  221. defer api.node.lock.Unlock()
  222. // Determine host and port.
  223. if host == nil {
  224. h := DefaultWSHost
  225. if api.node.config.WSHost != "" {
  226. h = api.node.config.WSHost
  227. }
  228. host = &h
  229. }
  230. if port == nil {
  231. port = &api.node.config.WSPort
  232. }
  233. // Determine config.
  234. config := wsConfig{
  235. Modules: api.node.config.WSModules,
  236. Origins: api.node.config.WSOrigins,
  237. // ExposeAll: api.node.config.WSExposeAll,
  238. }
  239. if apis != nil {
  240. config.Modules = nil
  241. for _, m := range strings.Split(*apis, ",") {
  242. config.Modules = append(config.Modules, strings.TrimSpace(m))
  243. }
  244. }
  245. if allowedOrigins != nil {
  246. config.Origins = nil
  247. for _, origin := range strings.Split(*allowedOrigins, ",") {
  248. config.Origins = append(config.Origins, strings.TrimSpace(origin))
  249. }
  250. }
  251. // Enable WebSocket on the server.
  252. server := api.node.wsServerForPort(*port)
  253. if err := server.setListenAddr(*host, *port); err != nil {
  254. return false, err
  255. }
  256. if err := server.enableWS(api.node.rpcAPIs, config); err != nil {
  257. return false, err
  258. }
  259. if err := server.start(); err != nil {
  260. return false, err
  261. }
  262. api.node.http.log.Info("WebSocket endpoint opened", "url", api.node.WSEndpoint())
  263. return true, nil
  264. }
  265. // StopWS terminates all WebSocket servers.
  266. func (api *privateAdminAPI) StopWS() (bool, error) {
  267. api.node.http.stopWS()
  268. api.node.ws.stop()
  269. return true, nil
  270. }
  271. // publicAdminAPI is the collection of administrative API methods exposed over
  272. // both secure and unsecure RPC channels.
  273. type publicAdminAPI struct {
  274. node *Node // Node interfaced by this API
  275. }
  276. // Peers retrieves all the information we know about each individual peer at the
  277. // protocol granularity.
  278. func (api *publicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
  279. server := api.node.Server()
  280. if server == nil {
  281. return nil, ErrNodeStopped
  282. }
  283. return server.PeersInfo(), nil
  284. }
  285. // NodeInfo retrieves all the information we know about the host node at the
  286. // protocol granularity.
  287. func (api *publicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) {
  288. server := api.node.Server()
  289. if server == nil {
  290. return nil, ErrNodeStopped
  291. }
  292. return server.NodeInfo(), nil
  293. }
  294. // Datadir retrieves the current data directory the node is using.
  295. func (api *publicAdminAPI) Datadir() string {
  296. return api.node.DataDir()
  297. }
  298. // publicWeb3API offers helper utils
  299. type publicWeb3API struct {
  300. stack *Node
  301. }
  302. // ClientVersion returns the node name
  303. func (s *publicWeb3API) ClientVersion() string {
  304. return s.stack.Server().Name
  305. }
  306. // Sha3 applies the ethereum sha3 implementation on the input.
  307. // It assumes the input is hex encoded.
  308. func (s *publicWeb3API) Sha3(input hexutil.Bytes) hexutil.Bytes {
  309. return crypto.Keccak256(input)
  310. }