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