github.com/DxChainNetwork/dxc@v0.8.1-0.20220824085222-1162e304b6e7/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/DxChainNetwork/dxc/accounts"
    29  	"github.com/DxChainNetwork/dxc/accounts/keystore"
    30  	"github.com/DxChainNetwork/dxc/cmd/utils"
    31  	"github.com/DxChainNetwork/dxc/common"
    32  	"github.com/DxChainNetwork/dxc/console/prompt"
    33  	"github.com/DxChainNetwork/dxc/eth"
    34  	"github.com/DxChainNetwork/dxc/eth/downloader"
    35  	"github.com/DxChainNetwork/dxc/ethclient"
    36  	"github.com/DxChainNetwork/dxc/internal/debug"
    37  	"github.com/DxChainNetwork/dxc/internal/ethapi"
    38  	"github.com/DxChainNetwork/dxc/internal/flags"
    39  	"github.com/DxChainNetwork/dxc/log"
    40  	"github.com/DxChainNetwork/dxc/metrics"
    41  	"github.com/DxChainNetwork/dxc/node"
    42  	"gopkg.in/urfave/cli.v1"
    43  )
    44  
    45  const (
    46  	clientIdentifier = "geth" // Client identifier to advertise over the network
    47  )
    48  
    49  var (
    50  	// Git SHA1 commit hash of the release (set via linker flags)
    51  	gitCommit = ""
    52  	gitDate   = ""
    53  	// The app that holds all commands and flags.
    54  	app = flags.NewApp(gitCommit, gitDate, "the go-ethereum command line interface")
    55  	// flags that configure the node
    56  	nodeFlags = []cli.Flag{
    57  		utils.IdentityFlag,
    58  		utils.UnlockedAccountFlag,
    59  		utils.PasswordFileFlag,
    60  		utils.BootnodesFlag,
    61  		utils.DataDirFlag,
    62  		utils.AncientFlag,
    63  		utils.MinFreeDiskSpaceFlag,
    64  		utils.KeyStoreDirFlag,
    65  		utils.ExternalSignerFlag,
    66  		utils.NoUSBFlag,
    67  		utils.USBFlag,
    68  		utils.SmartCardDaemonPathFlag,
    69  		utils.OverrideLondonFlag,
    70  		utils.EthashCacheDirFlag,
    71  		utils.EthashCachesInMemoryFlag,
    72  		utils.EthashCachesOnDiskFlag,
    73  		utils.EthashCachesLockMmapFlag,
    74  		utils.EthashDatasetDirFlag,
    75  		utils.EthashDatasetsInMemoryFlag,
    76  		utils.EthashDatasetsOnDiskFlag,
    77  		utils.EthashDatasetsLockMmapFlag,
    78  		utils.TxPoolLocalsFlag,
    79  		utils.TxPoolNoLocalsFlag,
    80  		utils.TxPoolJournalFlag,
    81  		utils.TxPoolRejournalFlag,
    82  		utils.TxPoolPriceLimitFlag,
    83  		utils.TxPoolPriceBumpFlag,
    84  		utils.TxPoolAccountSlotsFlag,
    85  		utils.TxPoolGlobalSlotsFlag,
    86  		utils.TxPoolAccountQueueFlag,
    87  		utils.TxPoolGlobalQueueFlag,
    88  		utils.TxPoolLifetimeFlag,
    89  		utils.SyncModeFlag,
    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.WhitelistFlag,
   105  		utils.BloomFilterSizeFlag,
   106  		utils.CacheFlag,
   107  		utils.CacheDatabaseFlag,
   108  		utils.CacheTrieFlag,
   109  		utils.CacheTrieJournalFlag,
   110  		utils.CacheTrieRejournalFlag,
   111  		utils.CacheGCFlag,
   112  		utils.CacheSnapshotFlag,
   113  		utils.CacheNoPrefetchFlag,
   114  		utils.CachePreimagesFlag,
   115  		utils.ListenPortFlag,
   116  		utils.MaxPeersFlag,
   117  		utils.MaxPendingPeersFlag,
   118  		utils.MiningEnabledFlag,
   119  		utils.MinerThreadsFlag,
   120  		utils.MinerNotifyFlag,
   121  		utils.LegacyMinerGasTargetFlag,
   122  		utils.MinerGasLimitFlag,
   123  		utils.MinerGasPriceFlag,
   124  		utils.MinerEtherbaseFlag,
   125  		utils.MinerExtraDataFlag,
   126  		utils.MinerRecommitIntervalFlag,
   127  		utils.MinerNoVerfiyFlag,
   128  		utils.NATFlag,
   129  		utils.NoDiscoverFlag,
   130  		utils.DiscoveryV5Flag,
   131  		utils.NetrestrictFlag,
   132  		utils.NodeKeyFileFlag,
   133  		utils.NodeKeyHexFlag,
   134  		utils.DNSDiscoveryFlag,
   135  		utils.MainnetFlag,
   136  		utils.DeveloperFlag,
   137  		utils.DeveloperPeriodFlag,
   138  		utils.TestnetFlag,
   139  		utils.VMEnableDebugFlag,
   140  		utils.NetworkIdFlag,
   141  		utils.EthStatsURLFlag,
   142  		utils.FakePoWFlag,
   143  		utils.NoCompactionFlag,
   144  		utils.GpoBlocksFlag,
   145  		utils.GpoPercentileFlag,
   146  		utils.GpoMaxGasPriceFlag,
   147  		utils.GpoIgnoreGasPriceFlag,
   148  		utils.MinerNotifyFullFlag,
   149  		configFileFlag,
   150  		utils.CatalystFlag,
   151  	}
   152  
   153  	rpcFlags = []cli.Flag{
   154  		utils.HTTPEnabledFlag,
   155  		utils.HTTPListenAddrFlag,
   156  		utils.HTTPPortFlag,
   157  		utils.HTTPCORSDomainFlag,
   158  		utils.HTTPVirtualHostsFlag,
   159  		utils.LegacyRPCEnabledFlag,
   160  		utils.LegacyRPCListenAddrFlag,
   161  		utils.LegacyRPCPortFlag,
   162  		utils.LegacyRPCCORSDomainFlag,
   163  		utils.LegacyRPCVirtualHostsFlag,
   164  		utils.LegacyRPCApiFlag,
   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.RPCGlobalTxFeeCapFlag,
   181  		utils.AllowUnprotectedTxs,
   182  	}
   183  
   184  	metricsFlags = []cli.Flag{
   185  		utils.MetricsEnabledFlag,
   186  		utils.MetricsEnabledExpensiveFlag,
   187  		utils.MetricsHTTPFlag,
   188  		utils.MetricsPortFlag,
   189  		utils.MetricsEnableInfluxDBFlag,
   190  		utils.MetricsInfluxDBEndpointFlag,
   191  		utils.MetricsInfluxDBDatabaseFlag,
   192  		utils.MetricsInfluxDBUsernameFlag,
   193  		utils.MetricsInfluxDBPasswordFlag,
   194  		utils.MetricsInfluxDBTagsFlag,
   195  		utils.MetricsEnableInfluxDBV2Flag,
   196  		utils.MetricsInfluxDBTokenFlag,
   197  		utils.MetricsInfluxDBBucketFlag,
   198  		utils.MetricsInfluxDBOrganizationFlag,
   199  	}
   200  )
   201  
   202  func init() {
   203  	// Initialize the CLI app and start Geth
   204  	app.Action = geth
   205  	app.HideVersion = true // we have a command to print the version
   206  	app.Copyright = "Copyright 2013-2021 The go-ethereum Authors"
   207  	app.Commands = []cli.Command{
   208  		// See chaincmd.go:
   209  		initCommand,
   210  		importCommand,
   211  		exportCommand,
   212  		importPreimagesCommand,
   213  		exportPreimagesCommand,
   214  		removedbCommand,
   215  		dumpCommand,
   216  		dumpGenesisCommand,
   217  		// See accountcmd.go:
   218  		accountCommand,
   219  		walletCommand,
   220  		// See consolecmd.go:
   221  		consoleCommand,
   222  		attachCommand,
   223  		javascriptCommand,
   224  		// See misccmd.go:
   225  		makecacheCommand,
   226  		makedagCommand,
   227  		versionCommand,
   228  		versionCheckCommand,
   229  		licenseCommand,
   230  		// See config.go
   231  		dumpConfigCommand,
   232  		// see dbcmd.go
   233  		dbCommand,
   234  		// See cmd/utils/flags_legacy.go
   235  		utils.ShowDeprecated,
   236  		// See snapshot.go
   237  		snapshotCommand,
   238  	}
   239  	sort.Sort(cli.CommandsByName(app.Commands))
   240  
   241  	app.Flags = append(app.Flags, nodeFlags...)
   242  	app.Flags = append(app.Flags, rpcFlags...)
   243  	app.Flags = append(app.Flags, consoleFlags...)
   244  	app.Flags = append(app.Flags, debug.Flags...)
   245  	app.Flags = append(app.Flags, metricsFlags...)
   246  
   247  	app.Before = func(ctx *cli.Context) error {
   248  		return debug.Setup(ctx)
   249  	}
   250  	app.After = func(ctx *cli.Context) error {
   251  		debug.Exit()
   252  		prompt.Stdin.Close() // Resets terminal mode.
   253  		return nil
   254  	}
   255  }
   256  
   257  func main() {
   258  	if err := app.Run(os.Args); err != nil {
   259  		fmt.Fprintln(os.Stderr, err)
   260  		os.Exit(1)
   261  	}
   262  }
   263  
   264  // prepare manipulates memory cache allowance and setups metric system.
   265  // This function should be called before launching devp2p stack.
   266  func prepare(ctx *cli.Context) {
   267  	// If we're running a known preset, log it for convenience.
   268  	switch {
   269  	case ctx.GlobalIsSet(utils.TestnetFlag.Name):
   270  		log.Info("Starting Geth on testnet...")
   271  	case ctx.GlobalIsSet(utils.DeveloperFlag.Name):
   272  		log.Info("Starting Geth in ephemeral dev mode...")
   273  	case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name):
   274  		log.Info("Starting Geth on Ethereum mainnet...")
   275  	}
   276  	// If we're a full node on mainnet without --cache specified, bump default cache allowance
   277  	if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
   278  		// Make sure we're not on any supported preconfigured testnet either
   279  		if !ctx.GlobalIsSet(utils.TestnetFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
   280  			// Nope, we're really on mainnet. Bump that cache up!
   281  			log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
   282  			ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
   283  		}
   284  	}
   285  	// If we're running a light client on any network, drop the cache to some meaningfully low amount
   286  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
   287  		log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
   288  		ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
   289  	}
   290  
   291  	// Start metrics export if enabled
   292  	utils.SetupMetrics(ctx)
   293  
   294  	// Start system runtime metrics collection
   295  	go metrics.CollectProcessMetrics(3 * time.Second)
   296  }
   297  
   298  // geth is the main entry point into the system if no special subcommand is ran.
   299  // It creates a default node based on the command line arguments and runs it in
   300  // blocking mode, waiting for it to be shut down.
   301  func geth(ctx *cli.Context) error {
   302  	if args := ctx.Args(); len(args) > 0 {
   303  		return fmt.Errorf("invalid command: %q", args[0])
   304  	}
   305  
   306  	prepare(ctx)
   307  	stack, backend := makeFullNode(ctx)
   308  	defer stack.Close()
   309  
   310  	startNode(ctx, stack, backend)
   311  	stack.Wait()
   312  	return nil
   313  }
   314  
   315  // startNode boots up the system node and all registered protocols, after which
   316  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   317  // miner.
   318  func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend) {
   319  	debug.Memsize.Add("node", stack)
   320  
   321  	// Start up the node itself
   322  	utils.StartNode(ctx, stack)
   323  
   324  	// Unlock any account specifically requested
   325  	unlockAccounts(ctx, stack)
   326  
   327  	// Register wallet event handlers to open and auto-derive wallets
   328  	events := make(chan accounts.WalletEvent, 16)
   329  	stack.AccountManager().Subscribe(events)
   330  
   331  	// Create a client to interact with local geth node.
   332  	rpcClient, err := stack.Attach()
   333  	if err != nil {
   334  		utils.Fatalf("Failed to attach to self: %v", err)
   335  	}
   336  	ethClient := ethclient.NewClient(rpcClient)
   337  
   338  	go func() {
   339  		// Open any wallets already attached
   340  		for _, wallet := range stack.AccountManager().Wallets() {
   341  			if err := wallet.Open(""); err != nil {
   342  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   343  			}
   344  		}
   345  		// Listen for wallet event till termination
   346  		for event := range events {
   347  			switch event.Kind {
   348  			case accounts.WalletArrived:
   349  				if err := event.Wallet.Open(""); err != nil {
   350  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   351  				}
   352  			case accounts.WalletOpened:
   353  				status, _ := event.Wallet.Status()
   354  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   355  
   356  				var derivationPaths []accounts.DerivationPath
   357  				if event.Wallet.URL().Scheme == "ledger" {
   358  					derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
   359  				}
   360  				derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
   361  
   362  				event.Wallet.SelfDerive(derivationPaths, ethClient)
   363  
   364  			case accounts.WalletDropped:
   365  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   366  				event.Wallet.Close()
   367  			}
   368  		}
   369  	}()
   370  
   371  	// Spawn a standalone goroutine for status synchronization monitoring,
   372  	// close the node when synchronization is complete if user required.
   373  	if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
   374  		go func() {
   375  			sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
   376  			defer sub.Unsubscribe()
   377  			for {
   378  				event := <-sub.Chan()
   379  				if event == nil {
   380  					continue
   381  				}
   382  				done, ok := event.Data.(downloader.DoneEvent)
   383  				if !ok {
   384  					continue
   385  				}
   386  				if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
   387  					log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
   388  						"age", common.PrettyAge(timestamp))
   389  					stack.Close()
   390  				}
   391  			}
   392  		}()
   393  	}
   394  
   395  	// Start auxiliary services if enabled
   396  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   397  		// Mining only makes sense if a full Ethereum node is running
   398  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   399  			utils.Fatalf("Light clients do not support mining")
   400  		}
   401  		ethBackend, ok := backend.(*eth.EthAPIBackend)
   402  		if !ok {
   403  			utils.Fatalf("Ethereum service not running: %v", err)
   404  		}
   405  		// Set the gas price to the limits from the CLI and start mining
   406  		gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   407  		ethBackend.TxPool().SetGasPrice(gasprice)
   408  		// start mining
   409  		threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   410  		if err := ethBackend.StartMining(threads); err != nil {
   411  			utils.Fatalf("Failed to start mining: %v", err)
   412  		}
   413  	}
   414  }
   415  
   416  // unlockAccounts unlocks any account specifically requested.
   417  func unlockAccounts(ctx *cli.Context, stack *node.Node) {
   418  	var unlocks []string
   419  	inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   420  	for _, input := range inputs {
   421  		if trimmed := strings.TrimSpace(input); trimmed != "" {
   422  			unlocks = append(unlocks, trimmed)
   423  		}
   424  	}
   425  	// Short circuit if there is no account to unlock.
   426  	if len(unlocks) == 0 {
   427  		return
   428  	}
   429  	// If insecure account unlocking is not allowed if node's APIs are exposed to external.
   430  	// Print warning log to user and skip unlocking.
   431  	if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
   432  		utils.Fatalf("Account unlock with HTTP access is forbidden!")
   433  	}
   434  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   435  	passwords := utils.MakePasswordList(ctx)
   436  	for i, account := range unlocks {
   437  		unlockAccount(ks, account, i, passwords)
   438  	}
   439  }