api.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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/p2p"
  24. "github.com/ethereum/go-ethereum/p2p/enode"
  25. "github.com/ethereum/go-ethereum/rpc"
  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 := enode.Parse(enode.ValidSchemes, 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 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 := enode.Parse(enode.ValidSchemes, 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. // AddTrustedPeer allows a remote node to always connect, even if slots are full
  69. func (api *PrivateAdminAPI) AddTrustedPeer(url string) (bool, error) {
  70. // Make sure the server is running, fail otherwise
  71. server := api.node.Server()
  72. if server == nil {
  73. return false, ErrNodeStopped
  74. }
  75. node, err := enode.Parse(enode.ValidSchemes, url)
  76. if err != nil {
  77. return false, fmt.Errorf("invalid enode: %v", err)
  78. }
  79. server.AddTrustedPeer(node)
  80. return true, nil
  81. }
  82. // RemoveTrustedPeer removes a remote node from the trusted peer set, but it
  83. // does not disconnect it automatically.
  84. func (api *PrivateAdminAPI) RemoveTrustedPeer(url string) (bool, error) {
  85. // Make sure the server is running, fail otherwise
  86. server := api.node.Server()
  87. if server == nil {
  88. return false, ErrNodeStopped
  89. }
  90. node, err := enode.Parse(enode.ValidSchemes, url)
  91. if err != nil {
  92. return false, fmt.Errorf("invalid enode: %v", err)
  93. }
  94. server.RemoveTrustedPeer(node)
  95. return true, nil
  96. }
  97. // PeerEvents creates an RPC subscription which receives peer events from the
  98. // node's p2p.Server
  99. func (api *PrivateAdminAPI) PeerEvents(ctx context.Context) (*rpc.Subscription, error) {
  100. // Make sure the server is running, fail otherwise
  101. server := api.node.Server()
  102. if server == nil {
  103. return nil, ErrNodeStopped
  104. }
  105. // Create the subscription
  106. notifier, supported := rpc.NotifierFromContext(ctx)
  107. if !supported {
  108. return nil, rpc.ErrNotificationsUnsupported
  109. }
  110. rpcSub := notifier.CreateSubscription()
  111. go func() {
  112. events := make(chan *p2p.PeerEvent)
  113. sub := server.SubscribeEvents(events)
  114. defer sub.Unsubscribe()
  115. for {
  116. select {
  117. case event := <-events:
  118. notifier.Notify(rpcSub.ID, event)
  119. case <-sub.Err():
  120. return
  121. case <-rpcSub.Err():
  122. return
  123. case <-notifier.Closed():
  124. return
  125. }
  126. }
  127. }()
  128. return rpcSub, nil
  129. }
  130. // StartRPC starts the HTTP RPC API server.
  131. func (api *PrivateAdminAPI) StartRPC(host *string, port *int, cors *string, apis *string, vhosts *string) (bool, error) {
  132. api.node.lock.Lock()
  133. defer api.node.lock.Unlock()
  134. if api.node.httpHandler != nil {
  135. return false, fmt.Errorf("HTTP RPC already running on %s", api.node.httpEndpoint)
  136. }
  137. if host == nil {
  138. h := DefaultHTTPHost
  139. if api.node.config.HTTPHost != "" {
  140. h = api.node.config.HTTPHost
  141. }
  142. host = &h
  143. }
  144. if port == nil {
  145. port = &api.node.config.HTTPPort
  146. }
  147. allowedOrigins := api.node.config.HTTPCors
  148. if cors != nil {
  149. allowedOrigins = nil
  150. for _, origin := range strings.Split(*cors, ",") {
  151. allowedOrigins = append(allowedOrigins, strings.TrimSpace(origin))
  152. }
  153. }
  154. allowedVHosts := api.node.config.HTTPVirtualHosts
  155. if vhosts != nil {
  156. allowedVHosts = nil
  157. for _, vhost := range strings.Split(*host, ",") {
  158. allowedVHosts = append(allowedVHosts, strings.TrimSpace(vhost))
  159. }
  160. }
  161. modules := api.node.httpWhitelist
  162. if apis != nil {
  163. modules = nil
  164. for _, m := range strings.Split(*apis, ",") {
  165. modules = append(modules, strings.TrimSpace(m))
  166. }
  167. }
  168. if err := api.node.startHTTP(fmt.Sprintf("%s:%d", *host, *port), api.node.rpcAPIs, modules, allowedOrigins, allowedVHosts, api.node.config.HTTPTimeouts, api.node.config.WSOrigins); err != nil {
  169. return false, err
  170. }
  171. return true, nil
  172. }
  173. // StopRPC terminates an already running HTTP RPC API endpoint.
  174. func (api *PrivateAdminAPI) StopRPC() (bool, error) {
  175. api.node.lock.Lock()
  176. defer api.node.lock.Unlock()
  177. if api.node.httpHandler == nil {
  178. return false, fmt.Errorf("HTTP RPC not running")
  179. }
  180. api.node.stopHTTP()
  181. return true, nil
  182. }
  183. // StartWS starts the websocket RPC API server.
  184. func (api *PrivateAdminAPI) StartWS(host *string, port *int, allowedOrigins *string, apis *string) (bool, error) {
  185. api.node.lock.Lock()
  186. defer api.node.lock.Unlock()
  187. if api.node.wsHandler != nil {
  188. return false, fmt.Errorf("WebSocket RPC already running on %s", api.node.wsEndpoint)
  189. }
  190. if host == nil {
  191. h := DefaultWSHost
  192. if api.node.config.WSHost != "" {
  193. h = api.node.config.WSHost
  194. }
  195. host = &h
  196. }
  197. if port == nil {
  198. port = &api.node.config.WSPort
  199. }
  200. origins := api.node.config.WSOrigins
  201. if allowedOrigins != nil {
  202. origins = nil
  203. for _, origin := range strings.Split(*allowedOrigins, ",") {
  204. origins = append(origins, strings.TrimSpace(origin))
  205. }
  206. }
  207. modules := api.node.config.WSModules
  208. if apis != nil {
  209. modules = nil
  210. for _, m := range strings.Split(*apis, ",") {
  211. modules = append(modules, strings.TrimSpace(m))
  212. }
  213. }
  214. if err := api.node.startWS(fmt.Sprintf("%s:%d", *host, *port), api.node.rpcAPIs, modules, origins, api.node.config.WSExposeAll); err != nil {
  215. return false, err
  216. }
  217. return true, nil
  218. }
  219. // StopWS terminates an already running websocket RPC API endpoint.
  220. func (api *PrivateAdminAPI) StopWS() (bool, error) {
  221. api.node.lock.Lock()
  222. defer api.node.lock.Unlock()
  223. if api.node.wsHandler == nil {
  224. return false, fmt.Errorf("WebSocket RPC not running")
  225. }
  226. api.node.stopWS()
  227. return true, nil
  228. }
  229. // PublicAdminAPI is the collection of administrative API methods exposed over
  230. // both secure and unsecure RPC channels.
  231. type PublicAdminAPI struct {
  232. node *Node // Node interfaced by this API
  233. }
  234. // NewPublicAdminAPI creates a new API definition for the public admin methods
  235. // of the node itself.
  236. func NewPublicAdminAPI(node *Node) *PublicAdminAPI {
  237. return &PublicAdminAPI{node: node}
  238. }
  239. // Peers retrieves all the information we know about each individual peer at the
  240. // protocol granularity.
  241. func (api *PublicAdminAPI) Peers() ([]*p2p.PeerInfo, error) {
  242. server := api.node.Server()
  243. if server == nil {
  244. return nil, ErrNodeStopped
  245. }
  246. return server.PeersInfo(), nil
  247. }
  248. // NodeInfo retrieves all the information we know about the host node at the
  249. // protocol granularity.
  250. func (api *PublicAdminAPI) NodeInfo() (*p2p.NodeInfo, error) {
  251. server := api.node.Server()
  252. if server == nil {
  253. return nil, ErrNodeStopped
  254. }
  255. return server.NodeInfo(), nil
  256. }
  257. // Datadir retrieves the current data directory the node is using.
  258. func (api *PublicAdminAPI) Datadir() string {
  259. return api.node.DataDir()
  260. }
  261. // PublicWeb3API offers helper utils
  262. type PublicWeb3API struct {
  263. stack *Node
  264. }
  265. // NewPublicWeb3API creates a new Web3Service instance
  266. func NewPublicWeb3API(stack *Node) *PublicWeb3API {
  267. return &PublicWeb3API{stack}
  268. }
  269. // ClientVersion returns the node name
  270. func (s *PublicWeb3API) ClientVersion() string {
  271. return s.stack.Server().Name
  272. }
  273. // Sha3 applies the ethereum sha3 implementation on the input.
  274. // It assumes the input is hex encoded.
  275. func (s *PublicWeb3API) Sha3(input hexutil.Bytes) hexutil.Bytes {
  276. return crypto.Keccak256(input)
  277. }