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