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