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