github.com/letterj/go-ethereum@v1.8.22-0.20190204142846-520024dfd689/mobile/geth.go (about)

     1  // Copyright 2016 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  // Contains all the wrappers from the node package to support client side node
    18  // management on mobile platforms.
    19  
    20  package geth
    21  
    22  import (
    23  	"encoding/json"
    24  	"fmt"
    25  	"path/filepath"
    26  
    27  	"github.com/ethereum/go-ethereum/core"
    28  	"github.com/ethereum/go-ethereum/eth"
    29  	"github.com/ethereum/go-ethereum/eth/downloader"
    30  	"github.com/ethereum/go-ethereum/ethclient"
    31  	"github.com/ethereum/go-ethereum/ethstats"
    32  	"github.com/ethereum/go-ethereum/internal/debug"
    33  	"github.com/ethereum/go-ethereum/les"
    34  	"github.com/ethereum/go-ethereum/node"
    35  	"github.com/ethereum/go-ethereum/p2p"
    36  	"github.com/ethereum/go-ethereum/p2p/nat"
    37  	"github.com/ethereum/go-ethereum/params"
    38  	whisper "github.com/ethereum/go-ethereum/whisper/whisperv6"
    39  )
    40  
    41  // NodeConfig represents the collection of configuration values to fine tune the Geth
    42  // node embedded into a mobile process. The available values are a subset of the
    43  // entire API provided by go-ethereum to reduce the maintenance surface and dev
    44  // complexity.
    45  type NodeConfig struct {
    46  	// Bootstrap nodes used to establish connectivity with the rest of the network.
    47  	BootstrapNodes *Enodes
    48  
    49  	// MaxPeers is the maximum number of peers that can be connected. If this is
    50  	// set to zero, then only the configured static and trusted peers can connect.
    51  	MaxPeers int
    52  
    53  	// EthereumEnabled specifies whether the node should run the Ethereum protocol.
    54  	EthereumEnabled bool
    55  
    56  	// EthereumNetworkID is the network identifier used by the Ethereum protocol to
    57  	// decide if remote peers should be accepted or not.
    58  	EthereumNetworkID int64 // uint64 in truth, but Java can't handle that...
    59  
    60  	// EthereumGenesis is the genesis JSON to use to seed the blockchain with. An
    61  	// empty genesis state is equivalent to using the mainnet's state.
    62  	EthereumGenesis string
    63  
    64  	// EthereumDatabaseCache is the system memory in MB to allocate for database caching.
    65  	// A minimum of 16MB is always reserved.
    66  	EthereumDatabaseCache int
    67  
    68  	// EthereumNetStats is a netstats connection string to use to report various
    69  	// chain, transaction and node stats to a monitoring server.
    70  	//
    71  	// It has the form "nodename:secret@host:port"
    72  	EthereumNetStats string
    73  
    74  	// WhisperEnabled specifies whether the node should run the Whisper protocol.
    75  	WhisperEnabled bool
    76  
    77  	// Listening address of pprof server.
    78  	PprofAddress string
    79  
    80  	// Ultra Light client options
    81  	ULC *eth.ULCConfig
    82  }
    83  
    84  // defaultNodeConfig contains the default node configuration values to use if all
    85  // or some fields are missing from the user's specified list.
    86  var defaultNodeConfig = &NodeConfig{
    87  	BootstrapNodes:        FoundationBootnodes(),
    88  	MaxPeers:              25,
    89  	EthereumEnabled:       true,
    90  	EthereumNetworkID:     1,
    91  	EthereumDatabaseCache: 16,
    92  }
    93  
    94  // NewNodeConfig creates a new node option set, initialized to the default values.
    95  func NewNodeConfig() *NodeConfig {
    96  	config := *defaultNodeConfig
    97  	return &config
    98  }
    99  
   100  // Node represents a Geth Ethereum node instance.
   101  type Node struct {
   102  	node *node.Node
   103  }
   104  
   105  // NewNode creates and configures a new Geth node.
   106  func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
   107  	// If no or partial configurations were specified, use defaults
   108  	if config == nil {
   109  		config = NewNodeConfig()
   110  	}
   111  	if config.MaxPeers == 0 {
   112  		config.MaxPeers = defaultNodeConfig.MaxPeers
   113  	}
   114  	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
   115  		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
   116  	}
   117  
   118  	if config.PprofAddress != "" {
   119  		debug.StartPProf(config.PprofAddress)
   120  	}
   121  
   122  	// Create the empty networking stack
   123  	nodeConf := &node.Config{
   124  		Name:        clientIdentifier,
   125  		Version:     params.VersionWithMeta,
   126  		DataDir:     datadir,
   127  		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
   128  		P2P: p2p.Config{
   129  			NoDiscovery:      true,
   130  			DiscoveryV5:      true,
   131  			BootstrapNodesV5: config.BootstrapNodes.nodes,
   132  			ListenAddr:       ":0",
   133  			NAT:              nat.Any(),
   134  			MaxPeers:         config.MaxPeers,
   135  		},
   136  	}
   137  
   138  	rawStack, err := node.New(nodeConf)
   139  	if err != nil {
   140  		return nil, err
   141  	}
   142  
   143  	debug.Memsize.Add("node", rawStack)
   144  
   145  	var genesis *core.Genesis
   146  	if config.EthereumGenesis != "" {
   147  		// Parse the user supplied genesis spec if not mainnet
   148  		genesis = new(core.Genesis)
   149  		if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
   150  			return nil, fmt.Errorf("invalid genesis spec: %v", err)
   151  		}
   152  		// If we have the testnet, hard code the chain configs too
   153  		if config.EthereumGenesis == TestnetGenesis() {
   154  			genesis.Config = params.TestnetChainConfig
   155  			if config.EthereumNetworkID == 1 {
   156  				config.EthereumNetworkID = 3
   157  			}
   158  		}
   159  	}
   160  	// Register the Ethereum protocol if requested
   161  	if config.EthereumEnabled {
   162  		ethConf := eth.DefaultConfig
   163  		ethConf.Genesis = genesis
   164  		ethConf.SyncMode = downloader.LightSync
   165  		ethConf.NetworkId = uint64(config.EthereumNetworkID)
   166  		ethConf.DatabaseCache = config.EthereumDatabaseCache
   167  		if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   168  			return les.New(ctx, &ethConf)
   169  		}); err != nil {
   170  			return nil, fmt.Errorf("ethereum init: %v", err)
   171  		}
   172  		// If netstats reporting is requested, do it
   173  		if config.EthereumNetStats != "" {
   174  			if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   175  				var lesServ *les.LightEthereum
   176  				ctx.Service(&lesServ)
   177  
   178  				return ethstats.New(config.EthereumNetStats, nil, lesServ)
   179  			}); err != nil {
   180  				return nil, fmt.Errorf("netstats init: %v", err)
   181  			}
   182  		}
   183  	}
   184  	// Register the Whisper protocol if requested
   185  	if config.WhisperEnabled {
   186  		if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) {
   187  			return whisper.New(&whisper.DefaultConfig), nil
   188  		}); err != nil {
   189  			return nil, fmt.Errorf("whisper init: %v", err)
   190  		}
   191  	}
   192  	return &Node{rawStack}, nil
   193  }
   194  
   195  // Start creates a live P2P node and starts running it.
   196  func (n *Node) Start() error {
   197  	return n.node.Start()
   198  }
   199  
   200  // Stop terminates a running node along with all it's services. If the node was
   201  // not started, an error is returned.
   202  func (n *Node) Stop() error {
   203  	return n.node.Stop()
   204  }
   205  
   206  // GetEthereumClient retrieves a client to access the Ethereum subsystem.
   207  func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
   208  	rpc, err := n.node.Attach()
   209  	if err != nil {
   210  		return nil, err
   211  	}
   212  	return &EthereumClient{ethclient.NewClient(rpc)}, nil
   213  }
   214  
   215  // GetNodeInfo gathers and returns a collection of metadata known about the host.
   216  func (n *Node) GetNodeInfo() *NodeInfo {
   217  	return &NodeInfo{n.node.Server().NodeInfo()}
   218  }
   219  
   220  // GetPeersInfo returns an array of metadata objects describing connected peers.
   221  func (n *Node) GetPeersInfo() *PeerInfos {
   222  	return &PeerInfos{n.node.Server().PeersInfo()}
   223  }