github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/mobile/geth.go (about) 1 // Copyright 2016 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum 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 Spectrum 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 Spectrum 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/SmartMeshFoundation/Spectrum/core" 28 "github.com/SmartMeshFoundation/Spectrum/eth" 29 "github.com/SmartMeshFoundation/Spectrum/eth/downloader" 30 "github.com/SmartMeshFoundation/Spectrum/ethclient" 31 "github.com/SmartMeshFoundation/Spectrum/ethstats" 32 "github.com/SmartMeshFoundation/Spectrum/les" 33 "github.com/SmartMeshFoundation/Spectrum/node" 34 "github.com/SmartMeshFoundation/Spectrum/p2p" 35 "github.com/SmartMeshFoundation/Spectrum/p2p/nat" 36 "github.com/SmartMeshFoundation/Spectrum/params" 37 whisper "github.com/SmartMeshFoundation/Spectrum/whisper/whisperv5" 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 Spectrum 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 // WhisperEnabled specifies whether the node should run the Whisper protocol. 74 WhisperEnabled bool 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 // Node represents a Geth Ethereum node instance. 94 type Node struct { 95 node *node.Node 96 } 97 98 // NewNode creates and configures a new Geth node. 99 func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) { 100 // If no or partial configurations were specified, use defaults 101 if config == nil { 102 config = NewNodeConfig() 103 } 104 if config.MaxPeers == 0 { 105 config.MaxPeers = defaultNodeConfig.MaxPeers 106 } 107 if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 { 108 config.BootstrapNodes = defaultNodeConfig.BootstrapNodes 109 } 110 // Create the empty networking stack 111 nodeConf := &node.Config{ 112 Name: clientIdentifier, 113 Version: params.Version, 114 DataDir: datadir, 115 KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores! 116 P2P: p2p.Config{ 117 NoDiscovery: true, 118 DiscoveryV5: true, 119 DiscoveryV5Addr: ":0", 120 BootstrapNodesV5: config.BootstrapNodes.nodes, 121 ListenAddr: ":0", 122 NAT: nat.Any(), 123 MaxPeers: config.MaxPeers, 124 }, 125 } 126 rawStack, err := node.New(nodeConf) 127 if err != nil { 128 return nil, err 129 } 130 131 var genesis *core.Genesis 132 if config.EthereumGenesis != "" { 133 // Parse the user supplied genesis spec if not mainnet 134 genesis = new(core.Genesis) 135 if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil { 136 return nil, fmt.Errorf("invalid genesis spec: %v", err) 137 } 138 // If we have the testnet, hard code the chain configs too 139 if config.EthereumGenesis == TestnetGenesis() { 140 genesis.Config = params.TestnetChainConfig 141 if config.EthereumNetworkID == 1 { 142 config.EthereumNetworkID = 3 143 } 144 } 145 } 146 // Register the Ethereum protocol if requested 147 if config.EthereumEnabled { 148 ethConf := eth.DefaultConfig 149 ethConf.Genesis = genesis 150 ethConf.SyncMode = downloader.LightSync 151 ethConf.NetworkId = uint64(config.EthereumNetworkID) 152 ethConf.DatabaseCache = config.EthereumDatabaseCache 153 if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 154 return les.New(ctx, ðConf) 155 }); err != nil { 156 return nil, fmt.Errorf("ethereum init: %v", err) 157 } 158 // If netstats reporting is requested, do it 159 if config.EthereumNetStats != "" { 160 if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 161 var lesServ *les.LightEthereum 162 ctx.Service(&lesServ) 163 164 return ethstats.New(config.EthereumNetStats, nil, lesServ) 165 }); err != nil { 166 return nil, fmt.Errorf("netstats init: %v", err) 167 } 168 } 169 } 170 // Register the Whisper protocol if requested 171 if config.WhisperEnabled { 172 if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) { 173 return whisper.New(&whisper.DefaultConfig), nil 174 }); err != nil { 175 return nil, fmt.Errorf("whisper init: %v", err) 176 } 177 } 178 return &Node{rawStack}, nil 179 } 180 181 // Start creates a live P2P node and starts running it. 182 func (n *Node) Start() error { 183 return n.node.Start() 184 } 185 186 // Stop terminates a running node along with all it's services. In the node was 187 // not started, an error is returned. 188 func (n *Node) Stop() error { 189 return n.node.Stop() 190 } 191 192 // GetEthereumClient retrieves a client to access the Ethereum subsystem. 193 func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) { 194 rpc, err := n.node.Attach() 195 if err != nil { 196 return nil, err 197 } 198 return &EthereumClient{ethclient.NewClient(rpc)}, nil 199 } 200 201 // GetNodeInfo gathers and returns a collection of metadata known about the host. 202 func (n *Node) GetNodeInfo() *NodeInfo { 203 return &NodeInfo{n.node.Server().NodeInfo()} 204 } 205 206 // GetPeersInfo returns an array of metadata objects describing connected peers. 207 func (n *Node) GetPeersInfo() *PeerInfos { 208 return &PeerInfos{n.node.Server().PeersInfo()} 209 }