github.com/DxChainNetwork/dxc@v0.8.1-0.20220824085222-1162e304b6e7/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/DxChainNetwork/dxc/core"
    28  	"github.com/DxChainNetwork/dxc/eth/downloader"
    29  	"github.com/DxChainNetwork/dxc/eth/ethconfig"
    30  	"github.com/DxChainNetwork/dxc/ethclient"
    31  	"github.com/DxChainNetwork/dxc/ethstats"
    32  	"github.com/DxChainNetwork/dxc/internal/debug"
    33  	"github.com/DxChainNetwork/dxc/les"
    34  	"github.com/DxChainNetwork/dxc/node"
    35  	"github.com/DxChainNetwork/dxc/p2p"
    36  	"github.com/DxChainNetwork/dxc/p2p/nat"
    37  	"github.com/DxChainNetwork/dxc/params"
    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  	// Listening address of pprof server.
    74  	PprofAddress string
    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  // AddBootstrapNode adds an additional bootstrap node to the node config.
    94  func (conf *NodeConfig) AddBootstrapNode(node *Enode) {
    95  	conf.BootstrapNodes.Append(node)
    96  }
    97  
    98  // EncodeJSON encodes a NodeConfig into a JSON data dump.
    99  func (conf *NodeConfig) EncodeJSON() (string, error) {
   100  	data, err := json.Marshal(conf)
   101  	return string(data), err
   102  }
   103  
   104  // String returns a printable representation of the node config.
   105  func (conf *NodeConfig) String() string {
   106  	return encodeOrError(conf)
   107  }
   108  
   109  // Node represents a Geth Ethereum node instance.
   110  type Node struct {
   111  	node *node.Node
   112  }
   113  
   114  // NewNode creates and configures a new Geth node.
   115  func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
   116  	// If no or partial configurations were specified, use defaults
   117  	if config == nil {
   118  		config = NewNodeConfig()
   119  	}
   120  	if config.MaxPeers == 0 {
   121  		config.MaxPeers = defaultNodeConfig.MaxPeers
   122  	}
   123  	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
   124  		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
   125  	}
   126  
   127  	if config.PprofAddress != "" {
   128  		debug.StartPProf(config.PprofAddress, true)
   129  	}
   130  
   131  	// Create the empty networking stack
   132  	nodeConf := &node.Config{
   133  		Name:        clientIdentifier,
   134  		Version:     params.VersionWithMeta,
   135  		DataDir:     datadir,
   136  		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
   137  		P2P: p2p.Config{
   138  			NoDiscovery:      true,
   139  			DiscoveryV5:      true,
   140  			BootstrapNodesV5: config.BootstrapNodes.nodes,
   141  			ListenAddr:       ":0",
   142  			NAT:              nat.Any(),
   143  			MaxPeers:         config.MaxPeers,
   144  		},
   145  	}
   146  
   147  	rawStack, err := node.New(nodeConf)
   148  	if err != nil {
   149  		return nil, err
   150  	}
   151  
   152  	debug.Memsize.Add("node", rawStack)
   153  
   154  	var genesis *core.Genesis
   155  	if config.EthereumGenesis != "" {
   156  		// Parse the user supplied genesis spec if not mainnet
   157  		genesis = new(core.Genesis)
   158  		if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
   159  			return nil, fmt.Errorf("invalid genesis spec: %v", err)
   160  		}
   161  	}
   162  	// Register the Ethereum protocol if requested
   163  	if config.EthereumEnabled {
   164  		ethConf := ethconfig.Defaults
   165  		ethConf.Genesis = genesis
   166  		ethConf.SyncMode = downloader.LightSync
   167  		ethConf.NetworkId = uint64(config.EthereumNetworkID)
   168  		ethConf.DatabaseCache = config.EthereumDatabaseCache
   169  		lesBackend, err := les.New(rawStack, &ethConf)
   170  		if err != nil {
   171  			return nil, fmt.Errorf("ethereum init: %v", err)
   172  		}
   173  		// If netstats reporting is requested, do it
   174  		if config.EthereumNetStats != "" {
   175  			if err := ethstats.New(rawStack, lesBackend.ApiBackend, lesBackend.Engine(), config.EthereumNetStats); err != nil {
   176  				return nil, fmt.Errorf("netstats init: %v", err)
   177  			}
   178  		}
   179  	}
   180  	return &Node{rawStack}, nil
   181  }
   182  
   183  // Close terminates a running node along with all it's services, tearing internal state
   184  // down. It is not possible to restart a closed node.
   185  func (n *Node) Close() error {
   186  	return n.node.Close()
   187  }
   188  
   189  // Start creates a live P2P node and starts running it.
   190  func (n *Node) Start() error {
   191  	// TODO: recreate the node so it can be started multiple times
   192  	return n.node.Start()
   193  }
   194  
   195  // Stop terminates a running node along with all its services. If the node was not started,
   196  // an error is returned. It is not possible to restart a stopped node.
   197  //
   198  // Deprecated: use Close()
   199  func (n *Node) Stop() error {
   200  	return n.node.Close()
   201  }
   202  
   203  // GetEthereumClient retrieves a client to access the Ethereum subsystem.
   204  func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
   205  	rpc, err := n.node.Attach()
   206  	if err != nil {
   207  		return nil, err
   208  	}
   209  	return &EthereumClient{ethclient.NewClient(rpc)}, nil
   210  }
   211  
   212  // GetNodeInfo gathers and returns a collection of metadata known about the host.
   213  func (n *Node) GetNodeInfo() *NodeInfo {
   214  	return &NodeInfo{n.node.Server().NodeInfo()}
   215  }
   216  
   217  // GetPeersInfo returns an array of metadata objects describing connected peers.
   218  func (n *Node) GetPeersInfo() *PeerInfos {
   219  	return &PeerInfos{n.node.Server().PeersInfo()}
   220  }