github.com/alexdevranger/node-1.8.27@v0.0.0-20221128213301-aa5841e41d2d/cmd/gdubx/main.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of go-dubxcoin.
     3  //
     4  // go-dubxcoin 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-dubxcoin 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-dubxcoin. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // gdubx 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/alexdevranger/node-1.8.27/accounts"
    32  	"github.com/alexdevranger/node-1.8.27/accounts/keystore"
    33  	"github.com/alexdevranger/node-1.8.27/cmd/utils"
    34  	"github.com/alexdevranger/node-1.8.27/console"
    35  	"github.com/alexdevranger/node-1.8.27/eth"
    36  	"github.com/alexdevranger/node-1.8.27/ethclient"
    37  	"github.com/alexdevranger/node-1.8.27/internal/debug"
    38  	"github.com/alexdevranger/node-1.8.27/log"
    39  	"github.com/alexdevranger/node-1.8.27/metrics"
    40  	"github.com/alexdevranger/node-1.8.27/node"
    41  	cli "gopkg.in/urfave/cli.v1"
    42  )
    43  
    44  const (
    45  	clientIdentifier = "gdubx" // 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-dubxcoin 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.GoerliFlag,
   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  		utils.RPCGlobalGasCap,
   154  	}
   155  
   156  	whisperFlags = []cli.Flag{
   157  		utils.WhisperEnabledFlag,
   158  		utils.WhisperMaxMessageSizeFlag,
   159  		utils.WhisperMinPOWFlag,
   160  		utils.WhisperRestrictConnectionBetweenLightClientsFlag,
   161  	}
   162  
   163  	metricsFlags = []cli.Flag{
   164  		utils.MetricsEnableInfluxDBFlag,
   165  		utils.MetricsInfluxDBEndpointFlag,
   166  		utils.MetricsInfluxDBDatabaseFlag,
   167  		utils.MetricsInfluxDBUsernameFlag,
   168  		utils.MetricsInfluxDBPasswordFlag,
   169  		utils.MetricsInfluxDBTagsFlag,
   170  	}
   171  )
   172  
   173  func init() {
   174  	// Initialize the CLI app and start Gdubx
   175  	app.Action = gdubx
   176  	app.HideVersion = true // we have a command to print the version
   177  	app.Copyright = "Copyright 2013-2018 The go-ethereum Authors"
   178  	app.Commands = []cli.Command{
   179  		// See chaincmd.go:
   180  		initCommand,
   181  		importCommand,
   182  		exportCommand,
   183  		importPreimagesCommand,
   184  		exportPreimagesCommand,
   185  		copydbCommand,
   186  		removedbCommand,
   187  		dumpCommand,
   188  		// See monitorcmd.go:
   189  		monitorCommand,
   190  		// See accountcmd.go:
   191  		accountCommand,
   192  		walletCommand,
   193  		// See consolecmd.go:
   194  		consoleCommand,
   195  		attachCommand,
   196  		javascriptCommand,
   197  		// See misccmd.go:
   198  		makecacheCommand,
   199  		makedagCommand,
   200  		versionCommand,
   201  		bugCommand,
   202  		licenseCommand,
   203  		// See config.go
   204  		dumpConfigCommand,
   205  	}
   206  	sort.Sort(cli.CommandsByName(app.Commands))
   207  
   208  	app.Flags = append(app.Flags, nodeFlags...)
   209  	app.Flags = append(app.Flags, rpcFlags...)
   210  	app.Flags = append(app.Flags, consoleFlags...)
   211  	app.Flags = append(app.Flags, debug.Flags...)
   212  	app.Flags = append(app.Flags, whisperFlags...)
   213  	app.Flags = append(app.Flags, metricsFlags...)
   214  
   215  	app.Before = func(ctx *cli.Context) error {
   216  		logdir := ""
   217  		if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
   218  			logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs")
   219  		}
   220  		if err := debug.Setup(ctx, logdir); err != nil {
   221  			return err
   222  		}
   223  		// Cap the cache allowance and tune the garbage collector
   224  		var mem gosigar.Mem
   225  		if err := mem.Get(); err == nil {
   226  			allowance := int(mem.Total / 1024 / 1024 / 3)
   227  			if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
   228  				log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
   229  				ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
   230  			}
   231  		}
   232  		// Ensure Go's GC ignores the database cache for trigger percentage
   233  		cache := ctx.GlobalInt(utils.CacheFlag.Name)
   234  		gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
   235  
   236  		log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
   237  		godebug.SetGCPercent(int(gogc))
   238  
   239  		// Start metrics export if enabled
   240  		utils.SetupMetrics(ctx)
   241  
   242  		// Start system runtime metrics collection
   243  		go metrics.CollectProcessMetrics(3 * time.Second)
   244  
   245  		return nil
   246  	}
   247  
   248  	app.After = func(ctx *cli.Context) error {
   249  		debug.Exit()
   250  		console.Stdin.Close() // Resets terminal mode.
   251  		return nil
   252  	}
   253  }
   254  
   255  func main() {
   256  	if err := app.Run(os.Args); err != nil {
   257  		fmt.Fprintln(os.Stderr, err)
   258  		os.Exit(1)
   259  	}
   260  }
   261  
   262  // gdubx is the main entry point into the system if no special subcommand is ran.
   263  // It creates a default node based on the command line arguments and runs it in
   264  // blocking mode, waiting for it to be shut down.
   265  func gdubx(ctx *cli.Context) error {
   266  	if args := ctx.Args(); len(args) > 0 {
   267  		return fmt.Errorf("invalid command: %q", args[0])
   268  	}
   269  	node := makeFullNode(ctx)
   270  	startNode(ctx, node)
   271  	node.Wait()
   272  	return nil
   273  }
   274  
   275  // startNode boots up the system node and all registered protocols, after which
   276  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   277  // miner.
   278  func startNode(ctx *cli.Context, stack *node.Node) {
   279  	debug.Memsize.Add("node", stack)
   280  
   281  	// Start up the node itself
   282  	utils.StartNode(stack)
   283  
   284  	// Unlock any account specifically requested
   285  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   286  
   287  	passwords := utils.MakePasswordList(ctx)
   288  	unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   289  	for i, account := range unlocks {
   290  		if trimmed := strings.TrimSpace(account); trimmed != "" {
   291  			unlockAccount(ctx, ks, trimmed, i, passwords)
   292  		}
   293  	}
   294  	// Register wallet event handlers to open and auto-derive wallets
   295  	events := make(chan accounts.WalletEvent, 16)
   296  	stack.AccountManager().Subscribe(events)
   297  
   298  	go func() {
   299  		// Create a chain state reader for self-derivation
   300  		rpcClient, err := stack.Attach()
   301  		if err != nil {
   302  			utils.Fatalf("Failed to attach to self: %v", err)
   303  		}
   304  		stateReader := ethclient.NewClient(rpcClient)
   305  
   306  		// Open any wallets already attached
   307  		for _, wallet := range stack.AccountManager().Wallets() {
   308  			if err := wallet.Open(""); err != nil {
   309  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   310  			}
   311  		}
   312  		// Listen for wallet event till termination
   313  		for event := range events {
   314  			switch event.Kind {
   315  			case accounts.WalletArrived:
   316  				if err := event.Wallet.Open(""); err != nil {
   317  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   318  				}
   319  			case accounts.WalletOpened:
   320  				status, _ := event.Wallet.Status()
   321  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   322  
   323  				derivationPath := accounts.DefaultBaseDerivationPath
   324  				if event.Wallet.URL().Scheme == "ledger" {
   325  					derivationPath = accounts.DefaultLedgerBaseDerivationPath
   326  				}
   327  				event.Wallet.SelfDerive(derivationPath, stateReader)
   328  
   329  			case accounts.WalletDropped:
   330  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   331  				event.Wallet.Close()
   332  			}
   333  		}
   334  	}()
   335  	// Start auxiliary services if enabled
   336  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   337  		// Mining only makes sense if a full Ethereum node is running
   338  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   339  			utils.Fatalf("Light clients do not support mining")
   340  		}
   341  		var ethereum *eth.Ethereum
   342  		if err := stack.Service(&ethereum); err != nil {
   343  			utils.Fatalf("Ethereum service not running: %v", err)
   344  		}
   345  		// Set the gas price to the limits from the CLI and start mining
   346  		gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
   347  		if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
   348  			gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   349  		}
   350  		ethereum.TxPool().SetGasPrice(gasprice)
   351  
   352  		threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
   353  		if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
   354  			threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   355  		}
   356  		if err := ethereum.StartMining(threads); err != nil {
   357  			utils.Fatalf("Failed to start mining: %v", err)
   358  		}
   359  	}
   360  }