github.com/daragao/go-ethereum@v1.8.14-0.20180809141559-45eaef243198/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.VersionWithMeta
   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:  metrics.DashboardEnabledFlag,
   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.Crit("Bootstrap URL invalid", "enode", url, "err", err)
   648  		}
   649  		cfg.BootstrapNodes = append(cfg.BootstrapNodes, node)
   650  	}
   651  }
   652  
   653  // setBootstrapNodesV5 creates a list of bootstrap nodes from the command line
   654  // flags, reverting to pre-configured ones if none have been specified.
   655  func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) {
   656  	urls := params.DiscoveryV5Bootnodes
   657  	switch {
   658  	case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV5Flag.Name):
   659  		if ctx.GlobalIsSet(BootnodesV5Flag.Name) {
   660  			urls = strings.Split(ctx.GlobalString(BootnodesV5Flag.Name), ",")
   661  		} else {
   662  			urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
   663  		}
   664  	case ctx.GlobalBool(RinkebyFlag.Name):
   665  		urls = params.RinkebyBootnodes
   666  	case cfg.BootstrapNodesV5 != nil:
   667  		return // already set, don't apply defaults.
   668  	}
   669  
   670  	cfg.BootstrapNodesV5 = make([]*discv5.Node, 0, len(urls))
   671  	for _, url := range urls {
   672  		node, err := discv5.ParseNode(url)
   673  		if err != nil {
   674  			log.Error("Bootstrap URL invalid", "enode", url, "err", err)
   675  			continue
   676  		}
   677  		cfg.BootstrapNodesV5 = append(cfg.BootstrapNodesV5, node)
   678  	}
   679  }
   680  
   681  // setListenAddress creates a TCP listening address string from set command
   682  // line flags.
   683  func setListenAddress(ctx *cli.Context, cfg *p2p.Config) {
   684  	if ctx.GlobalIsSet(ListenPortFlag.Name) {
   685  		cfg.ListenAddr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
   686  	}
   687  }
   688  
   689  // setNAT creates a port mapper from command line flags.
   690  func setNAT(ctx *cli.Context, cfg *p2p.Config) {
   691  	if ctx.GlobalIsSet(NATFlag.Name) {
   692  		natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
   693  		if err != nil {
   694  			Fatalf("Option %s: %v", NATFlag.Name, err)
   695  		}
   696  		cfg.NAT = natif
   697  	}
   698  }
   699  
   700  // splitAndTrim splits input separated by a comma
   701  // and trims excessive white space from the substrings.
   702  func splitAndTrim(input string) []string {
   703  	result := strings.Split(input, ",")
   704  	for i, r := range result {
   705  		result[i] = strings.TrimSpace(r)
   706  	}
   707  	return result
   708  }
   709  
   710  // setHTTP creates the HTTP RPC listener interface string from the set
   711  // command line flags, returning empty if the HTTP endpoint is disabled.
   712  func setHTTP(ctx *cli.Context, cfg *node.Config) {
   713  	if ctx.GlobalBool(RPCEnabledFlag.Name) && cfg.HTTPHost == "" {
   714  		cfg.HTTPHost = "127.0.0.1"
   715  		if ctx.GlobalIsSet(RPCListenAddrFlag.Name) {
   716  			cfg.HTTPHost = ctx.GlobalString(RPCListenAddrFlag.Name)
   717  		}
   718  	}
   719  
   720  	if ctx.GlobalIsSet(RPCPortFlag.Name) {
   721  		cfg.HTTPPort = ctx.GlobalInt(RPCPortFlag.Name)
   722  	}
   723  	if ctx.GlobalIsSet(RPCCORSDomainFlag.Name) {
   724  		cfg.HTTPCors = splitAndTrim(ctx.GlobalString(RPCCORSDomainFlag.Name))
   725  	}
   726  	if ctx.GlobalIsSet(RPCApiFlag.Name) {
   727  		cfg.HTTPModules = splitAndTrim(ctx.GlobalString(RPCApiFlag.Name))
   728  	}
   729  	if ctx.GlobalIsSet(RPCVirtualHostsFlag.Name) {
   730  		cfg.HTTPVirtualHosts = splitAndTrim(ctx.GlobalString(RPCVirtualHostsFlag.Name))
   731  	}
   732  }
   733  
   734  // setWS creates the WebSocket RPC listener interface string from the set
   735  // command line flags, returning empty if the HTTP endpoint is disabled.
   736  func setWS(ctx *cli.Context, cfg *node.Config) {
   737  	if ctx.GlobalBool(WSEnabledFlag.Name) && cfg.WSHost == "" {
   738  		cfg.WSHost = "127.0.0.1"
   739  		if ctx.GlobalIsSet(WSListenAddrFlag.Name) {
   740  			cfg.WSHost = ctx.GlobalString(WSListenAddrFlag.Name)
   741  		}
   742  	}
   743  
   744  	if ctx.GlobalIsSet(WSPortFlag.Name) {
   745  		cfg.WSPort = ctx.GlobalInt(WSPortFlag.Name)
   746  	}
   747  	if ctx.GlobalIsSet(WSAllowedOriginsFlag.Name) {
   748  		cfg.WSOrigins = splitAndTrim(ctx.GlobalString(WSAllowedOriginsFlag.Name))
   749  	}
   750  	if ctx.GlobalIsSet(WSApiFlag.Name) {
   751  		cfg.WSModules = splitAndTrim(ctx.GlobalString(WSApiFlag.Name))
   752  	}
   753  }
   754  
   755  // setIPC creates an IPC path configuration from the set command line flags,
   756  // returning an empty string if IPC was explicitly disabled, or the set path.
   757  func setIPC(ctx *cli.Context, cfg *node.Config) {
   758  	checkExclusive(ctx, IPCDisabledFlag, IPCPathFlag)
   759  	switch {
   760  	case ctx.GlobalBool(IPCDisabledFlag.Name):
   761  		cfg.IPCPath = ""
   762  	case ctx.GlobalIsSet(IPCPathFlag.Name):
   763  		cfg.IPCPath = ctx.GlobalString(IPCPathFlag.Name)
   764  	}
   765  }
   766  
   767  // makeDatabaseHandles raises out the number of allowed file handles per process
   768  // for Geth and returns half of the allowance to assign to the database.
   769  func makeDatabaseHandles() int {
   770  	limit, err := fdlimit.Current()
   771  	if err != nil {
   772  		Fatalf("Failed to retrieve file descriptor allowance: %v", err)
   773  	}
   774  	if limit < 2048 {
   775  		if err := fdlimit.Raise(2048); err != nil {
   776  			Fatalf("Failed to raise file descriptor allowance: %v", err)
   777  		}
   778  	}
   779  	if limit > 2048 { // cap database file descriptors even if more is available
   780  		limit = 2048
   781  	}
   782  	return limit / 2 // Leave half for networking and other stuff
   783  }
   784  
   785  // MakeAddress converts an account specified directly as a hex encoded string or
   786  // a key index in the key store to an internal account representation.
   787  func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) {
   788  	// If the specified account is a valid address, return it
   789  	if common.IsHexAddress(account) {
   790  		return accounts.Account{Address: common.HexToAddress(account)}, nil
   791  	}
   792  	// Otherwise try to interpret the account as a keystore index
   793  	index, err := strconv.Atoi(account)
   794  	if err != nil || index < 0 {
   795  		return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account)
   796  	}
   797  	log.Warn("-------------------------------------------------------------------")
   798  	log.Warn("Referring to accounts by order in the keystore folder is dangerous!")
   799  	log.Warn("This functionality is deprecated and will be removed in the future!")
   800  	log.Warn("Please use explicit addresses! (can search via `geth account list`)")
   801  	log.Warn("-------------------------------------------------------------------")
   802  
   803  	accs := ks.Accounts()
   804  	if len(accs) <= index {
   805  		return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs))
   806  	}
   807  	return accs[index], nil
   808  }
   809  
   810  // setEtherbase retrieves the etherbase either from the directly specified
   811  // command line flags or from the keystore if CLI indexed.
   812  func setEtherbase(ctx *cli.Context, ks *keystore.KeyStore, cfg *eth.Config) {
   813  	if ctx.GlobalIsSet(EtherbaseFlag.Name) {
   814  		account, err := MakeAddress(ks, ctx.GlobalString(EtherbaseFlag.Name))
   815  		if err != nil {
   816  			Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
   817  		}
   818  		cfg.Etherbase = account.Address
   819  	}
   820  }
   821  
   822  // MakePasswordList reads password lines from the file specified by the global --password flag.
   823  func MakePasswordList(ctx *cli.Context) []string {
   824  	path := ctx.GlobalString(PasswordFileFlag.Name)
   825  	if path == "" {
   826  		return nil
   827  	}
   828  	text, err := ioutil.ReadFile(path)
   829  	if err != nil {
   830  		Fatalf("Failed to read password file: %v", err)
   831  	}
   832  	lines := strings.Split(string(text), "\n")
   833  	// Sanitise DOS line endings.
   834  	for i := range lines {
   835  		lines[i] = strings.TrimRight(lines[i], "\r")
   836  	}
   837  	return lines
   838  }
   839  
   840  func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) {
   841  	setNodeKey(ctx, cfg)
   842  	setNAT(ctx, cfg)
   843  	setListenAddress(ctx, cfg)
   844  	setBootstrapNodes(ctx, cfg)
   845  	setBootstrapNodesV5(ctx, cfg)
   846  
   847  	lightClient := ctx.GlobalBool(LightModeFlag.Name) || ctx.GlobalString(SyncModeFlag.Name) == "light"
   848  	lightServer := ctx.GlobalInt(LightServFlag.Name) != 0
   849  	lightPeers := ctx.GlobalInt(LightPeersFlag.Name)
   850  
   851  	if ctx.GlobalIsSet(MaxPeersFlag.Name) {
   852  		cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name)
   853  		if lightServer && !ctx.GlobalIsSet(LightPeersFlag.Name) {
   854  			cfg.MaxPeers += lightPeers
   855  		}
   856  	} else {
   857  		if lightServer {
   858  			cfg.MaxPeers += lightPeers
   859  		}
   860  		if lightClient && ctx.GlobalIsSet(LightPeersFlag.Name) && cfg.MaxPeers < lightPeers {
   861  			cfg.MaxPeers = lightPeers
   862  		}
   863  	}
   864  	if !(lightClient || lightServer) {
   865  		lightPeers = 0
   866  	}
   867  	ethPeers := cfg.MaxPeers - lightPeers
   868  	if lightClient {
   869  		ethPeers = 0
   870  	}
   871  	log.Info("Maximum peer count", "ETH", ethPeers, "LES", lightPeers, "total", cfg.MaxPeers)
   872  
   873  	if ctx.GlobalIsSet(MaxPendingPeersFlag.Name) {
   874  		cfg.MaxPendingPeers = ctx.GlobalInt(MaxPendingPeersFlag.Name)
   875  	}
   876  	if ctx.GlobalIsSet(NoDiscoverFlag.Name) || lightClient {
   877  		cfg.NoDiscovery = true
   878  	}
   879  
   880  	// if we're running a light client or server, force enable the v5 peer discovery
   881  	// unless it is explicitly disabled with --nodiscover note that explicitly specifying
   882  	// --v5disc overrides --nodiscover, in which case the later only disables v4 discovery
   883  	forceV5Discovery := (lightClient || lightServer) && !ctx.GlobalBool(NoDiscoverFlag.Name)
   884  	if ctx.GlobalIsSet(DiscoveryV5Flag.Name) {
   885  		cfg.DiscoveryV5 = ctx.GlobalBool(DiscoveryV5Flag.Name)
   886  	} else if forceV5Discovery {
   887  		cfg.DiscoveryV5 = true
   888  	}
   889  
   890  	if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" {
   891  		list, err := netutil.ParseNetlist(netrestrict)
   892  		if err != nil {
   893  			Fatalf("Option %q: %v", NetrestrictFlag.Name, err)
   894  		}
   895  		cfg.NetRestrict = list
   896  	}
   897  
   898  	if ctx.GlobalBool(DeveloperFlag.Name) {
   899  		// --dev mode can't use p2p networking.
   900  		cfg.MaxPeers = 0
   901  		cfg.ListenAddr = ":0"
   902  		cfg.NoDiscovery = true
   903  		cfg.DiscoveryV5 = false
   904  	}
   905  }
   906  
   907  // SetNodeConfig applies node-related command line flags to the config.
   908  func SetNodeConfig(ctx *cli.Context, cfg *node.Config) {
   909  	SetP2PConfig(ctx, &cfg.P2P)
   910  	setIPC(ctx, cfg)
   911  	setHTTP(ctx, cfg)
   912  	setWS(ctx, cfg)
   913  	setNodeUserIdent(ctx, cfg)
   914  
   915  	switch {
   916  	case ctx.GlobalIsSet(DataDirFlag.Name):
   917  		cfg.DataDir = ctx.GlobalString(DataDirFlag.Name)
   918  	case ctx.GlobalBool(DeveloperFlag.Name):
   919  		cfg.DataDir = "" // unless explicitly requested, use memory databases
   920  	case ctx.GlobalBool(TestnetFlag.Name):
   921  		cfg.DataDir = filepath.Join(node.DefaultDataDir(), "testnet")
   922  	case ctx.GlobalBool(RinkebyFlag.Name):
   923  		cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby")
   924  	}
   925  
   926  	if ctx.GlobalIsSet(KeyStoreDirFlag.Name) {
   927  		cfg.KeyStoreDir = ctx.GlobalString(KeyStoreDirFlag.Name)
   928  	}
   929  	if ctx.GlobalIsSet(LightKDFFlag.Name) {
   930  		cfg.UseLightweightKDF = ctx.GlobalBool(LightKDFFlag.Name)
   931  	}
   932  	if ctx.GlobalIsSet(NoUSBFlag.Name) {
   933  		cfg.NoUSB = ctx.GlobalBool(NoUSBFlag.Name)
   934  	}
   935  }
   936  
   937  func setGPO(ctx *cli.Context, cfg *gasprice.Config) {
   938  	if ctx.GlobalIsSet(GpoBlocksFlag.Name) {
   939  		cfg.Blocks = ctx.GlobalInt(GpoBlocksFlag.Name)
   940  	}
   941  	if ctx.GlobalIsSet(GpoPercentileFlag.Name) {
   942  		cfg.Percentile = ctx.GlobalInt(GpoPercentileFlag.Name)
   943  	}
   944  }
   945  
   946  func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) {
   947  	if ctx.GlobalIsSet(TxPoolNoLocalsFlag.Name) {
   948  		cfg.NoLocals = ctx.GlobalBool(TxPoolNoLocalsFlag.Name)
   949  	}
   950  	if ctx.GlobalIsSet(TxPoolJournalFlag.Name) {
   951  		cfg.Journal = ctx.GlobalString(TxPoolJournalFlag.Name)
   952  	}
   953  	if ctx.GlobalIsSet(TxPoolRejournalFlag.Name) {
   954  		cfg.Rejournal = ctx.GlobalDuration(TxPoolRejournalFlag.Name)
   955  	}
   956  	if ctx.GlobalIsSet(TxPoolPriceLimitFlag.Name) {
   957  		cfg.PriceLimit = ctx.GlobalUint64(TxPoolPriceLimitFlag.Name)
   958  	}
   959  	if ctx.GlobalIsSet(TxPoolPriceBumpFlag.Name) {
   960  		cfg.PriceBump = ctx.GlobalUint64(TxPoolPriceBumpFlag.Name)
   961  	}
   962  	if ctx.GlobalIsSet(TxPoolAccountSlotsFlag.Name) {
   963  		cfg.AccountSlots = ctx.GlobalUint64(TxPoolAccountSlotsFlag.Name)
   964  	}
   965  	if ctx.GlobalIsSet(TxPoolGlobalSlotsFlag.Name) {
   966  		cfg.GlobalSlots = ctx.GlobalUint64(TxPoolGlobalSlotsFlag.Name)
   967  	}
   968  	if ctx.GlobalIsSet(TxPoolAccountQueueFlag.Name) {
   969  		cfg.AccountQueue = ctx.GlobalUint64(TxPoolAccountQueueFlag.Name)
   970  	}
   971  	if ctx.GlobalIsSet(TxPoolGlobalQueueFlag.Name) {
   972  		cfg.GlobalQueue = ctx.GlobalUint64(TxPoolGlobalQueueFlag.Name)
   973  	}
   974  	if ctx.GlobalIsSet(TxPoolLifetimeFlag.Name) {
   975  		cfg.Lifetime = ctx.GlobalDuration(TxPoolLifetimeFlag.Name)
   976  	}
   977  }
   978  
   979  func setEthash(ctx *cli.Context, cfg *eth.Config) {
   980  	if ctx.GlobalIsSet(EthashCacheDirFlag.Name) {
   981  		cfg.Ethash.CacheDir = ctx.GlobalString(EthashCacheDirFlag.Name)
   982  	}
   983  	if ctx.GlobalIsSet(EthashDatasetDirFlag.Name) {
   984  		cfg.Ethash.DatasetDir = ctx.GlobalString(EthashDatasetDirFlag.Name)
   985  	}
   986  	if ctx.GlobalIsSet(EthashCachesInMemoryFlag.Name) {
   987  		cfg.Ethash.CachesInMem = ctx.GlobalInt(EthashCachesInMemoryFlag.Name)
   988  	}
   989  	if ctx.GlobalIsSet(EthashCachesOnDiskFlag.Name) {
   990  		cfg.Ethash.CachesOnDisk = ctx.GlobalInt(EthashCachesOnDiskFlag.Name)
   991  	}
   992  	if ctx.GlobalIsSet(EthashDatasetsInMemoryFlag.Name) {
   993  		cfg.Ethash.DatasetsInMem = ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name)
   994  	}
   995  	if ctx.GlobalIsSet(EthashDatasetsOnDiskFlag.Name) {
   996  		cfg.Ethash.DatasetsOnDisk = ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name)
   997  	}
   998  }
   999  
  1000  // checkExclusive verifies that only a single instance of the provided flags was
  1001  // set by the user. Each flag might optionally be followed by a string type to
  1002  // specialize it further.
  1003  func checkExclusive(ctx *cli.Context, args ...interface{}) {
  1004  	set := make([]string, 0, 1)
  1005  	for i := 0; i < len(args); i++ {
  1006  		// Make sure the next argument is a flag and skip if not set
  1007  		flag, ok := args[i].(cli.Flag)
  1008  		if !ok {
  1009  			panic(fmt.Sprintf("invalid argument, not cli.Flag type: %T", args[i]))
  1010  		}
  1011  		// Check if next arg extends current and expand its name if so
  1012  		name := flag.GetName()
  1013  
  1014  		if i+1 < len(args) {
  1015  			switch option := args[i+1].(type) {
  1016  			case string:
  1017  				// Extended flag, expand the name and shift the arguments
  1018  				if ctx.GlobalString(flag.GetName()) == option {
  1019  					name += "=" + option
  1020  				}
  1021  				i++
  1022  
  1023  			case cli.Flag:
  1024  			default:
  1025  				panic(fmt.Sprintf("invalid argument, not cli.Flag or string extension: %T", args[i+1]))
  1026  			}
  1027  		}
  1028  		// Mark the flag if it's set
  1029  		if ctx.GlobalIsSet(flag.GetName()) {
  1030  			set = append(set, "--"+name)
  1031  		}
  1032  	}
  1033  	if len(set) > 1 {
  1034  		Fatalf("Flags %v can't be used at the same time", strings.Join(set, ", "))
  1035  	}
  1036  }
  1037  
  1038  // SetShhConfig applies shh-related command line flags to the config.
  1039  func SetShhConfig(ctx *cli.Context, stack *node.Node, cfg *whisper.Config) {
  1040  	if ctx.GlobalIsSet(WhisperMaxMessageSizeFlag.Name) {
  1041  		cfg.MaxMessageSize = uint32(ctx.GlobalUint(WhisperMaxMessageSizeFlag.Name))
  1042  	}
  1043  	if ctx.GlobalIsSet(WhisperMinPOWFlag.Name) {
  1044  		cfg.MinimumAcceptedPOW = ctx.GlobalFloat64(WhisperMinPOWFlag.Name)
  1045  	}
  1046  }
  1047  
  1048  // SetEthConfig applies eth-related command line flags to the config.
  1049  func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
  1050  	// Avoid conflicting network flags
  1051  	checkExclusive(ctx, DeveloperFlag, TestnetFlag, RinkebyFlag)
  1052  	checkExclusive(ctx, FastSyncFlag, LightModeFlag, SyncModeFlag)
  1053  	checkExclusive(ctx, LightServFlag, LightModeFlag)
  1054  	checkExclusive(ctx, LightServFlag, SyncModeFlag, "light")
  1055  
  1056  	ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  1057  	setEtherbase(ctx, ks, cfg)
  1058  	setGPO(ctx, &cfg.GPO)
  1059  	setTxPool(ctx, &cfg.TxPool)
  1060  	setEthash(ctx, cfg)
  1061  
  1062  	switch {
  1063  	case ctx.GlobalIsSet(SyncModeFlag.Name):
  1064  		cfg.SyncMode = *GlobalTextMarshaler(ctx, SyncModeFlag.Name).(*downloader.SyncMode)
  1065  	case ctx.GlobalBool(FastSyncFlag.Name):
  1066  		cfg.SyncMode = downloader.FastSync
  1067  	case ctx.GlobalBool(LightModeFlag.Name):
  1068  		cfg.SyncMode = downloader.LightSync
  1069  	}
  1070  	if ctx.GlobalIsSet(LightServFlag.Name) {
  1071  		cfg.LightServ = ctx.GlobalInt(LightServFlag.Name)
  1072  	}
  1073  	if ctx.GlobalIsSet(LightPeersFlag.Name) {
  1074  		cfg.LightPeers = ctx.GlobalInt(LightPeersFlag.Name)
  1075  	}
  1076  	if ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1077  		cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name)
  1078  	}
  1079  
  1080  	if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheDatabaseFlag.Name) {
  1081  		cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
  1082  	}
  1083  	cfg.DatabaseHandles = makeDatabaseHandles()
  1084  
  1085  	if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
  1086  		Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
  1087  	}
  1088  	cfg.NoPruning = ctx.GlobalString(GCModeFlag.Name) == "archive"
  1089  
  1090  	if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
  1091  		cfg.TrieCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
  1092  	}
  1093  	if ctx.GlobalIsSet(MinerThreadsFlag.Name) {
  1094  		cfg.MinerThreads = ctx.GlobalInt(MinerThreadsFlag.Name)
  1095  	}
  1096  	if ctx.GlobalIsSet(DocRootFlag.Name) {
  1097  		cfg.DocRoot = ctx.GlobalString(DocRootFlag.Name)
  1098  	}
  1099  	if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  1100  		cfg.ExtraData = []byte(ctx.GlobalString(ExtraDataFlag.Name))
  1101  	}
  1102  	if ctx.GlobalIsSet(GasPriceFlag.Name) {
  1103  		cfg.GasPrice = GlobalBig(ctx, GasPriceFlag.Name)
  1104  	}
  1105  	if ctx.GlobalIsSet(VMEnableDebugFlag.Name) {
  1106  		// TODO(fjl): force-enable this in --dev mode
  1107  		cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name)
  1108  	}
  1109  
  1110  	// Override any default configs for hard coded networks.
  1111  	switch {
  1112  	case ctx.GlobalBool(TestnetFlag.Name):
  1113  		if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1114  			cfg.NetworkId = 3
  1115  		}
  1116  		cfg.Genesis = core.DefaultTestnetGenesisBlock()
  1117  	case ctx.GlobalBool(RinkebyFlag.Name):
  1118  		if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1119  			cfg.NetworkId = 4
  1120  		}
  1121  		cfg.Genesis = core.DefaultRinkebyGenesisBlock()
  1122  	case ctx.GlobalBool(DeveloperFlag.Name):
  1123  		if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1124  			cfg.NetworkId = 1337
  1125  		}
  1126  		// Create new developer account or reuse existing one
  1127  		var (
  1128  			developer accounts.Account
  1129  			err       error
  1130  		)
  1131  		if accs := ks.Accounts(); len(accs) > 0 {
  1132  			developer = ks.Accounts()[0]
  1133  		} else {
  1134  			developer, err = ks.NewAccount("")
  1135  			if err != nil {
  1136  				Fatalf("Failed to create developer account: %v", err)
  1137  			}
  1138  		}
  1139  		if err := ks.Unlock(developer, ""); err != nil {
  1140  			Fatalf("Failed to unlock developer account: %v", err)
  1141  		}
  1142  		log.Info("Using developer account", "address", developer.Address)
  1143  
  1144  		cfg.Genesis = core.DeveloperGenesisBlock(uint64(ctx.GlobalInt(DeveloperPeriodFlag.Name)), developer.Address)
  1145  		if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  1146  			cfg.GasPrice = big.NewInt(1)
  1147  		}
  1148  	}
  1149  	// TODO(fjl): move trie cache generations into config
  1150  	if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  1151  		state.MaxTrieCacheGen = uint16(gen)
  1152  	}
  1153  }
  1154  
  1155  // SetDashboardConfig applies dashboard related command line flags to the config.
  1156  func SetDashboardConfig(ctx *cli.Context, cfg *dashboard.Config) {
  1157  	cfg.Host = ctx.GlobalString(DashboardAddrFlag.Name)
  1158  	cfg.Port = ctx.GlobalInt(DashboardPortFlag.Name)
  1159  	cfg.Refresh = ctx.GlobalDuration(DashboardRefreshFlag.Name)
  1160  }
  1161  
  1162  // RegisterEthService adds an Ethereum client to the stack.
  1163  func RegisterEthService(stack *node.Node, cfg *eth.Config) {
  1164  	var err error
  1165  	if cfg.SyncMode == downloader.LightSync {
  1166  		err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1167  			return les.New(ctx, cfg)
  1168  		})
  1169  	} else {
  1170  		err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1171  			fullNode, err := eth.New(ctx, cfg)
  1172  			if fullNode != nil && cfg.LightServ > 0 {
  1173  				ls, _ := les.NewLesServer(fullNode, cfg)
  1174  				fullNode.AddLesServer(ls)
  1175  			}
  1176  			return fullNode, err
  1177  		})
  1178  	}
  1179  	if err != nil {
  1180  		Fatalf("Failed to register the Ethereum service: %v", err)
  1181  	}
  1182  }
  1183  
  1184  // RegisterDashboardService adds a dashboard to the stack.
  1185  func RegisterDashboardService(stack *node.Node, cfg *dashboard.Config, commit string) {
  1186  	stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1187  		return dashboard.New(cfg, commit, ctx.ResolvePath("logs")), nil
  1188  	})
  1189  }
  1190  
  1191  // RegisterShhService configures Whisper and adds it to the given node.
  1192  func RegisterShhService(stack *node.Node, cfg *whisper.Config) {
  1193  	if err := stack.Register(func(n *node.ServiceContext) (node.Service, error) {
  1194  		return whisper.New(cfg), nil
  1195  	}); err != nil {
  1196  		Fatalf("Failed to register the Whisper service: %v", err)
  1197  	}
  1198  }
  1199  
  1200  // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  1201  // the given node.
  1202  func RegisterEthStatsService(stack *node.Node, url string) {
  1203  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1204  		// Retrieve both eth and les services
  1205  		var ethServ *eth.Ethereum
  1206  		ctx.Service(&ethServ)
  1207  
  1208  		var lesServ *les.LightEthereum
  1209  		ctx.Service(&lesServ)
  1210  
  1211  		return ethstats.New(url, ethServ, lesServ)
  1212  	}); err != nil {
  1213  		Fatalf("Failed to register the Ethereum Stats service: %v", err)
  1214  	}
  1215  }
  1216  
  1217  // SetupNetwork configures the system for either the main net or some test network.
  1218  func SetupNetwork(ctx *cli.Context) {
  1219  	// TODO(fjl): move target gas limit into config
  1220  	params.TargetGasLimit = ctx.GlobalUint64(TargetGasLimitFlag.Name)
  1221  }
  1222  
  1223  func SetupMetrics(ctx *cli.Context) {
  1224  	if metrics.Enabled {
  1225  		log.Info("Enabling metrics collection")
  1226  		var (
  1227  			enableExport = ctx.GlobalBool(MetricsEnableInfluxDBFlag.Name)
  1228  			endpoint     = ctx.GlobalString(MetricsInfluxDBEndpointFlag.Name)
  1229  			database     = ctx.GlobalString(MetricsInfluxDBDatabaseFlag.Name)
  1230  			username     = ctx.GlobalString(MetricsInfluxDBUsernameFlag.Name)
  1231  			password     = ctx.GlobalString(MetricsInfluxDBPasswordFlag.Name)
  1232  			hosttag      = ctx.GlobalString(MetricsInfluxDBHostTagFlag.Name)
  1233  		)
  1234  
  1235  		if enableExport {
  1236  			log.Info("Enabling metrics export to InfluxDB")
  1237  			go influxdb.InfluxDBWithTags(metrics.DefaultRegistry, 10*time.Second, endpoint, database, username, password, "geth.", map[string]string{
  1238  				"host": hosttag,
  1239  			})
  1240  		}
  1241  	}
  1242  }
  1243  
  1244  // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  1245  func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  1246  	var (
  1247  		cache   = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
  1248  		handles = makeDatabaseHandles()
  1249  	)
  1250  	name := "chaindata"
  1251  	if ctx.GlobalBool(LightModeFlag.Name) {
  1252  		name = "lightchaindata"
  1253  	}
  1254  	chainDb, err := stack.OpenDatabase(name, cache, handles)
  1255  	if err != nil {
  1256  		Fatalf("Could not open database: %v", err)
  1257  	}
  1258  	return chainDb
  1259  }
  1260  
  1261  func MakeGenesis(ctx *cli.Context) *core.Genesis {
  1262  	var genesis *core.Genesis
  1263  	switch {
  1264  	case ctx.GlobalBool(TestnetFlag.Name):
  1265  		genesis = core.DefaultTestnetGenesisBlock()
  1266  	case ctx.GlobalBool(RinkebyFlag.Name):
  1267  		genesis = core.DefaultRinkebyGenesisBlock()
  1268  	case ctx.GlobalBool(DeveloperFlag.Name):
  1269  		Fatalf("Developer chains are ephemeral")
  1270  	}
  1271  	return genesis
  1272  }
  1273  
  1274  // MakeChain creates a chain manager from set command line flags.
  1275  func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  1276  	var err error
  1277  	chainDb = MakeChainDatabase(ctx, stack)
  1278  
  1279  	config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx))
  1280  	if err != nil {
  1281  		Fatalf("%v", err)
  1282  	}
  1283  	var engine consensus.Engine
  1284  	if config.Clique != nil {
  1285  		engine = clique.New(config.Clique, chainDb)
  1286  	} else {
  1287  		engine = ethash.NewFaker()
  1288  		if !ctx.GlobalBool(FakePoWFlag.Name) {
  1289  			engine = ethash.New(ethash.Config{
  1290  				CacheDir:       stack.ResolvePath(eth.DefaultConfig.Ethash.CacheDir),
  1291  				CachesInMem:    eth.DefaultConfig.Ethash.CachesInMem,
  1292  				CachesOnDisk:   eth.DefaultConfig.Ethash.CachesOnDisk,
  1293  				DatasetDir:     stack.ResolvePath(eth.DefaultConfig.Ethash.DatasetDir),
  1294  				DatasetsInMem:  eth.DefaultConfig.Ethash.DatasetsInMem,
  1295  				DatasetsOnDisk: eth.DefaultConfig.Ethash.DatasetsOnDisk,
  1296  			})
  1297  		}
  1298  	}
  1299  	if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
  1300  		Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
  1301  	}
  1302  	cache := &core.CacheConfig{
  1303  		Disabled:      ctx.GlobalString(GCModeFlag.Name) == "archive",
  1304  		TrieNodeLimit: eth.DefaultConfig.TrieCache,
  1305  		TrieTimeLimit: eth.DefaultConfig.TrieTimeout,
  1306  	}
  1307  	if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
  1308  		cache.TrieNodeLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
  1309  	}
  1310  	vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
  1311  	chain, err = core.NewBlockChain(chainDb, cache, config, engine, vmcfg)
  1312  	if err != nil {
  1313  		Fatalf("Can't create BlockChain: %v", err)
  1314  	}
  1315  	return chain, chainDb
  1316  }
  1317  
  1318  // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  1319  // scripts to preload before starting.
  1320  func MakeConsolePreloads(ctx *cli.Context) []string {
  1321  	// Skip preloading if there's nothing to preload
  1322  	if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  1323  		return nil
  1324  	}
  1325  	// Otherwise resolve absolute paths and return them
  1326  	preloads := []string{}
  1327  
  1328  	assets := ctx.GlobalString(JSpathFlag.Name)
  1329  	for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  1330  		preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  1331  	}
  1332  	return preloads
  1333  }
  1334  
  1335  // MigrateFlags sets the global flag from a local flag when it's set.
  1336  // This is a temporary function used for migrating old command/flags to the
  1337  // new format.
  1338  //
  1339  // e.g. geth account new --keystore /tmp/mykeystore --lightkdf
  1340  //
  1341  // is equivalent after calling this method with:
  1342  //
  1343  // geth --keystore /tmp/mykeystore --lightkdf account new
  1344  //
  1345  // This allows the use of the existing configuration functionality.
  1346  // When all flags are migrated this function can be removed and the existing
  1347  // configuration functionality must be changed that is uses local flags
  1348  func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error {
  1349  	return func(ctx *cli.Context) error {
  1350  		for _, name := range ctx.FlagNames() {
  1351  			if ctx.IsSet(name) {
  1352  				ctx.GlobalSet(name, ctx.String(name))
  1353  			}
  1354  		}
  1355  		return action(ctx)
  1356  	}
  1357  }