github.com/bamzi/go-ethereum@v1.6.7-0.20170704111104-138f26c93af1/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 // ATM the url is left to the user and deployment to 444 JSpathFlag = cli.StringFlag{ 445 Name: "jspath", 446 Usage: "JavaScript root path for `loadScript`", 447 Value: ".", 448 } 449 450 // Gas price oracle settings 451 GpoBlocksFlag = cli.IntFlag{ 452 Name: "gpoblocks", 453 Usage: "Number of recent blocks to check for gas prices", 454 Value: eth.DefaultConfig.GPO.Blocks, 455 } 456 GpoPercentileFlag = cli.IntFlag{ 457 Name: "gpopercentile", 458 Usage: "Suggested gas price is the given percentile of a set of recent transaction gas prices", 459 Value: eth.DefaultConfig.GPO.Percentile, 460 } 461 WhisperEnabledFlag = cli.BoolFlag{ 462 Name: "shh", 463 Usage: "Enable Whisper", 464 } 465 WhisperMaxMessageSizeFlag = cli.IntFlag{ 466 Name: "shh.maxmessagesize", 467 Usage: "Max message size accepted", 468 Value: int(whisper.DefaultMaxMessageSize), 469 } 470 WhisperMinPOWFlag = cli.Float64Flag{ 471 Name: "shh.pow", 472 Usage: "Minimum POW accepted", 473 Value: whisper.DefaultMinimumPoW, 474 } 475 ) 476 477 // MakeDataDir retrieves the currently requested data directory, terminating 478 // if none (or the empty string) is specified. If the node is starting a testnet, 479 // the a subdirectory of the specified datadir will be used. 480 func MakeDataDir(ctx *cli.Context) string { 481 if path := ctx.GlobalString(DataDirFlag.Name); path != "" { 482 if ctx.GlobalBool(TestnetFlag.Name) { 483 return filepath.Join(path, "testnet") 484 } 485 if ctx.GlobalBool(RinkebyFlag.Name) { 486 return filepath.Join(path, "rinkeby") 487 } 488 return path 489 } 490 Fatalf("Cannot determine default data directory, please set manually (--datadir)") 491 return "" 492 } 493 494 // setNodeKey creates a node key from set command line flags, either loading it 495 // from a file or as a specified hex value. If neither flags were provided, this 496 // method returns nil and an emphemeral key is to be generated. 497 func setNodeKey(ctx *cli.Context, cfg *p2p.Config) { 498 var ( 499 hex = ctx.GlobalString(NodeKeyHexFlag.Name) 500 file = ctx.GlobalString(NodeKeyFileFlag.Name) 501 key *ecdsa.PrivateKey 502 err error 503 ) 504 switch { 505 case file != "" && hex != "": 506 Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name) 507 case file != "": 508 if key, err = crypto.LoadECDSA(file); err != nil { 509 Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err) 510 } 511 cfg.PrivateKey = key 512 case hex != "": 513 if key, err = crypto.HexToECDSA(hex); err != nil { 514 Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err) 515 } 516 cfg.PrivateKey = key 517 } 518 } 519 520 // setNodeUserIdent creates the user identifier from CLI flags. 521 func setNodeUserIdent(ctx *cli.Context, cfg *node.Config) { 522 if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 { 523 cfg.UserIdent = identity 524 } 525 } 526 527 // setBootstrapNodes creates a list of bootstrap nodes from the command line 528 // flags, reverting to pre-configured ones if none have been specified. 529 func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) { 530 urls := params.MainnetBootnodes 531 switch { 532 case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV4Flag.Name): 533 if ctx.GlobalIsSet(BootnodesV4Flag.Name) { 534 urls = strings.Split(ctx.GlobalString(BootnodesV4Flag.Name), ",") 535 } else { 536 urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",") 537 } 538 case ctx.GlobalBool(TestnetFlag.Name): 539 urls = params.TestnetBootnodes 540 case ctx.GlobalBool(RinkebyFlag.Name): 541 urls = params.RinkebyBootnodes 542 } 543 544 cfg.BootstrapNodes = make([]*discover.Node, 0, len(urls)) 545 for _, url := range urls { 546 node, err := discover.ParseNode(url) 547 if err != nil { 548 log.Error("Bootstrap URL invalid", "enode", url, "err", err) 549 continue 550 } 551 cfg.BootstrapNodes = append(cfg.BootstrapNodes, node) 552 } 553 } 554 555 // setBootstrapNodesV5 creates a list of bootstrap nodes from the command line 556 // flags, reverting to pre-configured ones if none have been specified. 557 func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) { 558 urls := params.DiscoveryV5Bootnodes 559 switch { 560 case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV5Flag.Name): 561 if ctx.GlobalIsSet(BootnodesV5Flag.Name) { 562 urls = strings.Split(ctx.GlobalString(BootnodesV5Flag.Name), ",") 563 } else { 564 urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",") 565 } 566 case ctx.GlobalBool(RinkebyFlag.Name): 567 urls = params.RinkebyV5Bootnodes 568 case cfg.BootstrapNodesV5 != nil: 569 return // already set, don't apply defaults. 570 } 571 572 cfg.BootstrapNodesV5 = make([]*discv5.Node, 0, len(urls)) 573 for _, url := range urls { 574 node, err := discv5.ParseNode(url) 575 if err != nil { 576 log.Error("Bootstrap URL invalid", "enode", url, "err", err) 577 continue 578 } 579 cfg.BootstrapNodesV5 = append(cfg.BootstrapNodesV5, node) 580 } 581 } 582 583 // setListenAddress creates a TCP listening address string from set command 584 // line flags. 585 func setListenAddress(ctx *cli.Context, cfg *p2p.Config) { 586 if ctx.GlobalIsSet(ListenPortFlag.Name) { 587 cfg.ListenAddr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name)) 588 } 589 } 590 591 // setDiscoveryV5Address creates a UDP listening address string from set command 592 // line flags for the V5 discovery protocol. 593 func setDiscoveryV5Address(ctx *cli.Context, cfg *p2p.Config) { 594 if ctx.GlobalIsSet(ListenPortFlag.Name) { 595 cfg.DiscoveryV5Addr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name)+1) 596 } 597 } 598 599 // setNAT creates a port mapper from command line flags. 600 func setNAT(ctx *cli.Context, cfg *p2p.Config) { 601 if ctx.GlobalIsSet(NATFlag.Name) { 602 natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name)) 603 if err != nil { 604 Fatalf("Option %s: %v", NATFlag.Name, err) 605 } 606 cfg.NAT = natif 607 } 608 } 609 610 // splitAndTrim splits input separated by a comma 611 // and trims excessive white space from the substrings. 612 func splitAndTrim(input string) []string { 613 result := strings.Split(input, ",") 614 for i, r := range result { 615 result[i] = strings.TrimSpace(r) 616 } 617 return result 618 } 619 620 // setHTTP creates the HTTP RPC listener interface string from the set 621 // command line flags, returning empty if the HTTP endpoint is disabled. 622 func setHTTP(ctx *cli.Context, cfg *node.Config) { 623 if ctx.GlobalBool(RPCEnabledFlag.Name) && cfg.HTTPHost == "" { 624 cfg.HTTPHost = "127.0.0.1" 625 if ctx.GlobalIsSet(RPCListenAddrFlag.Name) { 626 cfg.HTTPHost = ctx.GlobalString(RPCListenAddrFlag.Name) 627 } 628 } 629 630 if ctx.GlobalIsSet(RPCPortFlag.Name) { 631 cfg.HTTPPort = ctx.GlobalInt(RPCPortFlag.Name) 632 } 633 if ctx.GlobalIsSet(RPCCORSDomainFlag.Name) { 634 cfg.HTTPCors = splitAndTrim(ctx.GlobalString(RPCCORSDomainFlag.Name)) 635 } 636 if ctx.GlobalIsSet(RPCApiFlag.Name) { 637 cfg.HTTPModules = splitAndTrim(ctx.GlobalString(RPCApiFlag.Name)) 638 } 639 } 640 641 // setWS creates the WebSocket RPC listener interface string from the set 642 // command line flags, returning empty if the HTTP endpoint is disabled. 643 func setWS(ctx *cli.Context, cfg *node.Config) { 644 if ctx.GlobalBool(WSEnabledFlag.Name) && cfg.WSHost == "" { 645 cfg.WSHost = "127.0.0.1" 646 if ctx.GlobalIsSet(WSListenAddrFlag.Name) { 647 cfg.WSHost = ctx.GlobalString(WSListenAddrFlag.Name) 648 } 649 } 650 651 if ctx.GlobalIsSet(WSPortFlag.Name) { 652 cfg.WSPort = ctx.GlobalInt(WSPortFlag.Name) 653 } 654 if ctx.GlobalIsSet(WSAllowedOriginsFlag.Name) { 655 cfg.WSOrigins = splitAndTrim(ctx.GlobalString(WSAllowedOriginsFlag.Name)) 656 } 657 if ctx.GlobalIsSet(WSApiFlag.Name) { 658 cfg.WSModules = splitAndTrim(ctx.GlobalString(WSApiFlag.Name)) 659 } 660 } 661 662 // setIPC creates an IPC path configuration from the set command line flags, 663 // returning an empty string if IPC was explicitly disabled, or the set path. 664 func setIPC(ctx *cli.Context, cfg *node.Config) { 665 checkExclusive(ctx, IPCDisabledFlag, IPCPathFlag) 666 switch { 667 case ctx.GlobalBool(IPCDisabledFlag.Name): 668 cfg.IPCPath = "" 669 case ctx.GlobalIsSet(IPCPathFlag.Name): 670 cfg.IPCPath = ctx.GlobalString(IPCPathFlag.Name) 671 } 672 } 673 674 // makeDatabaseHandles raises out the number of allowed file handles per process 675 // for Geth and returns half of the allowance to assign to the database. 676 func makeDatabaseHandles() int { 677 if err := raiseFdLimit(2048); err != nil { 678 Fatalf("Failed to raise file descriptor allowance: %v", err) 679 } 680 limit, err := getFdLimit() 681 if err != nil { 682 Fatalf("Failed to retrieve file descriptor allowance: %v", err) 683 } 684 if limit > 2048 { // cap database file descriptors even if more is available 685 limit = 2048 686 } 687 return limit / 2 // Leave half for networking and other stuff 688 } 689 690 // MakeAddress converts an account specified directly as a hex encoded string or 691 // a key index in the key store to an internal account representation. 692 func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) { 693 // If the specified account is a valid address, return it 694 if common.IsHexAddress(account) { 695 return accounts.Account{Address: common.HexToAddress(account)}, nil 696 } 697 // Otherwise try to interpret the account as a keystore index 698 index, err := strconv.Atoi(account) 699 if err != nil || index < 0 { 700 return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account) 701 } 702 accs := ks.Accounts() 703 if len(accs) <= index { 704 return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs)) 705 } 706 return accs[index], nil 707 } 708 709 // setEtherbase retrieves the etherbase either from the directly specified 710 // command line flags or from the keystore if CLI indexed. 711 func setEtherbase(ctx *cli.Context, ks *keystore.KeyStore, cfg *eth.Config) { 712 if ctx.GlobalIsSet(EtherbaseFlag.Name) { 713 account, err := MakeAddress(ks, ctx.GlobalString(EtherbaseFlag.Name)) 714 if err != nil { 715 Fatalf("Option %q: %v", EtherbaseFlag.Name, err) 716 } 717 cfg.Etherbase = account.Address 718 return 719 } 720 accounts := ks.Accounts() 721 if (cfg.Etherbase == common.Address{}) { 722 if len(accounts) > 0 { 723 cfg.Etherbase = accounts[0].Address 724 } else { 725 log.Warn("No etherbase set and no accounts found as default") 726 } 727 } 728 } 729 730 // MakePasswordList reads password lines from the file specified by the global --password flag. 731 func MakePasswordList(ctx *cli.Context) []string { 732 path := ctx.GlobalString(PasswordFileFlag.Name) 733 if path == "" { 734 return nil 735 } 736 text, err := ioutil.ReadFile(path) 737 if err != nil { 738 Fatalf("Failed to read password file: %v", err) 739 } 740 lines := strings.Split(string(text), "\n") 741 // Sanitise DOS line endings. 742 for i := range lines { 743 lines[i] = strings.TrimRight(lines[i], "\r") 744 } 745 return lines 746 } 747 748 func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) { 749 setNodeKey(ctx, cfg) 750 setNAT(ctx, cfg) 751 setListenAddress(ctx, cfg) 752 setDiscoveryV5Address(ctx, cfg) 753 setBootstrapNodes(ctx, cfg) 754 setBootstrapNodesV5(ctx, cfg) 755 756 if ctx.GlobalIsSet(MaxPeersFlag.Name) { 757 cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name) 758 } 759 if ctx.GlobalIsSet(MaxPendingPeersFlag.Name) { 760 cfg.MaxPendingPeers = ctx.GlobalInt(MaxPendingPeersFlag.Name) 761 } 762 if ctx.GlobalIsSet(NoDiscoverFlag.Name) || ctx.GlobalBool(LightModeFlag.Name) { 763 cfg.NoDiscovery = true 764 } 765 766 // if we're running a light client or server, force enable the v5 peer discovery 767 // unless it is explicitly disabled with --nodiscover note that explicitly specifying 768 // --v5disc overrides --nodiscover, in which case the later only disables v4 discovery 769 forceV5Discovery := (ctx.GlobalBool(LightModeFlag.Name) || ctx.GlobalInt(LightServFlag.Name) > 0) && !ctx.GlobalBool(NoDiscoverFlag.Name) 770 if ctx.GlobalIsSet(DiscoveryV5Flag.Name) { 771 cfg.DiscoveryV5 = ctx.GlobalBool(DiscoveryV5Flag.Name) 772 } else if forceV5Discovery { 773 cfg.DiscoveryV5 = true 774 } 775 776 if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" { 777 list, err := netutil.ParseNetlist(netrestrict) 778 if err != nil { 779 Fatalf("Option %q: %v", NetrestrictFlag.Name, err) 780 } 781 cfg.NetRestrict = list 782 } 783 784 if ctx.GlobalBool(DevModeFlag.Name) { 785 // --dev mode can't use p2p networking. 786 cfg.MaxPeers = 0 787 cfg.ListenAddr = ":0" 788 cfg.DiscoveryV5Addr = ":0" 789 cfg.NoDiscovery = true 790 cfg.DiscoveryV5 = false 791 } 792 } 793 794 // SetNodeConfig applies node-related command line flags to the config. 795 func SetNodeConfig(ctx *cli.Context, cfg *node.Config) { 796 SetP2PConfig(ctx, &cfg.P2P) 797 setIPC(ctx, cfg) 798 setHTTP(ctx, cfg) 799 setWS(ctx, cfg) 800 setNodeUserIdent(ctx, cfg) 801 802 switch { 803 case ctx.GlobalIsSet(DataDirFlag.Name): 804 cfg.DataDir = ctx.GlobalString(DataDirFlag.Name) 805 case ctx.GlobalBool(DevModeFlag.Name): 806 cfg.DataDir = filepath.Join(os.TempDir(), "ethereum_dev_mode") 807 case ctx.GlobalBool(TestnetFlag.Name): 808 cfg.DataDir = filepath.Join(node.DefaultDataDir(), "testnet") 809 case ctx.GlobalBool(RinkebyFlag.Name): 810 cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby") 811 } 812 813 if ctx.GlobalIsSet(KeyStoreDirFlag.Name) { 814 cfg.KeyStoreDir = ctx.GlobalString(KeyStoreDirFlag.Name) 815 } 816 if ctx.GlobalIsSet(LightKDFFlag.Name) { 817 cfg.UseLightweightKDF = ctx.GlobalBool(LightKDFFlag.Name) 818 } 819 if ctx.GlobalIsSet(NoUSBFlag.Name) { 820 cfg.NoUSB = ctx.GlobalBool(NoUSBFlag.Name) 821 } 822 } 823 824 func setGPO(ctx *cli.Context, cfg *gasprice.Config) { 825 if ctx.GlobalIsSet(GpoBlocksFlag.Name) { 826 cfg.Blocks = ctx.GlobalInt(GpoBlocksFlag.Name) 827 } 828 if ctx.GlobalIsSet(GpoPercentileFlag.Name) { 829 cfg.Percentile = ctx.GlobalInt(GpoPercentileFlag.Name) 830 } 831 } 832 833 func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) { 834 if ctx.GlobalIsSet(TxPoolPriceLimitFlag.Name) { 835 cfg.PriceLimit = ctx.GlobalUint64(TxPoolPriceLimitFlag.Name) 836 } 837 if ctx.GlobalIsSet(TxPoolPriceBumpFlag.Name) { 838 cfg.PriceBump = ctx.GlobalUint64(TxPoolPriceBumpFlag.Name) 839 } 840 if ctx.GlobalIsSet(TxPoolAccountSlotsFlag.Name) { 841 cfg.AccountSlots = ctx.GlobalUint64(TxPoolAccountSlotsFlag.Name) 842 } 843 if ctx.GlobalIsSet(TxPoolGlobalSlotsFlag.Name) { 844 cfg.GlobalSlots = ctx.GlobalUint64(TxPoolGlobalSlotsFlag.Name) 845 } 846 if ctx.GlobalIsSet(TxPoolAccountQueueFlag.Name) { 847 cfg.AccountQueue = ctx.GlobalUint64(TxPoolAccountQueueFlag.Name) 848 } 849 if ctx.GlobalIsSet(TxPoolGlobalQueueFlag.Name) { 850 cfg.GlobalQueue = ctx.GlobalUint64(TxPoolGlobalQueueFlag.Name) 851 } 852 if ctx.GlobalIsSet(TxPoolLifetimeFlag.Name) { 853 cfg.Lifetime = ctx.GlobalDuration(TxPoolLifetimeFlag.Name) 854 } 855 } 856 857 func setEthash(ctx *cli.Context, cfg *eth.Config) { 858 if ctx.GlobalIsSet(EthashCacheDirFlag.Name) { 859 cfg.EthashCacheDir = ctx.GlobalString(EthashCacheDirFlag.Name) 860 } 861 if ctx.GlobalIsSet(EthashDatasetDirFlag.Name) { 862 cfg.EthashDatasetDir = ctx.GlobalString(EthashDatasetDirFlag.Name) 863 } 864 if ctx.GlobalIsSet(EthashCachesInMemoryFlag.Name) { 865 cfg.EthashCachesInMem = ctx.GlobalInt(EthashCachesInMemoryFlag.Name) 866 } 867 if ctx.GlobalIsSet(EthashCachesOnDiskFlag.Name) { 868 cfg.EthashCachesOnDisk = ctx.GlobalInt(EthashCachesOnDiskFlag.Name) 869 } 870 if ctx.GlobalIsSet(EthashDatasetsInMemoryFlag.Name) { 871 cfg.EthashDatasetsInMem = ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name) 872 } 873 if ctx.GlobalIsSet(EthashDatasetsOnDiskFlag.Name) { 874 cfg.EthashDatasetsOnDisk = ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name) 875 } 876 } 877 878 func checkExclusive(ctx *cli.Context, flags ...cli.Flag) { 879 set := make([]string, 0, 1) 880 for _, flag := range flags { 881 if ctx.GlobalIsSet(flag.GetName()) { 882 set = append(set, "--"+flag.GetName()) 883 } 884 } 885 if len(set) > 1 { 886 Fatalf("flags %v can't be used at the same time", strings.Join(set, ", ")) 887 } 888 } 889 890 // SetShhConfig applies shh-related command line flags to the config. 891 func SetShhConfig(ctx *cli.Context, stack *node.Node, cfg *whisper.Config) { 892 if ctx.GlobalIsSet(WhisperMaxMessageSizeFlag.Name) { 893 cfg.MaxMessageSize = uint32(ctx.GlobalUint(WhisperMaxMessageSizeFlag.Name)) 894 } 895 if ctx.GlobalIsSet(WhisperMinPOWFlag.Name) { 896 cfg.MinimumAcceptedPOW = ctx.GlobalFloat64(WhisperMinPOWFlag.Name) 897 } 898 } 899 900 // SetEthConfig applies eth-related command line flags to the config. 901 func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) { 902 // Avoid conflicting network flags 903 checkExclusive(ctx, DevModeFlag, TestnetFlag, RinkebyFlag) 904 checkExclusive(ctx, FastSyncFlag, LightModeFlag, SyncModeFlag) 905 906 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 907 setEtherbase(ctx, ks, cfg) 908 setGPO(ctx, &cfg.GPO) 909 setTxPool(ctx, &cfg.TxPool) 910 setEthash(ctx, cfg) 911 912 switch { 913 case ctx.GlobalIsSet(SyncModeFlag.Name): 914 cfg.SyncMode = *GlobalTextMarshaler(ctx, SyncModeFlag.Name).(*downloader.SyncMode) 915 case ctx.GlobalBool(FastSyncFlag.Name): 916 cfg.SyncMode = downloader.FastSync 917 case ctx.GlobalBool(LightModeFlag.Name): 918 cfg.SyncMode = downloader.LightSync 919 } 920 if ctx.GlobalIsSet(LightServFlag.Name) { 921 cfg.LightServ = ctx.GlobalInt(LightServFlag.Name) 922 } 923 if ctx.GlobalIsSet(LightPeersFlag.Name) { 924 cfg.LightPeers = ctx.GlobalInt(LightPeersFlag.Name) 925 } 926 if ctx.GlobalIsSet(NetworkIdFlag.Name) { 927 cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name) 928 } 929 930 // Ethereum needs to know maxPeers to calculate the light server peer ratio. 931 // TODO(fjl): ensure Ethereum can get MaxPeers from node. 932 cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name) 933 934 if ctx.GlobalIsSet(CacheFlag.Name) { 935 cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name) 936 } 937 cfg.DatabaseHandles = makeDatabaseHandles() 938 939 if ctx.GlobalIsSet(MinerThreadsFlag.Name) { 940 cfg.MinerThreads = ctx.GlobalInt(MinerThreadsFlag.Name) 941 } 942 if ctx.GlobalIsSet(DocRootFlag.Name) { 943 cfg.DocRoot = ctx.GlobalString(DocRootFlag.Name) 944 } 945 if ctx.GlobalIsSet(ExtraDataFlag.Name) { 946 cfg.ExtraData = []byte(ctx.GlobalString(ExtraDataFlag.Name)) 947 } 948 if ctx.GlobalIsSet(GasPriceFlag.Name) { 949 cfg.GasPrice = GlobalBig(ctx, GasPriceFlag.Name) 950 } 951 if ctx.GlobalIsSet(VMEnableDebugFlag.Name) { 952 // TODO(fjl): force-enable this in --dev mode 953 cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name) 954 } 955 956 // Override any default configs for hard coded networks. 957 switch { 958 case ctx.GlobalBool(TestnetFlag.Name): 959 if !ctx.GlobalIsSet(NetworkIdFlag.Name) { 960 cfg.NetworkId = 3 961 } 962 cfg.Genesis = core.DefaultTestnetGenesisBlock() 963 case ctx.GlobalBool(RinkebyFlag.Name): 964 if !ctx.GlobalIsSet(NetworkIdFlag.Name) { 965 cfg.NetworkId = 4 966 } 967 cfg.Genesis = core.DefaultRinkebyGenesisBlock() 968 case ctx.GlobalBool(DevModeFlag.Name): 969 cfg.Genesis = core.DevGenesisBlock() 970 if !ctx.GlobalIsSet(GasPriceFlag.Name) { 971 cfg.GasPrice = new(big.Int) 972 } 973 cfg.PowTest = true 974 } 975 976 // TODO(fjl): move trie cache generations into config 977 if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 { 978 state.MaxTrieCacheGen = uint16(gen) 979 } 980 } 981 982 // RegisterEthService adds an Ethereum client to the stack. 983 func RegisterEthService(stack *node.Node, cfg *eth.Config) { 984 var err error 985 if cfg.SyncMode == downloader.LightSync { 986 err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 987 return les.New(ctx, cfg) 988 }) 989 } else { 990 err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 991 fullNode, err := eth.New(ctx, cfg) 992 if fullNode != nil && cfg.LightServ > 0 { 993 ls, _ := les.NewLesServer(fullNode, cfg) 994 fullNode.AddLesServer(ls) 995 } 996 return fullNode, err 997 }) 998 } 999 if err != nil { 1000 Fatalf("Failed to register the Ethereum service: %v", err) 1001 } 1002 } 1003 1004 // RegisterShhService configures Whisper and adds it to the given node. 1005 func RegisterShhService(stack *node.Node, cfg *whisper.Config) { 1006 if err := stack.Register(func(n *node.ServiceContext) (node.Service, error) { 1007 return whisper.New(cfg), nil 1008 }); err != nil { 1009 Fatalf("Failed to register the Whisper service: %v", err) 1010 } 1011 } 1012 1013 // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to 1014 // th egiven node. 1015 func RegisterEthStatsService(stack *node.Node, url string) { 1016 if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 1017 // Retrieve both eth and les services 1018 var ethServ *eth.Ethereum 1019 ctx.Service(ðServ) 1020 1021 var lesServ *les.LightEthereum 1022 ctx.Service(&lesServ) 1023 1024 return ethstats.New(url, ethServ, lesServ) 1025 }); err != nil { 1026 Fatalf("Failed to register the Ethereum Stats service: %v", err) 1027 } 1028 } 1029 1030 // SetupNetwork configures the system for either the main net or some test network. 1031 func SetupNetwork(ctx *cli.Context) { 1032 // TODO(fjl): move target gas limit into config 1033 params.TargetGasLimit = new(big.Int).SetUint64(ctx.GlobalUint64(TargetGasLimitFlag.Name)) 1034 } 1035 1036 // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails. 1037 func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database { 1038 var ( 1039 cache = ctx.GlobalInt(CacheFlag.Name) 1040 handles = makeDatabaseHandles() 1041 ) 1042 name := "chaindata" 1043 if ctx.GlobalBool(LightModeFlag.Name) { 1044 name = "lightchaindata" 1045 } 1046 chainDb, err := stack.OpenDatabase(name, cache, handles) 1047 if err != nil { 1048 Fatalf("Could not open database: %v", err) 1049 } 1050 return chainDb 1051 } 1052 1053 func MakeGenesis(ctx *cli.Context) *core.Genesis { 1054 var genesis *core.Genesis 1055 switch { 1056 case ctx.GlobalBool(TestnetFlag.Name): 1057 genesis = core.DefaultTestnetGenesisBlock() 1058 case ctx.GlobalBool(RinkebyFlag.Name): 1059 genesis = core.DefaultRinkebyGenesisBlock() 1060 case ctx.GlobalBool(DevModeFlag.Name): 1061 genesis = core.DevGenesisBlock() 1062 } 1063 return genesis 1064 } 1065 1066 // MakeChain creates a chain manager from set command line flags. 1067 func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) { 1068 var err error 1069 chainDb = MakeChainDatabase(ctx, stack) 1070 1071 engine := ethash.NewFaker() 1072 if !ctx.GlobalBool(FakePoWFlag.Name) { 1073 engine = ethash.New("", 1, 0, "", 1, 0) 1074 } 1075 config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx)) 1076 if err != nil { 1077 Fatalf("%v", err) 1078 } 1079 vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)} 1080 chain, err = core.NewBlockChain(chainDb, config, engine, new(event.TypeMux), vmcfg) 1081 if err != nil { 1082 Fatalf("Can't create BlockChain: %v", err) 1083 } 1084 return chain, chainDb 1085 } 1086 1087 // MakeConsolePreloads retrieves the absolute paths for the console JavaScript 1088 // scripts to preload before starting. 1089 func MakeConsolePreloads(ctx *cli.Context) []string { 1090 // Skip preloading if there's nothing to preload 1091 if ctx.GlobalString(PreloadJSFlag.Name) == "" { 1092 return nil 1093 } 1094 // Otherwise resolve absolute paths and return them 1095 preloads := []string{} 1096 1097 assets := ctx.GlobalString(JSpathFlag.Name) 1098 for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") { 1099 preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file))) 1100 } 1101 return preloads 1102 } 1103 1104 // MigrateFlags sets the global flag from a local flag when it's set. 1105 // This is a temporary function used for migrating old command/flags to the 1106 // new format. 1107 // 1108 // e.g. geth account new --keystore /tmp/mykeystore --lightkdf 1109 // 1110 // is equivalent after calling this method with: 1111 // 1112 // geth --keystore /tmp/mykeystore --lightkdf account new 1113 // 1114 // This allows the use of the existing configuration functionality. 1115 // When all flags are migrated this function can be removed and the existing 1116 // configuration functionality must be changed that is uses local flags 1117 func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error { 1118 return func(ctx *cli.Context) error { 1119 for _, name := range ctx.FlagNames() { 1120 if ctx.IsSet(name) { 1121 ctx.GlobalSet(name, ctx.String(name)) 1122 } 1123 } 1124 return action(ctx) 1125 } 1126 }