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