github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/mobile/geth.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // Contains all the wrappers from the node package to support client side node
    19  // management on mobile platforms.
    20  
    21  package geth
    22  
    23  import (
    24  	"encoding/json"
    25  	"fmt"
    26  	"path/filepath"
    27  
    28  	"github.com/AigarNetwork/aigar/core"
    29  	"github.com/AigarNetwork/aigar/eth"
    30  	"github.com/AigarNetwork/aigar/eth/downloader"
    31  	"github.com/AigarNetwork/aigar/ethclient"
    32  	"github.com/AigarNetwork/aigar/ethstats"
    33  	"github.com/AigarNetwork/aigar/internal/debug"
    34  	"github.com/AigarNetwork/aigar/les"
    35  	"github.com/AigarNetwork/aigar/node"
    36  	"github.com/AigarNetwork/aigar/p2p"
    37  	"github.com/AigarNetwork/aigar/p2p/nat"
    38  	"github.com/AigarNetwork/aigar/params"
    39  	whisper "github.com/AigarNetwork/aigar/whisper/whisperv6"
    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  	// WhisperEnabled specifies whether the node should run the Whisper protocol.
    76  	WhisperEnabled bool
    77  
    78  	// Listening address of pprof server.
    79  	PprofAddress string
    80  }
    81  
    82  // defaultNodeConfig contains the default node configuration values to use if all
    83  // or some fields are missing from the user's specified list.
    84  var defaultNodeConfig = &NodeConfig{
    85  	BootstrapNodes:        FoundationBootnodes(),
    86  	MaxPeers:              25,
    87  	EthereumEnabled:       true,
    88  	EthereumNetworkID:     100,
    89  	EthereumDatabaseCache: 16,
    90  }
    91  
    92  // NewNodeConfig creates a new node option set, initialized to the default values.
    93  func NewNodeConfig() *NodeConfig {
    94  	config := *defaultNodeConfig
    95  	return &config
    96  }
    97  
    98  // Node represents a Geth Ethereum node instance.
    99  type Node struct {
   100  	node *node.Node
   101  }
   102  
   103  // NewNode creates and configures a new Geth node.
   104  func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
   105  	// If no or partial configurations were specified, use defaults
   106  	if config == nil {
   107  		config = NewNodeConfig()
   108  	}
   109  	if config.MaxPeers == 0 {
   110  		config.MaxPeers = defaultNodeConfig.MaxPeers
   111  	}
   112  	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
   113  		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
   114  	}
   115  
   116  	if config.PprofAddress != "" {
   117  		debug.StartPProf(config.PprofAddress)
   118  	}
   119  
   120  	// Create the empty networking stack
   121  	nodeConf := &node.Config{
   122  		Name:        clientIdentifier,
   123  		Version:     params.VersionWithMeta,
   124  		DataDir:     datadir,
   125  		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
   126  		P2P: p2p.Config{
   127  			NoDiscovery:      true,
   128  			DiscoveryV5:      true,
   129  			BootstrapNodesV5: config.BootstrapNodes.nodes,
   130  			ListenAddr:       ":0",
   131  			NAT:              nat.Any(),
   132  			MaxPeers:         config.MaxPeers,
   133  		},
   134  	}
   135  
   136  	rawStack, err := node.New(nodeConf)
   137  	if err != nil {
   138  		return nil, err
   139  	}
   140  
   141  	debug.Memsize.Add("node", rawStack)
   142  
   143  	var genesis *core.Genesis
   144  	if config.EthereumGenesis != "" {
   145  		// Parse the user supplied genesis spec if not mainnet
   146  		genesis = new(core.Genesis)
   147  		if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
   148  			return nil, fmt.Errorf("invalid genesis spec: %v", err)
   149  		}
   150  		// If we have the testnet, hard code the chain configs too
   151  		if config.EthereumGenesis == TestnetGenesis() {
   152  			genesis.Config = params.TestnetChainConfig
   153  			if config.EthereumNetworkID == 100 {
   154  				config.EthereumNetworkID = 3
   155  			}
   156  		}
   157  	}
   158  	// Register the Ethereum protocol if requested
   159  	if config.EthereumEnabled {
   160  		ethConf := eth.DefaultConfig
   161  		ethConf.Genesis = genesis
   162  		ethConf.SyncMode = downloader.LightSync
   163  		ethConf.NetworkId = uint64(config.EthereumNetworkID)
   164  		ethConf.DatabaseCache = config.EthereumDatabaseCache
   165  		if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   166  			return les.New(ctx, &ethConf)
   167  		}); err != nil {
   168  			return nil, fmt.Errorf("aigar init: %v", err)
   169  		}
   170  		// If netstats reporting is requested, do it
   171  		if config.EthereumNetStats != "" {
   172  			if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   173  				var lesServ *les.LightEthereum
   174  				ctx.Service(&lesServ)
   175  
   176  				return ethstats.New(config.EthereumNetStats, nil, lesServ)
   177  			}); err != nil {
   178  				return nil, fmt.Errorf("netstats init: %v", err)
   179  			}
   180  		}
   181  	}
   182  	// Register the Whisper protocol if requested
   183  	if config.WhisperEnabled {
   184  		if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) {
   185  			return whisper.New(&whisper.DefaultConfig), nil
   186  		}); err != nil {
   187  			return nil, fmt.Errorf("whisper init: %v", err)
   188  		}
   189  	}
   190  	return &Node{rawStack}, nil
   191  }
   192  
   193  // Close terminates a running node along with all it's services, tearing internal
   194  // state doen too. It's not possible to restart a closed node.
   195  func (n *Node) Close() error {
   196  	return n.node.Close()
   197  }
   198  
   199  // Start creates a live P2P node and starts running it.
   200  func (n *Node) Start() error {
   201  	return n.node.Start()
   202  }
   203  
   204  // Stop terminates a running node along with all it's services. If the node was
   205  // not started, an error is returned.
   206  func (n *Node) Stop() error {
   207  	return n.node.Stop()
   208  }
   209  
   210  // GetEthereumClient retrieves a client to access the Ethereum subsystem.
   211  func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
   212  	rpc, err := n.node.Attach()
   213  	if err != nil {
   214  		return nil, err
   215  	}
   216  	return &EthereumClient{ethclient.NewClient(rpc)}, nil
   217  }
   218  
   219  // GetNodeInfo gathers and returns a collection of metadata known about the host.
   220  func (n *Node) GetNodeInfo() *NodeInfo {
   221  	return &NodeInfo{n.node.Server().NodeInfo()}
   222  }
   223  
   224  // GetPeersInfo returns an array of metadata objects describing connected peers.
   225  func (n *Node) GetPeersInfo() *PeerInfos {
   226  	return &PeerInfos{n.node.Server().PeersInfo()}
   227  }