github.com/nnlgsakib/mind-dpos@v0.0.0-20230606105614-f3c8ca06f808/cmd/utils/flags.go (about)

     1  // Copyright 2015 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  // Package utils contains internal helper functions for go-ethereum commands.
    18  package utils
    19  
    20  import (
    21  	"crypto/ecdsa"
    22  	"fmt"
    23  	"io/ioutil"
    24  	"math/big"
    25  	"os"
    26  	"path/filepath"
    27  	"runtime"
    28  	"strconv"
    29  	"strings"
    30  
    31  	"github.com/TTCECO/gttc/accounts"
    32  	"github.com/TTCECO/gttc/accounts/keystore"
    33  	"github.com/TTCECO/gttc/common"
    34  	"github.com/TTCECO/gttc/common/fdlimit"
    35  	"github.com/TTCECO/gttc/consensus"
    36  	"github.com/TTCECO/gttc/consensus/alien"
    37  	"github.com/TTCECO/gttc/consensus/clique"
    38  	"github.com/TTCECO/gttc/consensus/ethash"
    39  	"github.com/TTCECO/gttc/core"
    40  	"github.com/TTCECO/gttc/core/state"
    41  	"github.com/TTCECO/gttc/core/vm"
    42  	"github.com/TTCECO/gttc/crypto"
    43  	"github.com/TTCECO/gttc/dashboard"
    44  	"github.com/TTCECO/gttc/eth"
    45  	"github.com/TTCECO/gttc/eth/downloader"
    46  	"github.com/TTCECO/gttc/eth/gasprice"
    47  	"github.com/TTCECO/gttc/ethdb"
    48  	"github.com/TTCECO/gttc/ethstats"
    49  	"github.com/TTCECO/gttc/les"
    50  	"github.com/TTCECO/gttc/log"
    51  	"github.com/TTCECO/gttc/metrics"
    52  	"github.com/TTCECO/gttc/node"
    53  	"github.com/TTCECO/gttc/p2p"
    54  	"github.com/TTCECO/gttc/p2p/discover"
    55  	"github.com/TTCECO/gttc/p2p/discv5"
    56  	"github.com/TTCECO/gttc/p2p/nat"
    57  	"github.com/TTCECO/gttc/p2p/netutil"
    58  	"github.com/TTCECO/gttc/params"
    59  	whisper "github.com/TTCECO/gttc/whisper/whisperv6"
    60  	"gopkg.in/urfave/cli.v1"
    61  )
    62  
    63  var (
    64  	CommandHelpTemplate = `{{.cmd.Name}}{{if .cmd.Subcommands}} command{{end}}{{if .cmd.Flags}} [command options]{{end}} [arguments...]
    65  {{if .cmd.Description}}{{.cmd.Description}}
    66  {{end}}{{if .cmd.Subcommands}}
    67  SUBCOMMANDS:
    68  	{{range .cmd.Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
    69  	{{end}}{{end}}{{if .categorizedFlags}}
    70  {{range $idx, $categorized := .categorizedFlags}}{{$categorized.Name}} OPTIONS:
    71  {{range $categorized.Flags}}{{"\t"}}{{.}}
    72  {{end}}
    73  {{end}}{{end}}`
    74  )
    75  
    76  func init() {
    77  	cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
    78  
    79  VERSION:
    80     {{.Version}}
    81  
    82  COMMANDS:
    83     {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
    84     {{end}}{{if .Flags}}
    85  GLOBAL OPTIONS:
    86     {{range .Flags}}{{.}}
    87     {{end}}{{end}}
    88  `
    89  
    90  	cli.CommandHelpTemplate = CommandHelpTemplate
    91  }
    92  
    93  // NewApp creates an app with sane defaults.
    94  func NewApp(gitCommit, usage string) *cli.App {
    95  	app := cli.NewApp()
    96  	app.Name = filepath.Base(os.Args[0])
    97  	app.Author = ""
    98  	//app.Authors = nil
    99  	app.Email = ""
   100  	app.Version = params.Version
   101  	if len(gitCommit) >= 8 {
   102  		app.Version += "-" + gitCommit[:8]
   103  	}
   104  	app.Usage = usage
   105  	return app
   106  }
   107  
   108  // These are all the command line flags we support.
   109  // If you add to this list, please remember to include the
   110  // flag in the appropriate command definition.
   111  //
   112  // The flags are defined here so their names and help texts
   113  // are the same for all commands.
   114  
   115  var (
   116  	// General settings
   117  	DataDirFlag = DirectoryFlag{
   118  		Name:  "datadir",
   119  		Usage: "Data directory for the databases and keystore",
   120  		Value: DirectoryString{node.DefaultDataDir()},
   121  	}
   122  	KeyStoreDirFlag = DirectoryFlag{
   123  		Name:  "keystore",
   124  		Usage: "Directory for the keystore (default = inside the datadir)",
   125  	}
   126  	NoUSBFlag = cli.BoolFlag{
   127  		Name:  "nousb",
   128  		Usage: "Disables monitoring for and managing USB hardware wallets",
   129  	}
   130  	NetworkIdFlag = cli.Uint64Flag{
   131  		Name:  "networkid",
   132  		Usage: "Network identifier (integer, 8848=Mainnet, 8341=Testnet)",
   133  		Value: params.MainnetChainConfig.ChainId.Uint64(),
   134  	}
   135  	TestnetFlag = cli.BoolFlag{
   136  		Name:  "testnet",
   137  		Usage: "TTC test network: pre-configured delegate-proof-of-stake test network",
   138  	}
   139  	RinkebyFlag = cli.BoolFlag{
   140  		Name:  "rinkeby",
   141  		Usage: "Rinkeby network: pre-configured proof-of-authority test network",
   142  	}
   143  	DeveloperFlag = cli.BoolFlag{
   144  		Name:  "dev",
   145  		Usage: "Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled",
   146  	}
   147  	DeveloperPeriodFlag = cli.IntFlag{
   148  		Name:  "dev.period",
   149  		Usage: "Block period to use in developer mode (0 = mine only if transaction pending)",
   150  	}
   151  	IdentityFlag = cli.StringFlag{
   152  		Name:  "identity",
   153  		Usage: "Custom node name",
   154  	}
   155  	DocRootFlag = DirectoryFlag{
   156  		Name:  "docroot",
   157  		Usage: "Document Root for HTTPClient file scheme",
   158  		Value: DirectoryString{homeDir()},
   159  	}
   160  	FastSyncFlag = cli.BoolFlag{
   161  		Name:  "fast",
   162  		Usage: "Enable fast syncing through state downloads (replaced by --syncmode)",
   163  	}
   164  	LightModeFlag = cli.BoolFlag{
   165  		Name:  "light",
   166  		Usage: "Enable light client mode (replaced by --syncmode)",
   167  	}
   168  	defaultSyncMode = eth.DefaultConfig.SyncMode
   169  	SyncModeFlag    = TextMarshalerFlag{
   170  		Name:  "syncmode",
   171  		Usage: `Blockchain sync mode ("fast", "full", or "light")`,
   172  		Value: &defaultSyncMode,
   173  	}
   174  	GCModeFlag = cli.StringFlag{
   175  		Name:  "gcmode",
   176  		Usage: `Blockchain garbage collection mode ("full", "archive")`,
   177  		Value: "full",
   178  	}
   179  	LightServFlag = cli.IntFlag{
   180  		Name:  "lightserv",
   181  		Usage: "Maximum percentage of time allowed for serving LES requests (0-90)",
   182  		Value: 0,
   183  	}
   184  	LightPeersFlag = cli.IntFlag{
   185  		Name:  "lightpeers",
   186  		Usage: "Maximum number of LES client peers",
   187  		Value: eth.DefaultConfig.LightPeers,
   188  	}
   189  	LightKDFFlag = cli.BoolFlag{
   190  		Name:  "lightkdf",
   191  		Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
   192  	}
   193  	// Dashboard settings
   194  	DashboardEnabledFlag = cli.BoolFlag{
   195  		Name:  "dashboard",
   196  		Usage: "Enable the dashboard",
   197  	}
   198  	DashboardAddrFlag = cli.StringFlag{
   199  		Name:  "dashboard.addr",
   200  		Usage: "Dashboard listening interface",
   201  		Value: dashboard.DefaultConfig.Host,
   202  	}
   203  	DashboardPortFlag = cli.IntFlag{
   204  		Name:  "dashboard.host",
   205  		Usage: "Dashboard listening port",
   206  		Value: dashboard.DefaultConfig.Port,
   207  	}
   208  	DashboardRefreshFlag = cli.DurationFlag{
   209  		Name:  "dashboard.refresh",
   210  		Usage: "Dashboard metrics collection refresh rate",
   211  		Value: dashboard.DefaultConfig.Refresh,
   212  	}
   213  	// Ethash settings
   214  	EthashCacheDirFlag = DirectoryFlag{
   215  		Name:  "ethash.cachedir",
   216  		Usage: "Directory to store the ethash verification caches (default = inside the datadir)",
   217  	}
   218  	EthashCachesInMemoryFlag = cli.IntFlag{
   219  		Name:  "ethash.cachesinmem",
   220  		Usage: "Number of recent ethash caches to keep in memory (16MB each)",
   221  		Value: eth.DefaultConfig.Ethash.CachesInMem,
   222  	}
   223  	EthashCachesOnDiskFlag = cli.IntFlag{
   224  		Name:  "ethash.cachesondisk",
   225  		Usage: "Number of recent ethash caches to keep on disk (16MB each)",
   226  		Value: eth.DefaultConfig.Ethash.CachesOnDisk,
   227  	}
   228  	EthashDatasetDirFlag = DirectoryFlag{
   229  		Name:  "ethash.dagdir",
   230  		Usage: "Directory to store the ethash mining DAGs (default = inside home folder)",
   231  		Value: DirectoryString{eth.DefaultConfig.Ethash.DatasetDir},
   232  	}
   233  	EthashDatasetsInMemoryFlag = cli.IntFlag{
   234  		Name:  "ethash.dagsinmem",
   235  		Usage: "Number of recent ethash mining DAGs to keep in memory (1+GB each)",
   236  		Value: eth.DefaultConfig.Ethash.DatasetsInMem,
   237  	}
   238  	EthashDatasetsOnDiskFlag = cli.IntFlag{
   239  		Name:  "ethash.dagsondisk",
   240  		Usage: "Number of recent ethash mining DAGs to keep on disk (1+GB each)",
   241  		Value: eth.DefaultConfig.Ethash.DatasetsOnDisk,
   242  	}
   243  	// Transaction pool settings
   244  	TxPoolNoLocalsFlag = cli.BoolFlag{
   245  		Name:  "txpool.nolocals",
   246  		Usage: "Disables price exemptions for locally submitted transactions",
   247  	}
   248  	TxPoolJournalFlag = cli.StringFlag{
   249  		Name:  "txpool.journal",
   250  		Usage: "Disk journal for local transaction to survive node restarts",
   251  		Value: core.DefaultTxPoolConfig.Journal,
   252  	}
   253  	TxPoolRejournalFlag = cli.DurationFlag{
   254  		Name:  "txpool.rejournal",
   255  		Usage: "Time interval to regenerate the local transaction journal",
   256  		Value: core.DefaultTxPoolConfig.Rejournal,
   257  	}
   258  	TxPoolPriceLimitFlag = cli.Uint64Flag{
   259  		Name:  "txpool.pricelimit",
   260  		Usage: "Minimum gas price limit to enforce for acceptance into the pool",
   261  		Value: eth.DefaultConfig.TxPool.PriceLimit,
   262  	}
   263  	TxPoolPriceBumpFlag = cli.Uint64Flag{
   264  		Name:  "txpool.pricebump",
   265  		Usage: "Price bump percentage to replace an already existing transaction",
   266  		Value: eth.DefaultConfig.TxPool.PriceBump,
   267  	}
   268  	TxPoolAccountSlotsFlag = cli.Uint64Flag{
   269  		Name:  "txpool.accountslots",
   270  		Usage: "Minimum number of executable transaction slots guaranteed per account",
   271  		Value: eth.DefaultConfig.TxPool.AccountSlots,
   272  	}
   273  	TxPoolGlobalSlotsFlag = cli.Uint64Flag{
   274  		Name:  "txpool.globalslots",
   275  		Usage: "Maximum number of executable transaction slots for all accounts",
   276  		Value: eth.DefaultConfig.TxPool.GlobalSlots,
   277  	}
   278  	TxPoolAccountQueueFlag = cli.Uint64Flag{
   279  		Name:  "txpool.accountqueue",
   280  		Usage: "Maximum number of non-executable transaction slots permitted per account",
   281  		Value: eth.DefaultConfig.TxPool.AccountQueue,
   282  	}
   283  	TxPoolGlobalQueueFlag = cli.Uint64Flag{
   284  		Name:  "txpool.globalqueue",
   285  		Usage: "Maximum number of non-executable transaction slots for all accounts",
   286  		Value: eth.DefaultConfig.TxPool.GlobalQueue,
   287  	}
   288  	TxPoolLifetimeFlag = cli.DurationFlag{
   289  		Name:  "txpool.lifetime",
   290  		Usage: "Maximum amount of time non-executable transaction are queued",
   291  		Value: eth.DefaultConfig.TxPool.Lifetime,
   292  	}
   293  	// Performance tuning settings
   294  	CacheFlag = cli.IntFlag{
   295  		Name:  "cache",
   296  		Usage: "Megabytes of memory allocated to internal caching",
   297  		Value: 1024,
   298  	}
   299  	CacheDatabaseFlag = cli.IntFlag{
   300  		Name:  "cache.database",
   301  		Usage: "Percentage of cache memory allowance to use for database io",
   302  		Value: 75,
   303  	}
   304  	CacheGCFlag = cli.IntFlag{
   305  		Name:  "cache.gc",
   306  		Usage: "Percentage of cache memory allowance to use for trie pruning",
   307  		Value: 25,
   308  	}
   309  	TrieCacheGenFlag = cli.IntFlag{
   310  		Name:  "trie-cache-gens",
   311  		Usage: "Number of trie node generations to keep in memory",
   312  		Value: int(state.MaxTrieCacheGen),
   313  	}
   314  	// Miner settings
   315  	MiningEnabledFlag = cli.BoolFlag{
   316  		Name:  "mine",
   317  		Usage: "Enable mining",
   318  	}
   319  	MinerThreadsFlag = cli.IntFlag{
   320  		Name:  "minerthreads",
   321  		Usage: "Number of CPU threads to use for mining",
   322  		Value: runtime.NumCPU(),
   323  	}
   324  	TargetGasLimitFlag = cli.Uint64Flag{
   325  		Name:  "targetgaslimit",
   326  		Usage: "Target gas limit sets the artificial target gas floor for the blocks to mine",
   327  		Value: params.GenesisGasLimit,
   328  	}
   329  	EtherbaseFlag = cli.StringFlag{
   330  		Name:  "etherbase",
   331  		Usage: "Public address for block mining rewards (default = first account created)",
   332  		Value: "0",
   333  	}
   334  	GasPriceFlag = BigFlag{
   335  		Name:  "gasprice",
   336  		Usage: "Minimal gas price to accept for mining a transactions",
   337  		Value: eth.DefaultConfig.GasPrice,
   338  	}
   339  	ExtraDataFlag = cli.StringFlag{
   340  		Name:  "extradata",
   341  		Usage: "Block extra data set by the miner (default = client version)",
   342  	}
   343  	// Account settings
   344  	UnlockedAccountFlag = cli.StringFlag{
   345  		Name:  "unlock",
   346  		Usage: "Comma separated list of accounts to unlock",
   347  		Value: "",
   348  	}
   349  	PasswordFileFlag = cli.StringFlag{
   350  		Name:  "password",
   351  		Usage: "Password file to use for non-interactive password input",
   352  		Value: "",
   353  	}
   354  
   355  	VMEnableDebugFlag = cli.BoolFlag{
   356  		Name:  "vmdebug",
   357  		Usage: "Record information useful for VM and contract debugging",
   358  	}
   359  	// Logging and debug settings
   360  	EthStatsURLFlag = cli.StringFlag{
   361  		Name:  "ethstats",
   362  		Usage: "Reporting URL of a ethstats service (nodename:secret@host:port)",
   363  	}
   364  	MetricsEnabledFlag = cli.BoolFlag{
   365  		Name:  metrics.MetricsEnabledFlag,
   366  		Usage: "Enable metrics collection and reporting",
   367  	}
   368  	FakePoWFlag = cli.BoolFlag{
   369  		Name:  "fakepow",
   370  		Usage: "Disables proof-of-work verification",
   371  	}
   372  	NoCompactionFlag = cli.BoolFlag{
   373  		Name:  "nocompaction",
   374  		Usage: "Disables db compaction after import",
   375  	}
   376  	// RPC settings
   377  	RPCEnabledFlag = cli.BoolFlag{
   378  		Name:  "rpc",
   379  		Usage: "Enable the HTTP-RPC server",
   380  	}
   381  	RPCListenAddrFlag = cli.StringFlag{
   382  		Name:  "rpcaddr",
   383  		Usage: "HTTP-RPC server listening interface",
   384  		Value: node.DefaultHTTPHost,
   385  	}
   386  	RPCPortFlag = cli.IntFlag{
   387  		Name:  "rpcport",
   388  		Usage: "HTTP-RPC server listening port",
   389  		Value: node.DefaultHTTPPort,
   390  	}
   391  	RPCCORSDomainFlag = cli.StringFlag{
   392  		Name:  "rpccorsdomain",
   393  		Usage: "Comma separated list of domains from which to accept cross origin requests (browser enforced)",
   394  		Value: "",
   395  	}
   396  	RPCVirtualHostsFlag = cli.StringFlag{
   397  		Name:  "rpcvhosts",
   398  		Usage: "Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard.",
   399  		Value: strings.Join(node.DefaultConfig.HTTPVirtualHosts, ","),
   400  	}
   401  	RPCApiFlag = cli.StringFlag{
   402  		Name:  "rpcapi",
   403  		Usage: "API's offered over the HTTP-RPC interface",
   404  		Value: "",
   405  	}
   406  	IPCDisabledFlag = cli.BoolFlag{
   407  		Name:  "ipcdisable",
   408  		Usage: "Disable the IPC-RPC server",
   409  	}
   410  	IPCPathFlag = DirectoryFlag{
   411  		Name:  "ipcpath",
   412  		Usage: "Filename for IPC socket/pipe within the datadir (explicit paths escape it)",
   413  	}
   414  	WSEnabledFlag = cli.BoolFlag{
   415  		Name:  "ws",
   416  		Usage: "Enable the WS-RPC server",
   417  	}
   418  	WSListenAddrFlag = cli.StringFlag{
   419  		Name:  "wsaddr",
   420  		Usage: "WS-RPC server listening interface",
   421  		Value: node.DefaultWSHost,
   422  	}
   423  	WSPortFlag = cli.IntFlag{
   424  		Name:  "wsport",
   425  		Usage: "WS-RPC server listening port",
   426  		Value: node.DefaultWSPort,
   427  	}
   428  	WSApiFlag = cli.StringFlag{
   429  		Name:  "wsapi",
   430  		Usage: "API's offered over the WS-RPC interface",
   431  		Value: "",
   432  	}
   433  	WSAllowedOriginsFlag = cli.StringFlag{
   434  		Name:  "wsorigins",
   435  		Usage: "Origins from which to accept websockets requests",
   436  		Value: "",
   437  	}
   438  	ExecFlag = cli.StringFlag{
   439  		Name:  "exec",
   440  		Usage: "Execute JavaScript statement",
   441  	}
   442  	PreloadJSFlag = cli.StringFlag{
   443  		Name:  "preload",
   444  		Usage: "Comma separated list of JavaScript files to preload into the console",
   445  	}
   446  
   447  	// Network Settings
   448  	MaxPeersFlag = cli.IntFlag{
   449  		Name:  "maxpeers",
   450  		Usage: "Maximum number of network peers (network disabled if set to 0)",
   451  		Value: 25,
   452  	}
   453  	MaxPendingPeersFlag = cli.IntFlag{
   454  		Name:  "maxpendpeers",
   455  		Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
   456  		Value: 0,
   457  	}
   458  	ListenPortFlag = cli.IntFlag{
   459  		Name:  "port",
   460  		Usage: "Network listening port",
   461  		Value: 30303,
   462  	}
   463  	BootnodesFlag = cli.StringFlag{
   464  		Name:  "bootnodes",
   465  		Usage: "Comma separated enode URLs for P2P discovery bootstrap (set v4+v5 instead for light servers)",
   466  		Value: "",
   467  	}
   468  	BootnodesV4Flag = cli.StringFlag{
   469  		Name:  "bootnodesv4",
   470  		Usage: "Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes)",
   471  		Value: "",
   472  	}
   473  	BootnodesV5Flag = cli.StringFlag{
   474  		Name:  "bootnodesv5",
   475  		Usage: "Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes)",
   476  		Value: "",
   477  	}
   478  	NodeKeyFileFlag = cli.StringFlag{
   479  		Name:  "nodekey",
   480  		Usage: "P2P node key file",
   481  	}
   482  	NodeKeyHexFlag = cli.StringFlag{
   483  		Name:  "nodekeyhex",
   484  		Usage: "P2P node key as hex (for testing)",
   485  	}
   486  	NATFlag = cli.StringFlag{
   487  		Name:  "nat",
   488  		Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
   489  		Value: "any",
   490  	}
   491  	NoDiscoverFlag = cli.BoolFlag{
   492  		Name:  "nodiscover",
   493  		Usage: "Disables the peer discovery mechanism (manual peer addition)",
   494  	}
   495  	DiscoveryV5Flag = cli.BoolFlag{
   496  		Name:  "v5disc",
   497  		Usage: "Enables the experimental RLPx V5 (Topic Discovery) mechanism",
   498  	}
   499  	NetrestrictFlag = cli.StringFlag{
   500  		Name:  "netrestrict",
   501  		Usage: "Restricts network communication to the given IP networks (CIDR masks)",
   502  	}
   503  
   504  	// ATM the url is left to the user and deployment to
   505  	JSpathFlag = cli.StringFlag{
   506  		Name:  "jspath",
   507  		Usage: "JavaScript root path for `loadScript`",
   508  		Value: ".",
   509  	}
   510  
   511  	// Gas price oracle settings
   512  	GpoBlocksFlag = cli.IntFlag{
   513  		Name:  "gpoblocks",
   514  		Usage: "Number of recent blocks to check for gas prices",
   515  		Value: eth.DefaultConfig.GPO.Blocks,
   516  	}
   517  	GpoPercentileFlag = cli.IntFlag{
   518  		Name:  "gpopercentile",
   519  		Usage: "Suggested gas price is the given percentile of a set of recent transaction gas prices",
   520  		Value: eth.DefaultConfig.GPO.Percentile,
   521  	}
   522  	WhisperEnabledFlag = cli.BoolFlag{
   523  		Name:  "shh",
   524  		Usage: "Enable Whisper",
   525  	}
   526  	WhisperMaxMessageSizeFlag = cli.IntFlag{
   527  		Name:  "shh.maxmessagesize",
   528  		Usage: "Max message size accepted",
   529  		Value: int(whisper.DefaultMaxMessageSize),
   530  	}
   531  	WhisperMinPOWFlag = cli.Float64Flag{
   532  		Name:  "shh.pow",
   533  		Usage: "Minimum POW accepted",
   534  		Value: whisper.DefaultMinimumPoW,
   535  	}
   536  
   537  	// PBFT settings
   538  	PBFTEnableFlag = cli.BoolFlag{
   539  		Name:  "pbft",
   540  		Usage: "PBFT miner coinbase send confirm transaction",
   541  	}
   542  
   543  	// Data side chain settings
   544  	SCAEnableFlag = cli.BoolFlag{
   545  		Name:  "sca",
   546  		Usage: "Side chain for App (dsc)",
   547  	}
   548  	SCAMainRPCAddrFlag = cli.StringFlag{
   549  		Name:  "sca.mainrpcaddr",
   550  		Usage: "Address of main chain ",
   551  		Value: "",
   552  	}
   553  	SCAMainRPCPortFlag = cli.IntFlag{
   554  		Name:  "sca.mainrpcport",
   555  		Usage: "Port of main chain rpc port",
   556  		Value: 0,
   557  	}
   558  	SCAPeriod = cli.IntFlag{
   559  		Name:  "sca.period",
   560  		Usage: "Period of each side chain block",
   561  		Value: 1,
   562  	}
   563  )
   564  
   565  // MakeDataDir retrieves the currently requested data directory, terminating
   566  // if none (or the empty string) is specified. If the node is starting a testnet,
   567  // the a subdirectory of the specified datadir will be used.
   568  func MakeDataDir(ctx *cli.Context) string {
   569  	if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
   570  		if ctx.GlobalBool(TestnetFlag.Name) {
   571  			return filepath.Join(path, "testnet")
   572  		}
   573  		if ctx.GlobalBool(RinkebyFlag.Name) {
   574  			return filepath.Join(path, "rinkeby")
   575  		}
   576  		return path
   577  	}
   578  	Fatalf("Cannot determine default data directory, please set manually (--datadir)")
   579  	return ""
   580  }
   581  
   582  // setNodeKey creates a node key from set command line flags, either loading it
   583  // from a file or as a specified hex value. If neither flags were provided, this
   584  // method returns nil and an emphemeral key is to be generated.
   585  func setNodeKey(ctx *cli.Context, cfg *p2p.Config) {
   586  	var (
   587  		hex  = ctx.GlobalString(NodeKeyHexFlag.Name)
   588  		file = ctx.GlobalString(NodeKeyFileFlag.Name)
   589  		key  *ecdsa.PrivateKey
   590  		err  error
   591  	)
   592  	switch {
   593  	case file != "" && hex != "":
   594  		Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
   595  	case file != "":
   596  		if key, err = crypto.LoadECDSA(file); err != nil {
   597  			Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
   598  		}
   599  		cfg.PrivateKey = key
   600  	case hex != "":
   601  		if key, err = crypto.HexToECDSA(hex); err != nil {
   602  			Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
   603  		}
   604  		cfg.PrivateKey = key
   605  	}
   606  }
   607  
   608  // setNodeUserIdent creates the user identifier from CLI flags.
   609  func setNodeUserIdent(ctx *cli.Context, cfg *node.Config) {
   610  	if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
   611  		cfg.UserIdent = identity
   612  	}
   613  }
   614  
   615  // setBootstrapNodes creates a list of bootstrap nodes from the command line
   616  // flags, reverting to pre-configured ones if none have been specified.
   617  func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) {
   618  	urls := params.MainnetBootnodes
   619  	switch {
   620  	case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV4Flag.Name):
   621  		if ctx.GlobalIsSet(BootnodesV4Flag.Name) {
   622  			urls = strings.Split(ctx.GlobalString(BootnodesV4Flag.Name), ",")
   623  		} else {
   624  			urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
   625  		}
   626  	case ctx.GlobalBool(TestnetFlag.Name):
   627  		urls = params.TestnetBootnodes
   628  	case ctx.GlobalBool(RinkebyFlag.Name):
   629  		urls = params.RinkebyBootnodes
   630  	case cfg.BootstrapNodes != nil:
   631  		return // already set, don't apply defaults.
   632  	}
   633  
   634  	cfg.BootstrapNodes = make([]*discover.Node, 0, len(urls))
   635  	for _, url := range urls {
   636  		node, err := discover.ParseNode(url)
   637  		if err != nil {
   638  			log.Error("Bootstrap URL invalid", "enode", url, "err", err)
   639  			continue
   640  		}
   641  		cfg.BootstrapNodes = append(cfg.BootstrapNodes, node)
   642  	}
   643  }
   644  
   645  // setBootstrapNodesV5 creates a list of bootstrap nodes from the command line
   646  // flags, reverting to pre-configured ones if none have been specified.
   647  func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) {
   648  	urls := params.DiscoveryV5Bootnodes
   649  	switch {
   650  	case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV5Flag.Name):
   651  		if ctx.GlobalIsSet(BootnodesV5Flag.Name) {
   652  			urls = strings.Split(ctx.GlobalString(BootnodesV5Flag.Name), ",")
   653  		} else {
   654  			urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
   655  		}
   656  	case ctx.GlobalBool(RinkebyFlag.Name):
   657  		urls = params.RinkebyBootnodes
   658  	case cfg.BootstrapNodesV5 != nil:
   659  		return // already set, don't apply defaults.
   660  	}
   661  
   662  	cfg.BootstrapNodesV5 = make([]*discv5.Node, 0, len(urls))
   663  	for _, url := range urls {
   664  		node, err := discv5.ParseNode(url)
   665  		if err != nil {
   666  			log.Error("Bootstrap URL invalid", "enode", url, "err", err)
   667  			continue
   668  		}
   669  		cfg.BootstrapNodesV5 = append(cfg.BootstrapNodesV5, node)
   670  	}
   671  }
   672  
   673  // setListenAddress creates a TCP listening address string from set command
   674  // line flags.
   675  func setListenAddress(ctx *cli.Context, cfg *p2p.Config) {
   676  	if ctx.GlobalIsSet(ListenPortFlag.Name) {
   677  		cfg.ListenAddr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
   678  	}
   679  }
   680  
   681  // setNAT creates a port mapper from command line flags.
   682  func setNAT(ctx *cli.Context, cfg *p2p.Config) {
   683  	if ctx.GlobalIsSet(NATFlag.Name) {
   684  		natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
   685  		if err != nil {
   686  			Fatalf("Option %s: %v", NATFlag.Name, err)
   687  		}
   688  		cfg.NAT = natif
   689  	}
   690  }
   691  
   692  // splitAndTrim splits input separated by a comma
   693  // and trims excessive white space from the substrings.
   694  func splitAndTrim(input string) []string {
   695  	result := strings.Split(input, ",")
   696  	for i, r := range result {
   697  		result[i] = strings.TrimSpace(r)
   698  	}
   699  	return result
   700  }
   701  
   702  // setHTTP creates the HTTP RPC listener interface string from the set
   703  // command line flags, returning empty if the HTTP endpoint is disabled.
   704  func setHTTP(ctx *cli.Context, cfg *node.Config) {
   705  	if ctx.GlobalBool(RPCEnabledFlag.Name) && cfg.HTTPHost == "" {
   706  		cfg.HTTPHost = "127.0.0.1"
   707  		if ctx.GlobalIsSet(RPCListenAddrFlag.Name) {
   708  			cfg.HTTPHost = ctx.GlobalString(RPCListenAddrFlag.Name)
   709  		}
   710  	}
   711  
   712  	if ctx.GlobalIsSet(RPCPortFlag.Name) {
   713  		cfg.HTTPPort = ctx.GlobalInt(RPCPortFlag.Name)
   714  	}
   715  	if ctx.GlobalIsSet(RPCCORSDomainFlag.Name) {
   716  		cfg.HTTPCors = splitAndTrim(ctx.GlobalString(RPCCORSDomainFlag.Name))
   717  	}
   718  	if ctx.GlobalIsSet(RPCApiFlag.Name) {
   719  		cfg.HTTPModules = splitAndTrim(ctx.GlobalString(RPCApiFlag.Name))
   720  	}
   721  	if ctx.GlobalIsSet(RPCVirtualHostsFlag.Name) {
   722  		cfg.HTTPVirtualHosts = splitAndTrim(ctx.GlobalString(RPCVirtualHostsFlag.Name))
   723  	}
   724  }
   725  
   726  // setWS creates the WebSocket RPC listener interface string from the set
   727  // command line flags, returning empty if the HTTP endpoint is disabled.
   728  func setWS(ctx *cli.Context, cfg *node.Config) {
   729  	if ctx.GlobalBool(WSEnabledFlag.Name) && cfg.WSHost == "" {
   730  		cfg.WSHost = "127.0.0.1"
   731  		if ctx.GlobalIsSet(WSListenAddrFlag.Name) {
   732  			cfg.WSHost = ctx.GlobalString(WSListenAddrFlag.Name)
   733  		}
   734  	}
   735  
   736  	if ctx.GlobalIsSet(WSPortFlag.Name) {
   737  		cfg.WSPort = ctx.GlobalInt(WSPortFlag.Name)
   738  	}
   739  	if ctx.GlobalIsSet(WSAllowedOriginsFlag.Name) {
   740  		cfg.WSOrigins = splitAndTrim(ctx.GlobalString(WSAllowedOriginsFlag.Name))
   741  	}
   742  	if ctx.GlobalIsSet(WSApiFlag.Name) {
   743  		cfg.WSModules = splitAndTrim(ctx.GlobalString(WSApiFlag.Name))
   744  	}
   745  }
   746  
   747  // setIPC creates an IPC path configuration from the set command line flags,
   748  // returning an empty string if IPC was explicitly disabled, or the set path.
   749  func setIPC(ctx *cli.Context, cfg *node.Config) {
   750  	checkExclusive(ctx, IPCDisabledFlag, IPCPathFlag)
   751  	switch {
   752  	case ctx.GlobalBool(IPCDisabledFlag.Name):
   753  		cfg.IPCPath = ""
   754  	case ctx.GlobalIsSet(IPCPathFlag.Name):
   755  		cfg.IPCPath = ctx.GlobalString(IPCPathFlag.Name)
   756  	}
   757  }
   758  
   759  // makeDatabaseHandles raises out the number of allowed file handles per process
   760  // for Geth and returns half of the allowance to assign to the database.
   761  func makeDatabaseHandles() int {
   762  	limit, err := fdlimit.Current()
   763  	if err != nil {
   764  		Fatalf("Failed to retrieve file descriptor allowance: %v", err)
   765  	}
   766  	if limit < 2048 {
   767  		if err := fdlimit.Raise(2048); err != nil {
   768  			Fatalf("Failed to raise file descriptor allowance: %v", err)
   769  		}
   770  	}
   771  	if limit > 2048 { // cap database file descriptors even if more is available
   772  		limit = 2048
   773  	}
   774  	return limit / 2 // Leave half for networking and other stuff
   775  }
   776  
   777  // MakeAddress converts an account specified directly as a hex encoded string or
   778  // a key index in the key store to an internal account representation.
   779  func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) {
   780  	// If the specified account is a valid address, return it
   781  	if common.IsHexAddress(account) {
   782  		return accounts.Account{Address: common.HexToAddress(account)}, nil
   783  	}
   784  	// Otherwise try to interpret the account as a keystore index
   785  	index, err := strconv.Atoi(account)
   786  	if err != nil || index < 0 {
   787  		return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account)
   788  	}
   789  	log.Warn("-------------------------------------------------------------------")
   790  	log.Warn("Referring to accounts by order in the keystore folder is dangerous!")
   791  	log.Warn("This functionality is deprecated and will be removed in the future!")
   792  	log.Warn("Please use explicit addresses! (can search via `geth account list`)")
   793  	log.Warn("-------------------------------------------------------------------")
   794  
   795  	accs := ks.Accounts()
   796  	if len(accs) <= index {
   797  		return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs))
   798  	}
   799  	return accs[index], nil
   800  }
   801  
   802  // setEtherbase retrieves the etherbase either from the directly specified
   803  // command line flags or from the keystore if CLI indexed.
   804  func setEtherbase(ctx *cli.Context, ks *keystore.KeyStore, cfg *eth.Config) {
   805  	if ctx.GlobalIsSet(EtherbaseFlag.Name) {
   806  		account, err := MakeAddress(ks, ctx.GlobalString(EtherbaseFlag.Name))
   807  		if err != nil {
   808  			Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
   809  		}
   810  		cfg.Etherbase = account.Address
   811  	}
   812  }
   813  
   814  // MakePasswordList reads password lines from the file specified by the global --password flag.
   815  func MakePasswordList(ctx *cli.Context) []string {
   816  	path := ctx.GlobalString(PasswordFileFlag.Name)
   817  	if path == "" {
   818  		return nil
   819  	}
   820  	text, err := ioutil.ReadFile(path)
   821  	if err != nil {
   822  		Fatalf("Failed to read password file: %v", err)
   823  	}
   824  	lines := strings.Split(string(text), "\n")
   825  	// Sanitise DOS line endings.
   826  	for i := range lines {
   827  		lines[i] = strings.TrimRight(lines[i], "\r")
   828  	}
   829  	return lines
   830  }
   831  
   832  func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) {
   833  	setNodeKey(ctx, cfg)
   834  	setNAT(ctx, cfg)
   835  	setListenAddress(ctx, cfg)
   836  	setBootstrapNodes(ctx, cfg)
   837  	setBootstrapNodesV5(ctx, cfg)
   838  
   839  	lightClient := ctx.GlobalBool(LightModeFlag.Name) || ctx.GlobalString(SyncModeFlag.Name) == "light"
   840  	lightServer := ctx.GlobalInt(LightServFlag.Name) != 0
   841  	lightPeers := ctx.GlobalInt(LightPeersFlag.Name)
   842  
   843  	if ctx.GlobalIsSet(MaxPeersFlag.Name) {
   844  		cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name)
   845  		if lightServer && !ctx.GlobalIsSet(LightPeersFlag.Name) {
   846  			cfg.MaxPeers += lightPeers
   847  		}
   848  	} else {
   849  		if lightServer {
   850  			cfg.MaxPeers += lightPeers
   851  		}
   852  		if lightClient && ctx.GlobalIsSet(LightPeersFlag.Name) && cfg.MaxPeers < lightPeers {
   853  			cfg.MaxPeers = lightPeers
   854  		}
   855  	}
   856  	if !(lightClient || lightServer) {
   857  		lightPeers = 0
   858  	}
   859  	ethPeers := cfg.MaxPeers - lightPeers
   860  	if lightClient {
   861  		ethPeers = 0
   862  	}
   863  	log.Info("Maximum peer count", "ETH", ethPeers, "LES", lightPeers, "total", cfg.MaxPeers)
   864  
   865  	if ctx.GlobalIsSet(MaxPendingPeersFlag.Name) {
   866  		cfg.MaxPendingPeers = ctx.GlobalInt(MaxPendingPeersFlag.Name)
   867  	}
   868  	if ctx.GlobalIsSet(NoDiscoverFlag.Name) || lightClient {
   869  		cfg.NoDiscovery = true
   870  	}
   871  
   872  	// if we're running a light client or server, force enable the v5 peer discovery
   873  	// unless it is explicitly disabled with --nodiscover note that explicitly specifying
   874  	// --v5disc overrides --nodiscover, in which case the later only disables v4 discovery
   875  	forceV5Discovery := (lightClient || lightServer) && !ctx.GlobalBool(NoDiscoverFlag.Name)
   876  	if ctx.GlobalIsSet(DiscoveryV5Flag.Name) {
   877  		cfg.DiscoveryV5 = ctx.GlobalBool(DiscoveryV5Flag.Name)
   878  	} else if forceV5Discovery {
   879  		cfg.DiscoveryV5 = true
   880  	}
   881  
   882  	if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" {
   883  		list, err := netutil.ParseNetlist(netrestrict)
   884  		if err != nil {
   885  			Fatalf("Option %q: %v", NetrestrictFlag.Name, err)
   886  		}
   887  		cfg.NetRestrict = list
   888  	}
   889  
   890  	if ctx.GlobalBool(DeveloperFlag.Name) {
   891  		// --dev mode can't use p2p networking.
   892  		cfg.MaxPeers = 0
   893  		cfg.ListenAddr = ":0"
   894  		cfg.NoDiscovery = true
   895  		cfg.DiscoveryV5 = false
   896  	}
   897  }
   898  
   899  // SetNodeConfig applies node-related command line flags to the config.
   900  func SetNodeConfig(ctx *cli.Context, cfg *node.Config) {
   901  	SetP2PConfig(ctx, &cfg.P2P)
   902  	setIPC(ctx, cfg)
   903  	setHTTP(ctx, cfg)
   904  	setWS(ctx, cfg)
   905  	setNodeUserIdent(ctx, cfg)
   906  
   907  	switch {
   908  	case ctx.GlobalIsSet(DataDirFlag.Name):
   909  		cfg.DataDir = ctx.GlobalString(DataDirFlag.Name)
   910  	case ctx.GlobalBool(DeveloperFlag.Name):
   911  		cfg.DataDir = "" // unless explicitly requested, use memory databases
   912  	case ctx.GlobalBool(TestnetFlag.Name):
   913  		cfg.DataDir = filepath.Join(node.DefaultDataDir(), "testnet")
   914  	case ctx.GlobalBool(RinkebyFlag.Name):
   915  		cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby")
   916  	}
   917  
   918  	if ctx.GlobalIsSet(KeyStoreDirFlag.Name) {
   919  		cfg.KeyStoreDir = ctx.GlobalString(KeyStoreDirFlag.Name)
   920  	}
   921  	if ctx.GlobalIsSet(LightKDFFlag.Name) {
   922  		cfg.UseLightweightKDF = ctx.GlobalBool(LightKDFFlag.Name)
   923  	}
   924  	if ctx.GlobalIsSet(NoUSBFlag.Name) {
   925  		cfg.NoUSB = ctx.GlobalBool(NoUSBFlag.Name)
   926  	}
   927  }
   928  
   929  func setGPO(ctx *cli.Context, cfg *gasprice.Config) {
   930  	if ctx.GlobalIsSet(GpoBlocksFlag.Name) {
   931  		cfg.Blocks = ctx.GlobalInt(GpoBlocksFlag.Name)
   932  	}
   933  	if ctx.GlobalIsSet(GpoPercentileFlag.Name) {
   934  		cfg.Percentile = ctx.GlobalInt(GpoPercentileFlag.Name)
   935  	}
   936  }
   937  
   938  func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) {
   939  	if ctx.GlobalIsSet(TxPoolNoLocalsFlag.Name) {
   940  		cfg.NoLocals = ctx.GlobalBool(TxPoolNoLocalsFlag.Name)
   941  	}
   942  	if ctx.GlobalIsSet(TxPoolJournalFlag.Name) {
   943  		cfg.Journal = ctx.GlobalString(TxPoolJournalFlag.Name)
   944  	}
   945  	if ctx.GlobalIsSet(TxPoolRejournalFlag.Name) {
   946  		cfg.Rejournal = ctx.GlobalDuration(TxPoolRejournalFlag.Name)
   947  	}
   948  	if ctx.GlobalIsSet(TxPoolPriceLimitFlag.Name) {
   949  		cfg.PriceLimit = ctx.GlobalUint64(TxPoolPriceLimitFlag.Name)
   950  	}
   951  	if ctx.GlobalIsSet(TxPoolPriceBumpFlag.Name) {
   952  		cfg.PriceBump = ctx.GlobalUint64(TxPoolPriceBumpFlag.Name)
   953  	}
   954  	if ctx.GlobalIsSet(TxPoolAccountSlotsFlag.Name) {
   955  		cfg.AccountSlots = ctx.GlobalUint64(TxPoolAccountSlotsFlag.Name)
   956  	}
   957  	if ctx.GlobalIsSet(TxPoolGlobalSlotsFlag.Name) {
   958  		cfg.GlobalSlots = ctx.GlobalUint64(TxPoolGlobalSlotsFlag.Name)
   959  	}
   960  	if ctx.GlobalIsSet(TxPoolAccountQueueFlag.Name) {
   961  		cfg.AccountQueue = ctx.GlobalUint64(TxPoolAccountQueueFlag.Name)
   962  	}
   963  	if ctx.GlobalIsSet(TxPoolGlobalQueueFlag.Name) {
   964  		cfg.GlobalQueue = ctx.GlobalUint64(TxPoolGlobalQueueFlag.Name)
   965  	}
   966  	if ctx.GlobalIsSet(TxPoolLifetimeFlag.Name) {
   967  		cfg.Lifetime = ctx.GlobalDuration(TxPoolLifetimeFlag.Name)
   968  	}
   969  }
   970  
   971  func setEthash(ctx *cli.Context, cfg *eth.Config) {
   972  	if ctx.GlobalIsSet(EthashCacheDirFlag.Name) {
   973  		cfg.Ethash.CacheDir = ctx.GlobalString(EthashCacheDirFlag.Name)
   974  	}
   975  	if ctx.GlobalIsSet(EthashDatasetDirFlag.Name) {
   976  		cfg.Ethash.DatasetDir = ctx.GlobalString(EthashDatasetDirFlag.Name)
   977  	}
   978  	if ctx.GlobalIsSet(EthashCachesInMemoryFlag.Name) {
   979  		cfg.Ethash.CachesInMem = ctx.GlobalInt(EthashCachesInMemoryFlag.Name)
   980  	}
   981  	if ctx.GlobalIsSet(EthashCachesOnDiskFlag.Name) {
   982  		cfg.Ethash.CachesOnDisk = ctx.GlobalInt(EthashCachesOnDiskFlag.Name)
   983  	}
   984  	if ctx.GlobalIsSet(EthashDatasetsInMemoryFlag.Name) {
   985  		cfg.Ethash.DatasetsInMem = ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name)
   986  	}
   987  	if ctx.GlobalIsSet(EthashDatasetsOnDiskFlag.Name) {
   988  		cfg.Ethash.DatasetsOnDisk = ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name)
   989  	}
   990  }
   991  
   992  // checkExclusive verifies that only a single isntance of the provided flags was
   993  // set by the user. Each flag might optionally be followed by a string type to
   994  // specialize it further.
   995  func checkExclusive(ctx *cli.Context, args ...interface{}) {
   996  	set := make([]string, 0, 1)
   997  	for i := 0; i < len(args); i++ {
   998  		// Make sure the next argument is a flag and skip if not set
   999  		flag, ok := args[i].(cli.Flag)
  1000  		if !ok {
  1001  			panic(fmt.Sprintf("invalid argument, not cli.Flag type: %T", args[i]))
  1002  		}
  1003  		// Check if next arg extends current and expand its name if so
  1004  		name := flag.GetName()
  1005  
  1006  		if i+1 < len(args) {
  1007  			switch option := args[i+1].(type) {
  1008  			case string:
  1009  				// Extended flag check, make sure value set doesn't conflict with passed in option
  1010  				if ctx.GlobalString(flag.GetName()) == option {
  1011  					name += "=" + option
  1012  					set = append(set, "--"+name)
  1013  				}
  1014  				// shift arguments and continue
  1015  				i++
  1016  				continue
  1017  
  1018  			case cli.Flag:
  1019  			default:
  1020  				panic(fmt.Sprintf("invalid argument, not cli.Flag or string extension: %T", args[i+1]))
  1021  			}
  1022  		}
  1023  		// Mark the flag if it's set
  1024  		if ctx.GlobalIsSet(flag.GetName()) {
  1025  			set = append(set, "--"+name)
  1026  		}
  1027  	}
  1028  	if len(set) > 1 {
  1029  		Fatalf("Flags %v can't be used at the same time", strings.Join(set, ", "))
  1030  	}
  1031  }
  1032  
  1033  // SetShhConfig applies shh-related command line flags to the config.
  1034  func SetShhConfig(ctx *cli.Context, stack *node.Node, cfg *whisper.Config) {
  1035  	if ctx.GlobalIsSet(WhisperMaxMessageSizeFlag.Name) {
  1036  		cfg.MaxMessageSize = uint32(ctx.GlobalUint(WhisperMaxMessageSizeFlag.Name))
  1037  	}
  1038  	if ctx.GlobalIsSet(WhisperMinPOWFlag.Name) {
  1039  		cfg.MinimumAcceptedPOW = ctx.GlobalFloat64(WhisperMinPOWFlag.Name)
  1040  	}
  1041  }
  1042  
  1043  // SetEthConfig applies eth-related command line flags to the config.
  1044  func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
  1045  	// Avoid conflicting network flags
  1046  	checkExclusive(ctx, DeveloperFlag, TestnetFlag, RinkebyFlag)
  1047  	checkExclusive(ctx, FastSyncFlag, LightModeFlag, SyncModeFlag)
  1048  	checkExclusive(ctx, LightServFlag, LightModeFlag)
  1049  	checkExclusive(ctx, LightServFlag, SyncModeFlag, "light")
  1050  
  1051  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  1052  	setEtherbase(ctx, ks, cfg)
  1053  	setGPO(ctx, &cfg.GPO)
  1054  	setTxPool(ctx, &cfg.TxPool)
  1055  	setEthash(ctx, cfg)
  1056  
  1057  	switch {
  1058  	case ctx.GlobalIsSet(SyncModeFlag.Name):
  1059  		cfg.SyncMode = *GlobalTextMarshaler(ctx, SyncModeFlag.Name).(*downloader.SyncMode)
  1060  	case ctx.GlobalBool(FastSyncFlag.Name):
  1061  		cfg.SyncMode = downloader.FastSync
  1062  	case ctx.GlobalBool(LightModeFlag.Name):
  1063  		cfg.SyncMode = downloader.LightSync
  1064  	}
  1065  	if ctx.GlobalIsSet(LightServFlag.Name) {
  1066  		cfg.LightServ = ctx.GlobalInt(LightServFlag.Name)
  1067  	}
  1068  	if ctx.GlobalIsSet(LightPeersFlag.Name) {
  1069  		cfg.LightPeers = ctx.GlobalInt(LightPeersFlag.Name)
  1070  	}
  1071  	if ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1072  		cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name)
  1073  	}
  1074  
  1075  	if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheDatabaseFlag.Name) {
  1076  		cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
  1077  	}
  1078  	cfg.DatabaseHandles = makeDatabaseHandles()
  1079  
  1080  	if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
  1081  		Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
  1082  	}
  1083  	cfg.NoPruning = ctx.GlobalString(GCModeFlag.Name) == "archive"
  1084  
  1085  	if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
  1086  		cfg.TrieCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
  1087  	}
  1088  	if ctx.GlobalIsSet(MinerThreadsFlag.Name) {
  1089  		cfg.MinerThreads = ctx.GlobalInt(MinerThreadsFlag.Name)
  1090  	}
  1091  	if ctx.GlobalIsSet(DocRootFlag.Name) {
  1092  		cfg.DocRoot = ctx.GlobalString(DocRootFlag.Name)
  1093  	}
  1094  	if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  1095  		cfg.ExtraData = []byte(ctx.GlobalString(ExtraDataFlag.Name))
  1096  	}
  1097  	if ctx.GlobalIsSet(GasPriceFlag.Name) {
  1098  		cfg.GasPrice = GlobalBig(ctx, GasPriceFlag.Name)
  1099  	}
  1100  	if ctx.GlobalIsSet(VMEnableDebugFlag.Name) {
  1101  		// TODO(fjl): force-enable this in --dev mode
  1102  		cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name)
  1103  	}
  1104  
  1105  	// Override any default configs for hard coded networks.
  1106  	switch {
  1107  	case ctx.GlobalBool(TestnetFlag.Name):
  1108  		if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1109  			cfg.NetworkId = 8341
  1110  		}
  1111  		cfg.SyncMode = downloader.FullSync
  1112  		cfg.Genesis = core.DefaultTestnetGenesisBlock()
  1113  	case ctx.GlobalBool(RinkebyFlag.Name):
  1114  		if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1115  			cfg.NetworkId = 4
  1116  		}
  1117  		cfg.Genesis = core.DefaultRinkebyGenesisBlock()
  1118  	case ctx.GlobalBool(DeveloperFlag.Name):
  1119  		// Create new developer account or reuse existing one
  1120  		var (
  1121  			developer accounts.Account
  1122  			err       error
  1123  		)
  1124  		if accs := ks.Accounts(); len(accs) > 0 {
  1125  			developer = ks.Accounts()[0]
  1126  		} else {
  1127  			developer, err = ks.NewAccount("")
  1128  			if err != nil {
  1129  				Fatalf("Failed to create developer account: %v", err)
  1130  			}
  1131  		}
  1132  		if err := ks.Unlock(developer, ""); err != nil {
  1133  			Fatalf("Failed to unlock developer account: %v", err)
  1134  		}
  1135  		log.Info("Using developer account", "address", developer.Address)
  1136  
  1137  		cfg.Genesis = core.DeveloperGenesisBlock(uint64(ctx.GlobalInt(DeveloperPeriodFlag.Name)), developer.Address)
  1138  		if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  1139  			cfg.GasPrice = big.NewInt(1)
  1140  		}
  1141  	}
  1142  	// TODO(fjl): move trie cache generations into config
  1143  	if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  1144  		state.MaxTrieCacheGen = uint16(gen)
  1145  	}
  1146  }
  1147  
  1148  // SetDashboardConfig applies dashboard related command line flags to the config.
  1149  func SetDashboardConfig(ctx *cli.Context, cfg *dashboard.Config) {
  1150  	cfg.Host = ctx.GlobalString(DashboardAddrFlag.Name)
  1151  	cfg.Port = ctx.GlobalInt(DashboardPortFlag.Name)
  1152  	cfg.Refresh = ctx.GlobalDuration(DashboardRefreshFlag.Name)
  1153  }
  1154  
  1155  // RegisterEthService adds an Ethereum client to the stack.
  1156  func RegisterEthService(stack *node.Node, cfg *eth.Config) {
  1157  	var err error
  1158  	if cfg.SyncMode == downloader.LightSync {
  1159  		err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1160  			return les.New(ctx, cfg)
  1161  		})
  1162  	} else {
  1163  		err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1164  			fullNode, err := eth.New(ctx, cfg)
  1165  			if fullNode != nil && cfg.LightServ > 0 {
  1166  				ls, _ := les.NewLesServer(fullNode, cfg)
  1167  				fullNode.AddLesServer(ls)
  1168  			}
  1169  			return fullNode, err
  1170  		})
  1171  	}
  1172  	if err != nil {
  1173  		Fatalf("Failed to register the Ethereum service: %v", err)
  1174  	}
  1175  }
  1176  
  1177  // RegisterDashboardService adds a dashboard to the stack.
  1178  func RegisterDashboardService(stack *node.Node, cfg *dashboard.Config, commit string) {
  1179  	stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1180  		return dashboard.New(cfg, commit)
  1181  	})
  1182  }
  1183  
  1184  // RegisterShhService configures Whisper and adds it to the given node.
  1185  func RegisterShhService(stack *node.Node, cfg *whisper.Config) {
  1186  	if err := stack.Register(func(n *node.ServiceContext) (node.Service, error) {
  1187  		return whisper.New(cfg), nil
  1188  	}); err != nil {
  1189  		Fatalf("Failed to register the Whisper service: %v", err)
  1190  	}
  1191  }
  1192  
  1193  // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  1194  // th egiven node.
  1195  func RegisterEthStatsService(stack *node.Node, url string) {
  1196  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1197  		// Retrieve both eth and les services
  1198  		var ethServ *eth.Ethereum
  1199  		ctx.Service(&ethServ)
  1200  
  1201  		var lesServ *les.LightEthereum
  1202  		ctx.Service(&lesServ)
  1203  
  1204  		return ethstats.New(url, ethServ, lesServ)
  1205  	}); err != nil {
  1206  		Fatalf("Failed to register the Ethereum Stats service: %v", err)
  1207  	}
  1208  }
  1209  
  1210  // SetupNetwork configures the system for either the main net or some test network.
  1211  func SetupNetwork(ctx *cli.Context) {
  1212  	// TODO(fjl): move target gas limit into config
  1213  	params.TargetGasLimit = ctx.GlobalUint64(TargetGasLimitFlag.Name)
  1214  }
  1215  
  1216  // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  1217  func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  1218  	var (
  1219  		cache   = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
  1220  		handles = makeDatabaseHandles()
  1221  	)
  1222  	name := "chaindata"
  1223  	if ctx.GlobalBool(LightModeFlag.Name) {
  1224  		name = "lightchaindata"
  1225  	}
  1226  	chainDb, err := stack.OpenDatabase(name, cache, handles)
  1227  	if err != nil {
  1228  		Fatalf("Could not open database: %v", err)
  1229  	}
  1230  	return chainDb
  1231  }
  1232  
  1233  func MakeGenesis(ctx *cli.Context) *core.Genesis {
  1234  	var genesis *core.Genesis
  1235  	switch {
  1236  	case ctx.GlobalBool(TestnetFlag.Name):
  1237  		genesis = core.DefaultTestnetGenesisBlock()
  1238  	case ctx.GlobalBool(RinkebyFlag.Name):
  1239  		genesis = core.DefaultRinkebyGenesisBlock()
  1240  	case ctx.GlobalBool(DeveloperFlag.Name):
  1241  		Fatalf("Developer chains are ephemeral")
  1242  	}
  1243  	return genesis
  1244  }
  1245  
  1246  // MakeChain creates a chain manager from set command line flags.
  1247  func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  1248  	var err error
  1249  	chainDb = MakeChainDatabase(ctx, stack)
  1250  
  1251  	config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx))
  1252  	if err != nil {
  1253  		Fatalf("%v", err)
  1254  	}
  1255  	var engine consensus.Engine
  1256  	if config.Clique != nil {
  1257  		engine = clique.New(config.Clique, chainDb)
  1258  	} else if config.Alien != nil {
  1259  		engine = alien.New(config.Alien, chainDb)
  1260  
  1261  	} else {
  1262  		engine = ethash.NewFaker()
  1263  		if !ctx.GlobalBool(FakePoWFlag.Name) {
  1264  			engine = ethash.New(ethash.Config{
  1265  				CacheDir:       stack.ResolvePath(eth.DefaultConfig.Ethash.CacheDir),
  1266  				CachesInMem:    eth.DefaultConfig.Ethash.CachesInMem,
  1267  				CachesOnDisk:   eth.DefaultConfig.Ethash.CachesOnDisk,
  1268  				DatasetDir:     stack.ResolvePath(eth.DefaultConfig.Ethash.DatasetDir),
  1269  				DatasetsInMem:  eth.DefaultConfig.Ethash.DatasetsInMem,
  1270  				DatasetsOnDisk: eth.DefaultConfig.Ethash.DatasetsOnDisk,
  1271  			})
  1272  		}
  1273  	}
  1274  	if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
  1275  		Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
  1276  	}
  1277  	cache := &core.CacheConfig{
  1278  		Disabled:      ctx.GlobalString(GCModeFlag.Name) == "archive",
  1279  		TrieNodeLimit: eth.DefaultConfig.TrieCache,
  1280  		TrieTimeLimit: eth.DefaultConfig.TrieTimeout,
  1281  	}
  1282  	if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
  1283  		cache.TrieNodeLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
  1284  	}
  1285  	vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
  1286  	chain, err = core.NewBlockChain(chainDb, cache, config, engine, vmcfg)
  1287  	if err != nil {
  1288  		Fatalf("Can't create BlockChain: %v", err)
  1289  	}
  1290  	return chain, chainDb
  1291  }
  1292  
  1293  // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  1294  // scripts to preload before starting.
  1295  func MakeConsolePreloads(ctx *cli.Context) []string {
  1296  	// Skip preloading if there's nothing to preload
  1297  	if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  1298  		return nil
  1299  	}
  1300  	// Otherwise resolve absolute paths and return them
  1301  	preloads := []string{}
  1302  
  1303  	assets := ctx.GlobalString(JSpathFlag.Name)
  1304  	for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  1305  		preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  1306  	}
  1307  	return preloads
  1308  }
  1309  
  1310  // MigrateFlags sets the global flag from a local flag when it's set.
  1311  // This is a temporary function used for migrating old command/flags to the
  1312  // new format.
  1313  //
  1314  // e.g. geth account new --keystore /tmp/mykeystore --lightkdf
  1315  //
  1316  // is equivalent after calling this method with:
  1317  //
  1318  // geth --keystore /tmp/mykeystore --lightkdf account new
  1319  //
  1320  // This allows the use of the existing configuration functionality.
  1321  // When all flags are migrated this function can be removed and the existing
  1322  // configuration functionality must be changed that is uses local flags
  1323  func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error {
  1324  	return func(ctx *cli.Context) error {
  1325  		for _, name := range ctx.FlagNames() {
  1326  			if ctx.IsSet(name) {
  1327  				ctx.GlobalSet(name, ctx.String(name))
  1328  			}
  1329  		}
  1330  		return action(ctx)
  1331  	}
  1332  }