github.com/juliankolbe/go-ethereum@v1.9.992/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/juliankolbe/go-ethereum/accounts" 31 "github.com/juliankolbe/go-ethereum/accounts/keystore" 32 "github.com/juliankolbe/go-ethereum/cmd/utils" 33 "github.com/juliankolbe/go-ethereum/common" 34 "github.com/juliankolbe/go-ethereum/console/prompt" 35 "github.com/juliankolbe/go-ethereum/eth" 36 "github.com/juliankolbe/go-ethereum/eth/downloader" 37 "github.com/juliankolbe/go-ethereum/ethclient" 38 "github.com/juliankolbe/go-ethereum/internal/debug" 39 "github.com/juliankolbe/go-ethereum/internal/ethapi" 40 "github.com/juliankolbe/go-ethereum/internal/flags" 41 "github.com/juliankolbe/go-ethereum/log" 42 "github.com/juliankolbe/go-ethereum/metrics" 43 "github.com/juliankolbe/go-ethereum/node" 44 gopsutil "github.com/shirou/gopsutil/mem" 45 "gopkg.in/urfave/cli.v1" 46 ) 47 48 const ( 49 clientIdentifier = "geth" // Client identifier to advertise over the network 50 ) 51 52 var ( 53 // Git SHA1 commit hash of the release (set via linker flags) 54 gitCommit = "" 55 gitDate = "" 56 // The app that holds all commands and flags. 57 app = flags.NewApp(gitCommit, gitDate, "the go-ethereum command line interface") 58 // flags that configure the node 59 nodeFlags = []cli.Flag{ 60 utils.IdentityFlag, 61 utils.UnlockedAccountFlag, 62 utils.PasswordFileFlag, 63 utils.BootnodesFlag, 64 utils.DataDirFlag, 65 utils.AncientFlag, 66 utils.MinFreeDiskSpaceFlag, 67 utils.KeyStoreDirFlag, 68 utils.ExternalSignerFlag, 69 utils.NoUSBFlag, 70 utils.USBFlag, 71 utils.SmartCardDaemonPathFlag, 72 utils.EthashCacheDirFlag, 73 utils.EthashCachesInMemoryFlag, 74 utils.EthashCachesOnDiskFlag, 75 utils.EthashCachesLockMmapFlag, 76 utils.EthashDatasetDirFlag, 77 utils.EthashDatasetsInMemoryFlag, 78 utils.EthashDatasetsOnDiskFlag, 79 utils.EthashDatasetsLockMmapFlag, 80 utils.TxPoolLocalsFlag, 81 utils.TxPoolNoLocalsFlag, 82 utils.TxPoolJournalFlag, 83 utils.TxPoolRejournalFlag, 84 utils.TxPoolPriceLimitFlag, 85 utils.TxPoolPriceBumpFlag, 86 utils.TxPoolAccountSlotsFlag, 87 utils.TxPoolGlobalSlotsFlag, 88 utils.TxPoolAccountQueueFlag, 89 utils.TxPoolGlobalQueueFlag, 90 utils.TxPoolLifetimeFlag, 91 utils.SyncModeFlag, 92 utils.ExitWhenSyncedFlag, 93 utils.GCModeFlag, 94 utils.SnapshotFlag, 95 utils.TxLookupLimitFlag, 96 utils.LightServeFlag, 97 utils.LightIngressFlag, 98 utils.LightEgressFlag, 99 utils.LightMaxPeersFlag, 100 utils.LightNoPruneFlag, 101 utils.LightKDFFlag, 102 utils.UltraLightServersFlag, 103 utils.UltraLightFractionFlag, 104 utils.UltraLightOnlyAnnounceFlag, 105 utils.LightNoSyncServeFlag, 106 utils.WhitelistFlag, 107 utils.BloomFilterSizeFlag, 108 utils.CacheFlag, 109 utils.CacheDatabaseFlag, 110 utils.CacheTrieFlag, 111 utils.CacheTrieJournalFlag, 112 utils.CacheTrieRejournalFlag, 113 utils.CacheGCFlag, 114 utils.CacheSnapshotFlag, 115 utils.CacheNoPrefetchFlag, 116 utils.CachePreimagesFlag, 117 utils.ListenPortFlag, 118 utils.MaxPeersFlag, 119 utils.MaxPendingPeersFlag, 120 utils.MiningEnabledFlag, 121 utils.MinerThreadsFlag, 122 utils.MinerNotifyFlag, 123 utils.MinerGasTargetFlag, 124 utils.MinerGasLimitFlag, 125 utils.MinerGasPriceFlag, 126 utils.MinerEtherbaseFlag, 127 utils.MinerExtraDataFlag, 128 utils.MinerRecommitIntervalFlag, 129 utils.MinerNoVerfiyFlag, 130 utils.NATFlag, 131 utils.NoDiscoverFlag, 132 utils.DiscoveryV5Flag, 133 utils.NetrestrictFlag, 134 utils.NodeKeyFileFlag, 135 utils.NodeKeyHexFlag, 136 utils.DNSDiscoveryFlag, 137 utils.MainnetFlag, 138 utils.DeveloperFlag, 139 utils.DeveloperPeriodFlag, 140 utils.RopstenFlag, 141 utils.RinkebyFlag, 142 utils.GoerliFlag, 143 utils.YoloV3Flag, 144 utils.VMEnableDebugFlag, 145 utils.NetworkIdFlag, 146 utils.EthStatsURLFlag, 147 utils.FakePoWFlag, 148 utils.NoCompactionFlag, 149 utils.GpoBlocksFlag, 150 utils.GpoPercentileFlag, 151 utils.GpoMaxGasPriceFlag, 152 utils.EWASMInterpreterFlag, 153 utils.EVMInterpreterFlag, 154 configFileFlag, 155 } 156 157 rpcFlags = []cli.Flag{ 158 utils.HTTPEnabledFlag, 159 utils.HTTPListenAddrFlag, 160 utils.HTTPPortFlag, 161 utils.HTTPCORSDomainFlag, 162 utils.HTTPVirtualHostsFlag, 163 utils.LegacyRPCEnabledFlag, 164 utils.LegacyRPCListenAddrFlag, 165 utils.LegacyRPCPortFlag, 166 utils.LegacyRPCCORSDomainFlag, 167 utils.LegacyRPCVirtualHostsFlag, 168 utils.LegacyRPCApiFlag, 169 utils.GraphQLEnabledFlag, 170 utils.GraphQLCORSDomainFlag, 171 utils.GraphQLVirtualHostsFlag, 172 utils.HTTPApiFlag, 173 utils.HTTPPathPrefixFlag, 174 utils.WSEnabledFlag, 175 utils.WSListenAddrFlag, 176 utils.WSPortFlag, 177 utils.WSApiFlag, 178 utils.WSAllowedOriginsFlag, 179 utils.WSPathPrefixFlag, 180 utils.IPCDisabledFlag, 181 utils.IPCPathFlag, 182 utils.InsecureUnlockAllowedFlag, 183 utils.RPCGlobalGasCapFlag, 184 utils.RPCGlobalTxFeeCapFlag, 185 utils.AllowUnprotectedTxs, 186 } 187 188 whisperFlags = []cli.Flag{ 189 utils.WhisperEnabledFlag, 190 utils.WhisperMaxMessageSizeFlag, 191 utils.WhisperMinPOWFlag, 192 utils.WhisperRestrictConnectionBetweenLightClientsFlag, 193 } 194 195 metricsFlags = []cli.Flag{ 196 utils.MetricsEnabledFlag, 197 utils.MetricsEnabledExpensiveFlag, 198 utils.MetricsHTTPFlag, 199 utils.MetricsPortFlag, 200 utils.MetricsEnableInfluxDBFlag, 201 utils.MetricsInfluxDBEndpointFlag, 202 utils.MetricsInfluxDBDatabaseFlag, 203 utils.MetricsInfluxDBUsernameFlag, 204 utils.MetricsInfluxDBPasswordFlag, 205 utils.MetricsInfluxDBTagsFlag, 206 } 207 ) 208 209 func init() { 210 // Initialize the CLI app and start Geth 211 app.Action = geth 212 app.HideVersion = true // we have a command to print the version 213 app.Copyright = "Copyright 2013-2021 The go-ethereum Authors" 214 app.Commands = []cli.Command{ 215 // See chaincmd.go: 216 initCommand, 217 importCommand, 218 exportCommand, 219 importPreimagesCommand, 220 exportPreimagesCommand, 221 copydbCommand, 222 removedbCommand, 223 dumpCommand, 224 dumpGenesisCommand, 225 // See accountcmd.go: 226 accountCommand, 227 walletCommand, 228 // See consolecmd.go: 229 consoleCommand, 230 attachCommand, 231 javascriptCommand, 232 // See misccmd.go: 233 makecacheCommand, 234 makedagCommand, 235 versionCommand, 236 versionCheckCommand, 237 licenseCommand, 238 // See config.go 239 dumpConfigCommand, 240 // see dbcmd.go 241 dbCommand, 242 // See cmd/utils/flags_legacy.go 243 utils.ShowDeprecated, 244 // See snapshot.go 245 snapshotCommand, 246 } 247 sort.Sort(cli.CommandsByName(app.Commands)) 248 249 app.Flags = append(app.Flags, nodeFlags...) 250 app.Flags = append(app.Flags, rpcFlags...) 251 app.Flags = append(app.Flags, consoleFlags...) 252 app.Flags = append(app.Flags, debug.Flags...) 253 app.Flags = append(app.Flags, whisperFlags...) 254 app.Flags = append(app.Flags, metricsFlags...) 255 256 app.Before = func(ctx *cli.Context) error { 257 return debug.Setup(ctx) 258 } 259 app.After = func(ctx *cli.Context) error { 260 debug.Exit() 261 prompt.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 // prepare manipulates memory cache allowance and setups metric system. 274 // This function should be called before launching devp2p stack. 275 func prepare(ctx *cli.Context) { 276 // If we're running a known preset, log it for convenience. 277 switch { 278 case ctx.GlobalIsSet(utils.RopstenFlag.Name): 279 log.Info("Starting Geth on Ropsten testnet...") 280 281 case ctx.GlobalIsSet(utils.RinkebyFlag.Name): 282 log.Info("Starting Geth on Rinkeby testnet...") 283 284 case ctx.GlobalIsSet(utils.GoerliFlag.Name): 285 log.Info("Starting Geth on Görli testnet...") 286 287 case ctx.GlobalIsSet(utils.YoloV3Flag.Name): 288 log.Info("Starting Geth on YOLOv3 testnet...") 289 290 case ctx.GlobalIsSet(utils.DeveloperFlag.Name): 291 log.Info("Starting Geth in ephemeral dev mode...") 292 293 case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name): 294 log.Info("Starting Geth on Ethereum mainnet...") 295 } 296 // If we're a full node on mainnet without --cache specified, bump default cache allowance 297 if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) { 298 // Make sure we're not on any supported preconfigured testnet either 299 if !ctx.GlobalIsSet(utils.RopstenFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) { 300 // Nope, we're really on mainnet. Bump that cache up! 301 log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096) 302 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096)) 303 } 304 } 305 // If we're running a light client on any network, drop the cache to some meaningfully low amount 306 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) { 307 log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128) 308 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128)) 309 } 310 // Cap the cache allowance and tune the garbage collector 311 mem, err := gopsutil.VirtualMemory() 312 if err == nil { 313 if 32<<(^uintptr(0)>>63) == 32 && mem.Total > 2*1024*1024*1024 { 314 log.Warn("Lowering memory allowance on 32bit arch", "available", mem.Total/1024/1024, "addressable", 2*1024) 315 mem.Total = 2 * 1024 * 1024 * 1024 316 } 317 allowance := int(mem.Total / 1024 / 1024 / 3) 318 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 319 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 320 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 321 } 322 } 323 // Ensure Go's GC ignores the database cache for trigger percentage 324 cache := ctx.GlobalInt(utils.CacheFlag.Name) 325 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 326 327 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 328 godebug.SetGCPercent(int(gogc)) 329 330 // Start metrics export if enabled 331 utils.SetupMetrics(ctx) 332 333 // Start system runtime metrics collection 334 go metrics.CollectProcessMetrics(3 * time.Second) 335 } 336 337 // geth is the main entry point into the system if no special subcommand is ran. 338 // It creates a default node based on the command line arguments and runs it in 339 // blocking mode, waiting for it to be shut down. 340 func geth(ctx *cli.Context) error { 341 if args := ctx.Args(); len(args) > 0 { 342 return fmt.Errorf("invalid command: %q", args[0]) 343 } 344 345 prepare(ctx) 346 stack, backend := makeFullNode(ctx) 347 defer stack.Close() 348 349 startNode(ctx, stack, backend) 350 stack.Wait() 351 return nil 352 } 353 354 // startNode boots up the system node and all registered protocols, after which 355 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 356 // miner. 357 func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend) { 358 debug.Memsize.Add("node", stack) 359 360 // Start up the node itself 361 utils.StartNode(ctx, stack) 362 363 // Unlock any account specifically requested 364 unlockAccounts(ctx, stack) 365 366 // Register wallet event handlers to open and auto-derive wallets 367 events := make(chan accounts.WalletEvent, 16) 368 stack.AccountManager().Subscribe(events) 369 370 // Create a client to interact with local geth node. 371 rpcClient, err := stack.Attach() 372 if err != nil { 373 utils.Fatalf("Failed to attach to self: %v", err) 374 } 375 ethClient := ethclient.NewClient(rpcClient) 376 377 go func() { 378 // Open any wallets already attached 379 for _, wallet := range stack.AccountManager().Wallets() { 380 if err := wallet.Open(""); err != nil { 381 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 382 } 383 } 384 // Listen for wallet event till termination 385 for event := range events { 386 switch event.Kind { 387 case accounts.WalletArrived: 388 if err := event.Wallet.Open(""); err != nil { 389 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 390 } 391 case accounts.WalletOpened: 392 status, _ := event.Wallet.Status() 393 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 394 395 var derivationPaths []accounts.DerivationPath 396 if event.Wallet.URL().Scheme == "ledger" { 397 derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath) 398 } 399 derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath) 400 401 event.Wallet.SelfDerive(derivationPaths, ethClient) 402 403 case accounts.WalletDropped: 404 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 405 event.Wallet.Close() 406 } 407 } 408 }() 409 410 // Spawn a standalone goroutine for status synchronization monitoring, 411 // close the node when synchronization is complete if user required. 412 if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) { 413 go func() { 414 sub := stack.EventMux().Subscribe(downloader.DoneEvent{}) 415 defer sub.Unsubscribe() 416 for { 417 event := <-sub.Chan() 418 if event == nil { 419 continue 420 } 421 done, ok := event.Data.(downloader.DoneEvent) 422 if !ok { 423 continue 424 } 425 if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute { 426 log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(), 427 "age", common.PrettyAge(timestamp)) 428 stack.Close() 429 } 430 } 431 }() 432 } 433 434 // Start auxiliary services if enabled 435 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 436 // Mining only makes sense if a full Ethereum node is running 437 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 438 utils.Fatalf("Light clients do not support mining") 439 } 440 ethBackend, ok := backend.(*eth.EthAPIBackend) 441 if !ok { 442 utils.Fatalf("Ethereum service not running: %v", err) 443 } 444 // Set the gas price to the limits from the CLI and start mining 445 gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 446 ethBackend.TxPool().SetGasPrice(gasprice) 447 // start mining 448 threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name) 449 if err := ethBackend.StartMining(threads); err != nil { 450 utils.Fatalf("Failed to start mining: %v", err) 451 } 452 } 453 } 454 455 // unlockAccounts unlocks any account specifically requested. 456 func unlockAccounts(ctx *cli.Context, stack *node.Node) { 457 var unlocks []string 458 inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 459 for _, input := range inputs { 460 if trimmed := strings.TrimSpace(input); trimmed != "" { 461 unlocks = append(unlocks, trimmed) 462 } 463 } 464 // Short circuit if there is no account to unlock. 465 if len(unlocks) == 0 { 466 return 467 } 468 // If insecure account unlocking is not allowed if node's APIs are exposed to external. 469 // Print warning log to user and skip unlocking. 470 if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() { 471 utils.Fatalf("Account unlock with HTTP access is forbidden!") 472 } 473 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 474 passwords := utils.MakePasswordList(ctx) 475 for i, account := range unlocks { 476 unlockAccount(ks, account, i, passwords) 477 } 478 }