api.go 8.9 KB

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