github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/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/tirogen/go-ethereum/accounts"
    29  	"github.com/tirogen/go-ethereum/accounts/keystore"
    30  	"github.com/tirogen/go-ethereum/cmd/utils"
    31  	"github.com/tirogen/go-ethereum/common"
    32  	"github.com/tirogen/go-ethereum/console/prompt"
    33  	"github.com/tirogen/go-ethereum/eth"
    34  	"github.com/tirogen/go-ethereum/eth/downloader"
    35  	"github.com/tirogen/go-ethereum/ethclient"
    36  	"github.com/tirogen/go-ethereum/internal/debug"
    37  	"github.com/tirogen/go-ethereum/internal/ethapi"
    38  	"github.com/tirogen/go-ethereum/internal/flags"
    39  	"github.com/tirogen/go-ethereum/log"
    40  	"github.com/tirogen/go-ethereum/metrics"
    41  	"github.com/tirogen/go-ethereum/node"
    42  
    43  	// Force-load the tracer engines to trigger registration
    44  	_ "github.com/tirogen/go-ethereum/eth/tracers/js"
    45  	_ "github.com/tirogen/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  	// flags that configure the node
    56  	nodeFlags = flags.Merge([]cli.Flag{
    57  		utils.IdentityFlag,
    58  		utils.UnlockedAccountFlag,
    59  		utils.PasswordFileFlag,
    60  		utils.BootnodesFlag,
    61  		utils.MinFreeDiskSpaceFlag,
    62  		utils.KeyStoreDirFlag,
    63  		utils.ExternalSignerFlag,
    64  		utils.NoUSBFlag,
    65  		utils.USBFlag,
    66  		utils.SmartCardDaemonPathFlag,
    67  		utils.OverrideTerminalTotalDifficulty,
    68  		utils.OverrideTerminalTotalDifficultyPassed,
    69  		utils.EthashCacheDirFlag,
    70  		utils.EthashCachesInMemoryFlag,
    71  		utils.EthashCachesOnDiskFlag,
    72  		utils.EthashCachesLockMmapFlag,
    73  		utils.EthashDatasetDirFlag,
    74  		utils.EthashDatasetsInMemoryFlag,
    75  		utils.EthashDatasetsOnDiskFlag,
    76  		utils.EthashDatasetsLockMmapFlag,
    77  		utils.TxPoolLocalsFlag,
    78  		utils.TxPoolNoLocalsFlag,
    79  		utils.TxPoolJournalFlag,
    80  		utils.TxPoolRejournalFlag,
    81  		utils.TxPoolPriceLimitFlag,
    82  		utils.TxPoolPriceBumpFlag,
    83  		utils.TxPoolAccountSlotsFlag,
    84  		utils.TxPoolGlobalSlotsFlag,
    85  		utils.TxPoolAccountQueueFlag,
    86  		utils.TxPoolGlobalQueueFlag,
    87  		utils.TxPoolLifetimeFlag,
    88  		utils.SyncModeFlag,
    89  		utils.SyncTargetFlag,
    90  		utils.ExitWhenSyncedFlag,
    91  		utils.GCModeFlag,
    92  		utils.SnapshotFlag,
    93  		utils.TxLookupLimitFlag,
    94  		utils.LightServeFlag,
    95  		utils.LightIngressFlag,
    96  		utils.LightEgressFlag,
    97  		utils.LightMaxPeersFlag,
    98  		utils.LightNoPruneFlag,
    99  		utils.LightKDFFlag,
   100  		utils.UltraLightServersFlag,
   101  		utils.UltraLightFractionFlag,
   102  		utils.UltraLightOnlyAnnounceFlag,
   103  		utils.LightNoSyncServeFlag,
   104  		utils.EthRequiredBlocksFlag,
   105  		utils.LegacyWhitelistFlag,
   106  		utils.BloomFilterSizeFlag,
   107  		utils.CacheFlag,
   108  		utils.CacheDatabaseFlag,
   109  		utils.CacheTrieFlag,
   110  		utils.CacheTrieJournalFlag,
   111  		utils.CacheTrieRejournalFlag,
   112  		utils.CacheGCFlag,
   113  		utils.CacheSnapshotFlag,
   114  		utils.CacheNoPrefetchFlag,
   115  		utils.CachePreimagesFlag,
   116  		utils.CacheLogSizeFlag,
   117  		utils.FDLimitFlag,
   118  		utils.ListenPortFlag,
   119  		utils.DiscoveryPortFlag,
   120  		utils.MaxPeersFlag,
   121  		utils.MaxPendingPeersFlag,
   122  		utils.MiningEnabledFlag,
   123  		utils.MinerThreadsFlag,
   124  		utils.MinerNotifyFlag,
   125  		utils.MinerGasLimitFlag,
   126  		utils.MinerGasPriceFlag,
   127  		utils.MinerEtherbaseFlag,
   128  		utils.MinerExtraDataFlag,
   129  		utils.MinerRecommitIntervalFlag,
   130  		utils.MinerNoVerifyFlag,
   131  		utils.MinerNewPayloadTimeout,
   132  		utils.NATFlag,
   133  		utils.NoDiscoverFlag,
   134  		utils.DiscoveryV5Flag,
   135  		utils.NetrestrictFlag,
   136  		utils.NodeKeyFileFlag,
   137  		utils.NodeKeyHexFlag,
   138  		utils.DNSDiscoveryFlag,
   139  		utils.DeveloperFlag,
   140  		utils.DeveloperPeriodFlag,
   141  		utils.DeveloperGasLimitFlag,
   142  		utils.VMEnableDebugFlag,
   143  		utils.NetworkIdFlag,
   144  		utils.EthStatsURLFlag,
   145  		utils.FakePoWFlag,
   146  		utils.NoCompactionFlag,
   147  		utils.GpoBlocksFlag,
   148  		utils.GpoPercentileFlag,
   149  		utils.GpoMaxGasPriceFlag,
   150  		utils.GpoIgnoreGasPriceFlag,
   151  		utils.MinerNotifyFullFlag,
   152  		configFileFlag,
   153  	}, utils.NetworkFlags, utils.DatabasePathFlags)
   154  
   155  	rpcFlags = []cli.Flag{
   156  		utils.HTTPEnabledFlag,
   157  		utils.HTTPListenAddrFlag,
   158  		utils.HTTPPortFlag,
   159  		utils.HTTPCORSDomainFlag,
   160  		utils.AuthListenFlag,
   161  		utils.AuthPortFlag,
   162  		utils.AuthVirtualHostsFlag,
   163  		utils.JWTSecretFlag,
   164  		utils.HTTPVirtualHostsFlag,
   165  		utils.GraphQLEnabledFlag,
   166  		utils.GraphQLCORSDomainFlag,
   167  		utils.GraphQLVirtualHostsFlag,
   168  		utils.HTTPApiFlag,
   169  		utils.HTTPPathPrefixFlag,
   170  		utils.WSEnabledFlag,
   171  		utils.WSListenAddrFlag,
   172  		utils.WSPortFlag,
   173  		utils.WSApiFlag,
   174  		utils.WSAllowedOriginsFlag,
   175  		utils.WSPathPrefixFlag,
   176  		utils.IPCDisabledFlag,
   177  		utils.IPCPathFlag,
   178  		utils.InsecureUnlockAllowedFlag,
   179  		utils.RPCGlobalGasCapFlag,
   180  		utils.RPCGlobalEVMTimeoutFlag,
   181  		utils.RPCGlobalTxFeeCapFlag,
   182  		utils.AllowUnprotectedTxs,
   183  	}
   184  
   185  	metricsFlags = []cli.Flag{
   186  		utils.MetricsEnabledFlag,
   187  		utils.MetricsEnabledExpensiveFlag,
   188  		utils.MetricsHTTPFlag,
   189  		utils.MetricsPortFlag,
   190  		utils.MetricsEnableInfluxDBFlag,
   191  		utils.MetricsInfluxDBEndpointFlag,
   192  		utils.MetricsInfluxDBDatabaseFlag,
   193  		utils.MetricsInfluxDBUsernameFlag,
   194  		utils.MetricsInfluxDBPasswordFlag,
   195  		utils.MetricsInfluxDBTagsFlag,
   196  		utils.MetricsEnableInfluxDBV2Flag,
   197  		utils.MetricsInfluxDBTokenFlag,
   198  		utils.MetricsInfluxDBBucketFlag,
   199  		utils.MetricsInfluxDBOrganizationFlag,
   200  	}
   201  )
   202  
   203  var app = flags.NewApp("the go-ethereum command line interface")
   204  
   205  func init() {
   206  	// Initialize the CLI app and start Geth
   207  	app.Action = geth
   208  	app.HideVersion = true // we have a command to print the version
   209  	app.Copyright = "Copyright 2013-2022 The go-ethereum Authors"
   210  	app.Commands = []*cli.Command{
   211  		// See chaincmd.go:
   212  		initCommand,
   213  		importCommand,
   214  		exportCommand,
   215  		importPreimagesCommand,
   216  		exportPreimagesCommand,
   217  		removedbCommand,
   218  		dumpCommand,
   219  		dumpGenesisCommand,
   220  		// See accountcmd.go:
   221  		accountCommand,
   222  		walletCommand,
   223  		// See consolecmd.go:
   224  		consoleCommand,
   225  		attachCommand,
   226  		javascriptCommand,
   227  		// See misccmd.go:
   228  		makecacheCommand,
   229  		makedagCommand,
   230  		versionCommand,
   231  		versionCheckCommand,
   232  		licenseCommand,
   233  		// See config.go
   234  		dumpConfigCommand,
   235  		// see dbcmd.go
   236  		dbCommand,
   237  		// See cmd/utils/flags_legacy.go
   238  		utils.ShowDeprecated,
   239  		// See snapshot.go
   240  		snapshotCommand,
   241  		// See verkle.go
   242  		verkleCommand,
   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 run.
   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  }