github.com/anthdm/go-ethereum@v1.8.4-0.20180412101906-60516c83b011/cmd/geth/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  	"os"
    23  	"runtime"
    24  	"sort"
    25  	"strings"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/accounts"
    29  	"github.com/ethereum/go-ethereum/accounts/keystore"
    30  	"github.com/ethereum/go-ethereum/cmd/utils"
    31  	"github.com/ethereum/go-ethereum/console"
    32  	"github.com/ethereum/go-ethereum/eth"
    33  	"github.com/ethereum/go-ethereum/ethclient"
    34  	"github.com/ethereum/go-ethereum/internal/debug"
    35  	"github.com/ethereum/go-ethereum/log"
    36  	"github.com/ethereum/go-ethereum/metrics"
    37  	"github.com/ethereum/go-ethereum/node"
    38  	"gopkg.in/urfave/cli.v1"
    39  )
    40  
    41  const (
    42  	clientIdentifier = "geth" // Client identifier to advertise over the network
    43  )
    44  
    45  var (
    46  	// Git SHA1 commit hash of the release (set via linker flags)
    47  	gitCommit = ""
    48  	// The app that holds all commands and flags.
    49  	app = utils.NewApp(gitCommit, "the go-ethereum command line interface")
    50  	// flags that configure the node
    51  	nodeFlags = []cli.Flag{
    52  		utils.IdentityFlag,
    53  		utils.UnlockedAccountFlag,
    54  		utils.PasswordFileFlag,
    55  		utils.BootnodesFlag,
    56  		utils.BootnodesV4Flag,
    57  		utils.BootnodesV5Flag,
    58  		utils.DataDirFlag,
    59  		utils.KeyStoreDirFlag,
    60  		utils.NoUSBFlag,
    61  		utils.DashboardEnabledFlag,
    62  		utils.DashboardAddrFlag,
    63  		utils.DashboardPortFlag,
    64  		utils.DashboardRefreshFlag,
    65  		utils.EthashCacheDirFlag,
    66  		utils.EthashCachesInMemoryFlag,
    67  		utils.EthashCachesOnDiskFlag,
    68  		utils.EthashDatasetDirFlag,
    69  		utils.EthashDatasetsInMemoryFlag,
    70  		utils.EthashDatasetsOnDiskFlag,
    71  		utils.TxPoolNoLocalsFlag,
    72  		utils.TxPoolJournalFlag,
    73  		utils.TxPoolRejournalFlag,
    74  		utils.TxPoolPriceLimitFlag,
    75  		utils.TxPoolPriceBumpFlag,
    76  		utils.TxPoolAccountSlotsFlag,
    77  		utils.TxPoolGlobalSlotsFlag,
    78  		utils.TxPoolAccountQueueFlag,
    79  		utils.TxPoolGlobalQueueFlag,
    80  		utils.TxPoolLifetimeFlag,
    81  		utils.FastSyncFlag,
    82  		utils.LightModeFlag,
    83  		utils.SyncModeFlag,
    84  		utils.GCModeFlag,
    85  		utils.LightServFlag,
    86  		utils.LightPeersFlag,
    87  		utils.LightKDFFlag,
    88  		utils.CacheFlag,
    89  		utils.CacheDatabaseFlag,
    90  		utils.CacheGCFlag,
    91  		utils.TrieCacheGenFlag,
    92  		utils.ListenPortFlag,
    93  		utils.MaxPeersFlag,
    94  		utils.MaxPendingPeersFlag,
    95  		utils.EtherbaseFlag,
    96  		utils.GasPriceFlag,
    97  		utils.MinerThreadsFlag,
    98  		utils.MiningEnabledFlag,
    99  		utils.TargetGasLimitFlag,
   100  		utils.NATFlag,
   101  		utils.NoDiscoverFlag,
   102  		utils.DiscoveryV5Flag,
   103  		utils.NetrestrictFlag,
   104  		utils.NodeKeyFileFlag,
   105  		utils.NodeKeyHexFlag,
   106  		utils.DeveloperFlag,
   107  		utils.DeveloperPeriodFlag,
   108  		utils.TestnetFlag,
   109  		utils.RinkebyFlag,
   110  		utils.VMEnableDebugFlag,
   111  		utils.NetworkIdFlag,
   112  		utils.RPCCORSDomainFlag,
   113  		utils.RPCVirtualHostsFlag,
   114  		utils.EthStatsURLFlag,
   115  		utils.MetricsEnabledFlag,
   116  		utils.FakePoWFlag,
   117  		utils.NoCompactionFlag,
   118  		utils.GpoBlocksFlag,
   119  		utils.GpoPercentileFlag,
   120  		utils.ExtraDataFlag,
   121  		configFileFlag,
   122  	}
   123  
   124  	rpcFlags = []cli.Flag{
   125  		utils.RPCEnabledFlag,
   126  		utils.RPCListenAddrFlag,
   127  		utils.RPCPortFlag,
   128  		utils.RPCApiFlag,
   129  		utils.WSEnabledFlag,
   130  		utils.WSListenAddrFlag,
   131  		utils.WSPortFlag,
   132  		utils.WSApiFlag,
   133  		utils.WSAllowedOriginsFlag,
   134  		utils.IPCDisabledFlag,
   135  		utils.IPCPathFlag,
   136  	}
   137  
   138  	whisperFlags = []cli.Flag{
   139  		utils.WhisperEnabledFlag,
   140  		utils.WhisperMaxMessageSizeFlag,
   141  		utils.WhisperMinPOWFlag,
   142  	}
   143  )
   144  
   145  func init() {
   146  	// Initialize the CLI app and start Geth
   147  	app.Action = geth
   148  	app.HideVersion = true // we have a command to print the version
   149  	app.Copyright = "Copyright 2013-2017 The go-ethereum Authors"
   150  	app.Commands = []cli.Command{
   151  		// See chaincmd.go:
   152  		initCommand,
   153  		importCommand,
   154  		exportCommand,
   155  		importPreimagesCommand,
   156  		exportPreimagesCommand,
   157  		copydbCommand,
   158  		removedbCommand,
   159  		dumpCommand,
   160  		// See monitorcmd.go:
   161  		monitorCommand,
   162  		// See accountcmd.go:
   163  		accountCommand,
   164  		walletCommand,
   165  		// See consolecmd.go:
   166  		consoleCommand,
   167  		attachCommand,
   168  		javascriptCommand,
   169  		// See misccmd.go:
   170  		makecacheCommand,
   171  		makedagCommand,
   172  		versionCommand,
   173  		bugCommand,
   174  		licenseCommand,
   175  		// See config.go
   176  		dumpConfigCommand,
   177  	}
   178  	sort.Sort(cli.CommandsByName(app.Commands))
   179  
   180  	app.Flags = append(app.Flags, nodeFlags...)
   181  	app.Flags = append(app.Flags, rpcFlags...)
   182  	app.Flags = append(app.Flags, consoleFlags...)
   183  	app.Flags = append(app.Flags, debug.Flags...)
   184  	app.Flags = append(app.Flags, whisperFlags...)
   185  
   186  	app.Before = func(ctx *cli.Context) error {
   187  		runtime.GOMAXPROCS(runtime.NumCPU())
   188  		if err := debug.Setup(ctx); err != nil {
   189  			return err
   190  		}
   191  		// Start system runtime metrics collection
   192  		go metrics.CollectProcessMetrics(3 * time.Second)
   193  
   194  		utils.SetupNetwork(ctx)
   195  		return nil
   196  	}
   197  
   198  	app.After = func(ctx *cli.Context) error {
   199  		debug.Exit()
   200  		console.Stdin.Close() // Resets terminal mode.
   201  		return nil
   202  	}
   203  }
   204  
   205  func main() {
   206  	if err := app.Run(os.Args); err != nil {
   207  		fmt.Fprintln(os.Stderr, err)
   208  		os.Exit(1)
   209  	}
   210  }
   211  
   212  // geth is the main entry point into the system if no special subcommand is ran.
   213  // It creates a default node based on the command line arguments and runs it in
   214  // blocking mode, waiting for it to be shut down.
   215  func geth(ctx *cli.Context) error {
   216  	node := makeFullNode(ctx)
   217  	startNode(ctx, node)
   218  	node.Wait()
   219  	return nil
   220  }
   221  
   222  // startNode boots up the system node and all registered protocols, after which
   223  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   224  // miner.
   225  func startNode(ctx *cli.Context, stack *node.Node) {
   226  	// Start up the node itself
   227  	utils.StartNode(stack)
   228  
   229  	// Unlock any account specifically requested
   230  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   231  
   232  	passwords := utils.MakePasswordList(ctx)
   233  	unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   234  	for i, account := range unlocks {
   235  		if trimmed := strings.TrimSpace(account); trimmed != "" {
   236  			unlockAccount(ctx, ks, trimmed, i, passwords)
   237  		}
   238  	}
   239  	// Register wallet event handlers to open and auto-derive wallets
   240  	events := make(chan accounts.WalletEvent, 16)
   241  	stack.AccountManager().Subscribe(events)
   242  
   243  	go func() {
   244  		// Create an chain state reader for self-derivation
   245  		rpcClient, err := stack.Attach()
   246  		if err != nil {
   247  			utils.Fatalf("Failed to attach to self: %v", err)
   248  		}
   249  		stateReader := ethclient.NewClient(rpcClient)
   250  
   251  		// Open any wallets already attached
   252  		for _, wallet := range stack.AccountManager().Wallets() {
   253  			if err := wallet.Open(""); err != nil {
   254  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   255  			}
   256  		}
   257  		// Listen for wallet event till termination
   258  		for event := range events {
   259  			switch event.Kind {
   260  			case accounts.WalletArrived:
   261  				if err := event.Wallet.Open(""); err != nil {
   262  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   263  				}
   264  			case accounts.WalletOpened:
   265  				status, _ := event.Wallet.Status()
   266  				log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
   267  
   268  				if event.Wallet.URL().Scheme == "ledger" {
   269  					event.Wallet.SelfDerive(accounts.DefaultLedgerBaseDerivationPath, stateReader)
   270  				} else {
   271  					event.Wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader)
   272  				}
   273  
   274  			case accounts.WalletDropped:
   275  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   276  				event.Wallet.Close()
   277  			}
   278  		}
   279  	}()
   280  	// Start auxiliary services if enabled
   281  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
   282  		// Mining only makes sense if a full Ethereum node is running
   283  		if ctx.GlobalBool(utils.LightModeFlag.Name) || ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
   284  			utils.Fatalf("Light clients do not support mining")
   285  		}
   286  		var ethereum *eth.Ethereum
   287  		if err := stack.Service(&ethereum); err != nil {
   288  			utils.Fatalf("Ethereum service not running: %v", err)
   289  		}
   290  		// Use a reduced number of threads if requested
   291  		if threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name); threads > 0 {
   292  			type threaded interface {
   293  				SetThreads(threads int)
   294  			}
   295  			if th, ok := ethereum.Engine().(threaded); ok {
   296  				th.SetThreads(threads)
   297  			}
   298  		}
   299  		// Set the gas price to the limits from the CLI and start mining
   300  		ethereum.TxPool().SetGasPrice(utils.GlobalBig(ctx, utils.GasPriceFlag.Name))
   301  		if err := ethereum.StartMining(true); err != nil {
   302  			utils.Fatalf("Failed to start mining: %v", err)
   303  		}
   304  	}
   305  }