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