gitee.com/moran666666/go-ubiq@v3.0.1+incompatible/cmd/gubiq/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  // gubiq 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/ubiq/go-ubiq/accounts"
    32  	"github.com/ubiq/go-ubiq/accounts/keystore"
    33  	"github.com/ubiq/go-ubiq/cmd/utils"
    34  	"github.com/ubiq/go-ubiq/console"
    35  	"github.com/ubiq/go-ubiq/eth"
    36  	"github.com/ubiq/go-ubiq/ethclient"
    37  	"github.com/ubiq/go-ubiq/internal/debug"
    38  	// "github.com/ubiq/go-ubiq/internal/openrpc"
    39  	"github.com/ubiq/go-ubiq/log"
    40  	"github.com/ubiq/go-ubiq/metrics"
    41  	"github.com/ubiq/go-ubiq/node"
    42  	// "github.com/ubiq/go-ubiq/rpc"
    43  	cli "gopkg.in/urfave/cli.v1"
    44  )
    45  
    46  const (
    47  	clientIdentifier = "gubiq" // Client identifier to advertise over the network
    48  )
    49  
    50  var (
    51  	// Git SHA1 commit hash of the release (set via linker flags)
    52  	gitCommit = ""
    53  	// The app that holds all commands and flags.
    54  	app = utils.NewApp(gitCommit, "the go-ubiq command line interface")
    55  	// flags that configure the node
    56  	nodeFlags = []cli.Flag{
    57  		utils.IdentityFlag,
    58  		utils.UnlockedAccountFlag,
    59  		utils.PasswordFileFlag,
    60  		utils.BootnodesFlag,
    61  		utils.BootnodesV4Flag,
    62  		utils.BootnodesV5Flag,
    63  		utils.DataDirFlag,
    64  		utils.KeyStoreDirFlag,
    65  		utils.NoUSBFlag,
    66  		utils.DashboardEnabledFlag,
    67  		utils.DashboardAddrFlag,
    68  		utils.DashboardPortFlag,
    69  		utils.DashboardRefreshFlag,
    70  		utils.UbqhashCacheDirFlag,
    71  		utils.UbqhashCachesInMemoryFlag,
    72  		utils.UbqhashCachesOnDiskFlag,
    73  		utils.UbqhashDatasetDirFlag,
    74  		utils.UbqhashDatasetsInMemoryFlag,
    75  		utils.UbqhashDatasetsOnDiskFlag,
    76  		utils.TxPoolLocalsFlag,
    77  		utils.TxPoolNoLocalsFlag,
    78  		utils.TxPoolJournalFlag,
    79  		utils.TxPoolRejournalFlag,
    80  		utils.TxPoolPriceLimitFlag,
    81  		utils.TxPoolPriceBumpFlag,
    82  		utils.TxPoolAccountSlotsFlag,
    83  		utils.TxPoolGlobalSlotsFlag,
    84  		utils.TxPoolAccountQueueFlag,
    85  		utils.TxPoolGlobalQueueFlag,
    86  		utils.TxPoolLifetimeFlag,
    87  		utils.SyncModeFlag,
    88  		utils.GCModeFlag,
    89  		utils.LightServFlag,
    90  		utils.LightPeersFlag,
    91  		utils.LightKDFFlag,
    92  		utils.WhitelistFlag,
    93  		utils.CacheFlag,
    94  		utils.CacheDatabaseFlag,
    95  		utils.CacheTrieFlag,
    96  		utils.CacheGCFlag,
    97  		utils.TrieCacheGenFlag,
    98  		utils.ListenPortFlag,
    99  		utils.MaxPeersFlag,
   100  		utils.MaxPendingPeersFlag,
   101  		utils.MiningEnabledFlag,
   102  		utils.MinerThreadsFlag,
   103  		utils.MinerLegacyThreadsFlag,
   104  		utils.MinerNotifyFlag,
   105  		utils.MinerGasTargetFlag,
   106  		utils.MinerLegacyGasTargetFlag,
   107  		utils.MinerGasLimitFlag,
   108  		utils.MinerGasPriceFlag,
   109  		utils.MinerLegacyGasPriceFlag,
   110  		utils.MinerEtherbaseFlag,
   111  		utils.MinerLegacyEtherbaseFlag,
   112  		utils.MinerExtraDataFlag,
   113  		utils.MinerLegacyExtraDataFlag,
   114  		utils.MinerRecommitIntervalFlag,
   115  		utils.MinerNoVerfiyFlag,
   116  		utils.NATFlag,
   117  		utils.NoDiscoverFlag,
   118  		utils.DiscoveryV5Flag,
   119  		utils.NetrestrictFlag,
   120  		utils.NodeKeyFileFlag,
   121  		utils.NodeKeyHexFlag,
   122  		utils.DeveloperFlag,
   123  		utils.DeveloperPeriodFlag,
   124  		utils.TestnetFlag,
   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 Gubiq
   175  	app.Action = gubiq
   176  	app.HideVersion = true // we have a command to print the version
   177  	app.Copyright = "Copyright 2013-2018 The go-ubiq 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  	// if err := rpc.SetDefaultOpenRPCSchemaRaw(openrpc.OpenRPCSchema); err != nil {
   255  	//	log.Crit("Setting OpenRPC default", "error", err)
   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  // gubiq 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 gubiq(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  	node.Wait()
   276  	return nil
   277  }
   278  
   279  // startNode boots up the system node and all registered protocols, after which
   280  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   281  // miner.
   282  func startNode(ctx *cli.Context, stack *node.Node) {
   283  	debug.Memsize.Add("node", stack)
   284  
   285  	// Start up the node itself
   286  	utils.StartNode(stack)
   287  
   288  	// Unlock any account specifically requested
   289  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   290  
   291  	passwords := utils.MakePasswordList(ctx)
   292  	unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   293  	for i, account := range unlocks {
   294  		if trimmed := strings.TrimSpace(account); trimmed != "" {
   295  			unlockAccount(ctx, ks, trimmed, i, passwords)
   296  		}
   297  	}
   298  	// Register wallet event handlers to open and auto-derive wallets
   299  	events := make(chan accounts.WalletEvent, 16)
   300  	stack.AccountManager().Subscribe(events)
   301  
   302  	go func() {
   303  		// Create a chain state reader for self-derivation
   304  		rpcClient, err := stack.Attach()
   305  		if err != nil {
   306  			utils.Fatalf("Failed to attach to self: %v", err)
   307  		}
   308  		stateReader := ethclient.NewClient(rpcClient)
   309  
   310  		// Open any wallets already attached
   311  		for _, wallet := range stack.AccountManager().Wallets() {
   312  			if err := wallet.Open(""); err != nil {
   313  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   314  			}
   315  		}
   316  		// Listen for wallet event till termination
   317  		for event := range events {
   318  			switch event.Kind {
   319  			case accounts.WalletArrived:
   320  				if err := event.Wallet.Open(""); err != nil {
   321  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   322  				}
   323  			case accounts.WalletOpened:
   324  				status, _ := event.Wallet.Status()
   325  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   326  
   327  				derivationPath := accounts.DefaultBaseDerivationPath
   328  				if event.Wallet.URL().Scheme == "ledger" {
   329  					derivationPath = accounts.DefaultLedgerBaseDerivationPath
   330  				}
   331  				event.Wallet.SelfDerive(derivationPath, stateReader)
   332  
   333  			case accounts.WalletDropped:
   334  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   335  				event.Wallet.Close()
   336  			}
   337  		}
   338  	}()
   339  	// Start auxiliary services if enabled
   340  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   341  		// Mining only makes sense if a full Ethereum node is running
   342  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   343  			utils.Fatalf("Light clients do not support mining")
   344  		}
   345  		var ethereum *eth.Ethereum
   346  		if err := stack.Service(&ethereum); err != nil {
   347  			utils.Fatalf("Ubiq service not running: %v", err)
   348  		}
   349  		// Set the gas price to the limits from the CLI and start mining
   350  		gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
   351  		if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
   352  			gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   353  		}
   354  		ethereum.TxPool().SetGasPrice(gasprice)
   355  
   356  		threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
   357  		if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
   358  			threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   359  		}
   360  		if err := ethereum.StartMining(threads); err != nil {
   361  			utils.Fatalf("Failed to start mining: %v", err)
   362  		}
   363  	}
   364  }