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