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