github.com/alexanderbez/go-ethereum@v1.8.17-0.20181024144731-0a57b29f0c8e/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/ethereum/go-ethereum/accounts" 33 "github.com/ethereum/go-ethereum/accounts/keystore" 34 "github.com/ethereum/go-ethereum/cmd/utils" 35 "github.com/ethereum/go-ethereum/console" 36 "github.com/ethereum/go-ethereum/eth" 37 "github.com/ethereum/go-ethereum/ethclient" 38 "github.com/ethereum/go-ethereum/internal/debug" 39 "github.com/ethereum/go-ethereum/log" 40 "github.com/ethereum/go-ethereum/metrics" 41 "github.com/ethereum/go-ethereum/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 utils.EWASMInterpreterFlag, 134 utils.EVMInterpreterFlag, 135 configFileFlag, 136 } 137 138 rpcFlags = []cli.Flag{ 139 utils.RPCEnabledFlag, 140 utils.RPCListenAddrFlag, 141 utils.RPCPortFlag, 142 utils.RPCApiFlag, 143 utils.WSEnabledFlag, 144 utils.WSListenAddrFlag, 145 utils.WSPortFlag, 146 utils.WSApiFlag, 147 utils.WSAllowedOriginsFlag, 148 utils.IPCDisabledFlag, 149 utils.IPCPathFlag, 150 } 151 152 whisperFlags = []cli.Flag{ 153 utils.WhisperEnabledFlag, 154 utils.WhisperMaxMessageSizeFlag, 155 utils.WhisperMinPOWFlag, 156 utils.WhisperRestrictConnectionBetweenLightClientsFlag, 157 } 158 159 metricsFlags = []cli.Flag{ 160 utils.MetricsEnableInfluxDBFlag, 161 utils.MetricsInfluxDBEndpointFlag, 162 utils.MetricsInfluxDBDatabaseFlag, 163 utils.MetricsInfluxDBUsernameFlag, 164 utils.MetricsInfluxDBPasswordFlag, 165 utils.MetricsInfluxDBHostTagFlag, 166 } 167 ) 168 169 func init() { 170 // Initialize the CLI app and start Geth 171 app.Action = geth 172 app.HideVersion = true // we have a command to print the version 173 app.Copyright = "Copyright 2013-2018 The go-ethereum Authors" 174 app.Commands = []cli.Command{ 175 // See chaincmd.go: 176 initCommand, 177 importCommand, 178 exportCommand, 179 importPreimagesCommand, 180 exportPreimagesCommand, 181 copydbCommand, 182 removedbCommand, 183 dumpCommand, 184 // See monitorcmd.go: 185 monitorCommand, 186 // See accountcmd.go: 187 accountCommand, 188 walletCommand, 189 // See consolecmd.go: 190 consoleCommand, 191 attachCommand, 192 javascriptCommand, 193 // See misccmd.go: 194 makecacheCommand, 195 makedagCommand, 196 versionCommand, 197 bugCommand, 198 licenseCommand, 199 // See config.go 200 dumpConfigCommand, 201 } 202 sort.Sort(cli.CommandsByName(app.Commands)) 203 204 app.Flags = append(app.Flags, nodeFlags...) 205 app.Flags = append(app.Flags, rpcFlags...) 206 app.Flags = append(app.Flags, consoleFlags...) 207 app.Flags = append(app.Flags, debug.Flags...) 208 app.Flags = append(app.Flags, whisperFlags...) 209 app.Flags = append(app.Flags, metricsFlags...) 210 211 app.Before = func(ctx *cli.Context) error { 212 runtime.GOMAXPROCS(runtime.NumCPU()) 213 214 logdir := "" 215 if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) { 216 logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs") 217 } 218 if err := debug.Setup(ctx, logdir); err != nil { 219 return err 220 } 221 // Cap the cache allowance and tune the garbage collector 222 var mem gosigar.Mem 223 if err := mem.Get(); err == nil { 224 allowance := int(mem.Total / 1024 / 1024 / 3) 225 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 226 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 227 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 228 } 229 } 230 // Ensure Go's GC ignores the database cache for trigger percentage 231 cache := ctx.GlobalInt(utils.CacheFlag.Name) 232 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 233 234 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 235 godebug.SetGCPercent(int(gogc)) 236 237 // Start metrics export if enabled 238 utils.SetupMetrics(ctx) 239 240 // Start system runtime metrics collection 241 go metrics.CollectProcessMetrics(3 * time.Second) 242 243 return nil 244 } 245 246 app.After = func(ctx *cli.Context) error { 247 debug.Exit() 248 console.Stdin.Close() // Resets terminal mode. 249 return nil 250 } 251 } 252 253 func main() { 254 if err := app.Run(os.Args); err != nil { 255 fmt.Fprintln(os.Stderr, err) 256 os.Exit(1) 257 } 258 } 259 260 // geth is the main entry point into the system if no special subcommand is ran. 261 // It creates a default node based on the command line arguments and runs it in 262 // blocking mode, waiting for it to be shut down. 263 func geth(ctx *cli.Context) error { 264 if args := ctx.Args(); len(args) > 0 { 265 return fmt.Errorf("invalid command: %q", args[0]) 266 } 267 node := makeFullNode(ctx) 268 startNode(ctx, node) 269 node.Wait() 270 return nil 271 } 272 273 // startNode boots up the system node and all registered protocols, after which 274 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 275 // miner. 276 func startNode(ctx *cli.Context, stack *node.Node) { 277 debug.Memsize.Add("node", stack) 278 279 // Start up the node itself 280 utils.StartNode(stack) 281 282 // Unlock any account specifically requested 283 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 284 285 passwords := utils.MakePasswordList(ctx) 286 unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 287 for i, account := range unlocks { 288 if trimmed := strings.TrimSpace(account); trimmed != "" { 289 unlockAccount(ctx, ks, trimmed, i, passwords) 290 } 291 } 292 // Register wallet event handlers to open and auto-derive wallets 293 events := make(chan accounts.WalletEvent, 16) 294 stack.AccountManager().Subscribe(events) 295 296 go func() { 297 // Create a chain state reader for self-derivation 298 rpcClient, err := stack.Attach() 299 if err != nil { 300 utils.Fatalf("Failed to attach to self: %v", err) 301 } 302 stateReader := ethclient.NewClient(rpcClient) 303 304 // Open any wallets already attached 305 for _, wallet := range stack.AccountManager().Wallets() { 306 if err := wallet.Open(""); err != nil { 307 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 308 } 309 } 310 // Listen for wallet event till termination 311 for event := range events { 312 switch event.Kind { 313 case accounts.WalletArrived: 314 if err := event.Wallet.Open(""); err != nil { 315 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 316 } 317 case accounts.WalletOpened: 318 status, _ := event.Wallet.Status() 319 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 320 321 derivationPath := accounts.DefaultBaseDerivationPath 322 if event.Wallet.URL().Scheme == "ledger" { 323 derivationPath = accounts.DefaultLedgerBaseDerivationPath 324 } 325 event.Wallet.SelfDerive(derivationPath, stateReader) 326 327 case accounts.WalletDropped: 328 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 329 event.Wallet.Close() 330 } 331 } 332 }() 333 // Start auxiliary services if enabled 334 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 335 // Mining only makes sense if a full Ethereum node is running 336 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 337 utils.Fatalf("Light clients do not support mining") 338 } 339 var ethereum *eth.Ethereum 340 if err := stack.Service(ðereum); err != nil { 341 utils.Fatalf("Ethereum service not running: %v", err) 342 } 343 // Set the gas price to the limits from the CLI and start mining 344 gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name) 345 if ctx.IsSet(utils.MinerGasPriceFlag.Name) { 346 gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 347 } 348 ethereum.TxPool().SetGasPrice(gasprice) 349 350 threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name) 351 if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) { 352 threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name) 353 } 354 if err := ethereum.StartMining(threads); err != nil { 355 utils.Fatalf("Failed to start mining: %v", err) 356 } 357 } 358 }