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