github.com/haliliceylan/bsc@v1.1.10-0.20220501224556-eb78d644ebcb/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  	"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.DirectBroadcastFlag,
    73  		utils.DisableSnapProtocolFlag,
    74  		utils.DiffSyncFlag,
    75  		utils.PipeCommitFlag,
    76  		utils.RangeLimitFlag,
    77  		utils.USBFlag,
    78  		utils.SmartCardDaemonPathFlag,
    79  		utils.OverrideBerlinFlag,
    80  		utils.EthashCacheDirFlag,
    81  		utils.EthashCachesInMemoryFlag,
    82  		utils.EthashCachesOnDiskFlag,
    83  		utils.EthashCachesLockMmapFlag,
    84  		utils.EthashDatasetDirFlag,
    85  		utils.EthashDatasetsInMemoryFlag,
    86  		utils.EthashDatasetsOnDiskFlag,
    87  		utils.EthashDatasetsLockMmapFlag,
    88  		utils.TxPoolLocalsFlag,
    89  		utils.TxPoolNoLocalsFlag,
    90  		utils.TxPoolJournalFlag,
    91  		utils.TxPoolRejournalFlag,
    92  		utils.TxPoolPriceLimitFlag,
    93  		utils.TxPoolPriceBumpFlag,
    94  		utils.TxPoolAccountSlotsFlag,
    95  		utils.TxPoolGlobalSlotsFlag,
    96  		utils.TxPoolAccountQueueFlag,
    97  		utils.TxPoolGlobalQueueFlag,
    98  		utils.TxPoolLifetimeFlag,
    99  		utils.TxPoolReannounceTimeFlag,
   100  		utils.SyncModeFlag,
   101  		utils.ExitWhenSyncedFlag,
   102  		utils.GCModeFlag,
   103  		utils.SnapshotFlag,
   104  		utils.TxLookupLimitFlag,
   105  		utils.LightServeFlag,
   106  		utils.LightIngressFlag,
   107  		utils.LightEgressFlag,
   108  		utils.LightMaxPeersFlag,
   109  		utils.LightNoPruneFlag,
   110  		utils.LightKDFFlag,
   111  		utils.UltraLightServersFlag,
   112  		utils.UltraLightFractionFlag,
   113  		utils.UltraLightOnlyAnnounceFlag,
   114  		utils.LightNoSyncServeFlag,
   115  		utils.WhitelistFlag,
   116  		utils.BloomFilterSizeFlag,
   117  		utils.TriesInMemoryFlag,
   118  		utils.CacheFlag,
   119  		utils.CacheDatabaseFlag,
   120  		utils.CacheTrieFlag,
   121  		utils.CacheTrieJournalFlag,
   122  		utils.CacheTrieRejournalFlag,
   123  		utils.CacheGCFlag,
   124  		utils.CacheSnapshotFlag,
   125  		utils.CachePreimagesFlag,
   126  		utils.PersistDiffFlag,
   127  		utils.DiffBlockFlag,
   128  		utils.ListenPortFlag,
   129  		utils.MaxPeersFlag,
   130  		utils.MaxPendingPeersFlag,
   131  		utils.MiningEnabledFlag,
   132  		utils.MinerThreadsFlag,
   133  		utils.MinerNotifyFlag,
   134  		utils.MinerGasTargetFlag,
   135  		utils.MinerGasLimitFlag,
   136  		utils.MinerGasPriceFlag,
   137  		utils.MinerEtherbaseFlag,
   138  		utils.MinerExtraDataFlag,
   139  		utils.MinerRecommitIntervalFlag,
   140  		utils.MinerDelayLeftoverFlag,
   141  		utils.MinerNoVerfiyFlag,
   142  		utils.NATFlag,
   143  		utils.NoDiscoverFlag,
   144  		utils.DiscoveryV5Flag,
   145  		utils.NetrestrictFlag,
   146  		utils.NodeKeyFileFlag,
   147  		utils.NodeKeyHexFlag,
   148  		utils.DNSDiscoveryFlag,
   149  		utils.MainnetFlag,
   150  		utils.DeveloperFlag,
   151  		utils.DeveloperPeriodFlag,
   152  		utils.RopstenFlag,
   153  		utils.RinkebyFlag,
   154  		utils.GoerliFlag,
   155  		utils.YoloV3Flag,
   156  		utils.VMEnableDebugFlag,
   157  		utils.NetworkIdFlag,
   158  		utils.EthStatsURLFlag,
   159  		utils.FakePoWFlag,
   160  		utils.NoCompactionFlag,
   161  		utils.GpoBlocksFlag,
   162  		utils.GpoPercentileFlag,
   163  		utils.GpoMaxGasPriceFlag,
   164  		utils.EWASMInterpreterFlag,
   165  		utils.EVMInterpreterFlag,
   166  		utils.MinerNotifyFullFlag,
   167  		configFileFlag,
   168  		utils.CatalystFlag,
   169  		utils.BlockAmountReserved,
   170  		utils.CheckSnapshotWithMPT,
   171  	}
   172  
   173  	rpcFlags = []cli.Flag{
   174  		utils.HTTPEnabledFlag,
   175  		utils.HTTPListenAddrFlag,
   176  		utils.HTTPPortFlag,
   177  		utils.HTTPCORSDomainFlag,
   178  		utils.HTTPVirtualHostsFlag,
   179  		utils.LegacyRPCEnabledFlag,
   180  		utils.LegacyRPCListenAddrFlag,
   181  		utils.LegacyRPCPortFlag,
   182  		utils.LegacyRPCCORSDomainFlag,
   183  		utils.LegacyRPCVirtualHostsFlag,
   184  		utils.LegacyRPCApiFlag,
   185  		utils.GraphQLEnabledFlag,
   186  		utils.GraphQLCORSDomainFlag,
   187  		utils.GraphQLVirtualHostsFlag,
   188  		utils.HTTPApiFlag,
   189  		utils.HTTPPathPrefixFlag,
   190  		utils.WSEnabledFlag,
   191  		utils.WSListenAddrFlag,
   192  		utils.WSPortFlag,
   193  		utils.WSApiFlag,
   194  		utils.WSAllowedOriginsFlag,
   195  		utils.WSPathPrefixFlag,
   196  		utils.IPCDisabledFlag,
   197  		utils.IPCPathFlag,
   198  		utils.InsecureUnlockAllowedFlag,
   199  		utils.RPCGlobalGasCapFlag,
   200  		utils.RPCGlobalTxFeeCapFlag,
   201  		utils.AllowUnprotectedTxs,
   202  	}
   203  
   204  	metricsFlags = []cli.Flag{
   205  		utils.MetricsEnabledFlag,
   206  		utils.MetricsEnabledExpensiveFlag,
   207  		utils.MetricsHTTPFlag,
   208  		utils.MetricsPortFlag,
   209  		utils.MetricsEnableInfluxDBFlag,
   210  		utils.MetricsInfluxDBEndpointFlag,
   211  		utils.MetricsInfluxDBDatabaseFlag,
   212  		utils.MetricsInfluxDBUsernameFlag,
   213  		utils.MetricsInfluxDBPasswordFlag,
   214  		utils.MetricsInfluxDBTagsFlag,
   215  	}
   216  )
   217  
   218  func init() {
   219  	// Initialize the CLI app and start Geth
   220  	app.Action = geth
   221  	app.HideVersion = true // we have a command to print the version
   222  	app.Copyright = "Copyright 2013-2020 The go-ethereum Authors and BSC Authors"
   223  	app.Commands = []cli.Command{
   224  		// See chaincmd.go:
   225  		initCommand,
   226  		initNetworkCommand,
   227  		importCommand,
   228  		exportCommand,
   229  		importPreimagesCommand,
   230  		exportPreimagesCommand,
   231  		removedbCommand,
   232  		dumpCommand,
   233  		dumpGenesisCommand,
   234  		// See accountcmd.go:
   235  		accountCommand,
   236  		walletCommand,
   237  		// See consolecmd.go:
   238  		consoleCommand,
   239  		attachCommand,
   240  		javascriptCommand,
   241  		// See misccmd.go:
   242  		makecacheCommand,
   243  		makedagCommand,
   244  		versionCommand,
   245  		versionCheckCommand,
   246  		licenseCommand,
   247  		// See config.go
   248  		dumpConfigCommand,
   249  		// see dbcmd.go
   250  		dbCommand,
   251  		// See cmd/utils/flags_legacy.go
   252  		utils.ShowDeprecated,
   253  		// See snapshot.go
   254  		snapshotCommand,
   255  	}
   256  	sort.Sort(cli.CommandsByName(app.Commands))
   257  
   258  	app.Flags = append(app.Flags, nodeFlags...)
   259  	app.Flags = append(app.Flags, rpcFlags...)
   260  	app.Flags = append(app.Flags, consoleFlags...)
   261  	app.Flags = append(app.Flags, debug.Flags...)
   262  	app.Flags = append(app.Flags, metricsFlags...)
   263  
   264  	app.Before = func(ctx *cli.Context) error {
   265  		return debug.Setup(ctx)
   266  	}
   267  	app.After = func(ctx *cli.Context) error {
   268  		debug.Exit()
   269  		prompt.Stdin.Close() // Resets terminal mode.
   270  		return nil
   271  	}
   272  }
   273  
   274  func main() {
   275  	if err := app.Run(os.Args); err != nil {
   276  		fmt.Fprintln(os.Stderr, err)
   277  		os.Exit(1)
   278  	}
   279  }
   280  
   281  // prepare manipulates memory cache allowance and setups metric system.
   282  // This function should be called before launching devp2p stack.
   283  func prepare(ctx *cli.Context) {
   284  	// If we're running a known preset, log it for convenience.
   285  	switch {
   286  	case ctx.GlobalIsSet(utils.RopstenFlag.Name):
   287  		log.Info("Starting Geth on Ropsten testnet...")
   288  
   289  	case ctx.GlobalIsSet(utils.RinkebyFlag.Name):
   290  		log.Info("Starting Geth on Rinkeby testnet...")
   291  
   292  	case ctx.GlobalIsSet(utils.GoerliFlag.Name):
   293  		log.Info("Starting Geth on Görli testnet...")
   294  
   295  	case ctx.GlobalIsSet(utils.YoloV3Flag.Name):
   296  		log.Info("Starting Geth on YOLOv3 testnet...")
   297  
   298  	case ctx.GlobalIsSet(utils.DeveloperFlag.Name):
   299  		log.Info("Starting Geth in ephemeral dev mode...")
   300  
   301  	case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name):
   302  		log.Info("Starting Geth on Ethereum mainnet...")
   303  	}
   304  	// If we're a full node on mainnet without --cache specified, bump default cache allowance
   305  	if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
   306  		// Make sure we're not on any supported preconfigured testnet either
   307  		if !ctx.GlobalIsSet(utils.RopstenFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
   308  			// Nope, we're really on mainnet. Bump that cache up!
   309  			log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
   310  			ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
   311  		}
   312  	}
   313  	// If we're running a light client on any network, drop the cache to some meaningfully low amount
   314  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
   315  		log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
   316  		ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
   317  	}
   318  
   319  	// Start metrics export if enabled
   320  	utils.SetupMetrics(ctx)
   321  
   322  	// Start system runtime metrics collection
   323  	go metrics.CollectProcessMetrics(3 * time.Second)
   324  }
   325  
   326  // geth is the main entry point into the system if no special subcommand is ran.
   327  // It creates a default node based on the command line arguments and runs it in
   328  // blocking mode, waiting for it to be shut down.
   329  func geth(ctx *cli.Context) error {
   330  	if args := ctx.Args(); len(args) > 0 {
   331  		return fmt.Errorf("invalid command: %q", args[0])
   332  	}
   333  
   334  	prepare(ctx)
   335  	stack, backend := makeFullNode(ctx)
   336  	defer stack.Close()
   337  
   338  	startNode(ctx, stack, backend)
   339  	stack.Wait()
   340  	return nil
   341  }
   342  
   343  // startNode boots up the system node and all registered protocols, after which
   344  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   345  // miner.
   346  func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend) {
   347  	debug.Memsize.Add("node", stack)
   348  
   349  	// Start up the node itself
   350  	utils.StartNode(ctx, stack)
   351  
   352  	// Unlock any account specifically requested
   353  	unlockAccounts(ctx, stack)
   354  
   355  	// Register wallet event handlers to open and auto-derive wallets
   356  	events := make(chan accounts.WalletEvent, 16)
   357  	stack.AccountManager().Subscribe(events)
   358  
   359  	// Create a client to interact with local geth node.
   360  	rpcClient, err := stack.Attach()
   361  	if err != nil {
   362  		utils.Fatalf("Failed to attach to self: %v", err)
   363  	}
   364  	ethClient := ethclient.NewClient(rpcClient)
   365  
   366  	go func() {
   367  		// Open any wallets already attached
   368  		for _, wallet := range stack.AccountManager().Wallets() {
   369  			if err := wallet.Open(""); err != nil {
   370  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   371  			}
   372  		}
   373  		// Listen for wallet event till termination
   374  		for event := range events {
   375  			switch event.Kind {
   376  			case accounts.WalletArrived:
   377  				if err := event.Wallet.Open(""); err != nil {
   378  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   379  				}
   380  			case accounts.WalletOpened:
   381  				status, _ := event.Wallet.Status()
   382  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   383  
   384  				var derivationPaths []accounts.DerivationPath
   385  				if event.Wallet.URL().Scheme == "ledger" {
   386  					derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
   387  				}
   388  				derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
   389  
   390  				event.Wallet.SelfDerive(derivationPaths, ethClient)
   391  
   392  			case accounts.WalletDropped:
   393  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   394  				event.Wallet.Close()
   395  			}
   396  		}
   397  	}()
   398  
   399  	// Spawn a standalone goroutine for status synchronization monitoring,
   400  	// close the node when synchronization is complete if user required.
   401  	if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
   402  		go func() {
   403  			sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
   404  			defer sub.Unsubscribe()
   405  			for {
   406  				event := <-sub.Chan()
   407  				if event == nil {
   408  					continue
   409  				}
   410  				done, ok := event.Data.(downloader.DoneEvent)
   411  				if !ok {
   412  					continue
   413  				}
   414  				if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
   415  					log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
   416  						"age", common.PrettyAge(timestamp))
   417  					stack.Close()
   418  				}
   419  			}
   420  		}()
   421  	}
   422  
   423  	// Start auxiliary services if enabled
   424  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   425  		// Mining only makes sense if a full Ethereum node is running
   426  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   427  			utils.Fatalf("Light clients do not support mining")
   428  		}
   429  		ethBackend, ok := backend.(*eth.EthAPIBackend)
   430  		if !ok {
   431  			utils.Fatalf("Ethereum service not running: %v", err)
   432  		}
   433  		// Set the gas price to the limits from the CLI and start mining
   434  		gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   435  		ethBackend.TxPool().SetGasPrice(gasprice)
   436  		// start mining
   437  		threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   438  		if err := ethBackend.StartMining(threads); err != nil {
   439  			utils.Fatalf("Failed to start mining: %v", err)
   440  		}
   441  	}
   442  }
   443  
   444  // unlockAccounts unlocks any account specifically requested.
   445  func unlockAccounts(ctx *cli.Context, stack *node.Node) {
   446  	var unlocks []string
   447  	inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   448  	for _, input := range inputs {
   449  		if trimmed := strings.TrimSpace(input); trimmed != "" {
   450  			unlocks = append(unlocks, trimmed)
   451  		}
   452  	}
   453  	// Short circuit if there is no account to unlock.
   454  	if len(unlocks) == 0 {
   455  		return
   456  	}
   457  	// If insecure account unlocking is not allowed if node's APIs are exposed to external.
   458  	// Print warning log to user and skip unlocking.
   459  	if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
   460  		utils.Fatalf("Account unlock with HTTP access is forbidden!")
   461  	}
   462  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   463  	passwords := utils.MakePasswordList(ctx)
   464  	for i, account := range unlocks {
   465  		unlockAccount(ks, account, i, passwords)
   466  	}
   467  }