github.com/jimmyx0x/go-ethereum@v1.10.28/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/downloader"
    29  	"github.com/ethereum/go-ethereum/eth/ethconfig"
    30  	"github.com/ethereum/go-ethereum/eth/filters"
    31  	"github.com/ethereum/go-ethereum/ethclient"
    32  	"github.com/ethereum/go-ethereum/ethstats"
    33  	"github.com/ethereum/go-ethereum/internal/debug"
    34  	"github.com/ethereum/go-ethereum/les"
    35  	"github.com/ethereum/go-ethereum/node"
    36  	"github.com/ethereum/go-ethereum/p2p"
    37  	"github.com/ethereum/go-ethereum/p2p/nat"
    38  	"github.com/ethereum/go-ethereum/params"
    39  	"github.com/ethereum/go-ethereum/rpc"
    40  )
    41  
    42  // NodeConfig represents the collection of configuration values to fine tune the Geth
    43  // node embedded into a mobile process. The available values are a subset of the
    44  // entire API provided by go-ethereum to reduce the maintenance surface and dev
    45  // complexity.
    46  type NodeConfig struct {
    47  	// Bootstrap nodes used to establish connectivity with the rest of the network.
    48  	BootstrapNodes *Enodes
    49  
    50  	// MaxPeers is the maximum number of peers that can be connected. If this is
    51  	// set to zero, then only the configured static and trusted peers can connect.
    52  	MaxPeers int
    53  
    54  	// EthereumEnabled specifies whether the node should run the Ethereum protocol.
    55  	EthereumEnabled bool
    56  
    57  	// EthereumNetworkID is the network identifier used by the Ethereum protocol to
    58  	// decide if remote peers should be accepted or not.
    59  	EthereumNetworkID int64 // uint64 in truth, but Java can't handle that...
    60  
    61  	// EthereumGenesis is the genesis JSON to use to seed the blockchain with. An
    62  	// empty genesis state is equivalent to using the mainnet's state.
    63  	EthereumGenesis string
    64  
    65  	// EthereumDatabaseCache is the system memory in MB to allocate for database caching.
    66  	// A minimum of 16MB is always reserved.
    67  	EthereumDatabaseCache int
    68  
    69  	// EthereumNetStats is a netstats connection string to use to report various
    70  	// chain, transaction and node stats to a monitoring server.
    71  	//
    72  	// It has the form "nodename:secret@host:port"
    73  	EthereumNetStats string
    74  
    75  	// Listening address of pprof server.
    76  	PprofAddress string
    77  }
    78  
    79  // defaultNodeConfig contains the default node configuration values to use if all
    80  // or some fields are missing from the user's specified list.
    81  var defaultNodeConfig = &NodeConfig{
    82  	BootstrapNodes:        FoundationBootnodes(),
    83  	MaxPeers:              25,
    84  	EthereumEnabled:       true,
    85  	EthereumNetworkID:     1,
    86  	EthereumDatabaseCache: 16,
    87  }
    88  
    89  // NewNodeConfig creates a new node option set, initialized to the default values.
    90  func NewNodeConfig() *NodeConfig {
    91  	config := *defaultNodeConfig
    92  	return &config
    93  }
    94  
    95  // AddBootstrapNode adds an additional bootstrap node to the node config.
    96  func (conf *NodeConfig) AddBootstrapNode(node *Enode) {
    97  	conf.BootstrapNodes.Append(node)
    98  }
    99  
   100  // EncodeJSON encodes a NodeConfig into a JSON data dump.
   101  func (conf *NodeConfig) EncodeJSON() (string, error) {
   102  	data, err := json.Marshal(conf)
   103  	return string(data), err
   104  }
   105  
   106  // String returns a printable representation of the node config.
   107  func (conf *NodeConfig) String() string {
   108  	return encodeOrError(conf)
   109  }
   110  
   111  // Node represents a Geth Ethereum node instance.
   112  type Node struct {
   113  	node *node.Node
   114  }
   115  
   116  // NewNode creates and configures a new Geth node.
   117  func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
   118  	// If no or partial configurations were specified, use defaults
   119  	if config == nil {
   120  		config = NewNodeConfig()
   121  	}
   122  	if config.MaxPeers == 0 {
   123  		config.MaxPeers = defaultNodeConfig.MaxPeers
   124  	}
   125  	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
   126  		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
   127  	}
   128  
   129  	if config.PprofAddress != "" {
   130  		debug.StartPProf(config.PprofAddress, true)
   131  	}
   132  
   133  	// Create the empty networking stack
   134  	nodeConf := &node.Config{
   135  		Name:        clientIdentifier,
   136  		Version:     params.VersionWithMeta,
   137  		DataDir:     datadir,
   138  		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
   139  		P2P: p2p.Config{
   140  			NoDiscovery:      true,
   141  			DiscoveryV5:      true,
   142  			BootstrapNodesV5: config.BootstrapNodes.nodes,
   143  			ListenAddr:       ":0",
   144  			NAT:              nat.Any(),
   145  			MaxPeers:         config.MaxPeers,
   146  		},
   147  	}
   148  
   149  	rawStack, err := node.New(nodeConf)
   150  	if err != nil {
   151  		return nil, err
   152  	}
   153  
   154  	debug.Memsize.Add("node", rawStack)
   155  
   156  	var genesis *core.Genesis
   157  	if config.EthereumGenesis != "" {
   158  		// Parse the user supplied genesis spec if not mainnet
   159  		genesis = new(core.Genesis)
   160  		if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
   161  			rawStack.Close()
   162  			return nil, fmt.Errorf("invalid genesis spec: %v", err)
   163  		}
   164  		// If we have the Ropsten testnet, hard code the chain configs too
   165  		if config.EthereumGenesis == RopstenGenesis() {
   166  			genesis.Config = params.RopstenChainConfig
   167  			if config.EthereumNetworkID == 1 {
   168  				config.EthereumNetworkID = 3
   169  			}
   170  		}
   171  		// If we have the Sepolia testnet, hard code the chain configs too
   172  		if config.EthereumGenesis == SepoliaGenesis() {
   173  			genesis.Config = params.SepoliaChainConfig
   174  			if config.EthereumNetworkID == 1 {
   175  				config.EthereumNetworkID = 11155111
   176  			}
   177  		}
   178  		// If we have the Rinkeby testnet, hard code the chain configs too
   179  		if config.EthereumGenesis == RinkebyGenesis() {
   180  			genesis.Config = params.RinkebyChainConfig
   181  			if config.EthereumNetworkID == 1 {
   182  				config.EthereumNetworkID = 4
   183  			}
   184  		}
   185  		// If we have the Goerli testnet, hard code the chain configs too
   186  		if config.EthereumGenesis == GoerliGenesis() {
   187  			genesis.Config = params.GoerliChainConfig
   188  			if config.EthereumNetworkID == 1 {
   189  				config.EthereumNetworkID = 5
   190  			}
   191  		}
   192  	}
   193  	// Register the Ethereum protocol if requested
   194  	if config.EthereumEnabled {
   195  		ethConf := ethconfig.Defaults
   196  		ethConf.Genesis = genesis
   197  		ethConf.SyncMode = downloader.LightSync
   198  		ethConf.NetworkId = uint64(config.EthereumNetworkID)
   199  		ethConf.DatabaseCache = config.EthereumDatabaseCache
   200  		lesBackend, err := les.New(rawStack, &ethConf)
   201  		if err != nil {
   202  			rawStack.Close()
   203  			return nil, fmt.Errorf("ethereum init: %v", err)
   204  		}
   205  		// Register log filter RPC API.
   206  		filterSystem := filters.NewFilterSystem(lesBackend.ApiBackend, filters.Config{
   207  			LogCacheSize: ethConf.FilterLogCacheSize,
   208  		})
   209  		rawStack.RegisterAPIs([]rpc.API{{
   210  			Namespace: "eth",
   211  			Service:   filters.NewFilterAPI(filterSystem, true),
   212  		}})
   213  		// If netstats reporting is requested, do it
   214  		if config.EthereumNetStats != "" {
   215  			if err := ethstats.New(rawStack, lesBackend.ApiBackend, lesBackend.Engine(), config.EthereumNetStats); err != nil {
   216  				rawStack.Close()
   217  				return nil, fmt.Errorf("netstats init: %v", err)
   218  			}
   219  		}
   220  	}
   221  	return &Node{rawStack}, nil
   222  }
   223  
   224  // Close terminates a running node along with all it's services, tearing internal state
   225  // down. It is not possible to restart a closed node.
   226  func (n *Node) Close() error {
   227  	return n.node.Close()
   228  }
   229  
   230  // Start creates a live P2P node and starts running it.
   231  func (n *Node) Start() error {
   232  	// TODO: recreate the node so it can be started multiple times
   233  	return n.node.Start()
   234  }
   235  
   236  // GetEthereumClient retrieves a client to access the Ethereum subsystem.
   237  func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
   238  	rpc, err := n.node.Attach()
   239  	if err != nil {
   240  		return nil, err
   241  	}
   242  	return &EthereumClient{ethclient.NewClient(rpc)}, nil
   243  }
   244  
   245  // GetNodeInfo gathers and returns a collection of metadata known about the host.
   246  func (n *Node) GetNodeInfo() *NodeInfo {
   247  	return &NodeInfo{n.node.Server().NodeInfo()}
   248  }
   249  
   250  // GetPeersInfo returns an array of metadata objects describing connected peers.
   251  func (n *Node) GetPeersInfo() *PeerInfos {
   252  	return &PeerInfos{n.node.Server().PeersInfo()}
   253  }