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