github.com/notegio/go-ethereum@v1.9.5-4/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/elastic/gosigar"
    32  	"github.com/ethereum/go-ethereum/accounts"
    33  	"github.com/ethereum/go-ethereum/accounts/keystore"
    34  	"github.com/ethereum/go-ethereum/cmd/utils"
    35  	"github.com/ethereum/go-ethereum/common"
    36  	"github.com/ethereum/go-ethereum/console"
    37  	"github.com/ethereum/go-ethereum/eth"
    38  	"github.com/ethereum/go-ethereum/eth/downloader"
    39  	"github.com/ethereum/go-ethereum/ethclient"
    40  	"github.com/ethereum/go-ethereum/internal/debug"
    41  	"github.com/ethereum/go-ethereum/les"
    42  	"github.com/ethereum/go-ethereum/log"
    43  	"github.com/ethereum/go-ethereum/metrics"
    44  	"github.com/ethereum/go-ethereum/node"
    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.OverlayFlag,
    68  		utils.AncientFlag,
    69  		utils.KeyStoreDirFlag,
    70  		utils.ExternalSignerFlag,
    71  		utils.NoUSBFlag,
    72  		utils.SmartCardDaemonPathFlag,
    73  		utils.OverrideIstanbulFlag,
    74  		utils.DashboardEnabledFlag,
    75  		utils.DashboardAddrFlag,
    76  		utils.DashboardPortFlag,
    77  		utils.DashboardRefreshFlag,
    78  		utils.EthashCacheDirFlag,
    79  		utils.EthashCachesInMemoryFlag,
    80  		utils.EthashCachesOnDiskFlag,
    81  		utils.EthashDatasetDirFlag,
    82  		utils.EthashDatasetsInMemoryFlag,
    83  		utils.EthashDatasetsOnDiskFlag,
    84  		utils.TxPoolLocalsFlag,
    85  		utils.TxPoolNoLocalsFlag,
    86  		utils.TxPoolJournalFlag,
    87  		utils.TxPoolRejournalFlag,
    88  		utils.TxPoolPriceLimitFlag,
    89  		utils.TxPoolPriceBumpFlag,
    90  		utils.TxPoolAccountSlotsFlag,
    91  		utils.TxPoolGlobalSlotsFlag,
    92  		utils.TxPoolAccountQueueFlag,
    93  		utils.TxPoolGlobalQueueFlag,
    94  		utils.TxPoolLifetimeFlag,
    95  		utils.SyncModeFlag,
    96  		utils.ExitWhenSyncedFlag,
    97  		utils.GCModeFlag,
    98  		utils.LightServeFlag,
    99  		utils.LightLegacyServFlag,
   100  		utils.LightIngressFlag,
   101  		utils.LightEgressFlag,
   102  		utils.LightMaxPeersFlag,
   103  		utils.LightLegacyPeersFlag,
   104  		utils.LightKDFFlag,
   105  		utils.UltraLightServersFlag,
   106  		utils.UltraLightFractionFlag,
   107  		utils.UltraLightOnlyAnnounceFlag,
   108  		utils.WhitelistFlag,
   109  		utils.CacheFlag,
   110  		utils.CacheDatabaseFlag,
   111  		utils.CacheTrieFlag,
   112  		utils.CacheGCFlag,
   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.DeveloperFlag,
   139  		utils.DeveloperPeriodFlag,
   140  		utils.TestnetFlag,
   141  		utils.RinkebyFlag,
   142  		utils.GoerliFlag,
   143  		utils.VMEnableDebugFlag,
   144  		utils.NetworkIdFlag,
   145  		utils.EthStatsURLFlag,
   146  		utils.FakePoWFlag,
   147  		utils.NoCompactionFlag,
   148  		utils.GpoBlocksFlag,
   149  		utils.GpoPercentileFlag,
   150  		utils.EWASMInterpreterFlag,
   151  		utils.EVMInterpreterFlag,
   152  		configFileFlag,
   153  		utils.KafkaLogBrokerFlag,
   154  		utils.KafkaLogTopicFlag,
   155  		utils.KafkaTransactionTopicFlag,
   156  		utils.KafkaTransactionConsumerGroupFlag,
   157  		utils.ReplicaSyncShutdownFlag,
   158  		utils.ReplicaStartupMaxAgeFlag,
   159  		utils.ReplicaRuntimeMaxOffsetAgeFlag,
   160  		utils.ReplicaRuntimeMaxBlockAgeFlag,
   161  		utils.ReplicaEVMConcurrencyFlag,
   162  		utils.ReplicaWarmAddressesFlag,
   163  	}
   164  
   165  	rpcFlags = []cli.Flag{
   166  		utils.RPCEnabledFlag,
   167  		utils.RPCListenAddrFlag,
   168  		utils.RPCPortFlag,
   169  		utils.RPCCORSDomainFlag,
   170  		utils.RPCVirtualHostsFlag,
   171  		utils.GraphQLEnabledFlag,
   172  		utils.GraphQLListenAddrFlag,
   173  		utils.GraphQLPortFlag,
   174  		utils.GraphQLCORSDomainFlag,
   175  		utils.GraphQLVirtualHostsFlag,
   176  		utils.RPCApiFlag,
   177  		utils.WSEnabledFlag,
   178  		utils.WSListenAddrFlag,
   179  		utils.WSPortFlag,
   180  		utils.WSApiFlag,
   181  		utils.WSAllowedOriginsFlag,
   182  		utils.IPCDisabledFlag,
   183  		utils.IPCPathFlag,
   184  		utils.InsecureUnlockAllowedFlag,
   185  		utils.RPCGlobalGasCap,
   186  	}
   187  
   188  	whisperFlags = []cli.Flag{
   189  		utils.WhisperEnabledFlag,
   190  		utils.WhisperMaxMessageSizeFlag,
   191  		utils.WhisperMinPOWFlag,
   192  		utils.WhisperRestrictConnectionBetweenLightClientsFlag,
   193  	}
   194  
   195  	metricsFlags = []cli.Flag{
   196  		utils.MetricsEnabledFlag,
   197  		utils.MetricsEnabledExpensiveFlag,
   198  		utils.MetricsEnableInfluxDBFlag,
   199  		utils.MetricsInfluxDBEndpointFlag,
   200  		utils.MetricsInfluxDBDatabaseFlag,
   201  		utils.MetricsInfluxDBUsernameFlag,
   202  		utils.MetricsInfluxDBPasswordFlag,
   203  		utils.MetricsInfluxDBTagsFlag,
   204  	}
   205  )
   206  
   207  func init() {
   208  	// Initialize the CLI app and start Geth
   209  	app.Action = geth
   210  	app.HideVersion = true // we have a command to print the version
   211  	app.Copyright = "Copyright 2013-2019 The go-ethereum Authors"
   212  	app.Commands = []cli.Command{
   213  		// See chaincmd.go:
   214  		initCommand,
   215  		importCommand,
   216  		exportCommand,
   217  		importPreimagesCommand,
   218  		exportPreimagesCommand,
   219  		copydbCommand,
   220  		removedbCommand,
   221  		dumpCommand,
   222  		inspectCommand,
   223  		setHeadCommand,
   224  		verifyStateTrieCommand,
   225  		compactCommand,
   226  		// See accountcmd.go:
   227  		accountCommand,
   228  		walletCommand,
   229  		// See consolecmd.go:
   230  		consoleCommand,
   231  		attachCommand,
   232  		javascriptCommand,
   233  		// See misccmd.go:
   234  		makecacheCommand,
   235  		makedagCommand,
   236  		versionCommand,
   237  		licenseCommand,
   238  		// See config.go
   239  		dumpConfigCommand,
   240  		// See retesteth.go
   241  		retestethCommand,
   242  		// See replica.go
   243  		replicaCommand,
   244  		// See txrelay.go
   245  		txrelayCommand,
   246  	}
   247  	sort.Sort(cli.CommandsByName(app.Commands))
   248  
   249  	app.Flags = append(app.Flags, nodeFlags...)
   250  	app.Flags = append(app.Flags, rpcFlags...)
   251  	app.Flags = append(app.Flags, consoleFlags...)
   252  	app.Flags = append(app.Flags, debug.Flags...)
   253  	app.Flags = append(app.Flags, whisperFlags...)
   254  	app.Flags = append(app.Flags, metricsFlags...)
   255  
   256  	app.Before = func(ctx *cli.Context) error {
   257  		logdir := ""
   258  		if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
   259  			logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs")
   260  		}
   261  		if err := debug.Setup(ctx, logdir); err != nil {
   262  			return err
   263  		}
   264  		return nil
   265  	}
   266  
   267  	app.After = func(ctx *cli.Context) error {
   268  		debug.Exit()
   269  		console.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 a full node on mainnet without --cache specified, bump default cache allowance
   285  	if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
   286  		// Make sure we're not on any supported preconfigured testnet either
   287  		if !ctx.GlobalIsSet(utils.TestnetFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
   288  			// Nope, we're really on mainnet. Bump that cache up!
   289  			log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
   290  			ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
   291  		}
   292  	}
   293  	// If we're running a light client on any network, drop the cache to some meaningfully low amount
   294  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
   295  		log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
   296  		ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
   297  	}
   298  	// Cap the cache allowance and tune the garbage collector
   299  	var mem gosigar.Mem
   300  	// Workaround until OpenBSD support lands into gosigar
   301  	// Check https://github.com/elastic/gosigar#supported-platforms
   302  	if runtime.GOOS != "openbsd" {
   303  		if err := mem.Get(); err == nil {
   304  			allowance := int(mem.Total / 1024 / 1024 / 3)
   305  			if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
   306  				log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
   307  				ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
   308  			}
   309  		}
   310  	}
   311  	// Ensure Go's GC ignores the database cache for trigger percentage
   312  	cache := ctx.GlobalInt(utils.CacheFlag.Name)
   313  	gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
   314  
   315  	log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
   316  	godebug.SetGCPercent(int(gogc))
   317  
   318  	// Start metrics export if enabled
   319  	utils.SetupMetrics(ctx)
   320  
   321  	// Start system runtime metrics collection
   322  	go metrics.CollectProcessMetrics(3 * time.Second)
   323  }
   324  
   325  // geth is the main entry point into the system if no special subcommand is ran.
   326  // It creates a default node based on the command line arguments and runs it in
   327  // blocking mode, waiting for it to be shut down.
   328  func geth(ctx *cli.Context) error {
   329  	if args := ctx.Args(); len(args) > 0 {
   330  		return fmt.Errorf("invalid command: %q", args[0])
   331  	}
   332  	prepare(ctx)
   333  	node := makeFullNode(ctx)
   334  	defer node.Close()
   335  	startNode(ctx, node)
   336  	node.Wait()
   337  	return nil
   338  }
   339  
   340  // startNode boots up the system node and all registered protocols, after which
   341  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   342  // miner.
   343  func startNode(ctx *cli.Context, stack *node.Node) {
   344  	debug.Memsize.Add("node", stack)
   345  
   346  	// Start up the node itself
   347  	utils.StartNode(stack)
   348  
   349  	// Unlock any account specifically requested
   350  	unlockAccounts(ctx, stack)
   351  
   352  	// Register wallet event handlers to open and auto-derive wallets
   353  	events := make(chan accounts.WalletEvent, 16)
   354  	stack.AccountManager().Subscribe(events)
   355  
   356  	// Create a client to interact with local geth node.
   357  	rpcClient, err := stack.Attach()
   358  	if err != nil {
   359  		utils.Fatalf("Failed to attach to self: %v", err)
   360  	}
   361  	ethClient := ethclient.NewClient(rpcClient)
   362  
   363  	// Set contract backend for ethereum service if local node
   364  	// is serving LES requests.
   365  	if ctx.GlobalInt(utils.LightLegacyServFlag.Name) > 0 || ctx.GlobalInt(utils.LightServeFlag.Name) > 0 {
   366  		var ethService *eth.Ethereum
   367  		if err := stack.Service(&ethService); err != nil {
   368  			utils.Fatalf("Failed to retrieve ethereum service: %v", err)
   369  		}
   370  		ethService.SetContractBackend(ethClient)
   371  	}
   372  	// Set contract backend for les service if local node is
   373  	// running as a light client.
   374  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   375  		var lesService *les.LightEthereum
   376  		if err := stack.Service(&lesService); err != nil {
   377  			utils.Fatalf("Failed to retrieve light ethereum service: %v", err)
   378  		}
   379  		lesService.SetContractBackend(ethClient)
   380  	}
   381  
   382  	go func() {
   383  		// Open any wallets already attached
   384  		for _, wallet := range stack.AccountManager().Wallets() {
   385  			if err := wallet.Open(""); err != nil {
   386  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   387  			}
   388  		}
   389  		// Listen for wallet event till termination
   390  		for event := range events {
   391  			switch event.Kind {
   392  			case accounts.WalletArrived:
   393  				if err := event.Wallet.Open(""); err != nil {
   394  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   395  				}
   396  			case accounts.WalletOpened:
   397  				status, _ := event.Wallet.Status()
   398  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   399  
   400  				var derivationPaths []accounts.DerivationPath
   401  				if event.Wallet.URL().Scheme == "ledger" {
   402  					derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
   403  				}
   404  				derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
   405  
   406  				event.Wallet.SelfDerive(derivationPaths, ethClient)
   407  
   408  			case accounts.WalletDropped:
   409  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   410  				event.Wallet.Close()
   411  			}
   412  		}
   413  	}()
   414  
   415  	// Spawn a standalone goroutine for status synchronization monitoring,
   416  	// close the node when synchronization is complete if user required.
   417  	if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
   418  		go func() {
   419  			sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
   420  			defer sub.Unsubscribe()
   421  			for {
   422  				event := <-sub.Chan()
   423  				if event == nil {
   424  					continue
   425  				}
   426  				done, ok := event.Data.(downloader.DoneEvent)
   427  				if !ok {
   428  					continue
   429  				}
   430  				if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
   431  					log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
   432  						"age", common.PrettyAge(timestamp))
   433  					stack.Stop()
   434  				}
   435  			}
   436  		}()
   437  	}
   438  
   439  	// Start auxiliary services if enabled
   440  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   441  		// Mining only makes sense if a full Ethereum node is running
   442  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   443  			utils.Fatalf("Light clients do not support mining")
   444  		}
   445  		var ethereum *eth.Ethereum
   446  		if err := stack.Service(&ethereum); err != nil {
   447  			utils.Fatalf("Ethereum service not running: %v", err)
   448  		}
   449  		// Set the gas price to the limits from the CLI and start mining
   450  		gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
   451  		if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
   452  			gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   453  		}
   454  		ethereum.TxPool().SetGasPrice(gasprice)
   455  
   456  		threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
   457  		if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
   458  			threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   459  		}
   460  		if err := ethereum.StartMining(threads); err != nil {
   461  			utils.Fatalf("Failed to start mining: %v", err)
   462  		}
   463  	}
   464  }
   465  
   466  // unlockAccounts unlocks any account specifically requested.
   467  func unlockAccounts(ctx *cli.Context, stack *node.Node) {
   468  	var unlocks []string
   469  	inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   470  	for _, input := range inputs {
   471  		if trimmed := strings.TrimSpace(input); trimmed != "" {
   472  			unlocks = append(unlocks, trimmed)
   473  		}
   474  	}
   475  	// Short circuit if there is no account to unlock.
   476  	if len(unlocks) == 0 {
   477  		return
   478  	}
   479  	// If insecure account unlocking is not allowed if node's APIs are exposed to external.
   480  	// Print warning log to user and skip unlocking.
   481  	if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
   482  		utils.Fatalf("Account unlock with HTTP access is forbidden!")
   483  	}
   484  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   485  	passwords := utils.MakePasswordList(ctx)
   486  	for i, account := range unlocks {
   487  		unlockAccount(ks, account, i, passwords)
   488  	}
   489  }