github.com/edxfund/validator@v1.8.16-0.20181020093046-c1def72855da/cmd/geth/main.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of go-ethereum. 3 // 4 // go-ethereum is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU 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 // go-ethereum 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 General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. 16 17 // geth is the official command-line client for Ethereum. 18 package main 19 20 import ( 21 "fmt" 22 "math" 23 "os" 24 "runtime" 25 godebug "runtime/debug" 26 "sort" 27 "strconv" 28 "strings" 29 "time" 30 31 "github.com/elastic/gosigar" 32 "github.com/EDXFund/Validator/accounts" 33 "github.com/EDXFund/Validator/accounts/keystore" 34 "github.com/EDXFund/Validator/cmd/utils" 35 "github.com/EDXFund/Validator/console" 36 "github.com/EDXFund/Validator/eth" 37 "github.com/EDXFund/Validator/ethclient" 38 "github.com/EDXFund/Validator/internal/debug" 39 "github.com/EDXFund/Validator/log" 40 "github.com/EDXFund/Validator/metrics" 41 "github.com/EDXFund/Validator/node" 42 "gopkg.in/urfave/cli.v1" 43 ) 44 45 const ( 46 clientIdentifier = "geth" // Client identifier to advertise over the network 47 ) 48 49 var ( 50 // Git SHA1 commit hash of the release (set via linker flags) 51 gitCommit = "" 52 // The app that holds all commands and flags. 53 app = utils.NewApp(gitCommit, "the go-ethereum command line interface") 54 // flags that configure the node 55 nodeFlags = []cli.Flag{ 56 utils.IdentityFlag, 57 utils.UnlockedAccountFlag, 58 utils.PasswordFileFlag, 59 utils.BootnodesFlag, 60 utils.BootnodesV4Flag, 61 utils.BootnodesV5Flag, 62 utils.DataDirFlag, 63 utils.KeyStoreDirFlag, 64 utils.NoUSBFlag, 65 utils.DashboardEnabledFlag, 66 utils.DashboardAddrFlag, 67 utils.DashboardPortFlag, 68 utils.DashboardRefreshFlag, 69 utils.EthashCacheDirFlag, 70 utils.EthashCachesInMemoryFlag, 71 utils.EthashCachesOnDiskFlag, 72 utils.EthashDatasetDirFlag, 73 utils.EthashDatasetsInMemoryFlag, 74 utils.EthashDatasetsOnDiskFlag, 75 utils.TxPoolLocalsFlag, 76 utils.TxPoolNoLocalsFlag, 77 utils.TxPoolJournalFlag, 78 utils.TxPoolRejournalFlag, 79 utils.TxPoolPriceLimitFlag, 80 utils.TxPoolPriceBumpFlag, 81 utils.TxPoolAccountSlotsFlag, 82 utils.TxPoolGlobalSlotsFlag, 83 utils.TxPoolAccountQueueFlag, 84 utils.TxPoolGlobalQueueFlag, 85 utils.TxPoolLifetimeFlag, 86 utils.SyncModeFlag, 87 utils.GCModeFlag, 88 utils.LightServFlag, 89 utils.LightPeersFlag, 90 utils.LightKDFFlag, 91 utils.CacheFlag, 92 utils.CacheDatabaseFlag, 93 utils.CacheGCFlag, 94 utils.TrieCacheGenFlag, 95 utils.ListenPortFlag, 96 utils.MaxPeersFlag, 97 utils.MaxPendingPeersFlag, 98 utils.MiningEnabledFlag, 99 utils.MinerThreadsFlag, 100 utils.MinerLegacyThreadsFlag, 101 utils.MinerNotifyFlag, 102 utils.MinerGasTargetFlag, 103 utils.MinerLegacyGasTargetFlag, 104 utils.MinerGasLimitFlag, 105 utils.MinerGasPriceFlag, 106 utils.MinerLegacyGasPriceFlag, 107 utils.MinerEtherbaseFlag, 108 utils.MinerLegacyEtherbaseFlag, 109 utils.MinerExtraDataFlag, 110 utils.MinerLegacyExtraDataFlag, 111 utils.MinerRecommitIntervalFlag, 112 utils.MinerNoVerfiyFlag, 113 utils.NATFlag, 114 utils.NoDiscoverFlag, 115 utils.DiscoveryV5Flag, 116 utils.NetrestrictFlag, 117 utils.NodeKeyFileFlag, 118 utils.NodeKeyHexFlag, 119 utils.DeveloperFlag, 120 utils.DeveloperPeriodFlag, 121 utils.TestnetFlag, 122 utils.RinkebyFlag, 123 utils.VMEnableDebugFlag, 124 utils.NetworkIdFlag, 125 utils.RPCCORSDomainFlag, 126 utils.RPCVirtualHostsFlag, 127 utils.EthStatsURLFlag, 128 utils.MetricsEnabledFlag, 129 utils.FakePoWFlag, 130 utils.NoCompactionFlag, 131 utils.GpoBlocksFlag, 132 utils.GpoPercentileFlag, 133 configFileFlag, 134 } 135 136 rpcFlags = []cli.Flag{ 137 utils.RPCEnabledFlag, 138 utils.RPCListenAddrFlag, 139 utils.RPCPortFlag, 140 utils.RPCApiFlag, 141 utils.WSEnabledFlag, 142 utils.WSListenAddrFlag, 143 utils.WSPortFlag, 144 utils.WSApiFlag, 145 utils.WSAllowedOriginsFlag, 146 utils.IPCDisabledFlag, 147 utils.IPCPathFlag, 148 } 149 150 whisperFlags = []cli.Flag{ 151 utils.WhisperEnabledFlag, 152 utils.WhisperMaxMessageSizeFlag, 153 utils.WhisperMinPOWFlag, 154 utils.WhisperRestrictConnectionBetweenLightClientsFlag, 155 } 156 157 metricsFlags = []cli.Flag{ 158 utils.MetricsEnableInfluxDBFlag, 159 utils.MetricsInfluxDBEndpointFlag, 160 utils.MetricsInfluxDBDatabaseFlag, 161 utils.MetricsInfluxDBUsernameFlag, 162 utils.MetricsInfluxDBPasswordFlag, 163 utils.MetricsInfluxDBHostTagFlag, 164 } 165 ) 166 167 func init() { 168 // Initialize the CLI app and start Geth 169 app.Action = geth 170 app.HideVersion = true // we have a command to print the version 171 app.Copyright = "Copyright 2013-2018 The go-ethereum Authors" 172 app.Commands = []cli.Command{ 173 // See chaincmd.go: 174 initCommand, 175 importCommand, 176 exportCommand, 177 importPreimagesCommand, 178 exportPreimagesCommand, 179 copydbCommand, 180 removedbCommand, 181 dumpCommand, 182 // See monitorcmd.go: 183 monitorCommand, 184 // See accountcmd.go: 185 accountCommand, 186 walletCommand, 187 // See consolecmd.go: 188 consoleCommand, 189 attachCommand, 190 javascriptCommand, 191 // See misccmd.go: 192 makecacheCommand, 193 makedagCommand, 194 versionCommand, 195 bugCommand, 196 licenseCommand, 197 // See config.go 198 dumpConfigCommand, 199 } 200 sort.Sort(cli.CommandsByName(app.Commands)) 201 202 app.Flags = append(app.Flags, nodeFlags...) 203 app.Flags = append(app.Flags, rpcFlags...) 204 app.Flags = append(app.Flags, consoleFlags...) 205 app.Flags = append(app.Flags, debug.Flags...) 206 app.Flags = append(app.Flags, whisperFlags...) 207 app.Flags = append(app.Flags, metricsFlags...) 208 209 app.Before = func(ctx *cli.Context) error { 210 runtime.GOMAXPROCS(runtime.NumCPU()) 211 212 logdir := "" 213 if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) { 214 logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs") 215 } 216 if err := debug.Setup(ctx, logdir); err != nil { 217 return err 218 } 219 // Cap the cache allowance and tune the garbage collector 220 var mem gosigar.Mem 221 if err := mem.Get(); err == nil { 222 allowance := int(mem.Total / 1024 / 1024 / 3) 223 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 224 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 225 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 226 } 227 } 228 // Ensure Go's GC ignores the database cache for trigger percentage 229 cache := ctx.GlobalInt(utils.CacheFlag.Name) 230 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 231 232 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 233 godebug.SetGCPercent(int(gogc)) 234 235 // Start metrics export if enabled 236 utils.SetupMetrics(ctx) 237 238 // Start system runtime metrics collection 239 go metrics.CollectProcessMetrics(3 * time.Second) 240 241 return nil 242 } 243 244 app.After = func(ctx *cli.Context) error { 245 debug.Exit() 246 console.Stdin.Close() // Resets terminal mode. 247 return nil 248 } 249 } 250 251 func main() { 252 if err := app.Run(os.Args); err != nil { 253 fmt.Fprintln(os.Stderr, err) 254 os.Exit(1) 255 } 256 } 257 258 // geth is the main entry point into the system if no special subcommand is ran. 259 // It creates a default node based on the command line arguments and runs it in 260 // blocking mode, waiting for it to be shut down. 261 func geth(ctx *cli.Context) error { 262 if args := ctx.Args(); len(args) > 0 { 263 return fmt.Errorf("invalid command: %q", args[0]) 264 } 265 node := makeFullNode(ctx) 266 startNode(ctx, node) 267 node.Wait() 268 return nil 269 } 270 271 // startNode boots up the system node and all registered protocols, after which 272 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 273 // miner. 274 func startNode(ctx *cli.Context, stack *node.Node) { 275 debug.Memsize.Add("node", stack) 276 277 // Start up the node itself 278 utils.StartNode(stack) 279 280 // Unlock any account specifically requested 281 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 282 283 passwords := utils.MakePasswordList(ctx) 284 unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 285 for i, account := range unlocks { 286 if trimmed := strings.TrimSpace(account); trimmed != "" { 287 unlockAccount(ctx, ks, trimmed, i, passwords) 288 } 289 } 290 // Register wallet event handlers to open and auto-derive wallets 291 events := make(chan accounts.WalletEvent, 16) 292 stack.AccountManager().Subscribe(events) 293 294 go func() { 295 // Create a chain state reader for self-derivation 296 rpcClient, err := stack.Attach() 297 if err != nil { 298 utils.Fatalf("Failed to attach to self: %v", err) 299 } 300 stateReader := ethclient.NewClient(rpcClient) 301 302 // Open any wallets already attached 303 for _, wallet := range stack.AccountManager().Wallets() { 304 if err := wallet.Open(""); err != nil { 305 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 306 } 307 } 308 // Listen for wallet event till termination 309 for event := range events { 310 switch event.Kind { 311 case accounts.WalletArrived: 312 if err := event.Wallet.Open(""); err != nil { 313 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 314 } 315 case accounts.WalletOpened: 316 status, _ := event.Wallet.Status() 317 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 318 319 derivationPath := accounts.DefaultBaseDerivationPath 320 if event.Wallet.URL().Scheme == "ledger" { 321 derivationPath = accounts.DefaultLedgerBaseDerivationPath 322 } 323 event.Wallet.SelfDerive(derivationPath, stateReader) 324 325 case accounts.WalletDropped: 326 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 327 event.Wallet.Close() 328 } 329 } 330 }() 331 // Start auxiliary services if enabled 332 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 333 // Mining only makes sense if a full Ethereum node is running 334 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 335 utils.Fatalf("Light clients do not support mining") 336 } 337 var ethereum *eth.Ethereum 338 if err := stack.Service(ðereum); err != nil { 339 utils.Fatalf("Ethereum service not running: %v", err) 340 } 341 // Set the gas price to the limits from the CLI and start mining 342 gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name) 343 if ctx.IsSet(utils.MinerGasPriceFlag.Name) { 344 gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 345 } 346 ethereum.TxPool().SetGasPrice(gasprice) 347 348 threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name) 349 if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) { 350 threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name) 351 } 352 if err := ethereum.StartMining(threads); err != nil { 353 utils.Fatalf("Failed to start mining: %v", err) 354 } 355 } 356 }