github.com/FUSIONFoundation/efsn@v3.6.2-0.20200916075423-dbb5dd5d2cc7+incompatible/cmd/efsn/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  // efsn 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/FusionFoundation/efsn/accounts"
    32  	"github.com/FusionFoundation/efsn/accounts/keystore"
    33  	"github.com/FusionFoundation/efsn/cmd/utils"
    34  	"github.com/FusionFoundation/efsn/common"
    35  	"github.com/FusionFoundation/efsn/consensus/datong"
    36  	"github.com/FusionFoundation/efsn/console"
    37  	"github.com/FusionFoundation/efsn/eth"
    38  	"github.com/FusionFoundation/efsn/ethclient"
    39  	"github.com/FusionFoundation/efsn/internal/debug"
    40  	"github.com/FusionFoundation/efsn/internal/ethapi"
    41  	"github.com/FusionFoundation/efsn/log"
    42  	"github.com/FusionFoundation/efsn/metrics"
    43  	"github.com/FusionFoundation/efsn/node"
    44  	"github.com/elastic/gosigar"
    45  	"gopkg.in/urfave/cli.v1"
    46  )
    47  
    48  const (
    49  	clientIdentifier = "efsn" // Client identifier to advertise over the network
    50  )
    51  
    52  var (
    53  	// Git SHA1 commit hash of the release (set via linker flags)
    54  	gitCommit = ""
    55  	// The app that holds all commands and flags.
    56  	app = utils.NewApp(gitCommit, "the efsn command line interface")
    57  	// flags that configure the node
    58  	nodeFlags = []cli.Flag{
    59  		utils.IdentityFlag,
    60  		utils.UnlockedAccountFlag,
    61  		utils.PasswordFileFlag,
    62  		utils.BootnodesFlag,
    63  		utils.BootnodesV4Flag,
    64  		utils.BootnodesV5Flag,
    65  		utils.DataDirFlag,
    66  		utils.KeyStoreDirFlag,
    67  		utils.NoUSBFlag,
    68  		utils.DashboardEnabledFlag,
    69  		utils.DashboardAddrFlag,
    70  		utils.DashboardPortFlag,
    71  		utils.DashboardRefreshFlag,
    72  		utils.EthashCacheDirFlag,
    73  		utils.EthashCachesInMemoryFlag,
    74  		utils.EthashCachesOnDiskFlag,
    75  		utils.EthashDatasetDirFlag,
    76  		utils.EthashDatasetsInMemoryFlag,
    77  		utils.EthashDatasetsOnDiskFlag,
    78  		utils.TxPoolLocalsFlag,
    79  		utils.TxPoolNoLocalsFlag,
    80  		utils.TxPoolJournalFlag,
    81  		utils.TxPoolRejournalFlag,
    82  		utils.TxPoolPriceLimitFlag,
    83  		utils.TxPoolPriceBumpFlag,
    84  		utils.TxPoolAccountSlotsFlag,
    85  		utils.TxPoolGlobalSlotsFlag,
    86  		utils.TxPoolAccountQueueFlag,
    87  		utils.TxPoolGlobalQueueFlag,
    88  		utils.TxPoolLifetimeFlag,
    89  		utils.SyncModeFlag,
    90  		utils.GCModeFlag,
    91  		utils.LightServFlag,
    92  		utils.LightPeersFlag,
    93  		utils.LightKDFFlag,
    94  		utils.CacheFlag,
    95  		utils.CacheDatabaseFlag,
    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.AutoBuyTicketsEnabledFlag,
   117  		utils.NATFlag,
   118  		utils.NoDiscoverFlag,
   119  		utils.DiscoveryV5Flag,
   120  		utils.NetrestrictFlag,
   121  		utils.NodeKeyFileFlag,
   122  		utils.NodeKeyHexFlag,
   123  		utils.DeveloperFlag,
   124  		utils.DeveloperPeriodFlag,
   125  		utils.TestnetFlag,
   126  		utils.RinkebyFlag,
   127  		utils.DevnetFlag,
   128  		utils.DevnetAddrFlag,
   129  		utils.VMEnableDebugFlag,
   130  		utils.NetworkIdFlag,
   131  		utils.RPCCORSDomainFlag,
   132  		utils.RPCVirtualHostsFlag,
   133  		utils.EthStatsURLFlag,
   134  		utils.MetricsEnabledFlag,
   135  		utils.FakePoWFlag,
   136  		utils.NoCompactionFlag,
   137  		utils.GpoBlocksFlag,
   138  		utils.GpoPercentileFlag,
   139  		utils.EWASMInterpreterFlag,
   140  		utils.EVMInterpreterFlag,
   141  		utils.ResyncFromHeightFlag,
   142  		utils.CheckPointsFileFlag,
   143  		configFileFlag,
   144  	}
   145  
   146  	rpcFlags = []cli.Flag{
   147  		utils.RPCEnabledFlag,
   148  		utils.RPCListenAddrFlag,
   149  		utils.RPCPortFlag,
   150  		utils.RPCApiFlag,
   151  		utils.WSEnabledFlag,
   152  		utils.WSListenAddrFlag,
   153  		utils.WSPortFlag,
   154  		utils.WSApiFlag,
   155  		utils.WSAllowedOriginsFlag,
   156  		utils.IPCDisabledFlag,
   157  		utils.IPCPathFlag,
   158  	}
   159  
   160  	whisperFlags = []cli.Flag{
   161  		utils.WhisperEnabledFlag,
   162  		utils.WhisperMaxMessageSizeFlag,
   163  		utils.WhisperMinPOWFlag,
   164  		utils.WhisperRestrictConnectionBetweenLightClientsFlag,
   165  	}
   166  
   167  	metricsFlags = []cli.Flag{
   168  		utils.MetricsEnableInfluxDBFlag,
   169  		utils.MetricsInfluxDBEndpointFlag,
   170  		utils.MetricsInfluxDBDatabaseFlag,
   171  		utils.MetricsInfluxDBUsernameFlag,
   172  		utils.MetricsInfluxDBPasswordFlag,
   173  		utils.MetricsInfluxDBHostTagFlag,
   174  	}
   175  )
   176  
   177  func init() {
   178  	// Initialize the CLI app and start Geth
   179  	app.Action = geth
   180  	app.HideVersion = true // we have a command to print the version
   181  	app.Copyright = "Copyright 2017-2020 The efsn Authors"
   182  	app.Commands = []cli.Command{
   183  		// See chaincmd.go:
   184  		initCommand,
   185  		importCommand,
   186  		exportCommand,
   187  		importPreimagesCommand,
   188  		exportPreimagesCommand,
   189  		copydbCommand,
   190  		removedbCommand,
   191  		dumpCommand,
   192  		// See monitorcmd.go:
   193  		monitorCommand,
   194  		// See accountcmd.go:
   195  		accountCommand,
   196  		walletCommand,
   197  		// See consolecmd.go:
   198  		consoleCommand,
   199  		attachCommand,
   200  		javascriptCommand,
   201  		// See misccmd.go:
   202  		makecacheCommand,
   203  		makedagCommand,
   204  		versionCommand,
   205  		bugCommand,
   206  		licenseCommand,
   207  		// See config.go
   208  		dumpConfigCommand,
   209  		// See rawtx.go
   210  		rawTxCommand,
   211  	}
   212  	sort.Sort(cli.CommandsByName(app.Commands))
   213  
   214  	app.Flags = append(app.Flags, nodeFlags...)
   215  	app.Flags = append(app.Flags, rpcFlags...)
   216  	app.Flags = append(app.Flags, consoleFlags...)
   217  	app.Flags = append(app.Flags, debug.Flags...)
   218  	app.Flags = append(app.Flags, whisperFlags...)
   219  	app.Flags = append(app.Flags, metricsFlags...)
   220  
   221  	app.Before = func(ctx *cli.Context) error {
   222  		runtime.GOMAXPROCS(runtime.NumCPU())
   223  
   224  		logdir := ""
   225  		if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
   226  			logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs")
   227  		}
   228  		if err := debug.Setup(ctx, logdir); err != nil {
   229  			return err
   230  		}
   231  		// Cap the cache allowance and tune the garbage collector
   232  		var mem gosigar.Mem
   233  		if err := mem.Get(); err == nil {
   234  			allowance := int(mem.Total / 1024 / 1024 / 3)
   235  			if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
   236  				log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
   237  				ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
   238  			}
   239  		}
   240  		// Ensure Go's GC ignores the database cache for trigger percentage
   241  		cache := ctx.GlobalInt(utils.CacheFlag.Name)
   242  		gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
   243  
   244  		log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
   245  		godebug.SetGCPercent(int(gogc))
   246  
   247  		// Start metrics export if enabled
   248  		utils.SetupMetrics(ctx)
   249  
   250  		// Start system runtime metrics collection
   251  		go metrics.CollectProcessMetrics(3 * time.Second)
   252  
   253  		return nil
   254  	}
   255  
   256  	app.After = func(ctx *cli.Context) error {
   257  		debug.Exit()
   258  		console.Stdin.Close() // Resets terminal mode.
   259  		return nil
   260  	}
   261  }
   262  
   263  func main() {
   264  	if err := app.Run(os.Args); err != nil {
   265  		fmt.Fprintln(os.Stderr, err)
   266  		os.Exit(1)
   267  	}
   268  }
   269  
   270  // efsn is the main entry point into the system if no special subcommand is ran.
   271  // It creates a default node based on the command line arguments and runs it in
   272  // blocking mode, waiting for it to be shut down.
   273  func geth(ctx *cli.Context) error {
   274  	if args := ctx.Args(); len(args) > 0 {
   275  		return fmt.Errorf("invalid command: %q", args[0])
   276  	}
   277  	node := makeFullNode(ctx)
   278  	startNode(ctx, node)
   279  	node.Wait()
   280  	return nil
   281  }
   282  
   283  // startNode boots up the system node and all registered protocols, after which
   284  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   285  // miner.
   286  func startNode(ctx *cli.Context, stack *node.Node) {
   287  	debug.Memsize.Add("node", stack)
   288  
   289  	// add more log and checking in devnet
   290  	if ctx.GlobalBool(utils.DevnetFlag.Name) {
   291  		common.InitDevnet()
   292  	} else if ctx.GlobalBool(utils.TestnetFlag.Name) {
   293  		common.InitTestnet()
   294  	}
   295  	datong.InitCheckPoints(ctx.GlobalString(utils.CheckPointsFileFlag.Name))
   296  
   297  	// Start up the node itself
   298  	utils.StartNode(stack)
   299  
   300  	// Unlock any account specifically requested
   301  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   302  
   303  	passwords := utils.MakePasswordList(ctx)
   304  	unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   305  	for i, account := range unlocks {
   306  		if trimmed := strings.TrimSpace(account); trimmed != "" {
   307  			unlockAccount(ctx, ks, trimmed, i, passwords)
   308  		}
   309  	}
   310  	// Register wallet event handlers to open and auto-derive wallets
   311  	events := make(chan accounts.WalletEvent, 16)
   312  	stack.AccountManager().Subscribe(events)
   313  
   314  	go func() {
   315  		// Create a chain state reader for self-derivation
   316  		rpcClient, err := stack.Attach()
   317  		if err != nil {
   318  			utils.Fatalf("Failed to attach to self: %v", err)
   319  		}
   320  		stateReader := ethclient.NewClient(rpcClient)
   321  
   322  		// Open any wallets already attached
   323  		for _, wallet := range stack.AccountManager().Wallets() {
   324  			if err := wallet.Open(""); err != nil {
   325  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   326  			}
   327  		}
   328  		// Listen for wallet event till termination
   329  		for event := range events {
   330  			switch event.Kind {
   331  			case accounts.WalletArrived:
   332  				if err := event.Wallet.Open(""); err != nil {
   333  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   334  				}
   335  			case accounts.WalletOpened:
   336  				status, _ := event.Wallet.Status()
   337  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   338  
   339  				derivationPath := accounts.DefaultBaseDerivationPath
   340  				if event.Wallet.URL().Scheme == "ledger" {
   341  					derivationPath = accounts.DefaultLedgerBaseDerivationPath
   342  				}
   343  				event.Wallet.SelfDerive(derivationPath, stateReader)
   344  
   345  			case accounts.WalletDropped:
   346  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   347  				event.Wallet.Close()
   348  			}
   349  		}
   350  	}()
   351  	// Start auto buy tickets
   352  	go ethapi.AutoBuyTicket(ctx.GlobalBool(utils.AutoBuyTicketsEnabledFlag.Name))
   353  	// Start report illegal
   354  	go ethapi.ReportIllegal()
   355  	// Start auxiliary services if enabled
   356  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   357  		// Mining only makes sense if a full Ethereum node is running
   358  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   359  			utils.Fatalf("Light clients do not support mining")
   360  		}
   361  		var ethereum *eth.Ethereum
   362  		if err := stack.Service(&ethereum); err != nil {
   363  			utils.Fatalf("Ethereum service not running: %v", err)
   364  		}
   365  		// Set the gas price to the limits from the CLI and start mining
   366  		gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
   367  		if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
   368  			gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   369  		}
   370  		ethereum.TxPool().SetGasPrice(gasprice)
   371  
   372  		threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
   373  		if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
   374  			threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   375  		}
   376  		if err := ethereum.StartMining(threads); err != nil {
   377  			utils.Fatalf("Failed to start mining: %v", err)
   378  		}
   379  	}
   380  }