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