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