github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/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  	"strings"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/accounts"
    28  	"github.com/ethereum/go-ethereum/accounts/keystore"
    29  	"github.com/ethereum/go-ethereum/cmd/utils"
    30  	"github.com/ethereum/go-ethereum/common"
    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  	// Ethereum address of the Geth release oracle.
    49  	relOracle = common.HexToAddress("0xfa7b9770ca4cb04296cac84f37736d4041251cdf")
    50  	// The app that holds all commands and flags.
    51  	app = utils.NewApp(gitCommit, "the go-ethereum command line interface")
    52  	// flags that configure the node
    53  	nodeFlags = []cli.Flag{
    54  		utils.IdentityFlag,
    55  		utils.UnlockedAccountFlag,
    56  		utils.PasswordFileFlag,
    57  		utils.BootnodesFlag,
    58  		utils.BootnodesV4Flag,
    59  		utils.BootnodesV5Flag,
    60  		utils.DataDirFlag,
    61  		utils.KeyStoreDirFlag,
    62  		utils.NoUSBFlag,
    63  		utils.EthashCacheDirFlag,
    64  		utils.EthashCachesInMemoryFlag,
    65  		utils.EthashCachesOnDiskFlag,
    66  		utils.EthashDatasetDirFlag,
    67  		utils.EthashDatasetsInMemoryFlag,
    68  		utils.EthashDatasetsOnDiskFlag,
    69  		utils.TxPoolPriceLimitFlag,
    70  		utils.TxPoolPriceBumpFlag,
    71  		utils.TxPoolAccountSlotsFlag,
    72  		utils.TxPoolGlobalSlotsFlag,
    73  		utils.TxPoolAccountQueueFlag,
    74  		utils.TxPoolGlobalQueueFlag,
    75  		utils.TxPoolLifetimeFlag,
    76  		utils.FastSyncFlag,
    77  		utils.LightModeFlag,
    78  		utils.SyncModeFlag,
    79  		utils.LightServFlag,
    80  		utils.LightPeersFlag,
    81  		utils.LightKDFFlag,
    82  		utils.CacheFlag,
    83  		utils.TrieCacheGenFlag,
    84  		utils.ListenPortFlag,
    85  		utils.ListenLocalIPFlag,
    86  		utils.ListenSetIPFlag,
    87  		//utils.BootnodeportFlag,
    88  		utils.MaxPeersFlag,
    89  		utils.MaxPendingPeersFlag,
    90  		utils.EtherbaseFlag,
    91  		utils.GasPriceFlag,
    92  		utils.MinerThreadsFlag,
    93  		utils.MiningEnabledFlag,
    94  		utils.TargetGasLimitFlag,
    95  		utils.NATFlag,
    96  		utils.NoDiscoverFlag,
    97  		utils.DiscoveryV5Flag,
    98  		utils.NetrestrictFlag,
    99  		utils.NodeKeyFileFlag,
   100  		utils.NodeKeyHexFlag,
   101  		utils.WhisperEnabledFlag,
   102  		utils.DevModeFlag,
   103  		utils.TestnetFlag,
   104  		utils.RinkebyFlag,
   105  		utils.OttomanFlag,
   106  		utils.ReapChainFlag,
   107  		utils.VMEnableDebugFlag,
   108  		utils.NetworkIdFlag,
   109  		utils.RPCCORSDomainFlag,
   110  		utils.EthStatsURLFlag,
   111  		utils.MetricsEnabledFlag,
   112  		utils.FakePoWFlag,
   113  		utils.NoCompactionFlag,
   114  		utils.GpoBlocksFlag,
   115  		utils.GpoPercentileFlag,
   116  		utils.ExtraDataFlag,
   117  		utils.GovernanceFlag,
   118  		configFileFlag,
   119  		utils.PoDCRequestTimeoutFlag,
   120  		utils.PoDCBlockPeriodFlag,
   121  		utils.PoDCBlockPauseTimeFlag,
   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  
   139  func init() {
   140  	// Initialize the CLI app and start Geth
   141  	app.Action = geth
   142  	app.HideVersion = true // we have a command to print the version
   143  	app.Copyright = "Copyright 2013-2017 The go-ethereum Authors"
   144  	app.Commands = []cli.Command{
   145  		// See chaincmd.go:
   146  		initCommand,
   147  		importCommand,
   148  		exportCommand,
   149  		removedbCommand,
   150  		dumpCommand,
   151  		// See monitorcmd.go:
   152  		monitorCommand,
   153  		// See accountcmd.go:
   154  		accountCommand,
   155  		walletCommand,
   156  		// See consolecmd.go:
   157  		consoleCommand,
   158  		attachCommand,
   159  		javascriptCommand,
   160  		// See misccmd.go:
   161  		makedagCommand,
   162  		versionCommand,
   163  		bugCommand,
   164  		licenseCommand,
   165  		// See config.go
   166  		dumpConfigCommand,
   167  	}
   168  
   169  	app.Flags = append(app.Flags, nodeFlags...)
   170  	app.Flags = append(app.Flags, rpcFlags...)
   171  	app.Flags = append(app.Flags, consoleFlags...)
   172  	app.Flags = append(app.Flags, debug.Flags...)
   173  
   174  	app.Before = func(ctx *cli.Context) error {
   175  		runtime.GOMAXPROCS(runtime.NumCPU())
   176  		if err := debug.Setup(ctx); err != nil {
   177  			return err
   178  		}
   179  		// Start system runtime metrics collection
   180  		go metrics.CollectProcessMetrics(3 * time.Second)
   181  
   182  		utils.SetupNetwork(ctx)
   183  		return nil
   184  	}
   185  
   186  	app.After = func(ctx *cli.Context) error {
   187  		debug.Exit()
   188  		console.Stdin.Close() // Resets terminal mode.
   189  		return nil
   190  	}
   191  }
   192  
   193  func main() {
   194  
   195  	if err := app.Run(os.Args); err != nil {
   196  		fmt.Fprintln(os.Stderr, err)
   197  		os.Exit(1)
   198  	}
   199  }
   200  
   201  // geth is the main entry point into the system if no special subcommand is ran.
   202  // It creates a default node based on the command line arguments and runs it in
   203  // blocking mode, waiting for it to be shut down.
   204  func geth(ctx *cli.Context) error {
   205  	//config.Config.GetConfig("REAPCHAIN_ENV", "SETUP_INFO")
   206  	node := makeFullNode(ctx)
   207  	startNode(ctx, node)
   208  	node.Wait()
   209  	// Wait blocks the thread until the node is stopped. If the node is not running
   210  	// at the time of invocation, the method immediately returns.
   211  	return nil
   212  }
   213  
   214  // startNode boots up the system node and all registered protocols, after which
   215  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   216  // miner.
   217  func startNode(ctx *cli.Context, stack *node.Node) {
   218  	// Start up the node itself
   219  	utils.StartNode(stack)
   220  
   221  	// Unlock any account specifically requested
   222  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   223  
   224  	passwords := utils.MakePasswordList(ctx)
   225  	unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   226  	for i, account := range unlocks {
   227  		if trimmed := strings.TrimSpace(account); trimmed != "" {
   228  			unlockAccount(ctx, ks, trimmed, i, passwords)
   229  		}
   230  	}
   231  	// Register wallet event handlers to open and auto-derive wallets
   232  	events := make(chan accounts.WalletEvent, 16)
   233  	stack.AccountManager().Subscribe(events) // 이벤트 핸들러 등록
   234  
   235  	go func() {
   236  		// Create an chain state reader for self-derivation
   237  		rpcClient, err := stack.Attach() // 핸들러에 붙인다.
   238  		if err != nil {
   239  			utils.Fatalf("Failed to attach to self: %v", err)
   240  			log.Info("You must start a node at first, and start the second node as miner if you want to avoid this error !")
   241  			//rpcClient를 로컬에 붙이면 에러남, 자기자신에게 rpc를 접속하면,, 안되게 되어있음. 192.168.0.2로 접속시. 안됨.
   242  
   243  		}
   244  		stateReader := ethclient.NewClient(rpcClient) //RPC  clinet 생성 ,, RPC client를 만들어야, geth가 네트웍 노드에서
   245  		//RPC 이벤트 들을 받을 수 있다.
   246  
   247  		// Open and self derive any wallets already attached
   248  		for _, wallet := range stack.AccountManager().Wallets() {
   249  			if err := wallet.Open(""); err != nil {
   250  				log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
   251  			} else {
   252  				wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader)
   253  			}
   254  		}
   255  		// Listen for wallet event till termination
   256  		for event := range events {
   257  			if event.Arrive {
   258  				if err := event.Wallet.Open(""); err != nil {
   259  					log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
   260  				} else {
   261  					log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", event.Wallet.Status())
   262  					event.Wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader)
   263  				}
   264  			} else {
   265  				log.Info("Old wallet dropped", "url", event.Wallet.URL())
   266  				event.Wallet.Close()
   267  			}
   268  		}
   269  	}()
   270  	// Start auxiliary services if enabled
   271  	// miner enable miner thread 1 .. 일때,, 아래 실행..
   272  	// 최초 노드는 마이너 안하나?
   273  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
   274  		var ethereum *eth.Ethereum
   275  		if err := stack.Service(&ethereum); err != nil {
   276  			utils.Fatalf("ethereum service not running: %v", err)
   277  		}
   278  		if threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name); threads > 0 {
   279  			type threaded interface {
   280  				SetThreads(threads int)
   281  			}
   282  			if th, ok := ethereum.Engine().(threaded); ok { //ethash engine
   283  				th.SetThreads(threads)
   284  			}
   285  		}
   286  		if err := ethereum.StartMining(true); err != nil { //마이닝 시작
   287  			utils.Fatalf("Failed to start mining: %v", err)
   288  		}
   289  	}
   290  }