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