github.com/JFJun/bsc@v1.0.0/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  	"math"
    23  	"os"
    24  	"runtime"
    25  	godebug "runtime/debug"
    26  	"sort"
    27  	"strconv"
    28  	"strings"
    29  	"time"
    30  
    31  	"github.com/JFJun/bsc/accounts"
    32  	"github.com/JFJun/bsc/accounts/keystore"
    33  	"github.com/JFJun/bsc/cmd/utils"
    34  	"github.com/JFJun/bsc/common"
    35  	"github.com/JFJun/bsc/console"
    36  	"github.com/JFJun/bsc/eth"
    37  	"github.com/JFJun/bsc/eth/downloader"
    38  	"github.com/JFJun/bsc/ethclient"
    39  	"github.com/JFJun/bsc/internal/debug"
    40  	"github.com/JFJun/bsc/les"
    41  	"github.com/JFJun/bsc/log"
    42  	"github.com/JFJun/bsc/metrics"
    43  	"github.com/JFJun/bsc/node"
    44  	"github.com/elastic/gosigar"
    45  	cli "gopkg.in/urfave/cli.v1"
    46  )
    47  
    48  const (
    49  	clientIdentifier = "geth" // Client identifier to advertise over the network
    50  )
    51  
    52  var (
    53  	// Git SHA1 commit hash of the release (set via linker flags)
    54  	gitCommit = ""
    55  	gitDate   = ""
    56  	// The app that holds all commands and flags.
    57  	app = utils.NewApp(gitCommit, gitDate, "the go-ethereum command line interface")
    58  	// flags that configure the node
    59  	nodeFlags = []cli.Flag{
    60  		utils.IdentityFlag,
    61  		utils.UnlockedAccountFlag,
    62  		utils.PasswordFileFlag,
    63  		utils.BootnodesFlag,
    64  		utils.BootnodesV4Flag,
    65  		utils.BootnodesV5Flag,
    66  		utils.DataDirFlag,
    67  		utils.AncientFlag,
    68  		utils.KeyStoreDirFlag,
    69  		utils.ExternalSignerFlag,
    70  		utils.NoUSBFlag,
    71  		utils.SmartCardDaemonPathFlag,
    72  		utils.OverrideIstanbulFlag,
    73  		utils.OverrideMuirGlacierFlag,
    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.LightServeFlag,
    98  		utils.LightLegacyServFlag,
    99  		utils.LightIngressFlag,
   100  		utils.LightEgressFlag,
   101  		utils.LightMaxPeersFlag,
   102  		utils.LightLegacyPeersFlag,
   103  		utils.LightKDFFlag,
   104  		utils.UltraLightServersFlag,
   105  		utils.UltraLightFractionFlag,
   106  		utils.UltraLightOnlyAnnounceFlag,
   107  		utils.WhitelistFlag,
   108  		utils.CacheFlag,
   109  		utils.CacheDatabaseFlag,
   110  		utils.CacheTrieFlag,
   111  		utils.CacheGCFlag,
   112  		utils.CacheSnapshotFlag,
   113  		utils.CacheNoPrefetchFlag,
   114  		utils.ListenPortFlag,
   115  		utils.MaxPeersFlag,
   116  		utils.MaxPendingPeersFlag,
   117  		utils.MiningEnabledFlag,
   118  		utils.MinerThreadsFlag,
   119  		utils.MinerLegacyThreadsFlag,
   120  		utils.MinerNotifyFlag,
   121  		utils.MinerGasTargetFlag,
   122  		utils.MinerLegacyGasTargetFlag,
   123  		utils.MinerGasLimitFlag,
   124  		utils.MinerGasPriceFlag,
   125  		utils.MinerLegacyGasPriceFlag,
   126  		utils.MinerEtherbaseFlag,
   127  		utils.MinerLegacyEtherbaseFlag,
   128  		utils.MinerExtraDataFlag,
   129  		utils.MinerLegacyExtraDataFlag,
   130  		utils.MinerRecommitIntervalFlag,
   131  		utils.MinerNoVerfiyFlag,
   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.LegacyTestnetFlag,
   142  		utils.RopstenFlag,
   143  		utils.RinkebyFlag,
   144  		utils.GoerliFlag,
   145  		utils.VMEnableDebugFlag,
   146  		utils.NetworkIdFlag,
   147  		utils.EthStatsURLFlag,
   148  		utils.FakePoWFlag,
   149  		utils.NoCompactionFlag,
   150  		utils.GpoBlocksFlag,
   151  		utils.GpoPercentileFlag,
   152  		utils.EWASMInterpreterFlag,
   153  		utils.EVMInterpreterFlag,
   154  		configFileFlag,
   155  	}
   156  
   157  	rpcFlags = []cli.Flag{
   158  		utils.RPCEnabledFlag,
   159  		utils.RPCListenAddrFlag,
   160  		utils.RPCPortFlag,
   161  		utils.RPCCORSDomainFlag,
   162  		utils.RPCVirtualHostsFlag,
   163  		utils.GraphQLEnabledFlag,
   164  		utils.GraphQLListenAddrFlag,
   165  		utils.GraphQLPortFlag,
   166  		utils.GraphQLCORSDomainFlag,
   167  		utils.GraphQLVirtualHostsFlag,
   168  		utils.RPCApiFlag,
   169  		utils.WSEnabledFlag,
   170  		utils.WSListenAddrFlag,
   171  		utils.WSPortFlag,
   172  		utils.WSApiFlag,
   173  		utils.WSAllowedOriginsFlag,
   174  		utils.IPCDisabledFlag,
   175  		utils.IPCPathFlag,
   176  		utils.InsecureUnlockAllowedFlag,
   177  		utils.RPCGlobalGasCap,
   178  	}
   179  
   180  	whisperFlags = []cli.Flag{
   181  		utils.WhisperEnabledFlag,
   182  		utils.WhisperMaxMessageSizeFlag,
   183  		utils.WhisperMinPOWFlag,
   184  		utils.WhisperRestrictConnectionBetweenLightClientsFlag,
   185  	}
   186  
   187  	metricsFlags = []cli.Flag{
   188  		utils.MetricsEnabledFlag,
   189  		utils.MetricsEnabledExpensiveFlag,
   190  		utils.MetricsEnableInfluxDBFlag,
   191  		utils.MetricsInfluxDBEndpointFlag,
   192  		utils.MetricsInfluxDBDatabaseFlag,
   193  		utils.MetricsInfluxDBUsernameFlag,
   194  		utils.MetricsInfluxDBPasswordFlag,
   195  		utils.MetricsInfluxDBTagsFlag,
   196  	}
   197  )
   198  
   199  func init() {
   200  	// Initialize the CLI app and start Geth
   201  	app.Action = geth
   202  	app.HideVersion = true // we have a command to print the version
   203  	app.Copyright = "Copyright 2013-2020 The go-ethereum Authors and BSC Authors"
   204  	app.Commands = []cli.Command{
   205  		// See chaincmd.go:
   206  		initCommand,
   207  		initNetworkCommand,
   208  		importCommand,
   209  		exportCommand,
   210  		importPreimagesCommand,
   211  		exportPreimagesCommand,
   212  		copydbCommand,
   213  		removedbCommand,
   214  		dumpCommand,
   215  		dumpGenesisCommand,
   216  		inspectCommand,
   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  		licenseCommand,
   229  		// See config.go
   230  		dumpConfigCommand,
   231  		// See retesteth.go
   232  		retestethCommand,
   233  	}
   234  	sort.Sort(cli.CommandsByName(app.Commands))
   235  
   236  	app.Flags = append(app.Flags, nodeFlags...)
   237  	app.Flags = append(app.Flags, rpcFlags...)
   238  	app.Flags = append(app.Flags, consoleFlags...)
   239  	app.Flags = append(app.Flags, debug.Flags...)
   240  	app.Flags = append(app.Flags, whisperFlags...)
   241  	app.Flags = append(app.Flags, metricsFlags...)
   242  
   243  	app.Before = func(ctx *cli.Context) error {
   244  		return debug.Setup(ctx)
   245  	}
   246  	app.After = func(ctx *cli.Context) error {
   247  		debug.Exit()
   248  		console.Stdin.Close() // Resets terminal mode.
   249  		return nil
   250  	}
   251  }
   252  
   253  func main() {
   254  	if err := app.Run(os.Args); err != nil {
   255  		fmt.Fprintln(os.Stderr, err)
   256  		os.Exit(1)
   257  	}
   258  }
   259  
   260  // prepare manipulates memory cache allowance and setups metric system.
   261  // This function should be called before launching devp2p stack.
   262  func prepare(ctx *cli.Context) {
   263  	// If we're running a known preset, log it for convenience.
   264  	switch {
   265  	case ctx.GlobalIsSet(utils.LegacyTestnetFlag.Name):
   266  		log.Info("Starting Geth on Ropsten testnet...")
   267  		log.Warn("The --testnet flag is ambiguous! Please specify one of --goerli, --rinkeby, or --ropsten.")
   268  		log.Warn("The generic --testnet flag is deprecated and will be removed in the future!")
   269  
   270  	case ctx.GlobalIsSet(utils.RopstenFlag.Name):
   271  		log.Info("Starting Geth on Ropsten testnet...")
   272  
   273  	case ctx.GlobalIsSet(utils.RinkebyFlag.Name):
   274  		log.Info("Starting Geth on Rinkeby testnet...")
   275  
   276  	case ctx.GlobalIsSet(utils.GoerliFlag.Name):
   277  		log.Info("Starting Geth on Görli testnet...")
   278  
   279  	case ctx.GlobalIsSet(utils.DeveloperFlag.Name):
   280  		log.Info("Starting Geth in ephemeral dev mode...")
   281  
   282  	case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name):
   283  		log.Info("Starting Geth on Ethereum mainnet...")
   284  	}
   285  	// If we're a full node on mainnet without --cache specified, bump default cache allowance
   286  	if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
   287  		// Make sure we're not on any supported preconfigured testnet either
   288  		if !ctx.GlobalIsSet(utils.LegacyTestnetFlag.Name) && !ctx.GlobalIsSet(utils.RopstenFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
   289  			// Nope, we're really on mainnet. Bump that cache up!
   290  			log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
   291  			ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
   292  		}
   293  	}
   294  	// If we're running a light client on any network, drop the cache to some meaningfully low amount
   295  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
   296  		log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
   297  		ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
   298  	}
   299  	// Cap the cache allowance and tune the garbage collector
   300  	var mem gosigar.Mem
   301  	// Workaround until OpenBSD support lands into gosigar
   302  	// Check https://github.com/elastic/gosigar#supported-platforms
   303  	if runtime.GOOS != "openbsd" {
   304  		if err := mem.Get(); err == nil {
   305  			allowance := int(mem.Total / 1024 / 1024 / 3)
   306  			if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
   307  				log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
   308  				ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
   309  			}
   310  		}
   311  	}
   312  	// Ensure Go's GC ignores the database cache for trigger percentage
   313  	cache := ctx.GlobalInt(utils.CacheFlag.Name)
   314  	gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
   315  
   316  	log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
   317  	godebug.SetGCPercent(int(gogc))
   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  	prepare(ctx)
   334  	node := makeFullNode(ctx)
   335  	defer node.Close()
   336  	startNode(ctx, node)
   337  	node.Wait()
   338  	return nil
   339  }
   340  
   341  // startNode boots up the system node and all registered protocols, after which
   342  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   343  // miner.
   344  func startNode(ctx *cli.Context, stack *node.Node) {
   345  	debug.Memsize.Add("node", stack)
   346  
   347  	// Start up the node itself
   348  	utils.StartNode(stack)
   349  
   350  	// Unlock any account specifically requested
   351  	unlockAccounts(ctx, stack)
   352  
   353  	// Register wallet event handlers to open and auto-derive wallets
   354  	events := make(chan accounts.WalletEvent, 16)
   355  	stack.AccountManager().Subscribe(events)
   356  
   357  	// Create a client to interact with local geth node.
   358  	rpcClient, err := stack.Attach()
   359  	if err != nil {
   360  		utils.Fatalf("Failed to attach to self: %v", err)
   361  	}
   362  	ethClient := ethclient.NewClient(rpcClient)
   363  
   364  	// Set contract backend for ethereum service if local node
   365  	// is serving LES requests.
   366  	if ctx.GlobalInt(utils.LightLegacyServFlag.Name) > 0 || ctx.GlobalInt(utils.LightServeFlag.Name) > 0 {
   367  		var ethService *eth.Ethereum
   368  		if err := stack.Service(&ethService); err != nil {
   369  			utils.Fatalf("Failed to retrieve ethereum service: %v", err)
   370  		}
   371  		ethService.SetContractBackend(ethClient)
   372  	}
   373  	// Set contract backend for les service if local node is
   374  	// running as a light client.
   375  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   376  		var lesService *les.LightEthereum
   377  		if err := stack.Service(&lesService); err != nil {
   378  			utils.Fatalf("Failed to retrieve light ethereum service: %v", err)
   379  		}
   380  		lesService.SetContractBackend(ethClient)
   381  	}
   382  
   383  	go func() {
   384  		// Open any wallets already attached
   385  		for _, wallet := range stack.AccountManager().Wallets() {
   386  			if err := wallet.Open(""); err != nil {
   387  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   388  			}
   389  		}
   390  		// Listen for wallet event till termination
   391  		for event := range events {
   392  			switch event.Kind {
   393  			case accounts.WalletArrived:
   394  				if err := event.Wallet.Open(""); err != nil {
   395  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   396  				}
   397  			case accounts.WalletOpened:
   398  				status, _ := event.Wallet.Status()
   399  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   400  
   401  				var derivationPaths []accounts.DerivationPath
   402  				if event.Wallet.URL().Scheme == "ledger" {
   403  					derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
   404  				}
   405  				derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
   406  
   407  				event.Wallet.SelfDerive(derivationPaths, ethClient)
   408  
   409  			case accounts.WalletDropped:
   410  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   411  				event.Wallet.Close()
   412  			}
   413  		}
   414  	}()
   415  
   416  	// Spawn a standalone goroutine for status synchronization monitoring,
   417  	// close the node when synchronization is complete if user required.
   418  	if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
   419  		go func() {
   420  			sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
   421  			defer sub.Unsubscribe()
   422  			for {
   423  				event := <-sub.Chan()
   424  				if event == nil {
   425  					continue
   426  				}
   427  				done, ok := event.Data.(downloader.DoneEvent)
   428  				if !ok {
   429  					continue
   430  				}
   431  				if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
   432  					log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
   433  						"age", common.PrettyAge(timestamp))
   434  					stack.Stop()
   435  				}
   436  			}
   437  		}()
   438  	}
   439  
   440  	// Start auxiliary services if enabled
   441  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   442  		// Mining only makes sense if a full Ethereum node is running
   443  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   444  			utils.Fatalf("Light clients do not support mining")
   445  		}
   446  		var ethereum *eth.Ethereum
   447  		if err := stack.Service(&ethereum); err != nil {
   448  			utils.Fatalf("Ethereum service not running: %v", err)
   449  		}
   450  		// Set the gas price to the limits from the CLI and start mining
   451  		gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
   452  		if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
   453  			gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   454  		}
   455  		ethereum.TxPool().SetGasPrice(gasprice)
   456  
   457  		threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
   458  		if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
   459  			threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   460  		}
   461  		if err := ethereum.StartMining(threads); err != nil {
   462  			utils.Fatalf("Failed to start mining: %v", err)
   463  		}
   464  	}
   465  }
   466  
   467  // unlockAccounts unlocks any account specifically requested.
   468  func unlockAccounts(ctx *cli.Context, stack *node.Node) {
   469  	var unlocks []string
   470  	inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   471  	for _, input := range inputs {
   472  		if trimmed := strings.TrimSpace(input); trimmed != "" {
   473  			unlocks = append(unlocks, trimmed)
   474  		}
   475  	}
   476  	// Short circuit if there is no account to unlock.
   477  	if len(unlocks) == 0 {
   478  		return
   479  	}
   480  	// If insecure account unlocking is not allowed if node's APIs are exposed to external.
   481  	// Print warning log to user and skip unlocking.
   482  	if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
   483  		utils.Fatalf("Account unlock with HTTP access is forbidden!")
   484  	}
   485  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   486  	passwords := utils.MakePasswordList(ctx)
   487  	for i, account := range unlocks {
   488  		unlockAccount(ks, account, i, passwords)
   489  	}
   490  }