github.com/insight-chain/inb-go@v1.1.3-0.20191221022159-da049980ae38/cmd/ginb/main.go (about)

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