github.com/aaa256/atlantis@v0.0.0-20210707112435-42ee889287a2/mobile/geth.go (about)

     1  // Copyright 2016 The go-athereum Authors
     2  // This file is part of the go-athereum library.
     3  //
     4  // The go-athereum 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-athereum 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-athereum 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 gath
    21  
    22  import (
    23  	"encoding/json"
    24  	"fmt"
    25  	"path/filepath"
    26  
    27  	"github.com/athereum/go-athereum/core"
    28  	"github.com/athereum/go-athereum/ath"
    29  	"github.com/athereum/go-athereum/ath/downloader"
    30  	"github.com/athereum/go-athereum/athclient"
    31  	"github.com/athereum/go-athereum/athstats"
    32  	"github.com/athereum/go-athereum/internal/debug"
    33  	"github.com/athereum/go-athereum/les"
    34  	"github.com/athereum/go-athereum/node"
    35  	"github.com/athereum/go-athereum/p2p"
    36  	"github.com/athereum/go-athereum/p2p/nat"
    37  	"github.com/athereum/go-athereum/params"
    38  	whisper "github.com/athereum/go-athereum/whisper/whisperv6"
    39  )
    40  
    41  // NodeConfig represents the collection of configuration values to fine tune the Gath
    42  // node embedded into a mobile process. The available values are a subset of the
    43  // entire API provided by go-athereum 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  	// AtlantisEnabled specifies whather the node should run the Atlantis protocol.
    54  	AtlantisEnabled bool
    55  
    56  	// AtlantisNetworkID is the network identifier used by the Atlantis protocol to
    57  	// decide if remote peers should be accepted or not.
    58  	AtlantisNetworkID int64 // uint64 in truth, but Java can't handle that...
    59  
    60  	// AtlantisGenesis 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  	AtlantisGenesis string
    63  
    64  	// AtlantisDatabaseCache is the system memory in MB to allocate for database caching.
    65  	// A minimum of 16MB is always reserved.
    66  	AtlantisDatabaseCache int
    67  
    68  	// AtlantisNetStats 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  	AtlantisNetStats string
    73  
    74  	// WhisperEnabled specifies whather the node should run the Whisper protocol.
    75  	WhisperEnabled bool
    76  
    77  	// Listening address of pprof server.
    78  	PprofAddress string
    79  }
    80  
    81  // defaultNodeConfig contains the default node configuration values to use if all
    82  // or some fields are missing from the user's specified list.
    83  var defaultNodeConfig = &NodeConfig{
    84  	BootstrapNodes:        FoundationBootnodes(),
    85  	MaxPeers:              25,
    86  	AtlantisEnabled:       true,
    87  	AtlantisNetworkID:     1,
    88  	AtlantisDatabaseCache: 16,
    89  }
    90  
    91  // NewNodeConfig creates a new node option set, initialized to the default values.
    92  func NewNodeConfig() *NodeConfig {
    93  	config := *defaultNodeConfig
    94  	return &config
    95  }
    96  
    97  // Node represents a Gath Atlantis node instance.
    98  type Node struct {
    99  	node *node.Node
   100  }
   101  
   102  // NewNode creates and configures a new Gath node.
   103  func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
   104  	// If no or partial configurations were specified, use defaults
   105  	if config == nil {
   106  		config = NewNodeConfig()
   107  	}
   108  	if config.MaxPeers == 0 {
   109  		config.MaxPeers = defaultNodeConfig.MaxPeers
   110  	}
   111  	if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
   112  		config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
   113  	}
   114  
   115  	if config.PprofAddress != "" {
   116  		debug.StartPProf(config.PprofAddress)
   117  	}
   118  
   119  	// Create the empty networking stack
   120  	nodeConf := &node.Config{
   121  		Name:        clientIdentifier,
   122  		Version:     params.Version,
   123  		DataDir:     datadir,
   124  		KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
   125  		P2P: p2p.Config{
   126  			NoDiscovery:      true,
   127  			DiscoveryV5:      true,
   128  			BootstrapNodesV5: config.BootstrapNodes.nodes,
   129  			ListenAddr:       ":0",
   130  			NAT:              nat.Any(),
   131  			MaxPeers:         config.MaxPeers,
   132  		},
   133  	}
   134  	rawStack, err := node.New(nodeConf)
   135  	if err != nil {
   136  		return nil, err
   137  	}
   138  
   139  	debug.Memsize.Add("node", rawStack)
   140  
   141  	var genesis *core.Genesis
   142  	if config.AtlantisGenesis != "" {
   143  		// Parse the user supplied genesis spec if not mainnet
   144  		genesis = new(core.Genesis)
   145  		if err := json.Unmarshal([]byte(config.AtlantisGenesis), genesis); err != nil {
   146  			return nil, fmt.Errorf("invalid genesis spec: %v", err)
   147  		}
   148  		// If we have the testnet, hard code the chain configs too
   149  		if config.AtlantisGenesis == TestnetGenesis() {
   150  			genesis.Config = params.TestnetChainConfig
   151  			if config.AtlantisNetworkID == 1 {
   152  				config.AtlantisNetworkID = 3
   153  			}
   154  		}
   155  	}
   156  	// Register the Atlantis protocol if requested
   157  	if config.AtlantisEnabled {
   158  		athConf := ath.DefaultConfig
   159  		athConf.Genesis = genesis
   160  		athConf.SyncMode = downloader.LightSync
   161  		athConf.NetworkId = uint64(config.AtlantisNetworkID)
   162  		athConf.DatabaseCache = config.AtlantisDatabaseCache
   163  		if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   164  			return les.New(ctx, &athConf)
   165  		}); err != nil {
   166  			return nil, fmt.Errorf("athereum init: %v", err)
   167  		}
   168  		// If netstats reporting is requested, do it
   169  		if config.AtlantisNetStats != "" {
   170  			if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   171  				var lesServ *les.LightAtlantis
   172  				ctx.Service(&lesServ)
   173  
   174  				return athstats.New(config.AtlantisNetStats, nil, lesServ)
   175  			}); err != nil {
   176  				return nil, fmt.Errorf("netstats init: %v", err)
   177  			}
   178  		}
   179  	}
   180  	// Register the Whisper protocol if requested
   181  	if config.WhisperEnabled {
   182  		if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) {
   183  			return whisper.New(&whisper.DefaultConfig), nil
   184  		}); err != nil {
   185  			return nil, fmt.Errorf("whisper init: %v", err)
   186  		}
   187  	}
   188  	return &Node{rawStack}, nil
   189  }
   190  
   191  // Start creates a live P2P node and starts running it.
   192  func (n *Node) Start() error {
   193  	return n.node.Start()
   194  }
   195  
   196  // Stop terminates a running node along with all it's services. In the node was
   197  // not started, an error is returned.
   198  func (n *Node) Stop() error {
   199  	return n.node.Stop()
   200  }
   201  
   202  // GetAtlantisClient retrieves a client to access the Atlantis subsystem.
   203  func (n *Node) GetAtlantisClient() (client *AtlantisClient, _ error) {
   204  	rpc, err := n.node.Attach()
   205  	if err != nil {
   206  		return nil, err
   207  	}
   208  	return &AtlantisClient{athclient.NewClient(rpc)}, nil
   209  }
   210  
   211  // GetNodeInfo gathers and returns a collection of metadata known about the host.
   212  func (n *Node) GetNodeInfo() *NodeInfo {
   213  	return &NodeInfo{n.node.Server().NodeInfo()}
   214  }
   215  
   216  // GetPeersInfo returns an array of metadata objects describing connected peers.
   217  func (n *Node) GetPeersInfo() *PeerInfos {
   218  	return &PeerInfos{n.node.Server().PeersInfo()}
   219  }