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