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