service

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 13, 2019 License: LGPL-3.0 Imports: 26 Imported by: 0

Documentation

Overview

Modified from go-ethereum under GNU Lesser General Public License

Modified from go-ethereum under GNU Lesser General Public License

Modified from go-ethereum under GNU Lesser General Public License

Modified from go-ethereum under GNU Lesser General Public License

Modified from go-ethereum under GNU Lesser General Public License

Index

Examples

Constants

View Source
const (
	DefaultHTTPHost        = "localhost" // Default host interface for the HTTP RPC server
	DefaultHTTPPort        = 38391       // Default TCP port for the public HTTP RPC server
	DefaultPrivateHTTPPort = 38491       // Default TCP port for the private HTTP RPC server
	DefaultWSHost          = "localhost" // Default host interface for the websocket RPC server
	DefaultWSPort          = 8546        // Default TCP port for the websocket RPC server
)

Variables

View Source
var (
	ErrDatadirUsed    = errors.New("datadir already used by another process")
	ErrNodeStopped    = errors.New("node not started")
	ErrNodeRunning    = errors.New("node already running")
	ErrServiceUnknown = errors.New("unknown service")
)
View Source
var DefaultConfig = Config{
	DataDir:      DefaultDataDir(),
	HTTPModules:  []string{"qkc"},
	HTTPTimeouts: rpc.DefaultHTTPTimeouts,
	WSPort:       DefaultWSPort,
	WSModules:    []string{},

	P2P: p2p.Config{
		ListenAddr: ":38291",
		MaxPeers:   25,
		NAT:        nat.Any(),
	},
}

DefaultConfig contains reasonable default settings.

Functions

func DefaultDataDir

func DefaultDataDir() string

DefaultDataDir is the default data directory to use for the databases and other persistence requirements.

Types

type Config

type Config struct {
	// Name sets the instance name of the node. It must not contain the / character and is
	// used in the devp2p node identifier. The instance name of geth is "geth". If no
	// value is specified, the basename of the current executable is used.
	Name string `toml:"-"`

	// Version should be set to the version number of the program. It is used
	// in the devp2p node identifier.
	Version string `toml:"-"`

	// DataDir is the file system folder the node should use for any data storage
	// requirements. The configured data directory will not be directly shared with
	// registered services, instead those can use utility methods to create/access
	// databases or flat files. This enables ephemeral nodes which can fully reside
	// in memory.
	DataDir string

	// Configuration of peer-to-peer networking.
	P2P p2p.Config

	// IPCPath is the requested location to place the IPC endpoint. If the path is
	// a simple file name, it is placed inside the data directory (or on the root
	// pipe path on Windows), whereas if it's a resolvable path name (absolute or
	// relative), then that specific path is enforced. An empty path disables IPC.
	IPCPath string `toml:",omitempty"`

	HTTPEndpoint string `toml:",omitempty"`

	// HTTPModules is a list of API modules to expose via the HTTP RPC interface.
	// If the module list is empty, all RPC API endpoints designated public will be
	// exposed.
	HTTPModules []string `toml:",omitempty"`

	HTTPPrivEndpoint string `toml:",omitempty"`

	// HTTPTimeouts allows for customization of the timeout values used by the HTTP RPC
	// interface.
	HTTPTimeouts rpc.HTTPTimeouts

	// WSHost is the host interface on which to start the websocket RPC server. If
	// this field is empty, no websocket API endpoint will be started.
	WSHost string `toml:",omitempty"`

	// WSPort is the TCP port number on which to start the websocket RPC server. The
	// default zero value is/ valid and will pick a port number randomly (useful for
	// ephemeral nodes).
	WSPort int `toml:",omitempty"`

	// WSOrigins is the list of domain to accept websocket requests from. Please be
	// aware that the server can only act upon the HTTP request the client sends and
	// cannot verify the validity of the request header.
	WSOrigins []string `toml:",omitempty"`

	// WSModules is a list of API modules to expose via the websocket RPC interface.
	// If the module list is empty, all RPC API endpoints designated public will be
	// exposed.
	WSModules []string `toml:",omitempty"`

	// WSExposeAll exposes all API modules via the WebSocket RPC interface rather
	// than just the public ones.
	//
	// *WARNING* Only set this if the node is running in a trusted network, exposing
	// private APIs to untrusted users is a major security risk.
	WSExposeAll bool `toml:",omitempty"`

	// grpc service endpoint
	SvrHost   string `toml:",omitempty"`
	SvrPort   uint16 `toml:",omitempty"`
	SvrModule string `toml:",omitempty"`

	// Logger is a custom logger to use with the p2p.Server.
	Logger log.Logger `toml:",omitempty"`
	// contains filtered or unexported fields
}

Config represents a small collection of configuration values to fine tune the P2P network layer of a protocol stack. These values can be further extended by all registered services.

func (*Config) GRPCEndpoint

func (c *Config) GRPCEndpoint() string

func (*Config) IPCEndpoint

func (c *Config) IPCEndpoint() string

IPCEndpoint resolves an IPC endpoint based on a configured value, taking into account the set data folders as well as the designated platform we're currently running on.

func (*Config) NodeDB

func (c *Config) NodeDB() string

NodeDB returns the path to the discovery node database.

func (*Config) NodeKey

func (c *Config) NodeKey() *ecdsa.PrivateKey

NodeKey retrieves the currently configured private key of the node, checking first any manually set key, falling back to the one found in the configured data folder. If no key can be found, a new one is generated.

func (*Config) NodeName

func (c *Config) NodeName() string

NodeName returns the devp2p node identifier.

func (*Config) ResolvePath

func (c *Config) ResolvePath(path string) string

ResolvePath resolves path in the instance directory.

func (*Config) StaticNodes

func (c *Config) StaticNodes() []*enode.Node

StaticNodes returns a list of node enode URLs configured as static nodes.

func (*Config) TrustedNodes

func (c *Config) TrustedNodes() []*enode.Node

TrustedNodes returns a list of node enode URLs configured as trusted nodes.

func (*Config) WSEndpoint

func (c *Config) WSEndpoint() string

WSEndpoint resolves a websocket endpoint based on the configured host interface and port parameters.

type DuplicateServiceError

type DuplicateServiceError struct {
	Kind reflect.Type
}

DuplicateServiceError is returned during Node startup if a registered service constructor returns a service of the same type that was already started.

func (*DuplicateServiceError) Error

func (e *DuplicateServiceError) Error() string

Error generates a textual representation of the duplicate service error.

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node is a container on which services can be registered.

func New

func New(conf *Config) (*Node, error)

New creates a new P2P node, ready for protocol registration.

func (*Node) Attach

func (n *Node) Attach() (*rpc.Client, error)

Attach creates an RPC client attached to an in-process API handler.

func (*Node) DataDir

func (n *Node) DataDir() string

DataDir retrieves the current datadir used by the protocol stack. Deprecated: No files should be stored in this directory, use InstanceDir instead.

func (*Node) EventMux

func (n *Node) EventMux() *event.TypeMux

EventMux retrieves the event multiplexer used by all the network services in the current protocol stack.

func (*Node) GetSigc

func (n *Node) GetSigc() chan os.Signal

func (*Node) HTTPEndpoint

func (n *Node) HTTPEndpoint() string

HTTPEndpoint retrieves the current HTTP endpoint used by the protocol stack.

func (*Node) IPCEndpoint

func (n *Node) IPCEndpoint() string

IPCEndpoint retrieves the current IPC endpoint used by the protocol stack.

func (*Node) InstanceDir

func (n *Node) InstanceDir() string

InstanceDir retrieves the instance directory used by the protocol stack.

func (*Node) IsMaster

func (n *Node) IsMaster() bool

func (*Node) RPCHandler

func (n *Node) RPCHandler() (*rpc.Server, error)

RPCHandler returns the in-process RPC request handler.

func (*Node) Register

func (n *Node) Register(constructor ServiceConstructor) error

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 (*Node) ResolvePath

func (n *Node) ResolvePath(x string) string

ResolvePath returns the absolute path of a resource in the instance directory.

func (*Node) Restart

func (n *Node) Restart() error

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 (*Node) Server

func (n *Node) Server() *p2p.Server

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 (*Node) Service

func (n *Node) Service(service interface{}) error

Service retrieves a currently running service registered of a specific type.

func (*Node) SetIsMaster

func (n *Node) SetIsMaster(isMaster bool)

func (*Node) Start

func (n *Node) Start() error

Start create a live P2P node and starts running it.

func (*Node) Stop

func (n *Node) Stop() error

Stop terminates a running node along with all it's services. In the node was not started, an error is returned.

func (*Node) Wait

func (n *Node) Wait()

Wait blocks the thread until the node is stopped. If the node is not running at the time of invocation, the method immediately returns.

type Service

type Service interface {
	// Protocols retrieves the P2P protocols the service wishes to start.
	Protocols() []p2p.Protocol

	// APIs retrieves the list of RPC descriptors the service provides
	APIs() []rpc.API

	// Start is called after all services have been constructed and the networking
	// layer was also initialized to spawn any goroutines required by the service.
	Init(server *p2p.Server) error

	// Stop terminates all goroutines belonging to the service, blocking until they
	// are all terminated.
	Stop() error
}

Service is an individual protocol that can be registered into a node.

Notes:

• Service life-cycle management is delegated to the node. The service is allowed to initialize itself upon creation, but no goroutines should be spun up outside of the Start method.

• Restart logic is not required as the node will create a fresh instance every time a service is started.

Example
// Modified from go-ethereum under GNU Lesser General Public License
package main

import (
	"fmt"
	"log"

	"github.com/QuarkChain/goquarkchain/p2p"
	"github.com/ethereum/go-ethereum/rpc"
)

// SampleService is a trivial network service that can be attached to a node for
// life cycle management.
//
// The following methods are needed to implement a node.Service:
//   - Protocols() []p2p.Protocol - devp2p protocols the service can communicate on
//   - APIs() []rpc.API           - api methods the service wants to expose on rpc channels
//   - Start() error              - method invoked when the node is ready to start the service
//   - Stop() error               - method invoked when the node terminates the service
type SampleService struct{}

func (s *SampleService) Protocols() []p2p.Protocol { return nil }
func (s *SampleService) APIs() []rpc.API           { return nil }
func (s *SampleService) Init(*p2p.Server) error    { fmt.Println("Service starting..."); return nil }
func (s *SampleService) Stop() error               { fmt.Println("Service stopping..."); return nil }

func main() {
	// Create a network node to run protocols with the default values.
	stack, err := New(&Config{})
	if err != nil {
		log.Fatalf("Failed to create network node: %v", err)
	}
	// Create and register a simple network service. This is done through the definition
	// of a node.ServiceConstructor that will instantiate a node.Service. The reason for
	// the factory method approach is to support service restarts without relying on the
	// individual implementations' support for such operations.
	constructor := func(context *ServiceContext) (Service, error) {
		return new(SampleService), nil
	}
	if err := stack.Register(constructor); err != nil {
		log.Fatalf("Failed to register service: %v", err)
	}
	// Boot up the entire protocol stack, do a restart and terminate
	if err := stack.Start(); err != nil {
		log.Fatalf("Failed to start the protocol stack: %v", err)
	}
	if err := stack.Restart(); err != nil {
		log.Fatalf("Failed to restart the protocol stack: %v", err)
	}
	if err := stack.Stop(); err != nil {
		log.Fatalf("Failed to stop the protocol stack: %v", err)
	}
}
Output:

Service starting...
Service stopping...
Service starting...
Service stopping...

type ServiceConstructor

type ServiceConstructor func(ctx *ServiceContext) (Service, error)

ServiceConstructor is the function signature of the constructors needed to be registered for service instantiation.

type ServiceContext

type ServiceContext struct {
	Shutdown  chan os.Signal
	Timestamp time.Time
	EventMux  *event.TypeMux // Event multiplexer used for decoupled notifications
	// contains filtered or unexported fields
}

ServiceContext is a collection of service independent options inherited from the protocol stack, that is passed to all constructors to be optionally used; as well as utility methods to operate on the service environment.

func (*ServiceContext) OpenDatabase

func (ctx *ServiceContext) OpenDatabase(name string, clean bool) (ethdb.Database, error)

OpenDatabase opens an existing database with the given name (or creates one if no previous can be found) from within the node's data directory. If the node is an ephemeral one, a memory database is returned.

func (*ServiceContext) ResolvePath

func (ctx *ServiceContext) ResolvePath(path string) string

ResolvePath resolves a user path into the data directory if that was relative and if the user actually uses persistent storage. It will return an empty string for emphemeral storage and the user's own input for absolute paths.

func (*ServiceContext) Service

func (ctx *ServiceContext) Service(service interface{}) error

Service retrieves a currently running service registered of a specific type.

type StopError

type StopError struct {
	Server   error
	Services map[reflect.Type]error
}

StopError is returned if a Node fails to stop either any of its registered services or itself.

func (*StopError) Error

func (e *StopError) Error() string

Error generates a textual representation of the stop error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL