github.com/Debrief-BC/go-debrief@v0.0.0-20200420203408-0c26ca968123/cmd/debrief/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  	"runtime"
    25  	godebug "runtime/debug"
    26  	"sort"
    27  	"strconv"
    28  	"strings"
    29  	"time"
    30  
    31  	"github.com/elastic/gosigar"
    32  	"github.com/Debrief-BC/go-debrief/accounts"
    33  	"github.com/Debrief-BC/go-debrief/accounts/keystore"
    34  	"github.com/Debrief-BC/go-debrief/cmd/utils"
    35  	"github.com/Debrief-BC/go-debrief/common"
    36  	"github.com/Debrief-BC/go-debrief/console"
    37  	"github.com/Debrief-BC/go-debrief/eth"
    38  	"github.com/Debrief-BC/go-debrief/eth/downloader"
    39  	"github.com/Debrief-BC/go-debrief/ethclient"
    40  	"github.com/Debrief-BC/go-debrief/internal/debug"
    41  	"github.com/Debrief-BC/go-debrief/les"
    42  	"github.com/Debrief-BC/go-debrief/log"
    43  	"github.com/Debrief-BC/go-debrief/metrics"
    44  	"github.com/Debrief-BC/go-debrief/node"
    45  	cli "gopkg.in/urfave/cli.v1"
    46  )
    47  
    48  const (
    49  	clientIdentifier = "debrief" // 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  	gitDate   = ""
    56  	// The app that holds all commands and flags.
    57  	app = utils.NewApp(gitCommit, gitDate, "the go-ethereum command line interface")
    58  	// flags that configure the node
    59  	nodeFlags = []cli.Flag{
    60  		utils.IdentityFlag,
    61  		utils.UnlockedAccountFlag,
    62  		utils.PasswordFileFlag,
    63  		utils.BootnodesFlag,
    64  		utils.BootnodesV4Flag,
    65  		utils.BootnodesV5Flag,
    66  		utils.DataDirFlag,
    67  		utils.AncientFlag,
    68  		utils.KeyStoreDirFlag,
    69  		utils.ExternalSignerFlag,
    70  		utils.NoUSBFlag,
    71  		utils.SmartCardDaemonPathFlag,
    72  		utils.OverrideIstanbulFlag,
    73  		utils.OverrideMuirGlacierFlag,
    74  		utils.EthashCacheDirFlag,
    75  		utils.EthashCachesInMemoryFlag,
    76  		utils.EthashCachesOnDiskFlag,
    77  		utils.EthashCachesLockMmapFlag,
    78  		utils.EthashDatasetDirFlag,
    79  		utils.EthashDatasetsInMemoryFlag,
    80  		utils.EthashDatasetsOnDiskFlag,
    81  		utils.EthashDatasetsLockMmapFlag,
    82  		utils.TxPoolLocalsFlag,
    83  		utils.TxPoolNoLocalsFlag,
    84  		utils.TxPoolJournalFlag,
    85  		utils.TxPoolRejournalFlag,
    86  		utils.TxPoolPriceLimitFlag,
    87  		utils.TxPoolPriceBumpFlag,
    88  		utils.TxPoolAccountSlotsFlag,
    89  		utils.TxPoolGlobalSlotsFlag,
    90  		utils.TxPoolAccountQueueFlag,
    91  		utils.TxPoolGlobalQueueFlag,
    92  		utils.TxPoolLifetimeFlag,
    93  		utils.SyncModeFlag,
    94  		utils.ExitWhenSyncedFlag,
    95  		utils.GCModeFlag,
    96  		utils.SnapshotFlag,
    97  		utils.LightServeFlag,
    98  		utils.LightLegacyServFlag,
    99  		utils.LightIngressFlag,
   100  		utils.LightEgressFlag,
   101  		utils.LightMaxPeersFlag,
   102  		utils.LightLegacyPeersFlag,
   103  		utils.LightKDFFlag,
   104  		utils.UltraLightServersFlag,
   105  		utils.UltraLightFractionFlag,
   106  		utils.UltraLightOnlyAnnounceFlag,
   107  		utils.WhitelistFlag,
   108  		utils.CacheFlag,
   109  		utils.CacheDatabaseFlag,
   110  		utils.CacheTrieFlag,
   111  		utils.CacheGCFlag,
   112  		utils.CacheSnapshotFlag,
   113  		utils.CacheNoPrefetchFlag,
   114  		utils.ListenPortFlag,
   115  		utils.MaxPeersFlag,
   116  		utils.MaxPendingPeersFlag,
   117  		utils.MiningEnabledFlag,
   118  		utils.MinerThreadsFlag,
   119  		utils.MinerLegacyThreadsFlag,
   120  		utils.MinerNotifyFlag,
   121  		utils.MinerGasTargetFlag,
   122  		utils.MinerLegacyGasTargetFlag,
   123  		utils.MinerGasLimitFlag,
   124  		utils.MinerGasPriceFlag,
   125  		utils.MinerLegacyGasPriceFlag,
   126  		utils.MinerEtherbaseFlag,
   127  		utils.MinerLegacyEtherbaseFlag,
   128  		utils.MinerExtraDataFlag,
   129  		utils.MinerLegacyExtraDataFlag,
   130  		utils.MinerRecommitIntervalFlag,
   131  		utils.MinerNoVerfiyFlag,
   132  		utils.NATFlag,
   133  		utils.NoDiscoverFlag,
   134  		utils.DiscoveryV5Flag,
   135  		utils.NetrestrictFlag,
   136  		utils.NodeKeyFileFlag,
   137  		utils.NodeKeyHexFlag,
   138  		utils.DNSDiscoveryFlag,
   139  		utils.DeveloperFlag,
   140  		utils.DeveloperPeriodFlag,
   141  		utils.TestnetFlag,
   142  		utils.RinkebyFlag,
   143  		utils.GoerliFlag,
   144  		utils.VMEnableDebugFlag,
   145  		utils.NetworkIdFlag,
   146  		utils.EthStatsURLFlag,
   147  		utils.FakePoWFlag,
   148  		utils.NoCompactionFlag,
   149  		utils.GpoBlocksFlag,
   150  		utils.GpoPercentileFlag,
   151  		utils.EWASMInterpreterFlag,
   152  		utils.EVMInterpreterFlag,
   153  		configFileFlag,
   154  	}
   155  
   156  	rpcFlags = []cli.Flag{
   157  		utils.RPCEnabledFlag,
   158  		utils.RPCListenAddrFlag,
   159  		utils.RPCPortFlag,
   160  		utils.RPCCORSDomainFlag,
   161  		utils.RPCVirtualHostsFlag,
   162  		utils.GraphQLEnabledFlag,
   163  		utils.GraphQLListenAddrFlag,
   164  		utils.GraphQLPortFlag,
   165  		utils.GraphQLCORSDomainFlag,
   166  		utils.GraphQLVirtualHostsFlag,
   167  		utils.RPCApiFlag,
   168  		utils.WSEnabledFlag,
   169  		utils.WSListenAddrFlag,
   170  		utils.WSPortFlag,
   171  		utils.WSApiFlag,
   172  		utils.WSAllowedOriginsFlag,
   173  		utils.IPCDisabledFlag,
   174  		utils.IPCPathFlag,
   175  		utils.InsecureUnlockAllowedFlag,
   176  		utils.RPCGlobalGasCap,
   177  	}
   178  
   179  	whisperFlags = []cli.Flag{
   180  		utils.WhisperEnabledFlag,
   181  		utils.WhisperMaxMessageSizeFlag,
   182  		utils.WhisperMinPOWFlag,
   183  		utils.WhisperRestrictConnectionBetweenLightClientsFlag,
   184  	}
   185  
   186  	metricsFlags = []cli.Flag{
   187  		utils.MetricsEnabledFlag,
   188  		utils.MetricsEnabledExpensiveFlag,
   189  		utils.MetricsEnableInfluxDBFlag,
   190  		utils.MetricsInfluxDBEndpointFlag,
   191  		utils.MetricsInfluxDBDatabaseFlag,
   192  		utils.MetricsInfluxDBUsernameFlag,
   193  		utils.MetricsInfluxDBPasswordFlag,
   194  		utils.MetricsInfluxDBTagsFlag,
   195  	}
   196  )
   197  
   198  func init() {
   199  	// Initialize the CLI app and start Geth
   200  	app.Action = geth
   201  	app.HideVersion = true // we have a command to print the version
   202  	app.Copyright = "Copyright 2013-2020 The go-ethereum Authors"
   203  	app.Commands = []cli.Command{
   204  		// See chaincmd.go:
   205  		initCommand,
   206  		importCommand,
   207  		exportCommand,
   208  		importPreimagesCommand,
   209  		exportPreimagesCommand,
   210  		copydbCommand,
   211  		removedbCommand,
   212  		dumpCommand,
   213  		dumpGenesisCommand,
   214  		inspectCommand,
   215  		// See accountcmd.go:
   216  		accountCommand,
   217  		walletCommand,
   218  		// See consolecmd.go:
   219  		consoleCommand,
   220  		attachCommand,
   221  		javascriptCommand,
   222  		// See misccmd.go:
   223  		makecacheCommand,
   224  		makedagCommand,
   225  		versionCommand,
   226  		licenseCommand,
   227  		// See config.go
   228  		dumpConfigCommand,
   229  		// See retesteth.go
   230  		retestethCommand,
   231  	}
   232  	sort.Sort(cli.CommandsByName(app.Commands))
   233  
   234  	app.Flags = append(app.Flags, nodeFlags...)
   235  	app.Flags = append(app.Flags, rpcFlags...)
   236  	app.Flags = append(app.Flags, consoleFlags...)
   237  	app.Flags = append(app.Flags, debug.Flags...)
   238  	app.Flags = append(app.Flags, whisperFlags...)
   239  	app.Flags = append(app.Flags, metricsFlags...)
   240  
   241  	app.Before = func(ctx *cli.Context) error {
   242  		return debug.Setup(ctx)
   243  	}
   244  	app.After = func(ctx *cli.Context) error {
   245  		debug.Exit()
   246  		console.Stdin.Close() // Resets terminal mode.
   247  		return nil
   248  	}
   249  }
   250  
   251  func main() {
   252  	if err := app.Run(os.Args); err != nil {
   253  		fmt.Fprintln(os.Stderr, err)
   254  		os.Exit(1)
   255  	}
   256  }
   257  
   258  // prepare manipulates memory cache allowance and setups metric system.
   259  // This function should be called before launching devp2p stack.
   260  func prepare(ctx *cli.Context) {
   261  	// If we're a full node on mainnet without --cache specified, bump default cache allowance
   262  	if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
   263  		// Make sure we're not on any supported preconfigured testnet either
   264  		if !ctx.GlobalIsSet(utils.TestnetFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
   265  			// Nope, we're really on mainnet. Bump that cache up!
   266  			log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
   267  			ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
   268  		}
   269  	}
   270  	// If we're running a light client on any network, drop the cache to some meaningfully low amount
   271  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
   272  		log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
   273  		ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
   274  	}
   275  	// Cap the cache allowance and tune the garbage collector
   276  	var mem gosigar.Mem
   277  	// Workaround until OpenBSD support lands into gosigar
   278  	// Check https://github.com/elastic/gosigar#supported-platforms
   279  	if runtime.GOOS != "openbsd" {
   280  		if err := mem.Get(); err == nil {
   281  			allowance := int(mem.Total / 1024 / 1024 / 3)
   282  			if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
   283  				log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
   284  				ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
   285  			}
   286  		}
   287  	}
   288  	// Ensure Go's GC ignores the database cache for trigger percentage
   289  	cache := ctx.GlobalInt(utils.CacheFlag.Name)
   290  	gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
   291  
   292  	log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
   293  	godebug.SetGCPercent(int(gogc))
   294  
   295  	// Start metrics export if enabled
   296  	utils.SetupMetrics(ctx)
   297  
   298  	// Start system runtime metrics collection
   299  	go metrics.CollectProcessMetrics(3 * time.Second)
   300  }
   301  
   302  // geth is the main entry point into the system if no special subcommand is ran.
   303  // It creates a default node based on the command line arguments and runs it in
   304  // blocking mode, waiting for it to be shut down.
   305  func geth(ctx *cli.Context) error {
   306  	if args := ctx.Args(); len(args) > 0 {
   307  		return fmt.Errorf("invalid command: %q", args[0])
   308  	}
   309  	prepare(ctx)
   310  	node := makeFullNode(ctx)
   311  	defer node.Close()
   312  	startNode(ctx, node)
   313  	node.Wait()
   314  	return nil
   315  }
   316  
   317  // startNode boots up the system node and all registered protocols, after which
   318  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   319  // miner.
   320  func startNode(ctx *cli.Context, stack *node.Node) {
   321  	debug.Memsize.Add("node", stack)
   322  
   323  	// Start up the node itself
   324  	utils.StartNode(stack)
   325  
   326  	// Unlock any account specifically requested
   327  	unlockAccounts(ctx, stack)
   328  
   329  	// Register wallet event handlers to open and auto-derive wallets
   330  	events := make(chan accounts.WalletEvent, 16)
   331  	stack.AccountManager().Subscribe(events)
   332  
   333  	// Create a client to interact with local geth node.
   334  	rpcClient, err := stack.Attach()
   335  	if err != nil {
   336  		utils.Fatalf("Failed to attach to self: %v", err)
   337  	}
   338  	ethClient := ethclient.NewClient(rpcClient)
   339  
   340  	// Set contract backend for ethereum service if local node
   341  	// is serving LES requests.
   342  	if ctx.GlobalInt(utils.LightLegacyServFlag.Name) > 0 || ctx.GlobalInt(utils.LightServeFlag.Name) > 0 {
   343  		var ethService *eth.Ethereum
   344  		if err := stack.Service(&ethService); err != nil {
   345  			utils.Fatalf("Failed to retrieve ethereum service: %v", err)
   346  		}
   347  		ethService.SetContractBackend(ethClient)
   348  	}
   349  	// Set contract backend for les service if local node is
   350  	// running as a light client.
   351  	if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   352  		var lesService *les.LightEthereum
   353  		if err := stack.Service(&lesService); err != nil {
   354  			utils.Fatalf("Failed to retrieve light ethereum service: %v", err)
   355  		}
   356  		lesService.SetContractBackend(ethClient)
   357  	}
   358  
   359  	go func() {
   360  		// Open any wallets already attached
   361  		for _, wallet := range stack.AccountManager().Wallets() {
   362  			if err := wallet.Open(""); err != nil {
   363  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   364  			}
   365  		}
   366  		// Listen for wallet event till termination
   367  		for event := range events {
   368  			switch event.Kind {
   369  			case accounts.WalletArrived:
   370  				if err := event.Wallet.Open(""); err != nil {
   371  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   372  				}
   373  			case accounts.WalletOpened:
   374  				status, _ := event.Wallet.Status()
   375  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   376  
   377  				var derivationPaths []accounts.DerivationPath
   378  				if event.Wallet.URL().Scheme == "ledger" {
   379  					derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
   380  				}
   381  				derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
   382  
   383  				event.Wallet.SelfDerive(derivationPaths, ethClient)
   384  
   385  			case accounts.WalletDropped:
   386  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   387  				event.Wallet.Close()
   388  			}
   389  		}
   390  	}()
   391  
   392  	// Spawn a standalone goroutine for status synchronization monitoring,
   393  	// close the node when synchronization is complete if user required.
   394  	if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
   395  		go func() {
   396  			sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
   397  			defer sub.Unsubscribe()
   398  			for {
   399  				event := <-sub.Chan()
   400  				if event == nil {
   401  					continue
   402  				}
   403  				done, ok := event.Data.(downloader.DoneEvent)
   404  				if !ok {
   405  					continue
   406  				}
   407  				if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
   408  					log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
   409  						"age", common.PrettyAge(timestamp))
   410  					stack.Stop()
   411  				}
   412  			}
   413  		}()
   414  	}
   415  
   416  	// Start auxiliary services if enabled
   417  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   418  		// Mining only makes sense if a full Ethereum node is running
   419  		if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   420  			utils.Fatalf("Light clients do not support mining")
   421  		}
   422  		var ethereum *eth.Ethereum
   423  		if err := stack.Service(&ethereum); err != nil {
   424  			utils.Fatalf("Ethereum service not running: %v", err)
   425  		}
   426  		// Set the gas price to the limits from the CLI and start mining
   427  		gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
   428  		if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
   429  			gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
   430  		}
   431  		ethereum.TxPool().SetGasPrice(gasprice)
   432  
   433  		threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
   434  		if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
   435  			threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
   436  		}
   437  		if err := ethereum.StartMining(threads); err != nil {
   438  			utils.Fatalf("Failed to start mining: %v", err)
   439  		}
   440  	}
   441  }
   442  
   443  // unlockAccounts unlocks any account specifically requested.
   444  func unlockAccounts(ctx *cli.Context, stack *node.Node) {
   445  	var unlocks []string
   446  	inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   447  	for _, input := range inputs {
   448  		if trimmed := strings.TrimSpace(input); trimmed != "" {
   449  			unlocks = append(unlocks, trimmed)
   450  		}
   451  	}
   452  	// Short circuit if there is no account to unlock.
   453  	if len(unlocks) == 0 {
   454  		return
   455  	}
   456  	// If insecure account unlocking is not allowed if node's APIs are exposed to external.
   457  	// Print warning log to user and skip unlocking.
   458  	if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
   459  		utils.Fatalf("Account unlock with HTTP access is forbidden!")
   460  	}
   461  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   462  	passwords := utils.MakePasswordList(ctx)
   463  	for i, account := range unlocks {
   464  		unlockAccount(ks, account, i, passwords)
   465  	}
   466  }