github.com/cranelv/ethereum_mpc@v0.0.0-20191031014521-23aeb1415092/cmd/utils/flags.go (about)

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