node.go 17.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package node

import (
	"errors"
21
	"fmt"
22
	"net"
23 24
	"os"
	"path/filepath"
25
	"reflect"
26
	"strings"
27 28
	"sync"

29
	"github.com/ethereum/go-ethereum/accounts"
30
	"github.com/ethereum/go-ethereum/ethdb"
31
	"github.com/ethereum/go-ethereum/event"
32
	"github.com/ethereum/go-ethereum/internal/debug"
33
	"github.com/ethereum/go-ethereum/log"
34
	"github.com/ethereum/go-ethereum/p2p"
35
	"github.com/ethereum/go-ethereum/rpc"
36
	"github.com/prometheus/prometheus/util/flock"
37 38
)

39
// Node is a container on which services can be registered.
40
type Node struct {
41
	eventmux *event.TypeMux // Event multiplexer used between the services of a stack
42 43
	config   *Config
	accman   *accounts.Manager
44

45 46
	ephemeralKeystore string         // if non-empty, the key directory that will be removed by Stop
	instanceDirLock   flock.Releaser // prevents concurrent use of instance directory
47

48
	serverConfig p2p.Config
49
	server       *p2p.Server // Currently running P2P networking layer
50

51 52
	serviceFuncs []ServiceConstructor     // Service constructors (in dependency order)
	services     map[reflect.Type]Service // Currently running services
53

54 55 56
	rpcAPIs       []rpc.API   // List of APIs currently provided by the node
	inprocHandler *rpc.Server // In-process RPC request handler to process the API requests

57 58 59 60
	ipcEndpoint string       // IPC endpoint to listen at (empty = IPC disabled)
	ipcListener net.Listener // IPC RPC listener socket to serve API requests
	ipcHandler  *rpc.Server  // IPC RPC request handler to process the API requests

61 62 63 64 65
	httpEndpoint  string       // HTTP endpoint (interface + port) to listen at (empty = HTTP disabled)
	httpWhitelist []string     // HTTP RPC modules to allow through this endpoint
	httpListener  net.Listener // HTTP RPC listener socket to server API requests
	httpHandler   *rpc.Server  // HTTP RPC request handler to process the API requests

66 67 68
	wsEndpoint string       // Websocket endpoint (interface + port) to listen at (empty = websocket disabled)
	wsListener net.Listener // Websocket RPC listener socket to server API requests
	wsHandler  *rpc.Server  // Websocket RPC request handler to process the API requests
69

70
	stop chan struct{} // Channel to wait for termination notifications
71
	lock sync.RWMutex
72 73

	log log.Logger
74 75 76 77
}

// New creates a new P2P node, ready for protocol registration.
func New(conf *Config) (*Node, error) {
78 79 80 81
	// Copy config and resolve the datadir so future changes to the current
	// working directory don't affect the node.
	confCopy := *conf
	conf = &confCopy
82
	if conf.DataDir != "" {
83 84
		absdatadir, err := filepath.Abs(conf.DataDir)
		if err != nil {
85 86
			return nil, err
		}
87 88 89 90 91 92 93 94 95
		conf.DataDir = absdatadir
	}
	// Ensure that the instance name doesn't cause weird conflicts with
	// other files in the data directory.
	if strings.ContainsAny(conf.Name, `/\`) {
		return nil, errors.New(`Config.Name must not contain '/' or '\'`)
	}
	if conf.Name == datadirDefaultKeyStore {
		return nil, errors.New(`Config.Name cannot be "` + datadirDefaultKeyStore + `"`)
96
	}
97 98 99 100 101
	if strings.HasSuffix(conf.Name, ".ipc") {
		return nil, errors.New(`Config.Name cannot end in ".ipc"`)
	}
	// Ensure that the AccountManager method works before the node has started.
	// We rely on this in cmd/geth.
102 103 104 105
	am, ephemeralKeystore, err := makeAccountManager(conf)
	if err != nil {
		return nil, err
	}
106 107 108
	if conf.Logger == nil {
		conf.Logger = log.New()
	}
109 110
	// Note: any interaction with Config that would create/touch files
	// in the data directory or instance directory is delayed until Start.
111
	return &Node{
112 113
		accman:            am,
		ephemeralKeystore: ephemeralKeystore,
114 115 116 117 118 119
		config:            conf,
		serviceFuncs:      []ServiceConstructor{},
		ipcEndpoint:       conf.IPCEndpoint(),
		httpEndpoint:      conf.HTTPEndpoint(),
		wsEndpoint:        conf.WSEndpoint(),
		eventmux:          new(event.TypeMux),
120
		log:               conf.Logger,
121 122 123
	}, nil
}

124 125 126
// Register injects a new service into the node's stack. The service created by
// the passed constructor must be unique in its type with regard to sibling ones.
func (n *Node) Register(constructor ServiceConstructor) error {
127 128 129
	n.lock.Lock()
	defer n.lock.Unlock()

130
	if n.server != nil {
131 132
		return ErrNodeRunning
	}
133
	n.serviceFuncs = append(n.serviceFuncs, constructor)
134 135 136 137 138 139 140 141 142
	return nil
}

// Start create a live P2P node and starts running it.
func (n *Node) Start() error {
	n.lock.Lock()
	defer n.lock.Unlock()

	// Short circuit if the node's already running
143
	if n.server != nil {
144 145
		return ErrNodeRunning
	}
146 147 148 149 150 151
	if err := n.openDataDir(); err != nil {
		return err
	}

	// Initialize the p2p server. This creates the node key and
	// discovery databases.
152 153 154
	n.serverConfig = n.config.P2P
	n.serverConfig.PrivateKey = n.config.NodeKey()
	n.serverConfig.Name = n.config.NodeName()
155
	n.serverConfig.Logger = n.log
156 157 158 159
	if n.serverConfig.StaticNodes == nil {
		n.serverConfig.StaticNodes = n.config.StaticNodes()
	}
	if n.serverConfig.TrustedNodes == nil {
160
		n.serverConfig.TrustedNodes = n.config.TrustedNodes()
161 162 163
	}
	if n.serverConfig.NodeDatabase == "" {
		n.serverConfig.NodeDatabase = n.config.NodeDB()
164
	}
165
	running := &p2p.Server{Config: n.serverConfig}
166
	n.log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name)
167 168

	// Otherwise copy and specialize the P2P configuration
169 170
	services := make(map[reflect.Type]Service)
	for _, constructor := range n.serviceFuncs {
171 172
		// Create a new context for the particular service
		ctx := &ServiceContext{
173
			config:         n.config,
174 175 176
			services:       make(map[reflect.Type]Service),
			EventMux:       n.eventmux,
			AccountManager: n.accman,
177
		}
178 179
		for kind, s := range services { // copy needed for threaded access
			ctx.services[kind] = s
180 181
		}
		// Construct and save the service
182 183 184 185
		service, err := constructor(ctx)
		if err != nil {
			return err
		}
186 187 188 189 190
		kind := reflect.TypeOf(service)
		if _, exists := services[kind]; exists {
			return &DuplicateServiceError{Kind: kind}
		}
		services[kind] = service
191 192 193 194 195 196
	}
	// Gather the protocols and start the freshly assembled P2P server
	for _, service := range services {
		running.Protocols = append(running.Protocols, service.Protocols()...)
	}
	if err := running.Start(); err != nil {
197
		return convertFileLockError(err)
198 199
	}
	// Start each of the services
200 201
	started := []reflect.Type{}
	for kind, service := range services {
202
		// Start the next service, stopping all previous upon failure
203
		if err := service.Start(running); err != nil {
204 205
			for _, kind := range started {
				services[kind].Stop()
206
			}
207 208
			running.Stop()

209 210 211
			return err
		}
		// Mark the service started for potential cleanup
212
		started = append(started, kind)
213
	}
214 215 216 217 218 219 220 221
	// Lastly start the configured RPC interfaces
	if err := n.startRPC(services); err != nil {
		for _, service := range services {
			service.Stop()
		}
		running.Stop()
		return err
	}
222 223
	// Finish initializing the startup
	n.services = services
224 225
	n.server = running
	n.stop = make(chan struct{})
226 227 228 229

	return nil
}

230 231 232 233 234 235 236 237 238
func (n *Node) openDataDir() error {
	if n.config.DataDir == "" {
		return nil // ephemeral
	}

	instdir := filepath.Join(n.config.DataDir, n.config.name())
	if err := os.MkdirAll(instdir, 0700); err != nil {
		return err
	}
239 240 241
	// Lock the instance directory to prevent concurrent use by another instance as well as
	// accidental use of the instance directory as a database.
	release, _, err := flock.New(filepath.Join(instdir, "LOCK"))
242
	if err != nil {
243
		return convertFileLockError(err)
244
	}
245
	n.instanceDirLock = release
246 247 248
	return nil
}

249 250 251
// startRPC is a helper method to start all the various RPC endpoint during node
// startup. It's not meant to be called at any time afterwards as it makes certain
// assumptions about the state of the node.
252
func (n *Node) startRPC(services map[reflect.Type]Service) error {
253
	// Gather all the possible APIs to surface
254 255 256 257
	apis := n.apis()
	for _, service := range services {
		apis = append(apis, service.APIs()...)
	}
258
	// Start the various API endpoints, terminating all in case of errors
259 260 261
	if err := n.startInProc(apis); err != nil {
		return err
	}
262
	if err := n.startIPC(apis); err != nil {
263
		n.stopInProc()
264 265
		return err
	}
266
	if err := n.startHTTP(n.httpEndpoint, apis, n.config.HTTPModules, n.config.HTTPCors, n.config.HTTPVirtualHosts, n.config.HTTPTimeouts); err != nil {
267
		n.stopIPC()
268
		n.stopInProc()
269 270
		return err
	}
271
	if err := n.startWS(n.wsEndpoint, apis, n.config.WSModules, n.config.WSOrigins, n.config.WSExposeAll); err != nil {
272 273
		n.stopHTTP()
		n.stopIPC()
274
		n.stopInProc()
275 276
		return err
	}
277 278 279 280 281
	// All API endpoints started successfully
	n.rpcAPIs = apis
	return nil
}

282 283 284 285 286 287 288 289
// startInProc initializes an in-process RPC endpoint.
func (n *Node) startInProc(apis []rpc.API) error {
	// Register all the APIs exposed by the services
	handler := rpc.NewServer()
	for _, api := range apis {
		if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
			return err
		}
290
		n.log.Debug("InProc registered", "service", api.Service, "namespace", api.Namespace)
291 292 293 294 295 296 297 298 299 300 301 302 303
	}
	n.inprocHandler = handler
	return nil
}

// stopInProc terminates the in-process RPC endpoint.
func (n *Node) stopInProc() {
	if n.inprocHandler != nil {
		n.inprocHandler.Stop()
		n.inprocHandler = nil
	}
}

304 305 306
// startIPC initializes and starts the IPC RPC endpoint.
func (n *Node) startIPC(apis []rpc.API) error {
	if n.ipcEndpoint == "" {
307
		return nil // IPC disabled.
308
	}
309
	listener, handler, err := rpc.StartIPCEndpoint(n.ipcEndpoint, apis)
310
	if err != nil {
311 312 313 314
		return err
	}
	n.ipcListener = listener
	n.ipcHandler = handler
315
	n.log.Info("IPC endpoint opened", "url", n.ipcEndpoint)
316 317 318 319 320 321 322 323 324
	return nil
}

// stopIPC terminates the IPC RPC endpoint.
func (n *Node) stopIPC() {
	if n.ipcListener != nil {
		n.ipcListener.Close()
		n.ipcListener = nil

325
		n.log.Info("IPC endpoint closed", "endpoint", n.ipcEndpoint)
326 327 328 329
	}
	if n.ipcHandler != nil {
		n.ipcHandler.Stop()
		n.ipcHandler = nil
330
	}
331 332 333
}

// startHTTP initializes and starts the HTTP RPC endpoint.
334
func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors []string, vhosts []string, timeouts rpc.HTTPTimeouts) error {
335
	// Short circuit if the HTTP endpoint isn't being exposed
336 337 338
	if endpoint == "" {
		return nil
	}
339
	listener, handler, err := rpc.StartHTTPEndpoint(endpoint, apis, modules, cors, vhosts, timeouts)
340
	if err != nil {
341 342
		return err
	}
343
	n.log.Info("HTTP endpoint opened", "url", fmt.Sprintf("http://%s", endpoint), "cors", strings.Join(cors, ","), "vhosts", strings.Join(vhosts, ","))
344
	// All listeners booted successfully
345 346 347
	n.httpEndpoint = endpoint
	n.httpListener = listener
	n.httpHandler = handler
348 349 350 351

	return nil
}

352 353 354 355 356 357
// stopHTTP terminates the HTTP RPC endpoint.
func (n *Node) stopHTTP() {
	if n.httpListener != nil {
		n.httpListener.Close()
		n.httpListener = nil

358
		n.log.Info("HTTP endpoint closed", "url", fmt.Sprintf("http://%s", n.httpEndpoint))
359 360 361 362 363 364 365
	}
	if n.httpHandler != nil {
		n.httpHandler.Stop()
		n.httpHandler = nil
	}
}

366
// startWS initializes and starts the websocket RPC endpoint.
367
func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins []string, exposeAll bool) error {
368 369 370 371
	// Short circuit if the WS endpoint isn't being exposed
	if endpoint == "" {
		return nil
	}
372 373
	listener, handler, err := rpc.StartWSEndpoint(endpoint, apis, modules, wsOrigins, exposeAll)
	if err != nil {
374 375
		return err
	}
376
	n.log.Info("WebSocket endpoint opened", "url", fmt.Sprintf("ws://%s", listener.Addr()))
377 378 379 380 381 382 383 384 385 386 387 388 389 390
	// All listeners booted successfully
	n.wsEndpoint = endpoint
	n.wsListener = listener
	n.wsHandler = handler

	return nil
}

// stopWS terminates the websocket RPC endpoint.
func (n *Node) stopWS() {
	if n.wsListener != nil {
		n.wsListener.Close()
		n.wsListener = nil

391
		n.log.Info("WebSocket endpoint closed", "url", fmt.Sprintf("ws://%s", n.wsEndpoint))
392 393 394 395 396 397 398
	}
	if n.wsHandler != nil {
		n.wsHandler.Stop()
		n.wsHandler = nil
	}
}

399 400 401 402 403 404 405
// Stop terminates a running node along with all it's services. In the node was
// not started, an error is returned.
func (n *Node) Stop() error {
	n.lock.Lock()
	defer n.lock.Unlock()

	// Short circuit if the node's not running
406
	if n.server == nil {
407 408
		return ErrNodeStopped
	}
409 410

	// Terminate the API, services and the p2p server.
411
	n.stopWS()
412
	n.stopHTTP()
413
	n.stopIPC()
414
	n.rpcAPIs = nil
415
	failure := &StopError{
416
		Services: make(map[reflect.Type]error),
417
	}
418
	for kind, service := range n.services {
419
		if err := service.Stop(); err != nil {
420
			failure.Services[kind] = err
421 422
		}
	}
423
	n.server.Stop()
424
	n.services = nil
425
	n.server = nil
426 427 428

	// Release instance directory lock.
	if n.instanceDirLock != nil {
429
		if err := n.instanceDirLock.Release(); err != nil {
430
			n.log.Error("Can't release datadir lock", "err", err)
431
		}
432 433 434 435
		n.instanceDirLock = nil
	}

	// unblock n.Wait
436
	close(n.stop)
437

438 439 440 441 442 443
	// Remove the keystore if it was created ephemerally.
	var keystoreErr error
	if n.ephemeralKeystore != "" {
		keystoreErr = os.RemoveAll(n.ephemeralKeystore)
	}

444 445 446
	if len(failure.Services) > 0 {
		return failure
	}
447 448 449
	if keystoreErr != nil {
		return keystoreErr
	}
450 451 452
	return nil
}

453 454 455 456 457
// Wait blocks the thread until the node is stopped. If the node is not running
// at the time of invocation, the method immediately returns.
func (n *Node) Wait() {
	n.lock.RLock()
	if n.server == nil {
458
		n.lock.RUnlock()
459 460 461 462 463 464 465 466
		return
	}
	stop := n.stop
	n.lock.RUnlock()

	<-stop
}

467 468 469 470 471 472 473 474 475 476 477 478
// Restart terminates a running node and boots up a new one in its place. If the
// node isn't running, an error is returned.
func (n *Node) Restart() error {
	if err := n.Stop(); err != nil {
		return err
	}
	if err := n.Start(); err != nil {
		return err
	}
	return nil
}

479
// Attach creates an RPC client attached to an in-process API handler.
480
func (n *Node) Attach() (*rpc.Client, error) {
481 482 483 484 485 486
	n.lock.RLock()
	defer n.lock.RUnlock()

	if n.server == nil {
		return nil, ErrNodeStopped
	}
487
	return rpc.DialInProc(n.inprocHandler), nil
488 489
}

490 491 492 493 494 495 496 497 498 499 500
// RPCHandler returns the in-process RPC request handler.
func (n *Node) RPCHandler() (*rpc.Server, error) {
	n.lock.RLock()
	defer n.lock.RUnlock()

	if n.inprocHandler == nil {
		return nil, ErrNodeStopped
	}
	return n.inprocHandler, nil
}

501 502 503 504 505 506 507
// Server retrieves the currently running P2P network layer. This method is meant
// only to inspect fields of the currently running server, life cycle management
// should be left to this Node entity.
func (n *Node) Server() *p2p.Server {
	n.lock.RLock()
	defer n.lock.RUnlock()

508
	return n.server
509 510
}

511 512
// Service retrieves a currently running service registered of a specific type.
func (n *Node) Service(service interface{}) error {
513 514 515 516 517
	n.lock.RLock()
	defer n.lock.RUnlock()

	// Short circuit if the node's not running
	if n.server == nil {
518
		return ErrNodeStopped
519 520
	}
	// Otherwise try to find the service to return
521 522 523 524
	element := reflect.ValueOf(service).Elem()
	if running, ok := n.services[element.Type()]; ok {
		element.Set(reflect.ValueOf(running))
		return nil
525
	}
526
	return ErrServiceUnknown
527 528
}

529
// DataDir retrieves the current datadir used by the protocol stack.
530
// Deprecated: No files should be stored in this directory, use InstanceDir instead.
531
func (n *Node) DataDir() string {
532
	return n.config.DataDir
533 534
}

535 536 537 538 539
// InstanceDir retrieves the instance directory used by the protocol stack.
func (n *Node) InstanceDir() string {
	return n.config.instanceDir()
}

540 541 542 543 544
// AccountManager retrieves the account manager used by the protocol stack.
func (n *Node) AccountManager() *accounts.Manager {
	return n.accman
}

545 546
// IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.
func (n *Node) IPCEndpoint() string {
547 548 549
	return n.ipcEndpoint
}

550 551 552 553 554 555 556 557 558 559
// HTTPEndpoint retrieves the current HTTP endpoint used by the protocol stack.
func (n *Node) HTTPEndpoint() string {
	return n.httpEndpoint
}

// WSEndpoint retrieves the current WS endpoint used by the protocol stack.
func (n *Node) WSEndpoint() string {
	return n.wsEndpoint
}

560 561 562
// EventMux retrieves the event multiplexer used by all the network services in
// the current protocol stack.
func (n *Node) EventMux() *event.TypeMux {
563
	return n.eventmux
564
}
565

566 567 568 569 570
// OpenDatabase opens an existing database with the given name (or creates one if no
// previous can be found) from within the node's instance directory. If the node is
// ephemeral, a memory database is returned.
func (n *Node) OpenDatabase(name string, cache, handles int) (ethdb.Database, error) {
	if n.config.DataDir == "" {
571
		return ethdb.NewMemDatabase(), nil
572
	}
573
	return ethdb.NewLDBDatabase(n.config.ResolvePath(name), cache, handles)
574 575 576 577
}

// ResolvePath returns the absolute path of a resource in the instance directory.
func (n *Node) ResolvePath(x string) string {
578
	return n.config.ResolvePath(x)
579 580
}

581 582 583
// apis returns the collection of RPC descriptors this node offers.
func (n *Node) apis() []rpc.API {
	return []rpc.API{
584 585 586 587 588 589 590 591 592 593 594 595
		{
			Namespace: "admin",
			Version:   "1.0",
			Service:   NewPrivateAdminAPI(n),
		}, {
			Namespace: "admin",
			Version:   "1.0",
			Service:   NewPublicAdminAPI(n),
			Public:    true,
		}, {
			Namespace: "debug",
			Version:   "1.0",
596
			Service:   debug.Handler,
597 598 599 600 601
		}, {
			Namespace: "debug",
			Version:   "1.0",
			Service:   NewPublicDebugAPI(n),
			Public:    true,
602 603 604 605 606
		}, {
			Namespace: "web3",
			Version:   "1.0",
			Service:   NewPublicWeb3API(n),
			Public:    true,
607 608
		},
	}
609
}