github.com/murrekatt/go-ethereum@v1.5.8-0.20170123175102-fc52f2c007fb/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  	"encoding/hex"
    22  	"fmt"
    23  	"os"
    24  	"runtime"
    25  	"strings"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/cmd/utils"
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/console"
    31  	"github.com/ethereum/go-ethereum/contracts/release"
    32  	"github.com/ethereum/go-ethereum/eth"
    33  	"github.com/ethereum/go-ethereum/internal/debug"
    34  	"github.com/ethereum/go-ethereum/logger"
    35  	"github.com/ethereum/go-ethereum/logger/glog"
    36  	"github.com/ethereum/go-ethereum/metrics"
    37  	"github.com/ethereum/go-ethereum/node"
    38  	"github.com/ethereum/go-ethereum/params"
    39  	"github.com/ethereum/go-ethereum/rlp"
    40  	"gopkg.in/urfave/cli.v1"
    41  )
    42  
    43  const (
    44  	clientIdentifier = "geth" // Client identifier to advertise over the network
    45  )
    46  
    47  var (
    48  	// Git SHA1 commit hash of the release (set via linker flags)
    49  	gitCommit = ""
    50  	// Ethereum address of the Geth release oracle.
    51  	relOracle = common.HexToAddress("0xfa7b9770ca4cb04296cac84f37736d4041251cdf")
    52  	// The app that holds all commands and flags.
    53  	app = utils.NewApp(gitCommit, "the go-ethereum command line interface")
    54  )
    55  
    56  func init() {
    57  	// Initialize the CLI app and start Geth
    58  	app.Action = geth
    59  	app.HideVersion = true // we have a command to print the version
    60  	app.Copyright = "Copyright 2013-2016 The go-ethereum Authors"
    61  	app.Commands = []cli.Command{
    62  		// See chaincmd.go:
    63  		initCommand,
    64  		importCommand,
    65  		exportCommand,
    66  		upgradedbCommand,
    67  		removedbCommand,
    68  		dumpCommand,
    69  		// See monitorcmd.go:
    70  		monitorCommand,
    71  		// See accountcmd.go:
    72  		accountCommand,
    73  		walletCommand,
    74  		// See consolecmd.go:
    75  		consoleCommand,
    76  		attachCommand,
    77  		javascriptCommand,
    78  		// See misccmd.go:
    79  		makedagCommand,
    80  		versionCommand,
    81  		licenseCommand,
    82  	}
    83  
    84  	app.Flags = []cli.Flag{
    85  		utils.IdentityFlag,
    86  		utils.UnlockedAccountFlag,
    87  		utils.PasswordFileFlag,
    88  		utils.BootnodesFlag,
    89  		utils.DataDirFlag,
    90  		utils.KeyStoreDirFlag,
    91  		utils.FastSyncFlag,
    92  		utils.LightModeFlag,
    93  		utils.LightServFlag,
    94  		utils.LightPeersFlag,
    95  		utils.LightKDFFlag,
    96  		utils.CacheFlag,
    97  		utils.TrieCacheGenFlag,
    98  		utils.JSpathFlag,
    99  		utils.ListenPortFlag,
   100  		utils.MaxPeersFlag,
   101  		utils.MaxPendingPeersFlag,
   102  		utils.EtherbaseFlag,
   103  		utils.GasPriceFlag,
   104  		utils.MinerThreadsFlag,
   105  		utils.MiningEnabledFlag,
   106  		utils.AutoDAGFlag,
   107  		utils.TargetGasLimitFlag,
   108  		utils.NATFlag,
   109  		utils.NoDiscoverFlag,
   110  		utils.DiscoveryV5Flag,
   111  		utils.NetrestrictFlag,
   112  		utils.NodeKeyFileFlag,
   113  		utils.NodeKeyHexFlag,
   114  		utils.RPCEnabledFlag,
   115  		utils.RPCListenAddrFlag,
   116  		utils.RPCPortFlag,
   117  		utils.RPCApiFlag,
   118  		utils.WSEnabledFlag,
   119  		utils.WSListenAddrFlag,
   120  		utils.WSPortFlag,
   121  		utils.WSApiFlag,
   122  		utils.WSAllowedOriginsFlag,
   123  		utils.IPCDisabledFlag,
   124  		utils.IPCApiFlag,
   125  		utils.IPCPathFlag,
   126  		utils.ExecFlag,
   127  		utils.PreloadJSFlag,
   128  		utils.WhisperEnabledFlag,
   129  		utils.DevModeFlag,
   130  		utils.TestNetFlag,
   131  		utils.VMForceJitFlag,
   132  		utils.VMJitCacheFlag,
   133  		utils.VMEnableJitFlag,
   134  		utils.VMEnableDebugFlag,
   135  		utils.NetworkIdFlag,
   136  		utils.RPCCORSDomainFlag,
   137  		utils.EthStatsURLFlag,
   138  		utils.MetricsEnabledFlag,
   139  		utils.FakePoWFlag,
   140  		utils.SolcPathFlag,
   141  		utils.GpoMinGasPriceFlag,
   142  		utils.GpoMaxGasPriceFlag,
   143  		utils.GpoFullBlockRatioFlag,
   144  		utils.GpobaseStepDownFlag,
   145  		utils.GpobaseStepUpFlag,
   146  		utils.GpobaseCorrectionFactorFlag,
   147  		utils.ExtraDataFlag,
   148  	}
   149  	app.Flags = append(app.Flags, debug.Flags...)
   150  
   151  	app.Before = func(ctx *cli.Context) error {
   152  		runtime.GOMAXPROCS(runtime.NumCPU())
   153  		if err := debug.Setup(ctx); err != nil {
   154  			return err
   155  		}
   156  		// Start system runtime metrics collection
   157  		go metrics.CollectProcessMetrics(3 * time.Second)
   158  
   159  		// This should be the only place where reporting is enabled
   160  		// because it is not intended to run while testing.
   161  		// In addition to this check, bad block reports are sent only
   162  		// for chains with the main network genesis block and network id 1.
   163  		eth.EnableBadBlockReporting = true
   164  
   165  		utils.SetupNetwork(ctx)
   166  		return nil
   167  	}
   168  
   169  	app.After = func(ctx *cli.Context) error {
   170  		debug.Exit()
   171  		console.Stdin.Close() // Resets terminal mode.
   172  		return nil
   173  	}
   174  }
   175  
   176  func main() {
   177  	if err := app.Run(os.Args); err != nil {
   178  		fmt.Fprintln(os.Stderr, err)
   179  		os.Exit(1)
   180  	}
   181  }
   182  
   183  // geth is the main entry point into the system if no special subcommand is ran.
   184  // It creates a default node based on the command line arguments and runs it in
   185  // blocking mode, waiting for it to be shut down.
   186  func geth(ctx *cli.Context) error {
   187  	node := makeFullNode(ctx)
   188  	startNode(ctx, node)
   189  	node.Wait()
   190  	return nil
   191  }
   192  
   193  func makeFullNode(ctx *cli.Context) *node.Node {
   194  	// Create the default extradata and construct the base node
   195  	var clientInfo = struct {
   196  		Version   uint
   197  		Name      string
   198  		GoVersion string
   199  		Os        string
   200  	}{uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch), clientIdentifier, runtime.Version(), runtime.GOOS}
   201  	extra, err := rlp.EncodeToBytes(clientInfo)
   202  	if err != nil {
   203  		glog.V(logger.Warn).Infoln("error setting canonical miner information:", err)
   204  	}
   205  	if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
   206  		glog.V(logger.Warn).Infoln("error setting canonical miner information: extra exceeds", params.MaximumExtraDataSize)
   207  		glog.V(logger.Debug).Infof("extra: %x\n", extra)
   208  		extra = nil
   209  	}
   210  	stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
   211  	utils.RegisterEthService(ctx, stack, extra)
   212  
   213  	// Whisper must be explicitly enabled, but is auto-enabled in --dev mode.
   214  	shhEnabled := ctx.GlobalBool(utils.WhisperEnabledFlag.Name)
   215  	shhAutoEnabled := !ctx.GlobalIsSet(utils.WhisperEnabledFlag.Name) && ctx.GlobalIsSet(utils.DevModeFlag.Name)
   216  	if shhEnabled || shhAutoEnabled {
   217  		utils.RegisterShhService(stack)
   218  	}
   219  	// Add the Ethereum Stats daemon if requested
   220  	if url := ctx.GlobalString(utils.EthStatsURLFlag.Name); url != "" {
   221  		utils.RegisterEthStatsService(stack, url)
   222  	}
   223  	// Add the release oracle service so it boots along with node.
   224  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   225  		config := release.Config{
   226  			Oracle: relOracle,
   227  			Major:  uint32(params.VersionMajor),
   228  			Minor:  uint32(params.VersionMinor),
   229  			Patch:  uint32(params.VersionPatch),
   230  		}
   231  		commit, _ := hex.DecodeString(gitCommit)
   232  		copy(config.Commit[:], commit)
   233  		return release.NewReleaseService(ctx, config)
   234  	}); err != nil {
   235  		utils.Fatalf("Failed to register the Geth release oracle service: %v", err)
   236  	}
   237  	return stack
   238  }
   239  
   240  // startNode boots up the system node and all registered protocols, after which
   241  // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
   242  // miner.
   243  func startNode(ctx *cli.Context, stack *node.Node) {
   244  	// Start up the node itself
   245  	utils.StartNode(stack)
   246  
   247  	// Unlock any account specifically requested
   248  	accman := stack.AccountManager()
   249  	passwords := utils.MakePasswordList(ctx)
   250  	accounts := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
   251  	for i, account := range accounts {
   252  		if trimmed := strings.TrimSpace(account); trimmed != "" {
   253  			unlockAccount(ctx, accman, trimmed, i, passwords)
   254  		}
   255  	}
   256  	// Start auxiliary services if enabled
   257  	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
   258  		var ethereum *eth.Ethereum
   259  		if err := stack.Service(&ethereum); err != nil {
   260  			utils.Fatalf("ethereum service not running: %v", err)
   261  		}
   262  		if err := ethereum.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name)); err != nil {
   263  			utils.Fatalf("Failed to start mining: %v", err)
   264  		}
   265  	}
   266  }