api.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. tls, auth, err := api.node.GetSecuritySupports()
  191. if err != nil {
  192. return false, err
  193. }
  194. if err := api.node.http.setListenAddr(*host, *port); err != nil {
  195. return false, err
  196. }
  197. if err := api.node.http.enableRPC(api.node.rpcAPIs, config, auth); err != nil {
  198. return false, err
  199. }
  200. if err := api.node.http.start(tls); err != nil {
  201. return false, err
  202. }
  203. return true, nil
  204. }
  205. // StartRPC starts the HTTP RPC API server.
  206. // This method is deprecated. Use StartHTTP instead.
  207. func (api *privateAdminAPI) StartRPC(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) {
  208. log.Warn("Deprecation warning", "method", "admin.StartRPC", "use-instead", "admin.StartHTTP")
  209. return api.StartHTTP(host, port, cors, apis, vhosts)
  210. }
  211. // StopHTTP shuts down the HTTP server.
  212. func (api *privateAdminAPI) StopHTTP() (bool, error) {
  213. api.node.http.stop()
  214. return true, nil
  215. }
  216. // StopRPC shuts down the HTTP server.
  217. // This method is deprecated. Use StopHTTP instead.
  218. func (api *privateAdminAPI) StopRPC() (bool, error) {
  219. log.Warn("Deprecation warning", "method", "admin.StopRPC", "use-instead", "admin.StopHTTP")
  220. return api.StopHTTP()
  221. }
  222. // StartWS starts the websocket RPC API server.
  223. func (api *privateAdminAPI) StartWS(host *string, port *int, allowedOrigins *string, apis *string) (bool, error) {
  224. api.node.lock.Lock()
  225. defer api.node.lock.Unlock()
  226. // Determine host and port.
  227. if host == nil {
  228. h := DefaultWSHost
  229. if api.node.config.WSHost != "" {
  230. h = api.node.config.WSHost
  231. }
  232. host = &h
  233. }
  234. if port == nil {
  235. port = &api.node.config.WSPort
  236. }
  237. // Determine config.
  238. config := wsConfig{
  239. Modules: api.node.config.WSModules,
  240. Origins: api.node.config.WSOrigins,
  241. // ExposeAll: api.node.config.WSExposeAll,
  242. }
  243. if apis != nil {
  244. config.Modules = nil
  245. for _, m := range strings.Split(*apis, ",") {
  246. config.Modules = append(config.Modules, strings.TrimSpace(m))
  247. }
  248. }
  249. if allowedOrigins != nil {
  250. config.Origins = nil
  251. for _, origin := range strings.Split(*allowedOrigins, ",") {
  252. config.Origins = append(config.Origins, strings.TrimSpace(origin))
  253. }
  254. }
  255. tls, auth, err := api.node.GetSecuritySupports()
  256. if err != nil {
  257. return false, err
  258. }
  259. // Enable WebSocket on the server.
  260. server := api.node.wsServerForPort(*port)
  261. if err := server.setListenAddr(*host, *port); err != nil {
  262. return false, err
  263. }
  264. if err := server.enableWS(api.node.rpcAPIs, config, auth); err != nil {
  265. return false, err
  266. }
  267. if err := server.start(tls); err != nil {
  268. return false, err
  269. }
  270. api.node.http.log.Info("WebSocket endpoint opened", "url", api.node.WSEndpoint())
  271. return true, nil
  272. }
  273. // StopWS terminates all WebSocket servers.
  274. func (api *privateAdminAPI) StopWS() (bool, error) {
  275. api.node.http.stopWS()
  276. api.node.ws.stop()
  277. return true, nil
  278. }
  279. // publicAdminAPI is the collection of administrative API methods exposed over
  280. // both secure and unsecure RPC channels.
  281. type publicAdminAPI struct {
  282. node *Node // Node interfaced by this API
  283. }
  284. // Quorum: an extended nodeInfo to include plugin details for current node
  285. type QuorumNodeInfo struct {
  286. *p2p.NodeInfo
  287. Plugins interface{} `json:"plugins"`
  288. }
  289. // Peers retrieves all the information we know about each individual peer at the
  290. // protocol granularity.
  291. func (api *publicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
  292. server := api.node.Server()
  293. if server == nil {
  294. return nil, ErrNodeStopped
  295. }
  296. return server.PeersInfo(), nil
  297. }
  298. func (api *publicAdminAPI) Qpeers() ([]*p2p.PeerInfo, error) {
  299. server := api.node.qserver
  300. if server == nil {
  301. return nil, nil
  302. }
  303. return server.PeersInfo(), nil
  304. }
  305. // NodeInfo retrieves all the information we know about the host node at the
  306. // protocol granularity.
  307. func (api *publicAdminAPI) NodeInfo() (*QuorumNodeInfo, error) {
  308. server := api.node.Server()
  309. if server == nil {
  310. return nil, ErrNodeStopped
  311. }
  312. return &QuorumNodeInfo{
  313. NodeInfo: server.NodeInfo(),
  314. Plugins: api.node.PluginManager().PluginsInfo(),
  315. }, nil
  316. }
  317. func (api *publicAdminAPI) QnodeInfo() (*QuorumNodeInfo, error) {
  318. server := api.node.QServer()
  319. if server == nil {
  320. return nil, nil
  321. }
  322. return &QuorumNodeInfo{
  323. NodeInfo: server.NodeInfo(),
  324. }, nil
  325. }
  326. // Datadir retrieves the current data directory the node is using.
  327. func (api *publicAdminAPI) Datadir() string {
  328. return api.node.DataDir()
  329. }
  330. // publicWeb3API offers helper utils
  331. type publicWeb3API struct {
  332. stack *Node
  333. }
  334. // ClientVersion returns the node name
  335. func (s *publicWeb3API) ClientVersion() string {
  336. return s.stack.Server().Name
  337. }
  338. // Sha3 applies the ethereum sha3 implementation on the input.
  339. // It assumes the input is hex encoded.
  340. func (s *publicWeb3API) Sha3(input hexutil.Bytes) hexutil.Bytes {
  341. return crypto.Keccak256(input)
  342. }