github.com/zjj1991/quorum@v0.0.0-20190524123704-ae4b0a1e1a19/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  	godebug "runtime/debug"
    25  	"sort"
    26  	"strconv"
    27  	"strings"
    28  	"time"
    29  
    30  	"github.com/elastic/gosigar"
    31  	"github.com/ethereum/go-ethereum/accounts"
    32  	"github.com/ethereum/go-ethereum/accounts/keystore"
    33  	"github.com/ethereum/go-ethereum/cmd/utils"
    34  	"github.com/ethereum/go-ethereum/console"
    35  	"github.com/ethereum/go-ethereum/eth"
    36  	"github.com/ethereum/go-ethereum/ethclient"
    37  	"github.com/ethereum/go-ethereum/internal/debug"
    38  	"github.com/ethereum/go-ethereum/log"
    39  	"github.com/ethereum/go-ethereum/metrics"
    40  	"github.com/ethereum/go-ethereum/node"
    41  	"gopkg.in/urfave/cli.v1"
    42  )
    43  
    44  const (
    45  	clientIdentifier = "geth" // Client identifier to advertise over the network
    46  )
    47  
    48  var (
    49  	// Git SHA1 commit hash of the release (set via linker flags)
    50  	gitCommit = ""
    51  	// The app that holds all commands and flags.
    52  	app = utils.NewApp(gitCommit, "the go-ethereum command line interface")
    53  	// flags that configure the node
    54  	nodeFlags = []cli.Flag{
    55  		utils.IdentityFlag,
    56  		utils.UnlockedAccountFlag,
    57  		utils.PasswordFileFlag,
    58  		utils.BootnodesFlag,
    59  		utils.BootnodesV4Flag,
    60  		utils.BootnodesV5Flag,
    61  		utils.DataDirFlag,
    62  		utils.KeyStoreDirFlag,
    63  		utils.NoUSBFlag,
    64  		utils.DashboardEnabledFlag,
    65  		utils.DashboardAddrFlag,
    66  		utils.DashboardPortFlag,
    67  		utils.DashboardRefreshFlag,
    68  		utils.EthashCacheDirFlag,
    69  		utils.EthashCachesInMemoryFlag,
    70  		utils.EthashCachesOnDiskFlag,
    71  		utils.EthashDatasetDirFlag,
    72  		utils.EthashDatasetsInMemoryFlag,
    73  		utils.EthashDatasetsOnDiskFlag,
    74  		utils.TxPoolLocalsFlag,
    75  		utils.TxPoolNoLocalsFlag,
    76  		utils.TxPoolJournalFlag,
    77  		utils.TxPoolRejournalFlag,
    78  		utils.TxPoolPriceLimitFlag,
    79  		utils.TxPoolPriceBumpFlag,
    80  		utils.TxPoolAccountSlotsFlag,
    81  		utils.TxPoolGlobalSlotsFlag,
    82  		utils.TxPoolAccountQueueFlag,
    83  		utils.TxPoolGlobalQueueFlag,
    84  		utils.TxPoolLifetimeFlag,
    85  		utils.SyncModeFlag,
    86  		utils.GCModeFlag,
    87  		utils.LightServFlag,
    88  		utils.LightPeersFlag,
    89  		utils.LightKDFFlag,
    90  		utils.CacheFlag,
    91  		utils.CacheDatabaseFlag,
    92  		utils.CacheGCFlag,
    93  		utils.TrieCacheGenFlag,
    94  		utils.ListenPortFlag,
    95  		utils.MaxPeersFlag,
    96  		utils.MaxPendingPeersFlag,
    97  		utils.MiningEnabledFlag,
    98  		utils.MinerThreadsFlag,
    99  		utils.MinerLegacyThreadsFlag,
   100  		utils.MinerNotifyFlag,
   101  		utils.MinerGasTargetFlag,
   102  		utils.MinerLegacyGasTargetFlag,
   103  		utils.MinerGasLimitFlag,
   104  		utils.MinerGasPriceFlag,
   105  		utils.MinerLegacyGasPriceFlag,
   106  		utils.MinerEtherbaseFlag,
   107  		utils.MinerLegacyEtherbaseFlag,
   108  		utils.MinerExtraDataFlag,
   109  		utils.MinerLegacyExtraDataFlag,
   110  		utils.MinerRecommitIntervalFlag,
   111  		utils.MinerNoVerfiyFlag,
   112  		utils.NATFlag,
   113  		utils.NoDiscoverFlag,
   114  		utils.DiscoveryV5Flag,
   115  		utils.NetrestrictFlag,
   116  		utils.NodeKeyFileFlag,
   117  		utils.NodeKeyHexFlag,
   118  		utils.DeveloperFlag,
   119  		utils.DeveloperPeriodFlag,
   120  		utils.TestnetFlag,
   121  		utils.RinkebyFlag,
   122  		utils.OttomanFlag,
   123  		utils.VMEnableDebugFlag,
   124  		utils.NetworkIdFlag,
   125  		utils.RPCCORSDomainFlag,
   126  		utils.RPCVirtualHostsFlag,
   127  		utils.EthStatsURLFlag,
   128  		utils.MetricsEnabledFlag,
   129  		utils.FakePoWFlag,
   130  		utils.NoCompactionFlag,
   131  		utils.GpoBlocksFlag,
   132  		utils.GpoPercentileFlag,
   133  		utils.EWASMInterpreterFlag,
   134  		utils.EVMInterpreterFlag,
   135  		configFileFlag,
   136  		utils.EnableNodePermissionFlag,
   137  		utils.RaftModeFlag,
   138  		utils.RaftBlockTimeFlag,
   139  		utils.RaftJoinExistingFlag,
   140  		utils.RaftPortFlag,
   141  		utils.EmitCheckpointsFlag,
   142  		utils.IstanbulRequestTimeoutFlag,
   143  		utils.IstanbulBlockPeriodFlag,
   144  	}
   145  
   146  	rpcFlags = []cli.Flag{
   147  		utils.RPCEnabledFlag,
   148  		utils.RPCListenAddrFlag,
   149  		utils.RPCPortFlag,
   150  		utils.RPCApiFlag,
   151  		utils.WSEnabledFlag,
   152  		utils.WSListenAddrFlag,
   153  		utils.WSPortFlag,
   154  		utils.WSApiFlag,
   155  		utils.WSAllowedOriginsFlag,
   156  		utils.IPCDisabledFlag,
   157  		utils.IPCPathFlag,
   158  	}
   159  
   160  	whisperFlags = []cli.Flag{
   161  		utils.WhisperEnabledFlag,
   162  		utils.WhisperMaxMessageSizeFlag,
   163  		utils.WhisperMinPOWFlag,
   164  		utils.WhisperRestrictConnectionBetweenLightClientsFlag,
   165  	}
   166  
   167  	metricsFlags = []cli.Flag{
   168  		utils.MetricsEnableInfluxDBFlag,
   169  		utils.MetricsInfluxDBEndpointFlag,
   170  		utils.MetricsInfluxDBDatabaseFlag,
   171  		utils.MetricsInfluxDBUsernameFlag,
   172  		utils.MetricsInfluxDBPasswordFlag,
   173  		utils.MetricsInfluxDBHostTagFlag,
   174  	}
   175  )
   176  
   177  func init() {
   178  	// Initialize the CLI app and start Geth
   179  	app.Action = geth
   180  	app.HideVersion = true // we have a command to print the version
   181  	app.Copyright = "Copyright 2013-2018 The go-ethereum Authors"
   182  	app.Commands = []cli.Command{
   183  		// See chaincmd.go:
   184  		initCommand,
   185  		importCommand,
   186  		exportCommand,
   187  		importPreimagesCommand,
   188  		exportPreimagesCommand,
   189  		copydbCommand,
   190  		removedbCommand,
   191  		dumpCommand,
   192  		// See monitorcmd.go:
   193  		monitorCommand,
   194  		// See accountcmd.go:
   195  		accountCommand,
   196  		walletCommand,
   197  		// See consolecmd.go:
   198  		consoleCommand,
   199  		attachCommand,
   200  		javascriptCommand,
   201  		// See misccmd.go:
   202  		makecacheCommand,
   203  		makedagCommand,
   204  		versionCommand,
   205  		bugCommand,
   206  		licenseCommand,
   207  		// See config.go
   208  		dumpConfigCommand,
   209  	}
   210  	sort.Sort(cli.CommandsByName(app.Commands))
   211  
   212  	app.Flags = append(app.Flags, nodeFlags...)
   213  	app.Flags = append(app.Flags, rpcFlags...)
   214  	app.Flags = append(app.Flags, consoleFlags...)
   215  	app.Flags = append(app.Flags, debug.Flags...)
   216  	app.Flags = append(app.Flags, whisperFlags...)
   217  	app.Flags = append(app.Flags, metricsFlags...)
   218  
   219  	app.Before = func(ctx *cli.Context) error {
   220  		logdir := ""
   221  		if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
   222  			logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs")
   223  		}
   224  		if err := debug.Setup(ctx, logdir); err != nil {
   225  			return err
   226  		}
   227  		// Cap the cache allowance and tune the garbage collector
   228  		var mem gosigar.Mem
   229  		if err := mem.Get(); err == nil {
   230  			allowance := int(mem.Total / 1024 / 1024 / 3)
   231  			if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
   232  				log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
   233  				ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
   234  			}
   235  		}
   236  		// Ensure Go's GC ignores the database cache for trigger percentage
   237  		cache := ctx.GlobalInt(utils.CacheFlag.Name)
   238  		gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
   239  
   240  		log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
   241  		godebug.SetGCPercent(int(gogc))
   242  
   243  		// Start metrics export if enabled
   244  		utils.SetupMetrics(ctx)
   245  
   246  		// Start system runtime metrics collection
   247  		go metrics.CollectProcessMetrics(3 * time.Second)
   248  
   249  		return nil
   250  	}
   251  
   252  	app.After = func(ctx *cli.Context) error {
   253  		debug.Exit()
   254  		console.Stdin.Close() // Resets terminal mode.
   255  		return nil
   256  	}
   257  }
   258  
   259  func main() {
   260  	if err := app.Run(os.Args); err != nil {
   261  		fmt.Fprintln(os.Stderr, err)
   262  		os.Exit(1)
   263  	}
   264  }
   265  
   266  // geth is the main entry point into the system if no special subcommand is ran.
   267  // It creates a default node based on the command line arguments and runs it in
   268  // blocking mode, waiting for it to be shut down.
   269  func geth(ctx *cli.Context) error {
   270  	if args := ctx.Args(); len(args) > 0 {
   271  		return fmt.Errorf("invalid command: %q", args[0])
   272  	}
   273  	node := makeFullNode(ctx)
   274  	startNode(ctx, node)
   275  
   276  	// Check if a valid consensus is used
   277  	quorumValidateConsensus(node, ctx.GlobalBool(utils.RaftModeFlag.Name))
   278  
   279  	node.Wait()
   280  	return nil
   281  }
   282  
   283  // startNode boots up the system node and all registered protocols, after which
   284  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   285  // miner.
   286  func startNode(ctx *cli.Context, stack *node.Node) {
   287  	log.DoEmitCheckpoints = ctx.GlobalBool(utils.EmitCheckpointsFlag.Name)
   288  	debug.Memsize.Add("node", stack)
   289  
   290  	// Start up the node itself
   291  	utils.StartNode(stack)
   292  
   293  	// Unlock any account specifically requested
   294  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   295  
   296  	passwords := utils.MakePasswordList(ctx)
   297  	unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   298  	for i, account := range unlocks {
   299  		if trimmed := strings.TrimSpace(account); trimmed != "" {
   300  			unlockAccount(ctx, ks, trimmed, i, passwords)
   301  		}
   302  	}
   303  	// Register wallet event handlers to open and auto-derive wallets
   304  	events := make(chan accounts.WalletEvent, 16)
   305  	stack.AccountManager().Subscribe(events)
   306  
   307  	go func() {
   308  		// Create a chain state reader for self-derivation
   309  		rpcClient, err := stack.Attach()
   310  		if err != nil {
   311  			utils.Fatalf("Failed to attach to self: %v", err)
   312  		}
   313  		stateReader := ethclient.NewClient(rpcClient)
   314  
   315  		// Open any wallets already attached
   316  		for _, wallet := range stack.AccountManager().Wallets() {
   317  			if err := wallet.Open(""); err != nil {
   318  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   319  			}
   320  		}
   321  		// Listen for wallet event till termination
   322  		for event := range events {
   323  			switch event.Kind {
   324  			case accounts.WalletArrived:
   325  				if err := event.Wallet.Open(""); err != nil {
   326  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   327  				}
   328  			case accounts.WalletOpened:
   329  				status, _ := event.Wallet.Status()
   330  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   331  
   332  				derivationPath := accounts.DefaultBaseDerivationPath
   333  				if event.Wallet.URL().Scheme == "ledger" {
   334  					derivationPath = accounts.DefaultLedgerBaseDerivationPath
   335  				}
   336  				event.Wallet.SelfDerive(derivationPath, stateReader)
   337  
   338  			case accounts.WalletDropped:
   339  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   340  				event.Wallet.Close()
   341  			}
   342  		}
   343  	}()
   344  	// Start auxiliary services if enabled
   345  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   346  		// Mining only makes sense if a full Ethereum node is running
   347  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   348  			utils.Fatalf("Light clients do not support mining")
   349  		}
   350  		var ethereum *eth.Ethereum
   351  		if err := stack.Service(&ethereum); err != nil {
   352  			utils.Fatalf("Ethereum service not running: %v", err)
   353  		}
   354  		// Set the gas price to the limits from the CLI and start mining
   355  		gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
   356  		if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
   357  			gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   358  		}
   359  		ethereum.TxPool().SetGasPrice(gasprice)
   360  
   361  		threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
   362  		if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
   363  			threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   364  		}
   365  		if err := ethereum.StartMining(threads); err != nil {
   366  			utils.Fatalf("Failed to start mining: %v", err)
   367  		}
   368  	}
   369  }