api.go 9.0 KB

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