github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/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" 29 "github.com/ethereum/go-ethereum/eth/downloader" 30 "github.com/ethereum/go-ethereum/ethclient" 31 "github.com/ethereum/go-ethereum/ethstats" 32 "github.com/ethereum/go-ethereum/internal/debug" 33 "github.com/ethereum/go-ethereum/les" 34 "github.com/ethereum/go-ethereum/node" 35 "github.com/ethereum/go-ethereum/p2p" 36 "github.com/ethereum/go-ethereum/p2p/nat" 37 "github.com/ethereum/go-ethereum/params" 38 whisper "github.com/ethereum/go-ethereum/whisper/whisperv6" 39 ) 40 41 // I am intentionally duplicating these constants different from downloader.SyncMode integer values, to ensure the 42 // backwards compatibility where the mobile node defaults to LightSync. 43 const SyncModeUnset = 0 // will be treated as SyncModeLightSync 44 const SyncModeFullSync = 1 45 const SyncModeFastSync = 2 46 const SyncModeLightSync = 3 47 48 // Deprecated: This used to be SyncModeCeloLatestSync. Geth will panic if started in this mode. 49 // Use UltraLightSync instead. 50 const DeprecatedSyncMode = 4 51 const UltraLightSync = 5 52 53 // NodeConfig represents the collection of configuration values to fine tune the Geth 54 // node embedded into a mobile process. The available values are a subset of the 55 // entire API provided by go-ethereum to reduce the maintenance surface and dev 56 // complexity. 57 type NodeConfig struct { 58 // Bootstrap nodes used to establish connectivity with the rest of the network. 59 BootstrapNodes *Enodes 60 61 // MaxPeers is the maximum number of peers that can be connected. If this is 62 // set to zero, then only the configured static and trusted peers can connect. 63 MaxPeers int 64 65 // EthereumEnabled specifies whether the node should run the Ethereum protocol. 66 EthereumEnabled bool 67 68 // EthereumNetworkID is the network identifier used by the Ethereum protocol to 69 // decide if remote peers should be accepted or not. 70 EthereumNetworkID int64 // uint64 in truth, but Java can't handle that... 71 72 // EthereumGenesis is the genesis JSON to use to seed the blockchain with. An 73 // empty genesis state is equivalent to using the mainnet's state. 74 EthereumGenesis string 75 76 // EthereumDatabaseCache is the system memory in MB to allocate for database caching. 77 // A minimum of 16MB is always reserved. 78 EthereumDatabaseCache int 79 80 // EthereumNetStats is a netstats connection string to use to report various 81 // chain, transaction and node stats to a monitoring server. 82 // 83 // It has the form "nodename:secret@host:port" 84 EthereumNetStats string 85 86 // WhisperEnabled specifies whether the node should run the Whisper protocol. 87 WhisperEnabled bool 88 89 // Listening address of pprof server. 90 PprofAddress string 91 92 // Sync mode for the node (eth/downloader/modes.go) 93 // This has to be integer since Enum exports to Java are not supported by "gomobile" 94 // See getSyncMode(syncMode int) 95 SyncMode int 96 97 // UseLightweightKDF lowers the memory and CPU requirements of the key store 98 // scrypt KDF at the expense of security. 99 // See https://geth.ethereum.org/doc/Mobile_Account-management for reference 100 UseLightweightKDF bool 101 102 // IPCPath is the requested location to place the IPC endpoint. If the path is 103 // a simple file name, it is placed inside the data directory (or on the root 104 // pipe path on Windows), whereas if it's a resolvable path name (absolute or 105 // relative), then that specific path is enforced. An empty path disables IPC. 106 IPCPath string 107 } 108 109 // defaultNodeConfig contains the default node configuration values to use if all 110 // or some fields are missing from the user's specified list. 111 var defaultNodeConfig = &NodeConfig{ 112 BootstrapNodes: FoundationBootnodes(), 113 MaxPeers: 25, 114 EthereumEnabled: true, 115 EthereumNetworkID: 1, 116 EthereumDatabaseCache: 16, 117 } 118 119 // NewNodeConfig creates a new node option set, initialized to the default values. 120 func NewNodeConfig() *NodeConfig { 121 config := *defaultNodeConfig 122 return &config 123 } 124 125 // Node represents a Geth Ethereum node instance. 126 type Node struct { 127 node *node.Node 128 } 129 130 // NewNode creates and configures a new Geth node. 131 func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) { 132 // If no or partial configurations were specified, use defaults 133 if config == nil { 134 config = NewNodeConfig() 135 } 136 if config.MaxPeers == 0 { 137 config.MaxPeers = defaultNodeConfig.MaxPeers 138 } 139 if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 { 140 config.BootstrapNodes = defaultNodeConfig.BootstrapNodes 141 } 142 143 if config.PprofAddress != "" { 144 debug.StartPProf(config.PprofAddress) 145 } 146 147 // Create the empty networking stack 148 nodeConf := &node.Config{ 149 Name: clientIdentifier, 150 Version: params.VersionWithMeta, 151 DataDir: datadir, 152 KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores! 153 UseLightweightKDF: config.UseLightweightKDF, 154 IPCPath: config.IPCPath, 155 P2P: p2p.Config{ 156 NoDiscovery: true, 157 DiscoveryV5: false, 158 BootstrapNodesV5: config.BootstrapNodes.nodes, 159 ListenAddr: ":0", 160 NAT: nat.Any(), 161 MaxPeers: config.MaxPeers, 162 }, 163 } 164 rawStack, err := node.New(nodeConf) 165 if err != nil { 166 return nil, err 167 } 168 169 debug.Memsize.Add("node", rawStack) 170 171 var genesis *core.Genesis 172 if config.EthereumGenesis != "" { 173 // Parse the user supplied genesis spec if not mainnet 174 genesis = new(core.Genesis) 175 if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil { 176 return nil, fmt.Errorf("invalid genesis spec: %v", err) 177 } 178 // If we have the testnet, hard code the chain configs too 179 if config.EthereumGenesis == TestnetGenesis() { 180 genesis.Config = params.TestnetChainConfig 181 if config.EthereumNetworkID == 1 { 182 config.EthereumNetworkID = 3 183 } 184 } 185 } 186 // Register the Ethereum protocol if requested 187 if config.EthereumEnabled { 188 ethConf := eth.DefaultConfig 189 ethConf.Genesis = genesis 190 191 ethConf.SyncMode = getSyncMode(config.SyncMode) 192 ethConf.NetworkId = uint64(config.EthereumNetworkID) 193 ethConf.DatabaseCache = config.EthereumDatabaseCache 194 // Use an in memory DB for validatorEnode table 195 ethConf.Istanbul.ValidatorEnodeDBPath = "" 196 // Use an in memory DB for roundState table 197 ethConf.Istanbul.RoundStateDBPath = "" 198 if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 199 return les.New(ctx, ðConf) 200 }); err != nil { 201 return nil, fmt.Errorf("ethereum init: %v", err) 202 } 203 // If netstats reporting is requested, do it 204 if config.EthereumNetStats != "" { 205 if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 206 var lesServ *les.LightEthereum 207 ctx.Service(&lesServ) 208 209 return ethstats.New(config.EthereumNetStats, nil, lesServ) 210 }); err != nil { 211 return nil, fmt.Errorf("netstats init: %v", err) 212 } 213 } 214 } 215 // Register the Whisper protocol if requested 216 if config.WhisperEnabled { 217 if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) { 218 return whisper.New(&whisper.DefaultConfig), nil 219 }); err != nil { 220 return nil, fmt.Errorf("whisper init: %v", err) 221 } 222 } 223 return &Node{rawStack}, nil 224 } 225 226 func getSyncMode(syncMode int) downloader.SyncMode { 227 switch syncMode { 228 case SyncModeFullSync: 229 return downloader.FullSync 230 case SyncModeFastSync: 231 return downloader.FastSync 232 case SyncModeUnset: 233 fallthrough 234 // If unset, default to light sync. 235 // This maintains backward compatibility. 236 case SyncModeLightSync: 237 return downloader.LightSync 238 case DeprecatedSyncMode: 239 panic("CeloLatestSync mode is no longer supported. Use UltraLightSync instead") 240 case UltraLightSync: 241 return downloader.UltraLightSync 242 default: 243 panic(fmt.Sprintf("Unexpected sync mode value: %d", syncMode)) 244 } 245 } 246 247 // Start creates a live P2P node and starts running it. 248 func (n *Node) Start() error { 249 return n.node.Start() 250 } 251 252 // Stop terminates a running node along with all it's services. If the node was 253 // not started, an error is returned. 254 func (n *Node) Stop() error { 255 return n.node.Stop() 256 } 257 258 // GetEthereumClient retrieves a client to access the Ethereum subsystem. 259 func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) { 260 rpc, err := n.node.Attach() 261 if err != nil { 262 return nil, err 263 } 264 return &EthereumClient{ethclient.NewClient(rpc)}, nil 265 } 266 267 // GetNodeInfo gathers and returns a collection of metadata known about the host. 268 func (n *Node) GetNodeInfo() *NodeInfo { 269 return &NodeInfo{n.node.Server().NodeInfo()} 270 } 271 272 // GetPeersInfo returns an array of metadata objects describing connected peers. 273 func (n *Node) GetPeersInfo() *PeerInfos { 274 return &PeerInfos{n.node.Server().PeersInfo()} 275 }