github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/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  	// A private network Enabled specifies whether the node should get a local ip ( 192.168.0.x ) for reapchian
    76  	PrivateNetEnabled bool
    77  
    78  
    79  }
    80  
    81  // defaultNodeConfig contains the default node configuration values to use if all
    82  // or some fields are missing from the user's specified list.
    83  var defaultNodeConfig = &NodeConfig{
    84  	BootstrapNodes:        FoundationBootnodes(),
    85  	MaxPeers:              25,
    86  	EthereumEnabled:       true,
    87  	EthereumNetworkID:     1,
    88  	EthereumDatabaseCache: 16,
    89  }
    90  
    91  // NewNodeConfig creates a new node option set, initialized to the default values.
    92  func NewNodeConfig() *NodeConfig {
    93  	config := *defaultNodeConfig
    94  	return &config
    95  }
    96  
    97  // Node represents a Geth Ethereum node instance.
    98  type Node struct {
    99  	node *node.Node
   100  }
   101  
   102  // NewNode creates and configures a new Geth node.
   103  func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
   104  	// If no or partial configurations were specified, use defaults
   105  	if config == nil {
   106  		config = NewNodeConfig()
   107  	}
   108  	if config.MaxPeers == 0 {
   109  		config.MaxPeers = defaultNodeConfig.MaxPeers
   110  	}
   111  	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
   112  		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
   113  	}
   114  	// Create the empty networking stack
   115  	nodeConf := &node.Config{
   116  		Name:        clientIdentifier,
   117  		Version:     params.Version,
   118  		DataDir:     datadir,
   119  		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
   120  		P2P: p2p.Config{
   121  			NoDiscovery:      true,
   122  			DiscoveryV5:      false,  /* disabled for simple */
   123  			DiscoveryV5Addr:  ":0",
   124  			BootstrapNodesV5: config.BootstrapNodes.nodes,
   125  			ListenAddr:       ":0",
   126  			NAT:              nat.Any(),
   127  			MaxPeers:         config.MaxPeers,
   128  		},
   129  	}
   130  	rawStack, err := node.New(nodeConf)
   131  	if err != nil {
   132  		return nil, err
   133  	}
   134  
   135  	var genesis *core.Genesis
   136  	if config.EthereumGenesis != "" {
   137  		// Parse the user supplied genesis spec if not mainnet  //genesis.json reading
   138  		genesis = new(core.Genesis)
   139  		if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
   140  			return nil, fmt.Errorf("invalid genesis spec: %v", err)
   141  		}
   142  		// If we have the testnet, hard code the chain configs too
   143  		if config.EthereumGenesis == TestnetGenesis() {
   144  			genesis.Config = params.TestnetChainConfig
   145  			if config.EthereumNetworkID == 1 {
   146  				config.EthereumNetworkID = 3
   147  			}
   148  		}
   149  	}
   150  	// Register the Ethereum protocol if requested
   151  	if config.EthereumEnabled {
   152  		ethConf := eth.DefaultConfig
   153  		ethConf.Genesis = genesis
   154  		ethConf.SyncMode = downloader.LightSync
   155  		ethConf.NetworkId = uint64(config.EthereumNetworkID)
   156  		ethConf.DatabaseCache = config.EthereumDatabaseCache
   157  		if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   158  			return les.New(ctx, &ethConf)
   159  		}); err != nil {
   160  			return nil, fmt.Errorf("ethereum init: %v", err)
   161  		}
   162  		// If netstats reporting is requested, do it
   163  		if config.EthereumNetStats != "" {
   164  			if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   165  				var lesServ *les.LightEthereum
   166  				ctx.Service(&lesServ)
   167  
   168  				return ethstats.New(config.EthereumNetStats, nil, lesServ)
   169  			}); err != nil {
   170  				return nil, fmt.Errorf("netstats init: %v", err)
   171  			}
   172  		}
   173  	}
   174  	// Register the Whisper protocol if requested
   175  	if config.WhisperEnabled {
   176  		if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
   177  			return nil, fmt.Errorf("whisper init: %v", err)
   178  		}
   179  	}
   180  	return &Node{rawStack}, nil
   181  }
   182  
   183  // Start creates a live P2P node and starts running it.
   184  func (n *Node) Start() error {
   185  	return n.node.Start()
   186  }
   187  
   188  // Stop terminates a running node along with all it's services. In the node was
   189  // not started, an error is returned.
   190  func (n *Node) Stop() error {
   191  	return n.node.Stop()
   192  }
   193  
   194  // GetEthereumClient retrieves a client to access the Ethereum subsystem.
   195  func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
   196  	rpc, err := n.node.Attach()
   197  	if err != nil {
   198  		return nil, err
   199  	}
   200  	return &EthereumClient{ethclient.NewClient(rpc)}, nil
   201  }
   202  
   203  // GetNodeInfo gathers and returns a collection of metadata known about the host.
   204  func (n *Node) GetNodeInfo() *NodeInfo {
   205  	return &NodeInfo{n.node.Server().NodeInfo()}
   206  }
   207  
   208  // GetPeersInfo returns an array of metadata objects describing connected peers.
   209  func (n *Node) GetPeersInfo() *PeerInfos {
   210  	return &PeerInfos{n.node.Server().PeersInfo()}
   211  }