github.com/valorbit/go-ethereum@v1.9.11-rc4/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 "runtime" 25 godebug "runtime/debug" 26 "sort" 27 "strconv" 28 "strings" 29 "time" 30 31 "github.com/elastic/gosigar" 32 "github.com/valorbit/go-ethereum/accounts" 33 "github.com/valorbit/go-ethereum/accounts/keystore" 34 "github.com/valorbit/go-ethereum/cmd/utils" 35 "github.com/valorbit/go-ethereum/common" 36 "github.com/valorbit/go-ethereum/console" 37 "github.com/valorbit/go-ethereum/eth" 38 "github.com/valorbit/go-ethereum/eth/downloader" 39 "github.com/valorbit/go-ethereum/ethclient" 40 "github.com/valorbit/go-ethereum/internal/debug" 41 "github.com/valorbit/go-ethereum/les" 42 "github.com/valorbit/go-ethereum/log" 43 "github.com/valorbit/go-ethereum/metrics" 44 "github.com/valorbit/go-ethereum/node" 45 cli "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 = utils.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.BootnodesV4Flag, 65 utils.BootnodesV5Flag, 66 utils.DataDirFlag, 67 utils.AncientFlag, 68 utils.KeyStoreDirFlag, 69 utils.ExternalSignerFlag, 70 utils.NoUSBFlag, 71 utils.SmartCardDaemonPathFlag, 72 utils.OverrideIstanbulFlag, 73 utils.OverrideMuirGlacierFlag, 74 utils.EthashCacheDirFlag, 75 utils.EthashCachesInMemoryFlag, 76 utils.EthashCachesOnDiskFlag, 77 utils.EthashDatasetDirFlag, 78 utils.EthashDatasetsInMemoryFlag, 79 utils.EthashDatasetsOnDiskFlag, 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.LightServeFlag, 95 utils.LightLegacyServFlag, 96 utils.LightIngressFlag, 97 utils.LightEgressFlag, 98 utils.LightMaxPeersFlag, 99 utils.LightLegacyPeersFlag, 100 utils.LightKDFFlag, 101 utils.UltraLightServersFlag, 102 utils.UltraLightFractionFlag, 103 utils.UltraLightOnlyAnnounceFlag, 104 utils.WhitelistFlag, 105 utils.CacheFlag, 106 utils.CacheDatabaseFlag, 107 utils.CacheTrieFlag, 108 utils.CacheGCFlag, 109 utils.CacheNoPrefetchFlag, 110 utils.ListenPortFlag, 111 utils.MaxPeersFlag, 112 utils.MaxPendingPeersFlag, 113 utils.MiningEnabledFlag, 114 utils.MinerThreadsFlag, 115 utils.MinerLegacyThreadsFlag, 116 utils.MinerNotifyFlag, 117 utils.MinerGasTargetFlag, 118 utils.MinerLegacyGasTargetFlag, 119 utils.MinerGasLimitFlag, 120 utils.MinerGasPriceFlag, 121 utils.MinerLegacyGasPriceFlag, 122 utils.MinerEtherbaseFlag, 123 utils.MinerLegacyEtherbaseFlag, 124 utils.MinerExtraDataFlag, 125 utils.MinerLegacyExtraDataFlag, 126 utils.MinerRecommitIntervalFlag, 127 utils.MinerNoVerfiyFlag, 128 utils.NATFlag, 129 utils.NoDiscoverFlag, 130 utils.DiscoveryV5Flag, 131 utils.NetrestrictFlag, 132 utils.NodeKeyFileFlag, 133 utils.NodeKeyHexFlag, 134 utils.DNSDiscoveryFlag, 135 utils.DeveloperFlag, 136 utils.DeveloperPeriodFlag, 137 utils.TestnetFlag, 138 utils.RinkebyFlag, 139 utils.GoerliFlag, 140 utils.ValorbitFlag, 141 utils.GranvilleFlag, 142 utils.VMEnableDebugFlag, 143 utils.NetworkIdFlag, 144 utils.EthStatsURLFlag, 145 utils.FakePoWFlag, 146 utils.NoCompactionFlag, 147 utils.GpoBlocksFlag, 148 utils.GpoPercentileFlag, 149 utils.EWASMInterpreterFlag, 150 utils.EVMInterpreterFlag, 151 configFileFlag, 152 } 153 154 rpcFlags = []cli.Flag{ 155 utils.RPCEnabledFlag, 156 utils.RPCListenAddrFlag, 157 utils.RPCPortFlag, 158 utils.RPCCORSDomainFlag, 159 utils.RPCVirtualHostsFlag, 160 utils.GraphQLEnabledFlag, 161 utils.GraphQLListenAddrFlag, 162 utils.GraphQLPortFlag, 163 utils.GraphQLCORSDomainFlag, 164 utils.GraphQLVirtualHostsFlag, 165 utils.RPCApiFlag, 166 utils.WSEnabledFlag, 167 utils.WSListenAddrFlag, 168 utils.WSPortFlag, 169 utils.WSApiFlag, 170 utils.WSAllowedOriginsFlag, 171 utils.IPCDisabledFlag, 172 utils.IPCPathFlag, 173 utils.InsecureUnlockAllowedFlag, 174 utils.RPCGlobalGasCap, 175 } 176 177 whisperFlags = []cli.Flag{ 178 utils.WhisperEnabledFlag, 179 utils.WhisperMaxMessageSizeFlag, 180 utils.WhisperMinPOWFlag, 181 utils.WhisperRestrictConnectionBetweenLightClientsFlag, 182 } 183 184 metricsFlags = []cli.Flag{ 185 utils.MetricsEnabledFlag, 186 utils.MetricsEnabledExpensiveFlag, 187 utils.MetricsEnableInfluxDBFlag, 188 utils.MetricsInfluxDBEndpointFlag, 189 utils.MetricsInfluxDBDatabaseFlag, 190 utils.MetricsInfluxDBUsernameFlag, 191 utils.MetricsInfluxDBPasswordFlag, 192 utils.MetricsInfluxDBTagsFlag, 193 } 194 ) 195 196 func init() { 197 // Initialize the CLI app and start Geth 198 app.Action = geth 199 app.HideVersion = true // we have a command to print the version 200 app.Copyright = "Copyright 2013-2020 The go-ethereum Authors" 201 app.Commands = []cli.Command{ 202 // See chaincmd.go: 203 initCommand, 204 importCommand, 205 exportCommand, 206 importPreimagesCommand, 207 exportPreimagesCommand, 208 copydbCommand, 209 removedbCommand, 210 dumpCommand, 211 dumpGenesisCommand, 212 inspectCommand, 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 licenseCommand, 225 // See config.go 226 dumpConfigCommand, 227 // See retesteth.go 228 retestethCommand, 229 } 230 sort.Sort(cli.CommandsByName(app.Commands)) 231 232 app.Flags = append(app.Flags, nodeFlags...) 233 app.Flags = append(app.Flags, rpcFlags...) 234 app.Flags = append(app.Flags, consoleFlags...) 235 app.Flags = append(app.Flags, debug.Flags...) 236 app.Flags = append(app.Flags, whisperFlags...) 237 app.Flags = append(app.Flags, metricsFlags...) 238 239 app.Before = func(ctx *cli.Context) error { 240 return debug.Setup(ctx) 241 } 242 app.After = func(ctx *cli.Context) error { 243 debug.Exit() 244 console.Stdin.Close() // Resets terminal mode. 245 return nil 246 } 247 } 248 249 func main() { 250 if err := app.Run(os.Args); err != nil { 251 fmt.Fprintln(os.Stderr, err) 252 os.Exit(1) 253 } 254 } 255 256 // prepare manipulates memory cache allowance and setups metric system. 257 // This function should be called before launching devp2p stack. 258 func prepare(ctx *cli.Context) { 259 // If we're a full node on mainnet without --cache specified, bump default cache allowance 260 if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) { 261 // Make sure we're not on any supported preconfigured testnet either 262 if !ctx.GlobalIsSet(utils.TestnetFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.GranvilleFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) { 263 // Nope, we're really on mainnet. Bump that cache up! 264 log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096) 265 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096)) 266 } 267 } 268 // If we're running a light client on any network, drop the cache to some meaningfully low amount 269 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) { 270 log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128) 271 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128)) 272 } 273 // Cap the cache allowance and tune the garbage collector 274 var mem gosigar.Mem 275 // Workaround until OpenBSD support lands into gosigar 276 // Check https://github.com/elastic/gosigar#supported-platforms 277 if runtime.GOOS != "openbsd" { 278 if err := mem.Get(); err == nil { 279 allowance := int(mem.Total / 1024 / 1024 / 3) 280 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 281 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 282 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 283 } 284 } 285 } 286 // Ensure Go's GC ignores the database cache for trigger percentage 287 cache := ctx.GlobalInt(utils.CacheFlag.Name) 288 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 289 290 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 291 godebug.SetGCPercent(int(gogc)) 292 293 // Start metrics export if enabled 294 utils.SetupMetrics(ctx) 295 296 // Start system runtime metrics collection 297 go metrics.CollectProcessMetrics(3 * time.Second) 298 } 299 300 // geth is the main entry point into the system if no special subcommand is ran. 301 // It creates a default node based on the command line arguments and runs it in 302 // blocking mode, waiting for it to be shut down. 303 func geth(ctx *cli.Context) error { 304 if args := ctx.Args(); len(args) > 0 { 305 return fmt.Errorf("invalid command: %q", args[0]) 306 } 307 prepare(ctx) 308 node := makeFullNode(ctx) 309 defer node.Close() 310 startNode(ctx, node) 311 node.Wait() 312 return nil 313 } 314 315 // startNode boots up the system node and all registered protocols, after which 316 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 317 // miner. 318 func startNode(ctx *cli.Context, stack *node.Node) { 319 debug.Memsize.Add("node", stack) 320 321 // Start up the node itself 322 utils.StartNode(stack) 323 324 // Unlock any account specifically requested 325 unlockAccounts(ctx, stack) 326 327 // Register wallet event handlers to open and auto-derive wallets 328 events := make(chan accounts.WalletEvent, 16) 329 stack.AccountManager().Subscribe(events) 330 331 // Create a client to interact with local geth node. 332 rpcClient, err := stack.Attach() 333 if err != nil { 334 utils.Fatalf("Failed to attach to self: %v", err) 335 } 336 ethClient := ethclient.NewClient(rpcClient) 337 338 // Set contract backend for ethereum service if local node 339 // is serving LES requests. 340 if ctx.GlobalInt(utils.LightLegacyServFlag.Name) > 0 || ctx.GlobalInt(utils.LightServeFlag.Name) > 0 { 341 var ethService *eth.Ethereum 342 if err := stack.Service(ðService); err != nil { 343 utils.Fatalf("Failed to retrieve ethereum service: %v", err) 344 } 345 ethService.SetContractBackend(ethClient) 346 } 347 // Set contract backend for les service if local node is 348 // running as a light client. 349 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 350 var lesService *les.LightEthereum 351 if err := stack.Service(&lesService); err != nil { 352 utils.Fatalf("Failed to retrieve light ethereum service: %v", err) 353 } 354 lesService.SetContractBackend(ethClient) 355 } 356 357 go func() { 358 // Open any wallets already attached 359 for _, wallet := range stack.AccountManager().Wallets() { 360 if err := wallet.Open(""); err != nil { 361 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 362 } 363 } 364 // Listen for wallet event till termination 365 for event := range events { 366 switch event.Kind { 367 case accounts.WalletArrived: 368 if err := event.Wallet.Open(""); err != nil { 369 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 370 } 371 case accounts.WalletOpened: 372 status, _ := event.Wallet.Status() 373 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 374 375 var derivationPaths []accounts.DerivationPath 376 if event.Wallet.URL().Scheme == "ledger" { 377 derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath) 378 } 379 derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath) 380 381 event.Wallet.SelfDerive(derivationPaths, ethClient) 382 383 case accounts.WalletDropped: 384 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 385 event.Wallet.Close() 386 } 387 } 388 }() 389 390 // Spawn a standalone goroutine for status synchronization monitoring, 391 // close the node when synchronization is complete if user required. 392 if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) { 393 go func() { 394 sub := stack.EventMux().Subscribe(downloader.DoneEvent{}) 395 defer sub.Unsubscribe() 396 for { 397 event := <-sub.Chan() 398 if event == nil { 399 continue 400 } 401 done, ok := event.Data.(downloader.DoneEvent) 402 if !ok { 403 continue 404 } 405 if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute { 406 log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(), 407 "age", common.PrettyAge(timestamp)) 408 stack.Stop() 409 } 410 } 411 }() 412 } 413 414 // Start auxiliary services if enabled 415 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 416 // Mining only makes sense if a full Ethereum node is running 417 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 418 utils.Fatalf("Light clients do not support mining") 419 } 420 var ethereum *eth.Ethereum 421 if err := stack.Service(ðereum); err != nil { 422 utils.Fatalf("Ethereum service not running: %v", err) 423 } 424 // Set the gas price to the limits from the CLI and start mining 425 gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name) 426 if ctx.IsSet(utils.MinerGasPriceFlag.Name) { 427 gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 428 } 429 ethereum.TxPool().SetGasPrice(gasprice) 430 431 threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name) 432 if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) { 433 threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name) 434 } 435 if err := ethereum.StartMining(threads); err != nil { 436 utils.Fatalf("Failed to start mining: %v", err) 437 } 438 } 439 } 440 441 // unlockAccounts unlocks any account specifically requested. 442 func unlockAccounts(ctx *cli.Context, stack *node.Node) { 443 var unlocks []string 444 inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 445 for _, input := range inputs { 446 if trimmed := strings.TrimSpace(input); trimmed != "" { 447 unlocks = append(unlocks, trimmed) 448 } 449 } 450 // Short circuit if there is no account to unlock. 451 if len(unlocks) == 0 { 452 return 453 } 454 // If insecure account unlocking is not allowed if node's APIs are exposed to external. 455 // Print warning log to user and skip unlocking. 456 if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() { 457 utils.Fatalf("Account unlock with HTTP access is forbidden!") 458 } 459 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 460 passwords := utils.MakePasswordList(ctx) 461 for i, account := range unlocks { 462 unlockAccount(ks, account, i, passwords) 463 } 464 }