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