github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/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/tacshi/go-ethereum/accounts"
    29  	"github.com/tacshi/go-ethereum/accounts/keystore"
    30  	"github.com/tacshi/go-ethereum/cmd/utils"
    31  	"github.com/tacshi/go-ethereum/common"
    32  	"github.com/tacshi/go-ethereum/console/prompt"
    33  	"github.com/tacshi/go-ethereum/eth"
    34  	"github.com/tacshi/go-ethereum/eth/downloader"
    35  	"github.com/tacshi/go-ethereum/ethclient"
    36  	"github.com/tacshi/go-ethereum/internal/debug"
    37  	"github.com/tacshi/go-ethereum/internal/ethapi"
    38  	"github.com/tacshi/go-ethereum/internal/flags"
    39  	"github.com/tacshi/go-ethereum/log"
    40  	"github.com/tacshi/go-ethereum/metrics"
    41  	"github.com/tacshi/go-ethereum/node"
    42  
    43  	// Force-load the tracer engines to trigger registration
    44  	_ "github.com/tacshi/go-ethereum/eth/tracers/js"
    45  	_ "github.com/tacshi/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.OverrideShanghai,
    68  		utils.EnablePersonal,
    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-2023 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.RinkebyFlag.Name):
   278  		log.Info("Starting Geth on Rinkeby testnet...")
   279  
   280  	case ctx.IsSet(utils.GoerliFlag.Name):
   281  		log.Info("Starting Geth on Görli testnet...")
   282  
   283  	case ctx.IsSet(utils.SepoliaFlag.Name):
   284  		log.Info("Starting Geth on Sepolia testnet...")
   285  
   286  	case ctx.IsSet(utils.DeveloperFlag.Name):
   287  		log.Info("Starting Geth in ephemeral dev mode...")
   288  		log.Warn(`You are running Geth in --dev mode. Please note the following:
   289  
   290    1. This mode is only intended for fast, iterative development without assumptions on
   291       security or persistence.
   292    2. The database is created in memory unless specified otherwise. Therefore, shutting down
   293       your computer or losing power will wipe your entire block data and chain state for
   294       your dev environment.
   295    3. A random, pre-allocated developer account will be available and unlocked as
   296       eth.coinbase, which can be used for testing. The random dev account is temporary,
   297       stored on a ramdisk, and will be lost if your machine is restarted.
   298    4. Mining is enabled by default. However, the client will only seal blocks if transactions
   299       are pending in the mempool. The miner's minimum accepted gas price is 1.
   300    5. Networking is disabled; there is no listen-address, the maximum number of peers is set
   301       to 0, and discovery is disabled.
   302  `)
   303  
   304  	case !ctx.IsSet(utils.NetworkIdFlag.Name):
   305  		log.Info("Starting Geth on Ethereum mainnet...")
   306  	}
   307  	// If we're a full node on mainnet without --cache specified, bump default cache allowance
   308  	if ctx.String(utils.SyncModeFlag.Name) != "light" && !ctx.IsSet(utils.CacheFlag.Name) && !ctx.IsSet(utils.NetworkIdFlag.Name) {
   309  		// Make sure we're not on any supported preconfigured testnet either
   310  		if !ctx.IsSet(utils.SepoliaFlag.Name) &&
   311  			!ctx.IsSet(utils.RinkebyFlag.Name) &&
   312  			!ctx.IsSet(utils.GoerliFlag.Name) &&
   313  			!ctx.IsSet(utils.DeveloperFlag.Name) {
   314  			// Nope, we're really on mainnet. Bump that cache up!
   315  			log.Info("Bumping default cache on mainnet", "provided", ctx.Int(utils.CacheFlag.Name), "updated", 4096)
   316  			ctx.Set(utils.CacheFlag.Name, strconv.Itoa(4096))
   317  		}
   318  	}
   319  	// If we're running a light client on any network, drop the cache to some meaningfully low amount
   320  	if ctx.String(utils.SyncModeFlag.Name) == "light" && !ctx.IsSet(utils.CacheFlag.Name) {
   321  		log.Info("Dropping default light client cache", "provided", ctx.Int(utils.CacheFlag.Name), "updated", 128)
   322  		ctx.Set(utils.CacheFlag.Name, strconv.Itoa(128))
   323  	}
   324  
   325  	// Start metrics export if enabled
   326  	utils.SetupMetrics(ctx)
   327  
   328  	// Start system runtime metrics collection
   329  	go metrics.CollectProcessMetrics(3 * time.Second)
   330  }
   331  
   332  // geth is the main entry point into the system if no special subcommand is run.
   333  // It creates a default node based on the command line arguments and runs it in
   334  // blocking mode, waiting for it to be shut down.
   335  func geth(ctx *cli.Context) error {
   336  	if args := ctx.Args().Slice(); len(args) > 0 {
   337  		return fmt.Errorf("invalid command: %q", args[0])
   338  	}
   339  
   340  	prepare(ctx)
   341  	stack, backend := makeFullNode(ctx)
   342  	defer stack.Close()
   343  
   344  	startNode(ctx, stack, backend, false)
   345  	stack.Wait()
   346  	return nil
   347  }
   348  
   349  // startNode boots up the system node and all registered protocols, after which
   350  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   351  // miner.
   352  func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend, isConsole bool) {
   353  	debug.Memsize.Add("node", stack)
   354  
   355  	// Start up the node itself
   356  	utils.StartNode(ctx, stack, isConsole)
   357  
   358  	// Unlock any account specifically requested
   359  	unlockAccounts(ctx, stack)
   360  
   361  	// Register wallet event handlers to open and auto-derive wallets
   362  	events := make(chan accounts.WalletEvent, 16)
   363  	stack.AccountManager().Subscribe(events)
   364  
   365  	// Create a client to interact with local geth node.
   366  	rpcClient, err := stack.Attach()
   367  	if err != nil {
   368  		utils.Fatalf("Failed to attach to self: %v", err)
   369  	}
   370  	ethClient := ethclient.NewClient(rpcClient)
   371  
   372  	go func() {
   373  		// Open any wallets already attached
   374  		for _, wallet := range stack.AccountManager().Wallets() {
   375  			if err := wallet.Open(""); err != nil {
   376  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   377  			}
   378  		}
   379  		// Listen for wallet event till termination
   380  		for event := range events {
   381  			switch event.Kind {
   382  			case accounts.WalletArrived:
   383  				if err := event.Wallet.Open(""); err != nil {
   384  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   385  				}
   386  			case accounts.WalletOpened:
   387  				status, _ := event.Wallet.Status()
   388  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   389  
   390  				var derivationPaths []accounts.DerivationPath
   391  				if event.Wallet.URL().Scheme == "ledger" {
   392  					derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
   393  				}
   394  				derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
   395  
   396  				event.Wallet.SelfDerive(derivationPaths, ethClient)
   397  
   398  			case accounts.WalletDropped:
   399  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   400  				event.Wallet.Close()
   401  			}
   402  		}
   403  	}()
   404  
   405  	// Spawn a standalone goroutine for status synchronization monitoring,
   406  	// close the node when synchronization is complete if user required.
   407  	if ctx.Bool(utils.ExitWhenSyncedFlag.Name) {
   408  		go func() {
   409  			sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
   410  			defer sub.Unsubscribe()
   411  			for {
   412  				event := <-sub.Chan()
   413  				if event == nil {
   414  					continue
   415  				}
   416  				done, ok := event.Data.(downloader.DoneEvent)
   417  				if !ok {
   418  					continue
   419  				}
   420  				if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
   421  					log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
   422  						"age", common.PrettyAge(timestamp))
   423  					stack.Close()
   424  				}
   425  			}
   426  		}()
   427  	}
   428  
   429  	// Start auxiliary services if enabled
   430  	if ctx.Bool(utils.MiningEnabledFlag.Name) || ctx.Bool(utils.DeveloperFlag.Name) {
   431  		// Mining only makes sense if a full Ethereum node is running
   432  		if ctx.String(utils.SyncModeFlag.Name) == "light" {
   433  			utils.Fatalf("Light clients do not support mining")
   434  		}
   435  		ethBackend, ok := backend.(*eth.EthAPIBackend)
   436  		if !ok {
   437  			utils.Fatalf("Ethereum service not running")
   438  		}
   439  		// Set the gas price to the limits from the CLI and start mining
   440  		gasprice := flags.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   441  		ethBackend.TxPool().SetGasPrice(gasprice)
   442  		// start mining
   443  		threads := ctx.Int(utils.MinerThreadsFlag.Name)
   444  		if err := ethBackend.StartMining(threads); err != nil {
   445  			utils.Fatalf("Failed to start mining: %v", err)
   446  		}
   447  	}
   448  }
   449  
   450  // unlockAccounts unlocks any account specifically requested.
   451  func unlockAccounts(ctx *cli.Context, stack *node.Node) {
   452  	var unlocks []string
   453  	inputs := strings.Split(ctx.String(utils.UnlockedAccountFlag.Name), ",")
   454  	for _, input := range inputs {
   455  		if trimmed := strings.TrimSpace(input); trimmed != "" {
   456  			unlocks = append(unlocks, trimmed)
   457  		}
   458  	}
   459  	// Short circuit if there is no account to unlock.
   460  	if len(unlocks) == 0 {
   461  		return
   462  	}
   463  	// If insecure account unlocking is not allowed if node's APIs are exposed to external.
   464  	// Print warning log to user and skip unlocking.
   465  	if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
   466  		utils.Fatalf("Account unlock with HTTP access is forbidden!")
   467  	}
   468  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   469  	passwords := utils.MakePasswordList(ctx)
   470  	for i, account := range unlocks {
   471  		unlockAccount(ks, account, i, passwords)
   472  	}
   473  }