github.com/hardtosaygoodbye/go-ethereum@v1.10.16-0.20220122011429-97003b9e6c15/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/hardtosaygoodbye/go-ethereum/accounts"
    29  	"github.com/hardtosaygoodbye/go-ethereum/accounts/keystore"
    30  	"github.com/hardtosaygoodbye/go-ethereum/cmd/utils"
    31  	"github.com/hardtosaygoodbye/go-ethereum/common"
    32  	"github.com/hardtosaygoodbye/go-ethereum/console/prompt"
    33  	"github.com/hardtosaygoodbye/go-ethereum/eth"
    34  	"github.com/hardtosaygoodbye/go-ethereum/eth/downloader"
    35  	"github.com/hardtosaygoodbye/go-ethereum/ethclient"
    36  	"github.com/hardtosaygoodbye/go-ethereum/internal/debug"
    37  	"github.com/hardtosaygoodbye/go-ethereum/internal/ethapi"
    38  	"github.com/hardtosaygoodbye/go-ethereum/internal/flags"
    39  	"github.com/hardtosaygoodbye/go-ethereum/log"
    40  	"github.com/hardtosaygoodbye/go-ethereum/metrics"
    41  	"github.com/hardtosaygoodbye/go-ethereum/node"
    42  
    43  	// Force-load the tracer engines to trigger registration
    44  	_ "github.com/hardtosaygoodbye/go-ethereum/eth/tracers/js"
    45  	_ "github.com/hardtosaygoodbye/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.WhitelistFlag,
   111  		utils.BloomFilterSizeFlag,
   112  		utils.CacheFlag,
   113  		utils.CacheDatabaseFlag,
   114  		utils.CacheTrieFlag,
   115  		utils.CacheTrieJournalFlag,
   116  		utils.CacheTrieRejournalFlag,
   117  		utils.CacheGCFlag,
   118  		utils.CacheSnapshotFlag,
   119  		utils.CacheNoPrefetchFlag,
   120  		utils.CachePreimagesFlag,
   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.MainnetFlag,
   142  		utils.DeveloperFlag,
   143  		utils.DeveloperPeriodFlag,
   144  		utils.DeveloperGasLimitFlag,
   145  		utils.RopstenFlag,
   146  		utils.SepoliaFlag,
   147  		utils.RinkebyFlag,
   148  		utils.GoerliFlag,
   149  		utils.VMEnableDebugFlag,
   150  		utils.NetworkIdFlag,
   151  		utils.EthStatsURLFlag,
   152  		utils.FakePoWFlag,
   153  		utils.NoCompactionFlag,
   154  		utils.GpoBlocksFlag,
   155  		utils.GpoPercentileFlag,
   156  		utils.GpoMaxGasPriceFlag,
   157  		utils.GpoIgnoreGasPriceFlag,
   158  		utils.MinerNotifyFullFlag,
   159  		configFileFlag,
   160  		utils.CatalystFlag,
   161  	}
   162  
   163  	rpcFlags = []cli.Flag{
   164  		utils.HTTPEnabledFlag,
   165  		utils.HTTPListenAddrFlag,
   166  		utils.HTTPPortFlag,
   167  		utils.HTTPCORSDomainFlag,
   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 = append(app.Flags, nodeFlags...)
   247  	app.Flags = append(app.Flags, rpcFlags...)
   248  	app.Flags = append(app.Flags, consoleFlags...)
   249  	app.Flags = append(app.Flags, debug.Flags...)
   250  	app.Flags = append(app.Flags, metricsFlags...)
   251  
   252  	app.Before = func(ctx *cli.Context) error {
   253  		return debug.Setup(ctx)
   254  	}
   255  	app.After = func(ctx *cli.Context) error {
   256  		debug.Exit()
   257  		prompt.Stdin.Close() // Resets terminal mode.
   258  		return nil
   259  	}
   260  }
   261  
   262  func main() {
   263  	if err := app.Run(os.Args); err != nil {
   264  		fmt.Fprintln(os.Stderr, err)
   265  		os.Exit(1)
   266  	}
   267  }
   268  
   269  // prepare manipulates memory cache allowance and setups metric system.
   270  // This function should be called before launching devp2p stack.
   271  func prepare(ctx *cli.Context) {
   272  	// If we're running a known preset, log it for convenience.
   273  	switch {
   274  	case ctx.GlobalIsSet(utils.RopstenFlag.Name):
   275  		log.Info("Starting Geth on Ropsten testnet...")
   276  
   277  	case ctx.GlobalIsSet(utils.SepoliaFlag.Name):
   278  		log.Info("Starting Geth on Sepolia testnet...")
   279  
   280  	case ctx.GlobalIsSet(utils.RinkebyFlag.Name):
   281  		log.Info("Starting Geth on Rinkeby testnet...")
   282  
   283  	case ctx.GlobalIsSet(utils.GoerliFlag.Name):
   284  		log.Info("Starting Geth on Görli testnet...")
   285  
   286  	case ctx.GlobalIsSet(utils.DeveloperFlag.Name):
   287  		log.Info("Starting Geth in ephemeral dev mode...")
   288  
   289  	case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name):
   290  		log.Info("Starting Geth on Ethereum mainnet...")
   291  	}
   292  	// If we're a full node on mainnet without --cache specified, bump default cache allowance
   293  	if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
   294  		// Make sure we're not on any supported preconfigured testnet either
   295  		if !ctx.GlobalIsSet(utils.RopstenFlag.Name) &&
   296  			!ctx.GlobalIsSet(utils.SepoliaFlag.Name) &&
   297  			!ctx.GlobalIsSet(utils.RinkebyFlag.Name) &&
   298  			!ctx.GlobalIsSet(utils.GoerliFlag.Name) &&
   299  			!ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
   300  			// Nope, we're really on mainnet. Bump that cache up!
   301  			log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
   302  			ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
   303  		}
   304  	}
   305  	// If we're running a light client on any network, drop the cache to some meaningfully low amount
   306  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
   307  		log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
   308  		ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
   309  	}
   310  
   311  	// Start metrics export if enabled
   312  	utils.SetupMetrics(ctx)
   313  
   314  	// Start system runtime metrics collection
   315  	go metrics.CollectProcessMetrics(3 * time.Second)
   316  }
   317  
   318  // geth is the main entry point into the system if no special subcommand is ran.
   319  // It creates a default node based on the command line arguments and runs it in
   320  // blocking mode, waiting for it to be shut down.
   321  func geth(ctx *cli.Context) error {
   322  	if args := ctx.Args(); len(args) > 0 {
   323  		return fmt.Errorf("invalid command: %q", args[0])
   324  	}
   325  
   326  	prepare(ctx)
   327  	stack, backend := makeFullNode(ctx)
   328  	defer stack.Close()
   329  
   330  	startNode(ctx, stack, backend, false)
   331  	stack.Wait()
   332  	return nil
   333  }
   334  
   335  // startNode boots up the system node and all registered protocols, after which
   336  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   337  // miner.
   338  func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend, isConsole bool) {
   339  	debug.Memsize.Add("node", stack)
   340  
   341  	// Start up the node itself
   342  	utils.StartNode(ctx, stack, isConsole)
   343  
   344  	// Unlock any account specifically requested
   345  	unlockAccounts(ctx, stack)
   346  
   347  	// Register wallet event handlers to open and auto-derive wallets
   348  	events := make(chan accounts.WalletEvent, 16)
   349  	stack.AccountManager().Subscribe(events)
   350  
   351  	// Create a client to interact with local geth node.
   352  	rpcClient, err := stack.Attach()
   353  	if err != nil {
   354  		utils.Fatalf("Failed to attach to self: %v", err)
   355  	}
   356  	ethClient := ethclient.NewClient(rpcClient)
   357  
   358  	go func() {
   359  		// Open any wallets already attached
   360  		for _, wallet := range stack.AccountManager().Wallets() {
   361  			if err := wallet.Open(""); err != nil {
   362  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   363  			}
   364  		}
   365  		// Listen for wallet event till termination
   366  		for event := range events {
   367  			switch event.Kind {
   368  			case accounts.WalletArrived:
   369  				if err := event.Wallet.Open(""); err != nil {
   370  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   371  				}
   372  			case accounts.WalletOpened:
   373  				status, _ := event.Wallet.Status()
   374  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   375  
   376  				var derivationPaths []accounts.DerivationPath
   377  				if event.Wallet.URL().Scheme == "ledger" {
   378  					derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
   379  				}
   380  				derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
   381  
   382  				event.Wallet.SelfDerive(derivationPaths, ethClient)
   383  
   384  			case accounts.WalletDropped:
   385  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   386  				event.Wallet.Close()
   387  			}
   388  		}
   389  	}()
   390  
   391  	// Spawn a standalone goroutine for status synchronization monitoring,
   392  	// close the node when synchronization is complete if user required.
   393  	if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
   394  		go func() {
   395  			sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
   396  			defer sub.Unsubscribe()
   397  			for {
   398  				event := <-sub.Chan()
   399  				if event == nil {
   400  					continue
   401  				}
   402  				done, ok := event.Data.(downloader.DoneEvent)
   403  				if !ok {
   404  					continue
   405  				}
   406  				if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
   407  					log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
   408  						"age", common.PrettyAge(timestamp))
   409  					stack.Close()
   410  				}
   411  			}
   412  		}()
   413  	}
   414  
   415  	// Start auxiliary services if enabled
   416  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   417  		// Mining only makes sense if a full Ethereum node is running
   418  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   419  			utils.Fatalf("Light clients do not support mining")
   420  		}
   421  		ethBackend, ok := backend.(*eth.EthAPIBackend)
   422  		if !ok {
   423  			utils.Fatalf("Ethereum service not running")
   424  		}
   425  		// Set the gas price to the limits from the CLI and start mining
   426  		gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   427  		ethBackend.TxPool().SetGasPrice(gasprice)
   428  		// start mining
   429  		threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   430  		if err := ethBackend.StartMining(threads); err != nil {
   431  			utils.Fatalf("Failed to start mining: %v", err)
   432  		}
   433  	}
   434  }
   435  
   436  // unlockAccounts unlocks any account specifically requested.
   437  func unlockAccounts(ctx *cli.Context, stack *node.Node) {
   438  	var unlocks []string
   439  	inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   440  	for _, input := range inputs {
   441  		if trimmed := strings.TrimSpace(input); trimmed != "" {
   442  			unlocks = append(unlocks, trimmed)
   443  		}
   444  	}
   445  	// Short circuit if there is no account to unlock.
   446  	if len(unlocks) == 0 {
   447  		return
   448  	}
   449  	// If insecure account unlocking is not allowed if node's APIs are exposed to external.
   450  	// Print warning log to user and skip unlocking.
   451  	if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
   452  		utils.Fatalf("Account unlock with HTTP access is forbidden!")
   453  	}
   454  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   455  	passwords := utils.MakePasswordList(ctx)
   456  	for i, account := range unlocks {
   457  		unlockAccount(ks, account, i, passwords)
   458  	}
   459  }