github.com/bcskill/bcschain/v3@v3.4.9-beta2/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  	"context"
    24  	"encoding/json"
    25  	"fmt"
    26  	"path/filepath"
    27  
    28  	"github.com/bcskill/bcschain/v3/core"
    29  	"github.com/bcskill/bcschain/v3/eth"
    30  	"github.com/bcskill/bcschain/v3/eth/downloader"
    31  	"github.com/bcskill/bcschain/v3/goclient"
    32  	"github.com/bcskill/bcschain/v3/les"
    33  	"github.com/bcskill/bcschain/v3/netstats"
    34  	"github.com/bcskill/bcschain/v3/node"
    35  	"github.com/bcskill/bcschain/v3/p2p"
    36  	"github.com/bcskill/bcschain/v3/p2p/nat"
    37  	"github.com/bcskill/bcschain/v3/params"
    38  	whisper "github.com/bcskill/bcschain/v3/whisper/whisperv6"
    39  )
    40  
    41  // NodeConfig represents the collection of configuration values to fine tune the GoChain
    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 GoChain protocol.
    54  	EthereumEnabled bool
    55  
    56  	// EthereumNetworkID is the network identifier used by the GoChain 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  
    78  // defaultNodeConfig contains the default node configuration values to use if all
    79  // or some fields are missing from the user's specified list.
    80  var defaultNodeConfig = &NodeConfig{
    81  	BootstrapNodes:        FoundationBootnodes(),
    82  	MaxPeers:              25,
    83  	EthereumEnabled:       true,
    84  	EthereumNetworkID:     1,
    85  	EthereumDatabaseCache: 16,
    86  }
    87  
    88  // NewNodeConfig creates a new node option set, initialized to the default values.
    89  func NewNodeConfig() *NodeConfig {
    90  	config := *defaultNodeConfig
    91  	return &config
    92  }
    93  
    94  // Node represents a GoChain GoChain node instance.
    95  type Node struct {
    96  	node *node.Node
    97  }
    98  
    99  // NewNode creates and configures a new GoChain node.
   100  func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
   101  	// If no or partial configurations were specified, use defaults
   102  	if config == nil {
   103  		config = NewNodeConfig()
   104  	}
   105  	if config.MaxPeers == 0 {
   106  		config.MaxPeers = defaultNodeConfig.MaxPeers
   107  	}
   108  	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
   109  		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
   110  	}
   111  	// Create the empty networking stack
   112  	nodeConf := &node.Config{
   113  		Name:        clientIdentifier,
   114  		Version:     params.Version,
   115  		DataDir:     datadir,
   116  		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
   117  		P2P: p2p.Config{
   118  			NoDiscovery:      true,
   119  			DiscoveryV5:      true,
   120  			BootstrapNodesV5: config.BootstrapNodes.nodes,
   121  			ListenAddr:       ":0",
   122  			NAT:              nat.Any(),
   123  			MaxPeers:         config.MaxPeers,
   124  		},
   125  	}
   126  	rawStack, err := node.New(nodeConf)
   127  	if err != nil {
   128  		return nil, err
   129  	}
   130  
   131  	var genesis *core.Genesis
   132  	if config.EthereumGenesis != "" {
   133  		// Parse the user supplied genesis spec if not mainnet
   134  		genesis = new(core.Genesis)
   135  		if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
   136  			return nil, fmt.Errorf("invalid genesis spec: %v", err)
   137  		}
   138  		// If we have the testnet, hard code the chain configs too
   139  		if config.EthereumGenesis == TestnetGenesis() {
   140  			genesis.Config = params.TestnetChainConfig
   141  			if config.EthereumNetworkID == 1 {
   142  				config.EthereumNetworkID = 3
   143  			}
   144  		}
   145  	}
   146  	// Register the GoChain protocol if requested
   147  	if config.EthereumEnabled {
   148  		ethConf := eth.DefaultConfig
   149  		ethConf.Genesis = genesis
   150  		ethConf.SyncMode = downloader.LightSync
   151  		ethConf.NetworkId = uint64(config.EthereumNetworkID)
   152  		ethConf.DatabaseCache = config.EthereumDatabaseCache
   153  		if err := rawStack.Register(func(sctx *node.ServiceContext) (node.Service, error) {
   154  			ctx := context.TODO()
   155  			return les.New(ctx, sctx, &ethConf)
   156  		}); err != nil {
   157  			return nil, fmt.Errorf("ethereum init: %v", err)
   158  		}
   159  		// If netstats reporting is requested, do it
   160  		if config.EthereumNetStats != "" {
   161  			if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   162  				var lesServ *les.LightGoChain
   163  				ctx.Service(&lesServ)
   164  				cfg, err := netstats.ParseConfig(config.EthereumNetStats)
   165  				if err != nil {
   166  					return nil, err
   167  				}
   168  				return netstats.New(cfg, nil, lesServ), nil
   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) {
   177  			return whisper.New(&whisper.DefaultConfig), nil
   178  		}); err != nil {
   179  			return nil, fmt.Errorf("whisper init: %v", err)
   180  		}
   181  	}
   182  	return &Node{rawStack}, nil
   183  }
   184  
   185  // Start creates a live P2P node and starts running it.
   186  func (n *Node) Start() error {
   187  	return n.node.Start()
   188  }
   189  
   190  // Stop terminates a running node along with all it's services. In the node was
   191  // not started, an error is returned.
   192  func (n *Node) Stop() error {
   193  	return n.node.Stop()
   194  }
   195  
   196  // GetGoClient retrieves a client to access the GoChain subsystem.
   197  func (n *Node) GetGoClient() (client *GoClient, _ error) {
   198  	rpc, err := n.node.Attach()
   199  	if err != nil {
   200  		return nil, err
   201  	}
   202  	return &GoClient{goclient.NewClient(rpc)}, nil
   203  }
   204  
   205  // GetNodeInfo gathers and returns a collection of metadata known about the host.
   206  func (n *Node) GetNodeInfo() *NodeInfo {
   207  	return &NodeInfo{n.node.Server().NodeInfo()}
   208  }
   209  
   210  // GetPeersInfo returns an array of metadata objects describing connected peers.
   211  func (n *Node) GetPeersInfo() *PeerInfos {
   212  	return &PeerInfos{n.node.Server().PeersInfo()}
   213  }