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