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