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