github.com/fff-chain/go-fff@v0.0.0-20220726032732-1c84420b8a99/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  	"github.com/fff-chain/go-fff/global_config"
    26  	"path/filepath"
    27  
    28  	"github.com/fff-chain/go-fff/core"
    29  	"github.com/fff-chain/go-fff/eth/downloader"
    30  	"github.com/fff-chain/go-fff/eth/ethconfig"
    31  	"github.com/fff-chain/go-fff/ethclient"
    32  	"github.com/fff-chain/go-fff/ethstats"
    33  	"github.com/fff-chain/go-fff/internal/debug"
    34  	"github.com/fff-chain/go-fff/les"
    35  	"github.com/fff-chain/go-fff/node"
    36  	"github.com/fff-chain/go-fff/p2p"
    37  	"github.com/fff-chain/go-fff/p2p/nat"
    38  	"github.com/fff-chain/go-fff/params"
    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  	// Listening address of pprof server.
    75  	PprofAddress string
    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:     int64(global_config.NetworkID),
    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  // AddBootstrapNode adds an additional bootstrap node to the node config.
    95  func (conf *NodeConfig) AddBootstrapNode(node *Enode) {
    96  	conf.BootstrapNodes.Append(node)
    97  }
    98  
    99  // EncodeJSON encodes a NodeConfig into a JSON data dump.
   100  func (conf *NodeConfig) EncodeJSON() (string, error) {
   101  	data, err := json.Marshal(conf)
   102  	return string(data), err
   103  }
   104  
   105  // String returns a printable representation of the node config.
   106  func (conf *NodeConfig) String() string {
   107  	return encodeOrError(conf)
   108  }
   109  
   110  // Node represents a Geth Ethereum node instance.
   111  type Node struct {
   112  	node *node.Node
   113  }
   114  
   115  // NewNode creates and configures a new Geth node.
   116  func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
   117  	// If no or partial configurations were specified, use defaults
   118  	if config == nil {
   119  		config = NewNodeConfig()
   120  	}
   121  	if config.MaxPeers == 0 {
   122  		config.MaxPeers = defaultNodeConfig.MaxPeers
   123  	}
   124  	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
   125  		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
   126  	}
   127  
   128  	if config.PprofAddress != "" {
   129  		debug.StartPProf(config.PprofAddress, true)
   130  	}
   131  
   132  	// Create the empty networking stack
   133  	nodeConf := &node.Config{
   134  		Name:        clientIdentifier,
   135  		Version:     params.VersionWithMeta,
   136  		DataDir:     datadir,
   137  		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
   138  		P2P: p2p.Config{
   139  			NoDiscovery:      true,
   140  			DiscoveryV5:      true,
   141  			BootstrapNodesV5: config.BootstrapNodes.nodes,
   142  			ListenAddr:       ":0",
   143  			NAT:              nat.Any(),
   144  			MaxPeers:         config.MaxPeers,
   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  		// If we have the Ropsten testnet, hard code the chain configs too
   162  		if config.EthereumGenesis == RopstenGenesis() {
   163  			genesis.Config = params.RopstenChainConfig
   164  			if config.EthereumNetworkID == 1 {
   165  				config.EthereumNetworkID = 3
   166  			}
   167  		}
   168  		// If we have the Rinkeby testnet, hard code the chain configs too
   169  		if config.EthereumGenesis == RinkebyGenesis() {
   170  			genesis.Config = params.RinkebyChainConfig
   171  			if config.EthereumNetworkID == 1 {
   172  				config.EthereumNetworkID = 4
   173  			}
   174  		}
   175  		// If we have the Goerli testnet, hard code the chain configs too
   176  		if config.EthereumGenesis == GoerliGenesis() {
   177  			genesis.Config = params.GoerliChainConfig
   178  			if config.EthereumNetworkID == 1 {
   179  				config.EthereumNetworkID = 5
   180  			}
   181  		}
   182  	}
   183  	// Register the Ethereum protocol if requested
   184  	if config.EthereumEnabled {
   185  		ethConf := ethconfig.Defaults
   186  		ethConf.Genesis = genesis
   187  		ethConf.SyncMode = downloader.LightSync
   188  		ethConf.NetworkId = uint64(config.EthereumNetworkID)
   189  		ethConf.DatabaseCache = config.EthereumDatabaseCache
   190  		lesBackend, err := les.New(rawStack, &ethConf)
   191  		if err != nil {
   192  			return nil, fmt.Errorf("ethereum init: %v", err)
   193  		}
   194  		// If netstats reporting is requested, do it
   195  		if config.EthereumNetStats != "" {
   196  			if err := ethstats.New(rawStack, lesBackend.ApiBackend, lesBackend.Engine(), config.EthereumNetStats); err != nil {
   197  				return nil, fmt.Errorf("netstats init: %v", err)
   198  			}
   199  		}
   200  	}
   201  	return &Node{rawStack}, nil
   202  }
   203  
   204  // Close terminates a running node along with all it's services, tearing internal state
   205  // down. It is not possible to restart a closed node.
   206  func (n *Node) Close() error {
   207  	return n.node.Close()
   208  }
   209  
   210  // Start creates a live P2P node and starts running it.
   211  func (n *Node) Start() error {
   212  	// TODO: recreate the node so it can be started multiple times
   213  	return n.node.Start()
   214  }
   215  
   216  // Stop terminates a running node along with all its services. If the node was not started,
   217  // an error is returned. It is not possible to restart a stopped node.
   218  //
   219  // Deprecated: use Close()
   220  func (n *Node) Stop() error {
   221  	return n.node.Close()
   222  }
   223  
   224  // GetEthereumClient retrieves a client to access the Ethereum subsystem.
   225  func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
   226  	rpc, err := n.node.Attach()
   227  	if err != nil {
   228  		return nil, err
   229  	}
   230  	return &EthereumClient{ethclient.NewClient(rpc)}, nil
   231  }
   232  
   233  // GetNodeInfo gathers and returns a collection of metadata known about the host.
   234  func (n *Node) GetNodeInfo() *NodeInfo {
   235  	return &NodeInfo{n.node.Server().NodeInfo()}
   236  }
   237  
   238  // GetPeersInfo returns an array of metadata objects describing connected peers.
   239  func (n *Node) GetPeersInfo() *PeerInfos {
   240  	return &PeerInfos{n.node.Server().PeersInfo()}
   241  }