github.com/codingfuture/orig-energi3@v0.8.4/node/node.go (about)

     1  // Copyright 2018 The Energi Core Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the Energi Core library.
     4  //
     5  // The Energi Core library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The Energi Core library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package node
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"net"
    24  	"os"
    25  	"path/filepath"
    26  	"reflect"
    27  	"strings"
    28  	"sync"
    29  
    30  	"github.com/ethereum/go-ethereum/accounts"
    31  	"github.com/ethereum/go-ethereum/ethdb"
    32  	"github.com/ethereum/go-ethereum/event"
    33  	"github.com/ethereum/go-ethereum/internal/debug"
    34  	"github.com/ethereum/go-ethereum/log"
    35  	"github.com/ethereum/go-ethereum/p2p"
    36  	"github.com/ethereum/go-ethereum/rpc"
    37  	"github.com/prometheus/prometheus/util/flock"
    38  )
    39  
    40  // Node is a container on which services can be registered.
    41  type Node struct {
    42  	eventmux *event.TypeMux // Event multiplexer used between the services of a stack
    43  	config   *Config
    44  	accman   *accounts.Manager
    45  
    46  	ephemeralKeystore string         // if non-empty, the key directory that will be removed by Stop
    47  	instanceDirLock   flock.Releaser // prevents concurrent use of instance directory
    48  
    49  	serverConfig p2p.Config
    50  	server       *p2p.Server // Currently running P2P networking layer
    51  
    52  	serviceFuncs []ServiceConstructor     // Service constructors (in dependency order)
    53  	services     map[reflect.Type]Service // Currently running services
    54  
    55  	rpcAPIs       []rpc.API   // List of APIs currently provided by the node
    56  	inprocHandler *rpc.Server // In-process RPC request handler to process the API requests
    57  
    58  	ipcEndpoint string       // IPC endpoint to listen at (empty = IPC disabled)
    59  	ipcListener net.Listener // IPC RPC listener socket to serve API requests
    60  	ipcHandler  *rpc.Server  // IPC RPC request handler to process the API requests
    61  
    62  	httpEndpoint  string       // HTTP endpoint (interface + port) to listen at (empty = HTTP disabled)
    63  	httpWhitelist []string     // HTTP RPC modules to allow through this endpoint
    64  	httpListener  net.Listener // HTTP RPC listener socket to server API requests
    65  	httpHandler   *rpc.Server  // HTTP RPC request handler to process the API requests
    66  
    67  	wsEndpoint string       // Websocket endpoint (interface + port) to listen at (empty = websocket disabled)
    68  	wsListener net.Listener // Websocket RPC listener socket to server API requests
    69  	wsHandler  *rpc.Server  // Websocket RPC request handler to process the API requests
    70  
    71  	stop chan struct{} // Channel to wait for termination notifications
    72  	lock sync.RWMutex
    73  
    74  	log log.Logger
    75  }
    76  
    77  // New creates a new P2P node, ready for protocol registration.
    78  func New(conf *Config) (*Node, error) {
    79  	// Copy config and resolve the datadir so future changes to the current
    80  	// working directory don't affect the node.
    81  	confCopy := *conf
    82  	conf = &confCopy
    83  	if conf.DataDir != "" {
    84  		absdatadir, err := filepath.Abs(conf.DataDir)
    85  		if err != nil {
    86  			return nil, err
    87  		}
    88  		conf.DataDir = absdatadir
    89  	}
    90  	// Ensure that the instance name doesn't cause weird conflicts with
    91  	// other files in the data directory.
    92  	if strings.ContainsAny(conf.Name, `/\`) {
    93  		return nil, errors.New(`Config.Name must not contain '/' or '\'`)
    94  	}
    95  	if conf.Name == datadirDefaultKeyStore {
    96  		return nil, errors.New(`Config.Name cannot be "` + datadirDefaultKeyStore + `"`)
    97  	}
    98  	if strings.HasSuffix(conf.Name, ".ipc") {
    99  		return nil, errors.New(`Config.Name cannot end in ".ipc"`)
   100  	}
   101  	// Ensure that the AccountManager method works before the node has started.
   102  	// We rely on this in cmd/energi3.
   103  	am, ephemeralKeystore, err := makeAccountManager(conf)
   104  	if err != nil {
   105  		return nil, err
   106  	}
   107  	if conf.Logger == nil {
   108  		conf.Logger = log.New()
   109  	}
   110  	// Note: any interaction with Config that would create/touch files
   111  	// in the data directory or instance directory is delayed until Start.
   112  	return &Node{
   113  		accman:            am,
   114  		ephemeralKeystore: ephemeralKeystore,
   115  		config:            conf,
   116  		serviceFuncs:      []ServiceConstructor{},
   117  		ipcEndpoint:       conf.IPCEndpoint(),
   118  		httpEndpoint:      conf.HTTPEndpoint(),
   119  		wsEndpoint:        conf.WSEndpoint(),
   120  		eventmux:          new(event.TypeMux),
   121  		log:               conf.Logger,
   122  	}, nil
   123  }
   124  
   125  // Register injects a new service into the node's stack. The service created by
   126  // the passed constructor must be unique in its type with regard to sibling ones.
   127  func (n *Node) Register(constructor ServiceConstructor) error {
   128  	n.lock.Lock()
   129  	defer n.lock.Unlock()
   130  
   131  	if n.server != nil {
   132  		return ErrNodeRunning
   133  	}
   134  	n.serviceFuncs = append(n.serviceFuncs, constructor)
   135  	return nil
   136  }
   137  
   138  // Start create a live P2P node and starts running it.
   139  func (n *Node) Start() error {
   140  	n.lock.Lock()
   141  	defer n.lock.Unlock()
   142  
   143  	// Short circuit if the node's already running
   144  	if n.server != nil {
   145  		return ErrNodeRunning
   146  	}
   147  	if err := n.openDataDir(); err != nil {
   148  		return err
   149  	}
   150  
   151  	// Initialize the p2p server. This creates the node key and
   152  	// discovery databases.
   153  	n.serverConfig = n.config.P2P
   154  	n.serverConfig.PrivateKey = n.config.NodeKey()
   155  	n.serverConfig.Name = n.config.NodeName()
   156  	n.serverConfig.Logger = n.log
   157  	if n.serverConfig.StaticNodes == nil {
   158  		n.serverConfig.StaticNodes = n.config.StaticNodes()
   159  	}
   160  	if n.serverConfig.TrustedNodes == nil {
   161  		n.serverConfig.TrustedNodes = n.config.TrustedNodes()
   162  	}
   163  	if n.serverConfig.NodeDatabase == "" {
   164  		n.serverConfig.NodeDatabase = n.config.NodeDB()
   165  	}
   166  	running := &p2p.Server{Config: n.serverConfig}
   167  	n.log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name)
   168  
   169  	// Otherwise copy and specialize the P2P configuration
   170  	services := make(map[reflect.Type]Service)
   171  	for _, constructor := range n.serviceFuncs {
   172  		// Create a new context for the particular service
   173  		ctx := &ServiceContext{
   174  			config:         n.config,
   175  			services:       make(map[reflect.Type]Service),
   176  			EventMux:       n.eventmux,
   177  			AccountManager: n.accman,
   178  		}
   179  		for kind, s := range services { // copy needed for threaded access
   180  			ctx.services[kind] = s
   181  		}
   182  		// Construct and save the service
   183  		service, err := constructor(ctx)
   184  		if err != nil {
   185  			return err
   186  		}
   187  		kind := reflect.TypeOf(service)
   188  		if _, exists := services[kind]; exists {
   189  			return &DuplicateServiceError{Kind: kind}
   190  		}
   191  		services[kind] = service
   192  	}
   193  	// Gather the protocols and start the freshly assembled P2P server
   194  	for _, service := range services {
   195  		running.Protocols = append(running.Protocols, service.Protocols()...)
   196  	}
   197  	if err := running.Start(); err != nil {
   198  		return convertFileLockError(err)
   199  	}
   200  	// Start each of the services
   201  	started := []reflect.Type{}
   202  	for kind, service := range services {
   203  		// Start the next service, stopping all previous upon failure
   204  		if err := service.Start(running); err != nil {
   205  			for _, kind := range started {
   206  				services[kind].Stop()
   207  			}
   208  			running.Stop()
   209  
   210  			return err
   211  		}
   212  		// Mark the service started for potential cleanup
   213  		started = append(started, kind)
   214  	}
   215  	// Lastly start the configured RPC interfaces
   216  	if err := n.startRPC(services); err != nil {
   217  		for _, service := range services {
   218  			service.Stop()
   219  		}
   220  		running.Stop()
   221  		return err
   222  	}
   223  	// Finish initializing the startup
   224  	n.services = services
   225  	n.server = running
   226  	n.stop = make(chan struct{})
   227  
   228  	return nil
   229  }
   230  
   231  func (n *Node) openDataDir() error {
   232  	if n.config.DataDir == "" {
   233  		return nil // ephemeral
   234  	}
   235  
   236  	instdir := filepath.Join(n.config.DataDir, n.config.name())
   237  	if err := os.MkdirAll(instdir, 0700); err != nil {
   238  		return err
   239  	}
   240  	// Lock the instance directory to prevent concurrent use by another instance as well as
   241  	// accidental use of the instance directory as a database.
   242  	release, _, err := flock.New(filepath.Join(instdir, "LOCK"))
   243  	if err != nil {
   244  		return convertFileLockError(err)
   245  	}
   246  	n.instanceDirLock = release
   247  	return nil
   248  }
   249  
   250  // startRPC is a helper method to start all the various RPC endpoint during node
   251  // startup. It's not meant to be called at any time afterwards as it makes certain
   252  // assumptions about the state of the node.
   253  func (n *Node) startRPC(services map[reflect.Type]Service) error {
   254  	// Gather all the possible APIs to surface
   255  	apis := n.apis()
   256  	for _, service := range services {
   257  		apis = append(apis, service.APIs()...)
   258  	}
   259  	// Start the various API endpoints, terminating all in case of errors
   260  	if err := n.startInProc(apis); err != nil {
   261  		return err
   262  	}
   263  	if err := n.startIPC(apis); err != nil {
   264  		n.stopInProc()
   265  		return err
   266  	}
   267  	if err := n.startHTTP(n.httpEndpoint, apis, n.config.HTTPModules, n.config.HTTPCors, n.config.HTTPVirtualHosts, n.config.HTTPTimeouts); err != nil {
   268  		n.stopIPC()
   269  		n.stopInProc()
   270  		return err
   271  	}
   272  	if err := n.startWS(n.wsEndpoint, apis, n.config.WSModules, n.config.WSOrigins, n.config.WSExposeAll); err != nil {
   273  		n.stopHTTP()
   274  		n.stopIPC()
   275  		n.stopInProc()
   276  		return err
   277  	}
   278  	// All API endpoints started successfully
   279  	n.rpcAPIs = apis
   280  	return nil
   281  }
   282  
   283  // startInProc initializes an in-process RPC endpoint.
   284  func (n *Node) startInProc(apis []rpc.API) error {
   285  	// Register all the APIs exposed by the services
   286  	handler := rpc.NewServer()
   287  	for _, api := range apis {
   288  		if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
   289  			return err
   290  		}
   291  		n.log.Debug("InProc registered", "namespace", api.Namespace)
   292  	}
   293  	n.inprocHandler = handler
   294  	return nil
   295  }
   296  
   297  // stopInProc terminates the in-process RPC endpoint.
   298  func (n *Node) stopInProc() {
   299  	if n.inprocHandler != nil {
   300  		n.inprocHandler.Stop()
   301  		n.inprocHandler = nil
   302  	}
   303  }
   304  
   305  // startIPC initializes and starts the IPC RPC endpoint.
   306  func (n *Node) startIPC(apis []rpc.API) error {
   307  	if n.ipcEndpoint == "" {
   308  		return nil // IPC disabled.
   309  	}
   310  	listener, handler, err := rpc.StartIPCEndpoint(n.ipcEndpoint, apis)
   311  	if err != nil {
   312  		return err
   313  	}
   314  	n.ipcListener = listener
   315  	n.ipcHandler = handler
   316  	n.log.Info("IPC endpoint opened", "url", n.ipcEndpoint)
   317  	return nil
   318  }
   319  
   320  // stopIPC terminates the IPC RPC endpoint.
   321  func (n *Node) stopIPC() {
   322  	if n.ipcListener != nil {
   323  		n.ipcListener.Close()
   324  		n.ipcListener = nil
   325  
   326  		n.log.Info("IPC endpoint closed", "url", n.ipcEndpoint)
   327  	}
   328  	if n.ipcHandler != nil {
   329  		n.ipcHandler.Stop()
   330  		n.ipcHandler = nil
   331  	}
   332  }
   333  
   334  // startHTTP initializes and starts the HTTP RPC endpoint.
   335  func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors []string, vhosts []string, timeouts rpc.HTTPTimeouts) error {
   336  	// Short circuit if the HTTP endpoint isn't being exposed
   337  	if endpoint == "" {
   338  		return nil
   339  	}
   340  	listener, handler, err := rpc.StartHTTPEndpoint(endpoint, apis, modules, cors, vhosts, timeouts)
   341  	if err != nil {
   342  		return err
   343  	}
   344  	n.log.Info("HTTP endpoint opened", "url", fmt.Sprintf("http://%s", endpoint), "cors", strings.Join(cors, ","), "vhosts", strings.Join(vhosts, ","))
   345  	// All listeners booted successfully
   346  	n.httpEndpoint = endpoint
   347  	n.httpListener = listener
   348  	n.httpHandler = handler
   349  
   350  	return nil
   351  }
   352  
   353  // stopHTTP terminates the HTTP RPC endpoint.
   354  func (n *Node) stopHTTP() {
   355  	if n.httpListener != nil {
   356  		n.httpListener.Close()
   357  		n.httpListener = nil
   358  
   359  		n.log.Info("HTTP endpoint closed", "url", fmt.Sprintf("http://%s", n.httpEndpoint))
   360  	}
   361  	if n.httpHandler != nil {
   362  		n.httpHandler.Stop()
   363  		n.httpHandler = nil
   364  	}
   365  }
   366  
   367  // startWS initializes and starts the websocket RPC endpoint.
   368  func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins []string, exposeAll bool) error {
   369  	// Short circuit if the WS endpoint isn't being exposed
   370  	if endpoint == "" {
   371  		return nil
   372  	}
   373  	listener, handler, err := rpc.StartWSEndpoint(endpoint, apis, modules, wsOrigins, exposeAll)
   374  	if err != nil {
   375  		return err
   376  	}
   377  	n.log.Info("WebSocket endpoint opened", "url", fmt.Sprintf("ws://%s", listener.Addr()))
   378  	// All listeners booted successfully
   379  	n.wsEndpoint = endpoint
   380  	n.wsListener = listener
   381  	n.wsHandler = handler
   382  
   383  	return nil
   384  }
   385  
   386  // stopWS terminates the websocket RPC endpoint.
   387  func (n *Node) stopWS() {
   388  	if n.wsListener != nil {
   389  		n.wsListener.Close()
   390  		n.wsListener = nil
   391  
   392  		n.log.Info("WebSocket endpoint closed", "url", fmt.Sprintf("ws://%s", n.wsEndpoint))
   393  	}
   394  	if n.wsHandler != nil {
   395  		n.wsHandler.Stop()
   396  		n.wsHandler = nil
   397  	}
   398  }
   399  
   400  // Stop terminates a running node along with all it's services. In the node was
   401  // not started, an error is returned.
   402  func (n *Node) Stop() error {
   403  	n.lock.Lock()
   404  	defer n.lock.Unlock()
   405  
   406  	// Short circuit if the node's not running
   407  	if n.server == nil {
   408  		return ErrNodeStopped
   409  	}
   410  
   411  	// Terminate the API, services and the p2p server.
   412  	n.stopWS()
   413  	n.stopHTTP()
   414  	n.stopIPC()
   415  	n.rpcAPIs = nil
   416  	failure := &StopError{
   417  		Services: make(map[reflect.Type]error),
   418  	}
   419  	for kind, service := range n.services {
   420  		if err := service.Stop(); err != nil {
   421  			failure.Services[kind] = err
   422  		}
   423  	}
   424  	n.server.Stop()
   425  	n.services = nil
   426  	n.server = nil
   427  
   428  	// Release instance directory lock.
   429  	if n.instanceDirLock != nil {
   430  		if err := n.instanceDirLock.Release(); err != nil {
   431  			n.log.Error("Can't release datadir lock", "err", err)
   432  		}
   433  		n.instanceDirLock = nil
   434  	}
   435  
   436  	// unblock n.Wait
   437  	close(n.stop)
   438  
   439  	// Remove the keystore if it was created ephemerally.
   440  	var keystoreErr error
   441  	if n.ephemeralKeystore != "" {
   442  		keystoreErr = os.RemoveAll(n.ephemeralKeystore)
   443  	}
   444  
   445  	if len(failure.Services) > 0 {
   446  		return failure
   447  	}
   448  	if keystoreErr != nil {
   449  		return keystoreErr
   450  	}
   451  	return nil
   452  }
   453  
   454  // Wait blocks the thread until the node is stopped. If the node is not running
   455  // at the time of invocation, the method immediately returns.
   456  func (n *Node) Wait() {
   457  	n.lock.RLock()
   458  	if n.server == nil {
   459  		n.lock.RUnlock()
   460  		return
   461  	}
   462  	stop := n.stop
   463  	n.lock.RUnlock()
   464  
   465  	<-stop
   466  }
   467  
   468  // Restart terminates a running node and boots up a new one in its place. If the
   469  // node isn't running, an error is returned.
   470  func (n *Node) Restart() error {
   471  	if err := n.Stop(); err != nil {
   472  		return err
   473  	}
   474  	if err := n.Start(); err != nil {
   475  		return err
   476  	}
   477  	return nil
   478  }
   479  
   480  // Attach creates an RPC client attached to an in-process API handler.
   481  func (n *Node) Attach() (*rpc.Client, error) {
   482  	n.lock.RLock()
   483  	defer n.lock.RUnlock()
   484  
   485  	if n.server == nil {
   486  		return nil, ErrNodeStopped
   487  	}
   488  	return rpc.DialInProc(n.inprocHandler), nil
   489  }
   490  
   491  // RPCHandler returns the in-process RPC request handler.
   492  func (n *Node) RPCHandler() (*rpc.Server, error) {
   493  	n.lock.RLock()
   494  	defer n.lock.RUnlock()
   495  
   496  	if n.inprocHandler == nil {
   497  		return nil, ErrNodeStopped
   498  	}
   499  	return n.inprocHandler, nil
   500  }
   501  
   502  // Server retrieves the currently running P2P network layer. This method is meant
   503  // only to inspect fields of the currently running server, life cycle management
   504  // should be left to this Node entity.
   505  func (n *Node) Server() *p2p.Server {
   506  	n.lock.RLock()
   507  	defer n.lock.RUnlock()
   508  
   509  	return n.server
   510  }
   511  
   512  // Service retrieves a currently running service registered of a specific type.
   513  func (n *Node) Service(service interface{}) error {
   514  	n.lock.RLock()
   515  	defer n.lock.RUnlock()
   516  
   517  	// Short circuit if the node's not running
   518  	if n.server == nil {
   519  		return ErrNodeStopped
   520  	}
   521  	// Otherwise try to find the service to return
   522  	element := reflect.ValueOf(service).Elem()
   523  	if running, ok := n.services[element.Type()]; ok {
   524  		element.Set(reflect.ValueOf(running))
   525  		return nil
   526  	}
   527  	return ErrServiceUnknown
   528  }
   529  
   530  // DataDir retrieves the current datadir used by the protocol stack.
   531  // Deprecated: No files should be stored in this directory, use InstanceDir instead.
   532  func (n *Node) DataDir() string {
   533  	return n.config.DataDir
   534  }
   535  
   536  // InstanceDir retrieves the instance directory used by the protocol stack.
   537  func (n *Node) InstanceDir() string {
   538  	return n.config.instanceDir()
   539  }
   540  
   541  // AccountManager retrieves the account manager used by the protocol stack.
   542  func (n *Node) AccountManager() *accounts.Manager {
   543  	return n.accman
   544  }
   545  
   546  // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
   547  func (n *Node) IPCEndpoint() string {
   548  	return n.ipcEndpoint
   549  }
   550  
   551  // HTTPEndpoint retrieves the current HTTP endpoint used by the protocol stack.
   552  func (n *Node) HTTPEndpoint() string {
   553  	n.lock.Lock()
   554  	defer n.lock.Unlock()
   555  
   556  	if n.httpListener != nil {
   557  		return n.httpListener.Addr().String()
   558  	}
   559  	return n.httpEndpoint
   560  }
   561  
   562  // WSEndpoint retrieves the current WS endpoint used by the protocol stack.
   563  func (n *Node) WSEndpoint() string {
   564  	n.lock.Lock()
   565  	defer n.lock.Unlock()
   566  
   567  	if n.wsListener != nil {
   568  		return n.wsListener.Addr().String()
   569  	}
   570  	return n.wsEndpoint
   571  }
   572  
   573  // EventMux retrieves the event multiplexer used by all the network services in
   574  // the current protocol stack.
   575  func (n *Node) EventMux() *event.TypeMux {
   576  	return n.eventmux
   577  }
   578  
   579  // OpenDatabase opens an existing database with the given name (or creates one if no
   580  // previous can be found) from within the node's instance directory. If the node is
   581  // ephemeral, a memory database is returned.
   582  func (n *Node) OpenDatabase(name string, cache, handles int) (ethdb.Database, error) {
   583  	if n.config.DataDir == "" {
   584  		return ethdb.NewMemDatabase(), nil
   585  	}
   586  	return ethdb.NewLDBDatabase(n.config.ResolvePath(name), cache, handles)
   587  }
   588  
   589  // ResolvePath returns the absolute path of a resource in the instance directory.
   590  func (n *Node) ResolvePath(x string) string {
   591  	return n.config.ResolvePath(x)
   592  }
   593  
   594  // apis returns the collection of RPC descriptors this node offers.
   595  func (n *Node) apis() []rpc.API {
   596  	return []rpc.API{
   597  		{
   598  			Namespace: "admin",
   599  			Version:   "1.0",
   600  			Service:   NewPrivateAdminAPI(n),
   601  		}, {
   602  			Namespace: "admin",
   603  			Version:   "1.0",
   604  			Service:   NewPublicAdminAPI(n),
   605  			Public:    true,
   606  		}, {
   607  			Namespace: "debug",
   608  			Version:   "1.0",
   609  			Service:   debug.Handler,
   610  		}, {
   611  			Namespace: "debug",
   612  			Version:   "1.0",
   613  			Service:   NewPublicDebugAPI(n),
   614  			Public:    true,
   615  		}, {
   616  			Namespace: "web3",
   617  			Version:   "1.0",
   618  			Service:   NewPublicWeb3API(n),
   619  			Public:    true,
   620  		},
   621  	}
   622  }