github.com/ImPedro29/bor@v0.2.7/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" 24 "io/ioutil" 25 "math" 26 "math/big" 27 "os" 28 "path/filepath" 29 godebug "runtime/debug" 30 "strconv" 31 "strings" 32 "text/tabwriter" 33 "text/template" 34 "time" 35 36 "github.com/ethereum/go-ethereum/accounts" 37 "github.com/ethereum/go-ethereum/accounts/keystore" 38 "github.com/ethereum/go-ethereum/common" 39 "github.com/ethereum/go-ethereum/common/fdlimit" 40 "github.com/ethereum/go-ethereum/consensus" 41 "github.com/ethereum/go-ethereum/consensus/clique" 42 "github.com/ethereum/go-ethereum/consensus/ethash" 43 "github.com/ethereum/go-ethereum/core" 44 "github.com/ethereum/go-ethereum/core/rawdb" 45 "github.com/ethereum/go-ethereum/core/vm" 46 "github.com/ethereum/go-ethereum/crypto" 47 "github.com/ethereum/go-ethereum/eth" 48 "github.com/ethereum/go-ethereum/eth/downloader" 49 "github.com/ethereum/go-ethereum/eth/ethconfig" 50 "github.com/ethereum/go-ethereum/eth/gasprice" 51 "github.com/ethereum/go-ethereum/eth/tracers" 52 "github.com/ethereum/go-ethereum/ethdb" 53 "github.com/ethereum/go-ethereum/ethstats" 54 "github.com/ethereum/go-ethereum/graphql" 55 "github.com/ethereum/go-ethereum/internal/ethapi" 56 "github.com/ethereum/go-ethereum/internal/flags" 57 "github.com/ethereum/go-ethereum/les" 58 "github.com/ethereum/go-ethereum/log" 59 "github.com/ethereum/go-ethereum/metrics" 60 "github.com/ethereum/go-ethereum/metrics/exp" 61 "github.com/ethereum/go-ethereum/metrics/influxdb" 62 "github.com/ethereum/go-ethereum/miner" 63 "github.com/ethereum/go-ethereum/node" 64 "github.com/ethereum/go-ethereum/p2p" 65 "github.com/ethereum/go-ethereum/p2p/enode" 66 "github.com/ethereum/go-ethereum/p2p/nat" 67 "github.com/ethereum/go-ethereum/p2p/netutil" 68 "github.com/ethereum/go-ethereum/params" 69 pcsclite "github.com/gballet/go-libpcsclite" 70 gopsutil "github.com/shirou/gopsutil/mem" 71 "gopkg.in/urfave/cli.v1" 72 ) 73 74 func init() { 75 cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...] 76 77 VERSION: 78 {{.Version}} 79 80 COMMANDS: 81 {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}} 82 {{end}}{{if .Flags}} 83 GLOBAL OPTIONS: 84 {{range .Flags}}{{.}} 85 {{end}}{{end}} 86 ` 87 cli.CommandHelpTemplate = flags.CommandHelpTemplate 88 cli.HelpPrinter = printHelp 89 } 90 91 func printHelp(out io.Writer, templ string, data interface{}) { 92 funcMap := template.FuncMap{"join": strings.Join} 93 t := template.Must(template.New("help").Funcs(funcMap).Parse(templ)) 94 w := tabwriter.NewWriter(out, 38, 8, 2, ' ', 0) 95 err := t.Execute(w, data) 96 if err != nil { 97 panic(err) 98 } 99 w.Flush() 100 } 101 102 // These are all the command line flags we support. 103 // If you add to this list, please remember to include the 104 // flag in the appropriate command definition. 105 // 106 // The flags are defined here so their names and help texts 107 // are the same for all commands. 108 109 var ( 110 // General settings 111 DataDirFlag = DirectoryFlag{ 112 Name: "datadir", 113 Usage: "Data directory for the databases and keystore", 114 Value: DirectoryString(node.DefaultDataDir()), 115 } 116 AncientFlag = DirectoryFlag{ 117 Name: "datadir.ancient", 118 Usage: "Data directory for ancient chain segments (default = inside chaindata)", 119 } 120 MinFreeDiskSpaceFlag = DirectoryFlag{ 121 Name: "datadir.minfreedisk", 122 Usage: "Minimum free disk space in MB, once reached triggers auto shut down (default = --cache.gc converted to MB, 0 = disabled)", 123 } 124 KeyStoreDirFlag = DirectoryFlag{ 125 Name: "keystore", 126 Usage: "Directory for the keystore (default = inside the datadir)", 127 } 128 NoUSBFlag = cli.BoolFlag{ 129 Name: "nousb", 130 Usage: "Disables monitoring for and managing USB hardware wallets (deprecated)", 131 } 132 USBFlag = cli.BoolFlag{ 133 Name: "usb", 134 Usage: "Enable monitoring and management of USB hardware wallets", 135 } 136 SmartCardDaemonPathFlag = cli.StringFlag{ 137 Name: "pcscdpath", 138 Usage: "Path to the smartcard daemon (pcscd) socket file", 139 Value: pcsclite.PCSCDSockName, 140 } 141 NetworkIdFlag = cli.Uint64Flag{ 142 Name: "networkid", 143 Usage: "Explicitly set network id (integer)(For testnets: use --ropsten, --rinkeby, --goerli instead)", 144 Value: ethconfig.Defaults.NetworkId, 145 } 146 MainnetFlag = cli.BoolFlag{ 147 Name: "mainnet", 148 Usage: "Ethereum mainnet", 149 } 150 GoerliFlag = cli.BoolFlag{ 151 Name: "goerli", 152 Usage: "Görli network: pre-configured proof-of-authority test network", 153 } 154 YoloV3Flag = cli.BoolFlag{ 155 Name: "yolov3", 156 Usage: "YOLOv3 network: pre-configured proof-of-authority shortlived test network.", 157 } 158 RinkebyFlag = cli.BoolFlag{ 159 Name: "rinkeby", 160 Usage: "Rinkeby network: pre-configured proof-of-authority test network", 161 } 162 RopstenFlag = cli.BoolFlag{ 163 Name: "ropsten", 164 Usage: "Ropsten network: pre-configured proof-of-work test network", 165 } 166 DeveloperFlag = cli.BoolFlag{ 167 Name: "dev", 168 Usage: "Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled", 169 } 170 DeveloperPeriodFlag = cli.IntFlag{ 171 Name: "dev.period", 172 Usage: "Block period to use in developer mode (0 = mine only if transaction pending)", 173 } 174 IdentityFlag = cli.StringFlag{ 175 Name: "identity", 176 Usage: "Custom node name", 177 } 178 DocRootFlag = DirectoryFlag{ 179 Name: "docroot", 180 Usage: "Document Root for HTTPClient file scheme", 181 Value: DirectoryString(HomeDir()), 182 } 183 ExitWhenSyncedFlag = cli.BoolFlag{ 184 Name: "exitwhensynced", 185 Usage: "Exits after block synchronisation completes", 186 } 187 IterativeOutputFlag = cli.BoolFlag{ 188 Name: "iterative", 189 Usage: "Print streaming JSON iteratively, delimited by newlines", 190 } 191 ExcludeStorageFlag = cli.BoolFlag{ 192 Name: "nostorage", 193 Usage: "Exclude storage entries (save db lookups)", 194 } 195 IncludeIncompletesFlag = cli.BoolFlag{ 196 Name: "incompletes", 197 Usage: "Include accounts for which we don't have the address (missing preimage)", 198 } 199 ExcludeCodeFlag = cli.BoolFlag{ 200 Name: "nocode", 201 Usage: "Exclude contract code (save db lookups)", 202 } 203 defaultSyncMode = ethconfig.Defaults.SyncMode 204 SyncModeFlag = TextMarshalerFlag{ 205 Name: "syncmode", 206 Usage: `Blockchain sync mode ("fast", "full", "snap" or "light")`, 207 Value: &defaultSyncMode, 208 } 209 GCModeFlag = cli.StringFlag{ 210 Name: "gcmode", 211 Usage: `Blockchain garbage collection mode ("full", "archive")`, 212 Value: "full", 213 } 214 SnapshotFlag = cli.BoolTFlag{ 215 Name: "snapshot", 216 Usage: `Enables snapshot-database mode (default = enable)`, 217 } 218 TxLookupLimitFlag = cli.Uint64Flag{ 219 Name: "txlookuplimit", 220 Usage: "Number of recent blocks to maintain transactions index for (default = about one year, 0 = entire chain)", 221 Value: ethconfig.Defaults.TxLookupLimit, 222 } 223 LightKDFFlag = cli.BoolFlag{ 224 Name: "lightkdf", 225 Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength", 226 } 227 WhitelistFlag = cli.StringFlag{ 228 Name: "whitelist", 229 Usage: "Comma separated block number-to-hash mappings to enforce (<number>=<hash>)", 230 } 231 BloomFilterSizeFlag = cli.Uint64Flag{ 232 Name: "bloomfilter.size", 233 Usage: "Megabytes of memory allocated to bloom-filter for pruning", 234 Value: 2048, 235 } 236 OverrideBerlinFlag = cli.Uint64Flag{ 237 Name: "override.berlin", 238 Usage: "Manually specify Berlin fork-block, overriding the bundled setting", 239 } 240 // Light server and client settings 241 LightServeFlag = cli.IntFlag{ 242 Name: "light.serve", 243 Usage: "Maximum percentage of time allowed for serving LES requests (multi-threaded processing allows values over 100)", 244 Value: ethconfig.Defaults.LightServ, 245 } 246 LightIngressFlag = cli.IntFlag{ 247 Name: "light.ingress", 248 Usage: "Incoming bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited)", 249 Value: ethconfig.Defaults.LightIngress, 250 } 251 LightEgressFlag = cli.IntFlag{ 252 Name: "light.egress", 253 Usage: "Outgoing bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited)", 254 Value: ethconfig.Defaults.LightEgress, 255 } 256 LightMaxPeersFlag = cli.IntFlag{ 257 Name: "light.maxpeers", 258 Usage: "Maximum number of light clients to serve, or light servers to attach to", 259 Value: ethconfig.Defaults.LightPeers, 260 } 261 UltraLightServersFlag = cli.StringFlag{ 262 Name: "ulc.servers", 263 Usage: "List of trusted ultra-light servers", 264 Value: strings.Join(ethconfig.Defaults.UltraLightServers, ","), 265 } 266 UltraLightFractionFlag = cli.IntFlag{ 267 Name: "ulc.fraction", 268 Usage: "Minimum % of trusted ultra-light servers required to announce a new head", 269 Value: ethconfig.Defaults.UltraLightFraction, 270 } 271 UltraLightOnlyAnnounceFlag = cli.BoolFlag{ 272 Name: "ulc.onlyannounce", 273 Usage: "Ultra light server sends announcements only", 274 } 275 LightNoPruneFlag = cli.BoolFlag{ 276 Name: "light.nopruning", 277 Usage: "Disable ancient light chain data pruning", 278 } 279 LightNoSyncServeFlag = cli.BoolFlag{ 280 Name: "light.nosyncserve", 281 Usage: "Enables serving light clients before syncing", 282 } 283 // Ethash settings 284 EthashCacheDirFlag = DirectoryFlag{ 285 Name: "ethash.cachedir", 286 Usage: "Directory to store the ethash verification caches (default = inside the datadir)", 287 } 288 EthashCachesInMemoryFlag = cli.IntFlag{ 289 Name: "ethash.cachesinmem", 290 Usage: "Number of recent ethash caches to keep in memory (16MB each)", 291 Value: ethconfig.Defaults.Ethash.CachesInMem, 292 } 293 EthashCachesOnDiskFlag = cli.IntFlag{ 294 Name: "ethash.cachesondisk", 295 Usage: "Number of recent ethash caches to keep on disk (16MB each)", 296 Value: ethconfig.Defaults.Ethash.CachesOnDisk, 297 } 298 EthashCachesLockMmapFlag = cli.BoolFlag{ 299 Name: "ethash.cacheslockmmap", 300 Usage: "Lock memory maps of recent ethash caches", 301 } 302 EthashDatasetDirFlag = DirectoryFlag{ 303 Name: "ethash.dagdir", 304 Usage: "Directory to store the ethash mining DAGs", 305 Value: DirectoryString(ethconfig.Defaults.Ethash.DatasetDir), 306 } 307 EthashDatasetsInMemoryFlag = cli.IntFlag{ 308 Name: "ethash.dagsinmem", 309 Usage: "Number of recent ethash mining DAGs to keep in memory (1+GB each)", 310 Value: ethconfig.Defaults.Ethash.DatasetsInMem, 311 } 312 EthashDatasetsOnDiskFlag = cli.IntFlag{ 313 Name: "ethash.dagsondisk", 314 Usage: "Number of recent ethash mining DAGs to keep on disk (1+GB each)", 315 Value: ethconfig.Defaults.Ethash.DatasetsOnDisk, 316 } 317 EthashDatasetsLockMmapFlag = cli.BoolFlag{ 318 Name: "ethash.dagslockmmap", 319 Usage: "Lock memory maps for recent ethash mining DAGs", 320 } 321 // Transaction pool settings 322 TxPoolLocalsFlag = cli.StringFlag{ 323 Name: "txpool.locals", 324 Usage: "Comma separated accounts to treat as locals (no flush, priority inclusion)", 325 } 326 TxPoolNoLocalsFlag = cli.BoolFlag{ 327 Name: "txpool.nolocals", 328 Usage: "Disables price exemptions for locally submitted transactions", 329 } 330 TxPoolJournalFlag = cli.StringFlag{ 331 Name: "txpool.journal", 332 Usage: "Disk journal for local transaction to survive node restarts", 333 Value: core.DefaultTxPoolConfig.Journal, 334 } 335 TxPoolRejournalFlag = cli.DurationFlag{ 336 Name: "txpool.rejournal", 337 Usage: "Time interval to regenerate the local transaction journal", 338 Value: core.DefaultTxPoolConfig.Rejournal, 339 } 340 TxPoolPriceLimitFlag = cli.Uint64Flag{ 341 Name: "txpool.pricelimit", 342 Usage: "Minimum gas price limit to enforce for acceptance into the pool", 343 Value: ethconfig.Defaults.TxPool.PriceLimit, 344 } 345 TxPoolPriceBumpFlag = cli.Uint64Flag{ 346 Name: "txpool.pricebump", 347 Usage: "Price bump percentage to replace an already existing transaction", 348 Value: ethconfig.Defaults.TxPool.PriceBump, 349 } 350 TxPoolAccountSlotsFlag = cli.Uint64Flag{ 351 Name: "txpool.accountslots", 352 Usage: "Minimum number of executable transaction slots guaranteed per account", 353 Value: ethconfig.Defaults.TxPool.AccountSlots, 354 } 355 TxPoolGlobalSlotsFlag = cli.Uint64Flag{ 356 Name: "txpool.globalslots", 357 Usage: "Maximum number of executable transaction slots for all accounts", 358 Value: ethconfig.Defaults.TxPool.GlobalSlots, 359 } 360 TxPoolAccountQueueFlag = cli.Uint64Flag{ 361 Name: "txpool.accountqueue", 362 Usage: "Maximum number of non-executable transaction slots permitted per account", 363 Value: ethconfig.Defaults.TxPool.AccountQueue, 364 } 365 TxPoolGlobalQueueFlag = cli.Uint64Flag{ 366 Name: "txpool.globalqueue", 367 Usage: "Maximum number of non-executable transaction slots for all accounts", 368 Value: ethconfig.Defaults.TxPool.GlobalQueue, 369 } 370 TxPoolLifetimeFlag = cli.DurationFlag{ 371 Name: "txpool.lifetime", 372 Usage: "Maximum amount of time non-executable transaction are queued", 373 Value: ethconfig.Defaults.TxPool.Lifetime, 374 } 375 // Performance tuning settings 376 BorLogsFlag = cli.BoolFlag{ 377 Name: "bor.logs", 378 Usage: "Enable bor logs retrieval", 379 } 380 CacheFlag = cli.IntFlag{ 381 Name: "cache", 382 Usage: "Megabytes of memory allocated to internal caching (default = 4096 mainnet full node, 128 light mode)", 383 Value: 1024, 384 } 385 CacheDatabaseFlag = cli.IntFlag{ 386 Name: "cache.database", 387 Usage: "Percentage of cache memory allowance to use for database io", 388 Value: 50, 389 } 390 CacheTrieFlag = cli.IntFlag{ 391 Name: "cache.trie", 392 Usage: "Percentage of cache memory allowance to use for trie caching (default = 15% full mode, 30% archive mode)", 393 Value: 15, 394 } 395 CacheTrieJournalFlag = cli.StringFlag{ 396 Name: "cache.trie.journal", 397 Usage: "Disk journal directory for trie cache to survive node restarts", 398 Value: ethconfig.Defaults.TrieCleanCacheJournal, 399 } 400 CacheTrieRejournalFlag = cli.DurationFlag{ 401 Name: "cache.trie.rejournal", 402 Usage: "Time interval to regenerate the trie cache journal", 403 Value: ethconfig.Defaults.TrieCleanCacheRejournal, 404 } 405 CacheGCFlag = cli.IntFlag{ 406 Name: "cache.gc", 407 Usage: "Percentage of cache memory allowance to use for trie pruning (default = 25% full mode, 0% archive mode)", 408 Value: 25, 409 } 410 CacheSnapshotFlag = cli.IntFlag{ 411 Name: "cache.snapshot", 412 Usage: "Percentage of cache memory allowance to use for snapshot caching (default = 10% full mode, 20% archive mode)", 413 Value: 10, 414 } 415 CacheNoPrefetchFlag = cli.BoolFlag{ 416 Name: "cache.noprefetch", 417 Usage: "Disable heuristic state prefetch during block import (less CPU and disk IO, more time waiting for data)", 418 } 419 CachePreimagesFlag = cli.BoolFlag{ 420 Name: "cache.preimages", 421 Usage: "Enable recording the SHA3/keccak preimages of trie keys", 422 } 423 // Miner settings 424 MiningEnabledFlag = cli.BoolFlag{ 425 Name: "mine", 426 Usage: "Enable mining", 427 } 428 MinerThreadsFlag = cli.IntFlag{ 429 Name: "miner.threads", 430 Usage: "Number of CPU threads to use for mining", 431 Value: 0, 432 } 433 MinerNotifyFlag = cli.StringFlag{ 434 Name: "miner.notify", 435 Usage: "Comma separated HTTP URL list to notify of new work packages", 436 } 437 MinerNotifyFullFlag = cli.BoolFlag{ 438 Name: "miner.notify.full", 439 Usage: "Notify with pending block headers instead of work packages", 440 } 441 MinerGasTargetFlag = cli.Uint64Flag{ 442 Name: "miner.gastarget", 443 Usage: "Target gas floor for mined blocks", 444 Value: ethconfig.Defaults.Miner.GasFloor, 445 } 446 MinerGasLimitFlag = cli.Uint64Flag{ 447 Name: "miner.gaslimit", 448 Usage: "Target gas ceiling for mined blocks", 449 Value: ethconfig.Defaults.Miner.GasCeil, 450 } 451 MinerGasPriceFlag = BigFlag{ 452 Name: "miner.gasprice", 453 Usage: "Minimum gas price for mining a transaction", 454 Value: ethconfig.Defaults.Miner.GasPrice, 455 } 456 MinerEtherbaseFlag = cli.StringFlag{ 457 Name: "miner.etherbase", 458 Usage: "Public address for block mining rewards (default = first account)", 459 Value: "0", 460 } 461 MinerExtraDataFlag = cli.StringFlag{ 462 Name: "miner.extradata", 463 Usage: "Block extra data set by the miner (default = client version)", 464 } 465 MinerRecommitIntervalFlag = cli.DurationFlag{ 466 Name: "miner.recommit", 467 Usage: "Time interval to recreate the block being mined", 468 Value: ethconfig.Defaults.Miner.Recommit, 469 } 470 MinerNoVerfiyFlag = cli.BoolFlag{ 471 Name: "miner.noverify", 472 Usage: "Disable remote sealing verification", 473 } 474 // Account settings 475 UnlockedAccountFlag = cli.StringFlag{ 476 Name: "unlock", 477 Usage: "Comma separated list of accounts to unlock", 478 Value: "", 479 } 480 PasswordFileFlag = cli.StringFlag{ 481 Name: "password", 482 Usage: "Password file to use for non-interactive password input", 483 Value: "", 484 } 485 ExternalSignerFlag = cli.StringFlag{ 486 Name: "signer", 487 Usage: "External signer (url or path to ipc file)", 488 Value: "", 489 } 490 VMEnableDebugFlag = cli.BoolFlag{ 491 Name: "vmdebug", 492 Usage: "Record information useful for VM and contract debugging", 493 } 494 InsecureUnlockAllowedFlag = cli.BoolFlag{ 495 Name: "allow-insecure-unlock", 496 Usage: "Allow insecure account unlocking when account-related RPCs are exposed by http", 497 } 498 RPCGlobalGasCapFlag = cli.Uint64Flag{ 499 Name: "rpc.gascap", 500 Usage: "Sets a cap on gas that can be used in eth_call/estimateGas (0=infinite)", 501 Value: ethconfig.Defaults.RPCGasCap, 502 } 503 RPCGlobalTxFeeCapFlag = cli.Float64Flag{ 504 Name: "rpc.txfeecap", 505 Usage: "Sets a cap on transaction fee (in ether) that can be sent via the RPC APIs (0 = no cap)", 506 Value: ethconfig.Defaults.RPCTxFeeCap, 507 } 508 // Logging and debug settings 509 EthStatsURLFlag = cli.StringFlag{ 510 Name: "ethstats", 511 Usage: "Reporting URL of a ethstats service (nodename:secret@host:port)", 512 } 513 FakePoWFlag = cli.BoolFlag{ 514 Name: "fakepow", 515 Usage: "Disables proof-of-work verification", 516 } 517 NoCompactionFlag = cli.BoolFlag{ 518 Name: "nocompaction", 519 Usage: "Disables db compaction after import", 520 } 521 // RPC settings 522 IPCDisabledFlag = cli.BoolFlag{ 523 Name: "ipcdisable", 524 Usage: "Disable the IPC-RPC server", 525 } 526 IPCPathFlag = DirectoryFlag{ 527 Name: "ipcpath", 528 Usage: "Filename for IPC socket/pipe within the datadir (explicit paths escape it)", 529 } 530 HTTPEnabledFlag = cli.BoolFlag{ 531 Name: "http", 532 Usage: "Enable the HTTP-RPC server", 533 } 534 HTTPListenAddrFlag = cli.StringFlag{ 535 Name: "http.addr", 536 Usage: "HTTP-RPC server listening interface", 537 Value: node.DefaultHTTPHost, 538 } 539 HTTPPortFlag = cli.IntFlag{ 540 Name: "http.port", 541 Usage: "HTTP-RPC server listening port", 542 Value: node.DefaultHTTPPort, 543 } 544 HTTPCORSDomainFlag = cli.StringFlag{ 545 Name: "http.corsdomain", 546 Usage: "Comma separated list of domains from which to accept cross origin requests (browser enforced)", 547 Value: "", 548 } 549 HTTPVirtualHostsFlag = cli.StringFlag{ 550 Name: "http.vhosts", 551 Usage: "Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard.", 552 Value: strings.Join(node.DefaultConfig.HTTPVirtualHosts, ","), 553 } 554 HTTPApiFlag = cli.StringFlag{ 555 Name: "http.api", 556 Usage: "API's offered over the HTTP-RPC interface", 557 Value: "", 558 } 559 HTTPPathPrefixFlag = cli.StringFlag{ 560 Name: "http.rpcprefix", 561 Usage: "HTTP path path prefix on which JSON-RPC is served. Use '/' to serve on all paths.", 562 Value: "", 563 } 564 GraphQLEnabledFlag = cli.BoolFlag{ 565 Name: "graphql", 566 Usage: "Enable GraphQL on the HTTP-RPC server. Note that GraphQL can only be started if an HTTP server is started as well.", 567 } 568 GraphQLCORSDomainFlag = cli.StringFlag{ 569 Name: "graphql.corsdomain", 570 Usage: "Comma separated list of domains from which to accept cross origin requests (browser enforced)", 571 Value: "", 572 } 573 GraphQLVirtualHostsFlag = cli.StringFlag{ 574 Name: "graphql.vhosts", 575 Usage: "Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard.", 576 Value: strings.Join(node.DefaultConfig.GraphQLVirtualHosts, ","), 577 } 578 WSEnabledFlag = cli.BoolFlag{ 579 Name: "ws", 580 Usage: "Enable the WS-RPC server", 581 } 582 WSListenAddrFlag = cli.StringFlag{ 583 Name: "ws.addr", 584 Usage: "WS-RPC server listening interface", 585 Value: node.DefaultWSHost, 586 } 587 WSPortFlag = cli.IntFlag{ 588 Name: "ws.port", 589 Usage: "WS-RPC server listening port", 590 Value: node.DefaultWSPort, 591 } 592 WSApiFlag = cli.StringFlag{ 593 Name: "ws.api", 594 Usage: "API's offered over the WS-RPC interface", 595 Value: "", 596 } 597 WSAllowedOriginsFlag = cli.StringFlag{ 598 Name: "ws.origins", 599 Usage: "Origins from which to accept websockets requests", 600 Value: "", 601 } 602 WSPathPrefixFlag = cli.StringFlag{ 603 Name: "ws.rpcprefix", 604 Usage: "HTTP path prefix on which JSON-RPC is served. Use '/' to serve on all paths.", 605 Value: "", 606 } 607 ExecFlag = cli.StringFlag{ 608 Name: "exec", 609 Usage: "Execute JavaScript statement", 610 } 611 PreloadJSFlag = cli.StringFlag{ 612 Name: "preload", 613 Usage: "Comma separated list of JavaScript files to preload into the console", 614 } 615 AllowUnprotectedTxs = cli.BoolFlag{ 616 Name: "rpc.allow-unprotected-txs", 617 Usage: "Allow for unprotected (non EIP155 signed) transactions to be submitted via RPC", 618 } 619 620 // Network Settings 621 MaxPeersFlag = cli.IntFlag{ 622 Name: "maxpeers", 623 Usage: "Maximum number of network peers (network disabled if set to 0)", 624 Value: node.DefaultConfig.P2P.MaxPeers, 625 } 626 MaxPendingPeersFlag = cli.IntFlag{ 627 Name: "maxpendpeers", 628 Usage: "Maximum number of pending connection attempts (defaults used if set to 0)", 629 Value: node.DefaultConfig.P2P.MaxPendingPeers, 630 } 631 ListenPortFlag = cli.IntFlag{ 632 Name: "port", 633 Usage: "Network listening port", 634 Value: 30303, 635 } 636 BootnodesFlag = cli.StringFlag{ 637 Name: "bootnodes", 638 Usage: "Comma separated enode URLs for P2P discovery bootstrap", 639 Value: "", 640 } 641 NodeKeyFileFlag = cli.StringFlag{ 642 Name: "nodekey", 643 Usage: "P2P node key file", 644 } 645 NodeKeyHexFlag = cli.StringFlag{ 646 Name: "nodekeyhex", 647 Usage: "P2P node key as hex (for testing)", 648 } 649 NATFlag = cli.StringFlag{ 650 Name: "nat", 651 Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)", 652 Value: "any", 653 } 654 NoDiscoverFlag = cli.BoolFlag{ 655 Name: "nodiscover", 656 Usage: "Disables the peer discovery mechanism (manual peer addition)", 657 } 658 DiscoveryV5Flag = cli.BoolFlag{ 659 Name: "v5disc", 660 Usage: "Enables the experimental RLPx V5 (Topic Discovery) mechanism", 661 } 662 NetrestrictFlag = cli.StringFlag{ 663 Name: "netrestrict", 664 Usage: "Restricts network communication to the given IP networks (CIDR masks)", 665 } 666 DNSDiscoveryFlag = cli.StringFlag{ 667 Name: "discovery.dns", 668 Usage: "Sets DNS discovery entry points (use \"\" to disable DNS)", 669 } 670 671 // ATM the url is left to the user and deployment to 672 JSpathFlag = cli.StringFlag{ 673 Name: "jspath", 674 Usage: "JavaScript root path for `loadScript`", 675 Value: ".", 676 } 677 678 // Gas price oracle settings 679 GpoBlocksFlag = cli.IntFlag{ 680 Name: "gpo.blocks", 681 Usage: "Number of recent blocks to check for gas prices", 682 Value: ethconfig.Defaults.GPO.Blocks, 683 } 684 GpoPercentileFlag = cli.IntFlag{ 685 Name: "gpo.percentile", 686 Usage: "Suggested gas price is the given percentile of a set of recent transaction gas prices", 687 Value: ethconfig.Defaults.GPO.Percentile, 688 } 689 GpoMaxGasPriceFlag = cli.Int64Flag{ 690 Name: "gpo.maxprice", 691 Usage: "Maximum gas price will be recommended by gpo", 692 Value: ethconfig.Defaults.GPO.MaxPrice.Int64(), 693 } 694 695 // Metrics flags 696 MetricsEnabledFlag = cli.BoolFlag{ 697 Name: "metrics", 698 Usage: "Enable metrics collection and reporting", 699 } 700 MetricsEnabledExpensiveFlag = cli.BoolFlag{ 701 Name: "metrics.expensive", 702 Usage: "Enable expensive metrics collection and reporting", 703 } 704 705 // MetricsHTTPFlag defines the endpoint for a stand-alone metrics HTTP endpoint. 706 // Since the pprof service enables sensitive/vulnerable behavior, this allows a user 707 // to enable a public-OK metrics endpoint without having to worry about ALSO exposing 708 // other profiling behavior or information. 709 MetricsHTTPFlag = cli.StringFlag{ 710 Name: "metrics.addr", 711 Usage: "Enable stand-alone metrics HTTP server listening interface", 712 Value: metrics.DefaultConfig.HTTP, 713 } 714 MetricsPortFlag = cli.IntFlag{ 715 Name: "metrics.port", 716 Usage: "Metrics HTTP server listening port", 717 Value: metrics.DefaultConfig.Port, 718 } 719 MetricsEnableInfluxDBFlag = cli.BoolFlag{ 720 Name: "metrics.influxdb", 721 Usage: "Enable metrics export/push to an external InfluxDB database", 722 } 723 MetricsInfluxDBEndpointFlag = cli.StringFlag{ 724 Name: "metrics.influxdb.endpoint", 725 Usage: "InfluxDB API endpoint to report metrics to", 726 Value: metrics.DefaultConfig.InfluxDBEndpoint, 727 } 728 MetricsInfluxDBDatabaseFlag = cli.StringFlag{ 729 Name: "metrics.influxdb.database", 730 Usage: "InfluxDB database name to push reported metrics to", 731 Value: metrics.DefaultConfig.InfluxDBDatabase, 732 } 733 MetricsInfluxDBUsernameFlag = cli.StringFlag{ 734 Name: "metrics.influxdb.username", 735 Usage: "Username to authorize access to the database", 736 Value: metrics.DefaultConfig.InfluxDBUsername, 737 } 738 MetricsInfluxDBPasswordFlag = cli.StringFlag{ 739 Name: "metrics.influxdb.password", 740 Usage: "Password to authorize access to the database", 741 Value: metrics.DefaultConfig.InfluxDBPassword, 742 } 743 // Tags are part of every measurement sent to InfluxDB. Queries on tags are faster in InfluxDB. 744 // For example `host` tag could be used so that we can group all nodes and average a measurement 745 // across all of them, but also so that we can select a specific node and inspect its measurements. 746 // https://docs.influxdata.com/influxdb/v1.4/concepts/key_concepts/#tag-key 747 MetricsInfluxDBTagsFlag = cli.StringFlag{ 748 Name: "metrics.influxdb.tags", 749 Usage: "Comma-separated InfluxDB tags (key/values) attached to all measurements", 750 Value: metrics.DefaultConfig.InfluxDBTags, 751 } 752 EWASMInterpreterFlag = cli.StringFlag{ 753 Name: "vm.ewasm", 754 Usage: "External ewasm configuration (default = built-in interpreter)", 755 Value: "", 756 } 757 EVMInterpreterFlag = cli.StringFlag{ 758 Name: "vm.evm", 759 Usage: "External EVM configuration (default = built-in interpreter)", 760 Value: "", 761 } 762 763 CatalystFlag = cli.BoolFlag{ 764 Name: "catalyst", 765 Usage: "Catalyst mode (eth2 integration testing)", 766 } 767 ) 768 769 // MakeDataDir retrieves the currently requested data directory, terminating 770 // if none (or the empty string) is specified. If the node is starting a testnet, 771 // then a subdirectory of the specified datadir will be used. 772 func MakeDataDir(ctx *cli.Context) string { 773 if path := ctx.GlobalString(DataDirFlag.Name); path != "" { 774 if ctx.GlobalBool(RopstenFlag.Name) { 775 // Maintain compatibility with older Geth configurations storing the 776 // Ropsten database in `testnet` instead of `ropsten`. 777 return filepath.Join(path, "ropsten") 778 } 779 if ctx.GlobalBool(RinkebyFlag.Name) { 780 return filepath.Join(path, "rinkeby") 781 } 782 if ctx.GlobalBool(GoerliFlag.Name) { 783 return filepath.Join(path, "goerli") 784 } 785 if ctx.GlobalBool(YoloV3Flag.Name) { 786 return filepath.Join(path, "yolo-v3") 787 } 788 return path 789 } 790 Fatalf("Cannot determine default data directory, please set manually (--datadir)") 791 return "" 792 } 793 794 // setNodeKey creates a node key from set command line flags, either loading it 795 // from a file or as a specified hex value. If neither flags were provided, this 796 // method returns nil and an emphemeral key is to be generated. 797 func setNodeKey(ctx *cli.Context, cfg *p2p.Config) { 798 var ( 799 hex = ctx.GlobalString(NodeKeyHexFlag.Name) 800 file = ctx.GlobalString(NodeKeyFileFlag.Name) 801 key *ecdsa.PrivateKey 802 err error 803 ) 804 switch { 805 case file != "" && hex != "": 806 Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name) 807 case file != "": 808 if key, err = crypto.LoadECDSA(file); err != nil { 809 Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err) 810 } 811 cfg.PrivateKey = key 812 case hex != "": 813 if key, err = crypto.HexToECDSA(hex); err != nil { 814 Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err) 815 } 816 cfg.PrivateKey = key 817 } 818 } 819 820 // setNodeUserIdent creates the user identifier from CLI flags. 821 func setNodeUserIdent(ctx *cli.Context, cfg *node.Config) { 822 if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 { 823 cfg.UserIdent = identity 824 } 825 } 826 827 // setBootstrapNodes creates a list of bootstrap nodes from the command line 828 // flags, reverting to pre-configured ones if none have been specified. 829 func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) { 830 urls := params.MainnetBootnodes 831 switch { 832 case ctx.GlobalIsSet(BootnodesFlag.Name): 833 urls = SplitAndTrim(ctx.GlobalString(BootnodesFlag.Name)) 834 case ctx.GlobalBool(RopstenFlag.Name): 835 urls = params.RopstenBootnodes 836 case ctx.GlobalBool(RinkebyFlag.Name): 837 urls = params.RinkebyBootnodes 838 case ctx.GlobalBool(GoerliFlag.Name): 839 urls = params.GoerliBootnodes 840 case ctx.GlobalBool(YoloV3Flag.Name): 841 urls = params.YoloV3Bootnodes 842 case cfg.BootstrapNodes != nil: 843 return // already set, don't apply defaults. 844 } 845 846 cfg.BootstrapNodes = make([]*enode.Node, 0, len(urls)) 847 for _, url := range urls { 848 if url != "" { 849 node, err := enode.Parse(enode.ValidSchemes, url) 850 if err != nil { 851 log.Crit("Bootstrap URL invalid", "enode", url, "err", err) 852 continue 853 } 854 cfg.BootstrapNodes = append(cfg.BootstrapNodes, node) 855 } 856 } 857 } 858 859 // setBootstrapNodesV5 creates a list of bootstrap nodes from the command line 860 // flags, reverting to pre-configured ones if none have been specified. 861 func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) { 862 urls := params.V5Bootnodes 863 switch { 864 case ctx.GlobalIsSet(BootnodesFlag.Name): 865 urls = SplitAndTrim(ctx.GlobalString(BootnodesFlag.Name)) 866 case cfg.BootstrapNodesV5 != nil: 867 return // already set, don't apply defaults. 868 } 869 870 cfg.BootstrapNodesV5 = make([]*enode.Node, 0, len(urls)) 871 for _, url := range urls { 872 if url != "" { 873 node, err := enode.Parse(enode.ValidSchemes, url) 874 if err != nil { 875 log.Error("Bootstrap URL invalid", "enode", url, "err", err) 876 continue 877 } 878 cfg.BootstrapNodesV5 = append(cfg.BootstrapNodesV5, node) 879 } 880 } 881 } 882 883 // setListenAddress creates a TCP listening address string from set command 884 // line flags. 885 func setListenAddress(ctx *cli.Context, cfg *p2p.Config) { 886 if ctx.GlobalIsSet(ListenPortFlag.Name) { 887 cfg.ListenAddr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name)) 888 } 889 } 890 891 // setNAT creates a port mapper from command line flags. 892 func setNAT(ctx *cli.Context, cfg *p2p.Config) { 893 if ctx.GlobalIsSet(NATFlag.Name) { 894 natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name)) 895 if err != nil { 896 Fatalf("Option %s: %v", NATFlag.Name, err) 897 } 898 cfg.NAT = natif 899 } 900 } 901 902 // SplitAndTrim splits input separated by a comma 903 // and trims excessive white space from the substrings. 904 func SplitAndTrim(input string) (ret []string) { 905 l := strings.Split(input, ",") 906 for _, r := range l { 907 if r = strings.TrimSpace(r); r != "" { 908 ret = append(ret, r) 909 } 910 } 911 return ret 912 } 913 914 // setHTTP creates the HTTP RPC listener interface string from the set 915 // command line flags, returning empty if the HTTP endpoint is disabled. 916 func setHTTP(ctx *cli.Context, cfg *node.Config) { 917 if ctx.GlobalBool(LegacyRPCEnabledFlag.Name) && cfg.HTTPHost == "" { 918 log.Warn("The flag --rpc is deprecated and will be removed June 2021, please use --http") 919 cfg.HTTPHost = "127.0.0.1" 920 if ctx.GlobalIsSet(LegacyRPCListenAddrFlag.Name) { 921 cfg.HTTPHost = ctx.GlobalString(LegacyRPCListenAddrFlag.Name) 922 log.Warn("The flag --rpcaddr is deprecated and will be removed June 2021, please use --http.addr") 923 } 924 } 925 if ctx.GlobalBool(HTTPEnabledFlag.Name) && cfg.HTTPHost == "" { 926 cfg.HTTPHost = "127.0.0.1" 927 if ctx.GlobalIsSet(HTTPListenAddrFlag.Name) { 928 cfg.HTTPHost = ctx.GlobalString(HTTPListenAddrFlag.Name) 929 } 930 } 931 932 if ctx.GlobalIsSet(LegacyRPCPortFlag.Name) { 933 cfg.HTTPPort = ctx.GlobalInt(LegacyRPCPortFlag.Name) 934 log.Warn("The flag --rpcport is deprecated and will be removed June 2021, please use --http.port") 935 } 936 if ctx.GlobalIsSet(HTTPPortFlag.Name) { 937 cfg.HTTPPort = ctx.GlobalInt(HTTPPortFlag.Name) 938 } 939 940 if ctx.GlobalIsSet(LegacyRPCCORSDomainFlag.Name) { 941 cfg.HTTPCors = SplitAndTrim(ctx.GlobalString(LegacyRPCCORSDomainFlag.Name)) 942 log.Warn("The flag --rpccorsdomain is deprecated and will be removed June 2021, please use --http.corsdomain") 943 } 944 if ctx.GlobalIsSet(HTTPCORSDomainFlag.Name) { 945 cfg.HTTPCors = SplitAndTrim(ctx.GlobalString(HTTPCORSDomainFlag.Name)) 946 } 947 948 if ctx.GlobalIsSet(LegacyRPCApiFlag.Name) { 949 cfg.HTTPModules = SplitAndTrim(ctx.GlobalString(LegacyRPCApiFlag.Name)) 950 log.Warn("The flag --rpcapi is deprecated and will be removed June 2021, please use --http.api") 951 } 952 if ctx.GlobalIsSet(HTTPApiFlag.Name) { 953 cfg.HTTPModules = SplitAndTrim(ctx.GlobalString(HTTPApiFlag.Name)) 954 } 955 956 if ctx.GlobalIsSet(LegacyRPCVirtualHostsFlag.Name) { 957 cfg.HTTPVirtualHosts = SplitAndTrim(ctx.GlobalString(LegacyRPCVirtualHostsFlag.Name)) 958 log.Warn("The flag --rpcvhosts is deprecated and will be removed June 2021, please use --http.vhosts") 959 } 960 if ctx.GlobalIsSet(HTTPVirtualHostsFlag.Name) { 961 cfg.HTTPVirtualHosts = SplitAndTrim(ctx.GlobalString(HTTPVirtualHostsFlag.Name)) 962 } 963 964 if ctx.GlobalIsSet(HTTPPathPrefixFlag.Name) { 965 cfg.HTTPPathPrefix = ctx.GlobalString(HTTPPathPrefixFlag.Name) 966 } 967 if ctx.GlobalIsSet(AllowUnprotectedTxs.Name) { 968 cfg.AllowUnprotectedTxs = ctx.GlobalBool(AllowUnprotectedTxs.Name) 969 } 970 } 971 972 // setGraphQL creates the GraphQL listener interface string from the set 973 // command line flags, returning empty if the GraphQL endpoint is disabled. 974 func setGraphQL(ctx *cli.Context, cfg *node.Config) { 975 if ctx.GlobalIsSet(GraphQLCORSDomainFlag.Name) { 976 cfg.GraphQLCors = SplitAndTrim(ctx.GlobalString(GraphQLCORSDomainFlag.Name)) 977 } 978 if ctx.GlobalIsSet(GraphQLVirtualHostsFlag.Name) { 979 cfg.GraphQLVirtualHosts = SplitAndTrim(ctx.GlobalString(GraphQLVirtualHostsFlag.Name)) 980 } 981 } 982 983 // setWS creates the WebSocket RPC listener interface string from the set 984 // command line flags, returning empty if the HTTP endpoint is disabled. 985 func setWS(ctx *cli.Context, cfg *node.Config) { 986 if ctx.GlobalBool(WSEnabledFlag.Name) && cfg.WSHost == "" { 987 cfg.WSHost = "127.0.0.1" 988 if ctx.GlobalIsSet(WSListenAddrFlag.Name) { 989 cfg.WSHost = ctx.GlobalString(WSListenAddrFlag.Name) 990 } 991 } 992 if ctx.GlobalIsSet(WSPortFlag.Name) { 993 cfg.WSPort = ctx.GlobalInt(WSPortFlag.Name) 994 } 995 996 if ctx.GlobalIsSet(WSAllowedOriginsFlag.Name) { 997 cfg.WSOrigins = SplitAndTrim(ctx.GlobalString(WSAllowedOriginsFlag.Name)) 998 } 999 1000 if ctx.GlobalIsSet(WSApiFlag.Name) { 1001 cfg.WSModules = SplitAndTrim(ctx.GlobalString(WSApiFlag.Name)) 1002 } 1003 1004 if ctx.GlobalIsSet(WSPathPrefixFlag.Name) { 1005 cfg.WSPathPrefix = ctx.GlobalString(WSPathPrefixFlag.Name) 1006 } 1007 } 1008 1009 // setIPC creates an IPC path configuration from the set command line flags, 1010 // returning an empty string if IPC was explicitly disabled, or the set path. 1011 func setIPC(ctx *cli.Context, cfg *node.Config) { 1012 CheckExclusive(ctx, IPCDisabledFlag, IPCPathFlag) 1013 switch { 1014 case ctx.GlobalBool(IPCDisabledFlag.Name): 1015 cfg.IPCPath = "" 1016 case ctx.GlobalIsSet(IPCPathFlag.Name): 1017 cfg.IPCPath = ctx.GlobalString(IPCPathFlag.Name) 1018 } 1019 } 1020 1021 // setLes configures the les server and ultra light client settings from the command line flags. 1022 func setLes(ctx *cli.Context, cfg *ethconfig.Config) { 1023 if ctx.GlobalIsSet(LightServeFlag.Name) { 1024 cfg.LightServ = ctx.GlobalInt(LightServeFlag.Name) 1025 } 1026 if ctx.GlobalIsSet(LightIngressFlag.Name) { 1027 cfg.LightIngress = ctx.GlobalInt(LightIngressFlag.Name) 1028 } 1029 if ctx.GlobalIsSet(LightEgressFlag.Name) { 1030 cfg.LightEgress = ctx.GlobalInt(LightEgressFlag.Name) 1031 } 1032 if ctx.GlobalIsSet(LightMaxPeersFlag.Name) { 1033 cfg.LightPeers = ctx.GlobalInt(LightMaxPeersFlag.Name) 1034 } 1035 if ctx.GlobalIsSet(UltraLightServersFlag.Name) { 1036 cfg.UltraLightServers = strings.Split(ctx.GlobalString(UltraLightServersFlag.Name), ",") 1037 } 1038 if ctx.GlobalIsSet(UltraLightFractionFlag.Name) { 1039 cfg.UltraLightFraction = ctx.GlobalInt(UltraLightFractionFlag.Name) 1040 } 1041 if cfg.UltraLightFraction <= 0 && cfg.UltraLightFraction > 100 { 1042 log.Error("Ultra light fraction is invalid", "had", cfg.UltraLightFraction, "updated", ethconfig.Defaults.UltraLightFraction) 1043 cfg.UltraLightFraction = ethconfig.Defaults.UltraLightFraction 1044 } 1045 if ctx.GlobalIsSet(UltraLightOnlyAnnounceFlag.Name) { 1046 cfg.UltraLightOnlyAnnounce = ctx.GlobalBool(UltraLightOnlyAnnounceFlag.Name) 1047 } 1048 if ctx.GlobalIsSet(LightNoPruneFlag.Name) { 1049 cfg.LightNoPrune = ctx.GlobalBool(LightNoPruneFlag.Name) 1050 } 1051 if ctx.GlobalIsSet(LightNoSyncServeFlag.Name) { 1052 cfg.LightNoSyncServe = ctx.GlobalBool(LightNoSyncServeFlag.Name) 1053 } 1054 } 1055 1056 // MakeDatabaseHandles raises out the number of allowed file handles per process 1057 // for Geth and returns half of the allowance to assign to the database. 1058 func MakeDatabaseHandles() int { 1059 limit, err := fdlimit.Maximum() 1060 if err != nil { 1061 Fatalf("Failed to retrieve file descriptor allowance: %v", err) 1062 } 1063 raised, err := fdlimit.Raise(uint64(limit)) 1064 if err != nil { 1065 Fatalf("Failed to raise file descriptor allowance: %v", err) 1066 } 1067 return int(raised / 2) // Leave half for networking and other stuff 1068 } 1069 1070 // MakeAddress converts an account specified directly as a hex encoded string or 1071 // a key index in the key store to an internal account representation. 1072 func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) { 1073 // If the specified account is a valid address, return it 1074 if common.IsHexAddress(account) { 1075 return accounts.Account{Address: common.HexToAddress(account)}, nil 1076 } 1077 // Otherwise try to interpret the account as a keystore index 1078 index, err := strconv.Atoi(account) 1079 if err != nil || index < 0 { 1080 return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account) 1081 } 1082 log.Warn("-------------------------------------------------------------------") 1083 log.Warn("Referring to accounts by order in the keystore folder is dangerous!") 1084 log.Warn("This functionality is deprecated and will be removed in the future!") 1085 log.Warn("Please use explicit addresses! (can search via `geth account list`)") 1086 log.Warn("-------------------------------------------------------------------") 1087 1088 accs := ks.Accounts() 1089 if len(accs) <= index { 1090 return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs)) 1091 } 1092 return accs[index], nil 1093 } 1094 1095 // setEtherbase retrieves the etherbase either from the directly specified 1096 // command line flags or from the keystore if CLI indexed. 1097 func setEtherbase(ctx *cli.Context, ks *keystore.KeyStore, cfg *ethconfig.Config) { 1098 // Extract the current etherbase 1099 var etherbase string 1100 if ctx.GlobalIsSet(MinerEtherbaseFlag.Name) { 1101 etherbase = ctx.GlobalString(MinerEtherbaseFlag.Name) 1102 } 1103 // Convert the etherbase into an address and configure it 1104 if etherbase != "" { 1105 if ks != nil { 1106 account, err := MakeAddress(ks, etherbase) 1107 if err != nil { 1108 Fatalf("Invalid miner etherbase: %v", err) 1109 } 1110 cfg.Miner.Etherbase = account.Address 1111 } else { 1112 Fatalf("No etherbase configured") 1113 } 1114 } 1115 } 1116 1117 // MakePasswordList reads password lines from the file specified by the global --password flag. 1118 func MakePasswordList(ctx *cli.Context) []string { 1119 path := ctx.GlobalString(PasswordFileFlag.Name) 1120 if path == "" { 1121 return nil 1122 } 1123 text, err := ioutil.ReadFile(path) 1124 if err != nil { 1125 Fatalf("Failed to read password file: %v", err) 1126 } 1127 lines := strings.Split(string(text), "\n") 1128 // Sanitise DOS line endings. 1129 for i := range lines { 1130 lines[i] = strings.TrimRight(lines[i], "\r") 1131 } 1132 return lines 1133 } 1134 1135 func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) { 1136 setNodeKey(ctx, cfg) 1137 setNAT(ctx, cfg) 1138 setListenAddress(ctx, cfg) 1139 setBootstrapNodes(ctx, cfg) 1140 setBootstrapNodesV5(ctx, cfg) 1141 1142 lightClient := ctx.GlobalString(SyncModeFlag.Name) == "light" 1143 lightServer := (ctx.GlobalInt(LightServeFlag.Name) != 0) 1144 1145 lightPeers := ctx.GlobalInt(LightMaxPeersFlag.Name) 1146 if lightClient && !ctx.GlobalIsSet(LightMaxPeersFlag.Name) { 1147 // dynamic default - for clients we use 1/10th of the default for servers 1148 lightPeers /= 10 1149 } 1150 1151 if ctx.GlobalIsSet(MaxPeersFlag.Name) { 1152 cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name) 1153 if lightServer && !ctx.GlobalIsSet(LightMaxPeersFlag.Name) { 1154 cfg.MaxPeers += lightPeers 1155 } 1156 } else { 1157 if lightServer { 1158 cfg.MaxPeers += lightPeers 1159 } 1160 if lightClient && ctx.GlobalIsSet(LightMaxPeersFlag.Name) && cfg.MaxPeers < lightPeers { 1161 cfg.MaxPeers = lightPeers 1162 } 1163 } 1164 if !(lightClient || lightServer) { 1165 lightPeers = 0 1166 } 1167 ethPeers := cfg.MaxPeers - lightPeers 1168 if lightClient { 1169 ethPeers = 0 1170 } 1171 log.Info("Maximum peer count", "ETH", ethPeers, "LES", lightPeers, "total", cfg.MaxPeers) 1172 1173 if ctx.GlobalIsSet(MaxPendingPeersFlag.Name) { 1174 cfg.MaxPendingPeers = ctx.GlobalInt(MaxPendingPeersFlag.Name) 1175 } 1176 if ctx.GlobalIsSet(NoDiscoverFlag.Name) || lightClient { 1177 cfg.NoDiscovery = true 1178 } 1179 1180 // if we're running a light client or server, force enable the v5 peer discovery 1181 // unless it is explicitly disabled with --nodiscover note that explicitly specifying 1182 // --v5disc overrides --nodiscover, in which case the later only disables v4 discovery 1183 forceV5Discovery := (lightClient || lightServer) && !ctx.GlobalBool(NoDiscoverFlag.Name) 1184 if ctx.GlobalIsSet(DiscoveryV5Flag.Name) { 1185 cfg.DiscoveryV5 = ctx.GlobalBool(DiscoveryV5Flag.Name) 1186 } else if forceV5Discovery { 1187 cfg.DiscoveryV5 = true 1188 } 1189 1190 if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" { 1191 list, err := netutil.ParseNetlist(netrestrict) 1192 if err != nil { 1193 Fatalf("Option %q: %v", NetrestrictFlag.Name, err) 1194 } 1195 cfg.NetRestrict = list 1196 } 1197 1198 if ctx.GlobalBool(DeveloperFlag.Name) || ctx.GlobalBool(CatalystFlag.Name) { 1199 // --dev mode can't use p2p networking. 1200 cfg.MaxPeers = 0 1201 cfg.ListenAddr = "" 1202 cfg.NoDial = true 1203 cfg.NoDiscovery = true 1204 cfg.DiscoveryV5 = false 1205 } 1206 } 1207 1208 // SetNodeConfig applies node-related command line flags to the config. 1209 func SetNodeConfig(ctx *cli.Context, cfg *node.Config) { 1210 SetP2PConfig(ctx, &cfg.P2P) 1211 setIPC(ctx, cfg) 1212 setHTTP(ctx, cfg) 1213 setGraphQL(ctx, cfg) 1214 setWS(ctx, cfg) 1215 setNodeUserIdent(ctx, cfg) 1216 setDataDir(ctx, cfg) 1217 setSmartCard(ctx, cfg) 1218 1219 if ctx.GlobalIsSet(ExternalSignerFlag.Name) { 1220 cfg.ExternalSigner = ctx.GlobalString(ExternalSignerFlag.Name) 1221 } 1222 1223 if ctx.GlobalIsSet(KeyStoreDirFlag.Name) { 1224 cfg.KeyStoreDir = ctx.GlobalString(KeyStoreDirFlag.Name) 1225 } 1226 if ctx.GlobalIsSet(LightKDFFlag.Name) { 1227 cfg.UseLightweightKDF = ctx.GlobalBool(LightKDFFlag.Name) 1228 } 1229 if ctx.GlobalIsSet(NoUSBFlag.Name) || cfg.NoUSB { 1230 log.Warn("Option nousb is deprecated and USB is deactivated by default. Use --usb to enable") 1231 } 1232 if ctx.GlobalIsSet(USBFlag.Name) { 1233 cfg.USB = ctx.GlobalBool(USBFlag.Name) 1234 } 1235 if ctx.GlobalIsSet(InsecureUnlockAllowedFlag.Name) { 1236 cfg.InsecureUnlockAllowed = ctx.GlobalBool(InsecureUnlockAllowedFlag.Name) 1237 } 1238 } 1239 1240 func setSmartCard(ctx *cli.Context, cfg *node.Config) { 1241 // Skip enabling smartcards if no path is set 1242 path := ctx.GlobalString(SmartCardDaemonPathFlag.Name) 1243 if path == "" { 1244 return 1245 } 1246 // Sanity check that the smartcard path is valid 1247 fi, err := os.Stat(path) 1248 if err != nil { 1249 log.Info("Smartcard socket not found, disabling", "err", err) 1250 return 1251 } 1252 if fi.Mode()&os.ModeType != os.ModeSocket { 1253 log.Error("Invalid smartcard daemon path", "path", path, "type", fi.Mode().String()) 1254 return 1255 } 1256 // Smartcard daemon path exists and is a socket, enable it 1257 cfg.SmartCardDaemonPath = path 1258 } 1259 1260 func setDataDir(ctx *cli.Context, cfg *node.Config) { 1261 switch { 1262 case ctx.GlobalIsSet(DataDirFlag.Name): 1263 cfg.DataDir = ctx.GlobalString(DataDirFlag.Name) 1264 case ctx.GlobalBool(DeveloperFlag.Name): 1265 cfg.DataDir = "" // unless explicitly requested, use memory databases 1266 case ctx.GlobalBool(RopstenFlag.Name) && cfg.DataDir == node.DefaultDataDir(): 1267 // Maintain compatibility with older Geth configurations storing the 1268 // Ropsten database in `testnet` instead of `ropsten`. 1269 legacyPath := filepath.Join(node.DefaultDataDir(), "testnet") 1270 if _, err := os.Stat(legacyPath); !os.IsNotExist(err) { 1271 log.Warn("Using the deprecated `testnet` datadir. Future versions will store the Ropsten chain in `ropsten`.") 1272 cfg.DataDir = legacyPath 1273 } else { 1274 cfg.DataDir = filepath.Join(node.DefaultDataDir(), "ropsten") 1275 } 1276 1277 cfg.DataDir = filepath.Join(node.DefaultDataDir(), "ropsten") 1278 case ctx.GlobalBool(RinkebyFlag.Name) && cfg.DataDir == node.DefaultDataDir(): 1279 cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby") 1280 case ctx.GlobalBool(GoerliFlag.Name) && cfg.DataDir == node.DefaultDataDir(): 1281 cfg.DataDir = filepath.Join(node.DefaultDataDir(), "goerli") 1282 case ctx.GlobalBool(YoloV3Flag.Name) && cfg.DataDir == node.DefaultDataDir(): 1283 cfg.DataDir = filepath.Join(node.DefaultDataDir(), "yolo-v3") 1284 } 1285 } 1286 1287 func setGPO(ctx *cli.Context, cfg *gasprice.Config, light bool) { 1288 // If we are running the light client, apply another group 1289 // settings for gas oracle. 1290 if light { 1291 cfg.Blocks = ethconfig.LightClientGPO.Blocks 1292 cfg.Percentile = ethconfig.LightClientGPO.Percentile 1293 } 1294 if ctx.GlobalIsSet(GpoBlocksFlag.Name) { 1295 cfg.Blocks = ctx.GlobalInt(GpoBlocksFlag.Name) 1296 } 1297 if ctx.GlobalIsSet(GpoPercentileFlag.Name) { 1298 cfg.Percentile = ctx.GlobalInt(GpoPercentileFlag.Name) 1299 } 1300 if ctx.GlobalIsSet(GpoMaxGasPriceFlag.Name) { 1301 cfg.MaxPrice = big.NewInt(ctx.GlobalInt64(GpoMaxGasPriceFlag.Name)) 1302 } 1303 } 1304 1305 func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) { 1306 if ctx.GlobalIsSet(TxPoolLocalsFlag.Name) { 1307 locals := strings.Split(ctx.GlobalString(TxPoolLocalsFlag.Name), ",") 1308 for _, account := range locals { 1309 if trimmed := strings.TrimSpace(account); !common.IsHexAddress(trimmed) { 1310 Fatalf("Invalid account in --txpool.locals: %s", trimmed) 1311 } else { 1312 cfg.Locals = append(cfg.Locals, common.HexToAddress(account)) 1313 } 1314 } 1315 } 1316 if ctx.GlobalIsSet(TxPoolNoLocalsFlag.Name) { 1317 cfg.NoLocals = ctx.GlobalBool(TxPoolNoLocalsFlag.Name) 1318 } 1319 if ctx.GlobalIsSet(TxPoolJournalFlag.Name) { 1320 cfg.Journal = ctx.GlobalString(TxPoolJournalFlag.Name) 1321 } 1322 if ctx.GlobalIsSet(TxPoolRejournalFlag.Name) { 1323 cfg.Rejournal = ctx.GlobalDuration(TxPoolRejournalFlag.Name) 1324 } 1325 if ctx.GlobalIsSet(TxPoolPriceLimitFlag.Name) { 1326 cfg.PriceLimit = ctx.GlobalUint64(TxPoolPriceLimitFlag.Name) 1327 } 1328 if ctx.GlobalIsSet(TxPoolPriceBumpFlag.Name) { 1329 cfg.PriceBump = ctx.GlobalUint64(TxPoolPriceBumpFlag.Name) 1330 } 1331 if ctx.GlobalIsSet(TxPoolAccountSlotsFlag.Name) { 1332 cfg.AccountSlots = ctx.GlobalUint64(TxPoolAccountSlotsFlag.Name) 1333 } 1334 if ctx.GlobalIsSet(TxPoolGlobalSlotsFlag.Name) { 1335 cfg.GlobalSlots = ctx.GlobalUint64(TxPoolGlobalSlotsFlag.Name) 1336 } 1337 if ctx.GlobalIsSet(TxPoolAccountQueueFlag.Name) { 1338 cfg.AccountQueue = ctx.GlobalUint64(TxPoolAccountQueueFlag.Name) 1339 } 1340 if ctx.GlobalIsSet(TxPoolGlobalQueueFlag.Name) { 1341 cfg.GlobalQueue = ctx.GlobalUint64(TxPoolGlobalQueueFlag.Name) 1342 } 1343 if ctx.GlobalIsSet(TxPoolLifetimeFlag.Name) { 1344 cfg.Lifetime = ctx.GlobalDuration(TxPoolLifetimeFlag.Name) 1345 } 1346 } 1347 1348 func setEthash(ctx *cli.Context, cfg *ethconfig.Config) { 1349 if ctx.GlobalIsSet(EthashCacheDirFlag.Name) { 1350 cfg.Ethash.CacheDir = ctx.GlobalString(EthashCacheDirFlag.Name) 1351 } 1352 if ctx.GlobalIsSet(EthashDatasetDirFlag.Name) { 1353 cfg.Ethash.DatasetDir = ctx.GlobalString(EthashDatasetDirFlag.Name) 1354 } 1355 if ctx.GlobalIsSet(EthashCachesInMemoryFlag.Name) { 1356 cfg.Ethash.CachesInMem = ctx.GlobalInt(EthashCachesInMemoryFlag.Name) 1357 } 1358 if ctx.GlobalIsSet(EthashCachesOnDiskFlag.Name) { 1359 cfg.Ethash.CachesOnDisk = ctx.GlobalInt(EthashCachesOnDiskFlag.Name) 1360 } 1361 if ctx.GlobalIsSet(EthashCachesLockMmapFlag.Name) { 1362 cfg.Ethash.CachesLockMmap = ctx.GlobalBool(EthashCachesLockMmapFlag.Name) 1363 } 1364 if ctx.GlobalIsSet(EthashDatasetsInMemoryFlag.Name) { 1365 cfg.Ethash.DatasetsInMem = ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name) 1366 } 1367 if ctx.GlobalIsSet(EthashDatasetsOnDiskFlag.Name) { 1368 cfg.Ethash.DatasetsOnDisk = ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name) 1369 } 1370 if ctx.GlobalIsSet(EthashDatasetsLockMmapFlag.Name) { 1371 cfg.Ethash.DatasetsLockMmap = ctx.GlobalBool(EthashDatasetsLockMmapFlag.Name) 1372 } 1373 } 1374 1375 func setMiner(ctx *cli.Context, cfg *miner.Config) { 1376 if ctx.GlobalIsSet(MinerNotifyFlag.Name) { 1377 cfg.Notify = strings.Split(ctx.GlobalString(MinerNotifyFlag.Name), ",") 1378 } 1379 cfg.NotifyFull = ctx.GlobalBool(MinerNotifyFullFlag.Name) 1380 if ctx.GlobalIsSet(MinerExtraDataFlag.Name) { 1381 cfg.ExtraData = []byte(ctx.GlobalString(MinerExtraDataFlag.Name)) 1382 } 1383 if ctx.GlobalIsSet(MinerGasTargetFlag.Name) { 1384 cfg.GasFloor = ctx.GlobalUint64(MinerGasTargetFlag.Name) 1385 } 1386 if ctx.GlobalIsSet(MinerGasLimitFlag.Name) { 1387 cfg.GasCeil = ctx.GlobalUint64(MinerGasLimitFlag.Name) 1388 } 1389 if ctx.GlobalIsSet(MinerGasPriceFlag.Name) { 1390 cfg.GasPrice = GlobalBig(ctx, MinerGasPriceFlag.Name) 1391 } 1392 if ctx.GlobalIsSet(MinerRecommitIntervalFlag.Name) { 1393 cfg.Recommit = ctx.GlobalDuration(MinerRecommitIntervalFlag.Name) 1394 } 1395 if ctx.GlobalIsSet(MinerNoVerfiyFlag.Name) { 1396 cfg.Noverify = ctx.GlobalBool(MinerNoVerfiyFlag.Name) 1397 } 1398 } 1399 1400 func setWhitelist(ctx *cli.Context, cfg *ethconfig.Config) { 1401 whitelist := ctx.GlobalString(WhitelistFlag.Name) 1402 if whitelist == "" { 1403 return 1404 } 1405 cfg.Whitelist = make(map[uint64]common.Hash) 1406 for _, entry := range strings.Split(whitelist, ",") { 1407 parts := strings.Split(entry, "=") 1408 if len(parts) != 2 { 1409 Fatalf("Invalid whitelist entry: %s", entry) 1410 } 1411 number, err := strconv.ParseUint(parts[0], 0, 64) 1412 if err != nil { 1413 Fatalf("Invalid whitelist block number %s: %v", parts[0], err) 1414 } 1415 var hash common.Hash 1416 if err = hash.UnmarshalText([]byte(parts[1])); err != nil { 1417 Fatalf("Invalid whitelist hash %s: %v", parts[1], err) 1418 } 1419 cfg.Whitelist[number] = hash 1420 } 1421 } 1422 1423 // CheckExclusive verifies that only a single instance of the provided flags was 1424 // set by the user. Each flag might optionally be followed by a string type to 1425 // specialize it further. 1426 func CheckExclusive(ctx *cli.Context, args ...interface{}) { 1427 set := make([]string, 0, 1) 1428 for i := 0; i < len(args); i++ { 1429 // Make sure the next argument is a flag and skip if not set 1430 flag, ok := args[i].(cli.Flag) 1431 if !ok { 1432 panic(fmt.Sprintf("invalid argument, not cli.Flag type: %T", args[i])) 1433 } 1434 // Check if next arg extends current and expand its name if so 1435 name := flag.GetName() 1436 1437 if i+1 < len(args) { 1438 switch option := args[i+1].(type) { 1439 case string: 1440 // Extended flag check, make sure value set doesn't conflict with passed in option 1441 if ctx.GlobalString(flag.GetName()) == option { 1442 name += "=" + option 1443 set = append(set, "--"+name) 1444 } 1445 // shift arguments and continue 1446 i++ 1447 continue 1448 1449 case cli.Flag: 1450 default: 1451 panic(fmt.Sprintf("invalid argument, not cli.Flag or string extension: %T", args[i+1])) 1452 } 1453 } 1454 // Mark the flag if it's set 1455 if ctx.GlobalIsSet(flag.GetName()) { 1456 set = append(set, "--"+name) 1457 } 1458 } 1459 if len(set) > 1 { 1460 Fatalf("Flags %v can't be used at the same time", strings.Join(set, ", ")) 1461 } 1462 } 1463 1464 // SetEthConfig applies eth-related command line flags to the config. 1465 func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) { 1466 // Avoid conflicting network flags 1467 CheckExclusive(ctx, MainnetFlag, DeveloperFlag, RopstenFlag, RinkebyFlag, GoerliFlag, YoloV3Flag) 1468 CheckExclusive(ctx, LightServeFlag, SyncModeFlag, "light") 1469 CheckExclusive(ctx, DeveloperFlag, ExternalSignerFlag) // Can't use both ephemeral unlocked and external signer 1470 if ctx.GlobalString(GCModeFlag.Name) == "archive" && ctx.GlobalUint64(TxLookupLimitFlag.Name) != 0 { 1471 ctx.GlobalSet(TxLookupLimitFlag.Name, "0") 1472 log.Warn("Disable transaction unindexing for archive node") 1473 } 1474 if ctx.GlobalIsSet(LightServeFlag.Name) && ctx.GlobalUint64(TxLookupLimitFlag.Name) != 0 { 1475 log.Warn("LES server cannot serve old transaction status and cannot connect below les/4 protocol version if transaction lookup index is limited") 1476 } 1477 var ks *keystore.KeyStore 1478 if keystores := stack.AccountManager().Backends(keystore.KeyStoreType); len(keystores) > 0 { 1479 ks = keystores[0].(*keystore.KeyStore) 1480 } 1481 setEtherbase(ctx, ks, cfg) 1482 setGPO(ctx, &cfg.GPO, ctx.GlobalString(SyncModeFlag.Name) == "light") 1483 setTxPool(ctx, &cfg.TxPool) 1484 setEthash(ctx, cfg) 1485 setMiner(ctx, &cfg.Miner) 1486 setWhitelist(ctx, cfg) 1487 setLes(ctx, cfg) 1488 1489 if ctx.GlobalIsSet(BorLogsFlag.Name) { 1490 cfg.BorLogs = ctx.GlobalBool(BorLogsFlag.Name) 1491 } 1492 1493 // Cap the cache allowance and tune the garbage collector 1494 mem, err := gopsutil.VirtualMemory() 1495 if err == nil { 1496 if 32<<(^uintptr(0)>>63) == 32 && mem.Total > 2*1024*1024*1024 { 1497 log.Warn("Lowering memory allowance on 32bit arch", "available", mem.Total/1024/1024, "addressable", 2*1024) 1498 mem.Total = 2 * 1024 * 1024 * 1024 1499 } 1500 allowance := int(mem.Total / 1024 / 1024 / 3) 1501 if cache := ctx.GlobalInt(CacheFlag.Name); cache > allowance { 1502 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 1503 ctx.GlobalSet(CacheFlag.Name, strconv.Itoa(allowance)) 1504 } 1505 } 1506 // Ensure Go's GC ignores the database cache for trigger percentage 1507 cache := ctx.GlobalInt(CacheFlag.Name) 1508 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 1509 1510 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 1511 godebug.SetGCPercent(int(gogc)) 1512 1513 if ctx.GlobalIsSet(SyncModeFlag.Name) { 1514 cfg.SyncMode = *GlobalTextMarshaler(ctx, SyncModeFlag.Name).(*downloader.SyncMode) 1515 } 1516 if ctx.GlobalIsSet(NetworkIdFlag.Name) { 1517 cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name) 1518 } 1519 if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheDatabaseFlag.Name) { 1520 cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100 1521 } 1522 cfg.DatabaseHandles = MakeDatabaseHandles() 1523 if ctx.GlobalIsSet(AncientFlag.Name) { 1524 cfg.DatabaseFreezer = ctx.GlobalString(AncientFlag.Name) 1525 } 1526 1527 if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" { 1528 Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name) 1529 } 1530 if ctx.GlobalIsSet(GCModeFlag.Name) { 1531 cfg.NoPruning = ctx.GlobalString(GCModeFlag.Name) == "archive" 1532 } 1533 if ctx.GlobalIsSet(CacheNoPrefetchFlag.Name) { 1534 cfg.NoPrefetch = ctx.GlobalBool(CacheNoPrefetchFlag.Name) 1535 } 1536 // Read the value from the flag no matter if it's set or not. 1537 cfg.Preimages = ctx.GlobalBool(CachePreimagesFlag.Name) 1538 if cfg.NoPruning && !cfg.Preimages { 1539 cfg.Preimages = true 1540 log.Info("Enabling recording of key preimages since archive mode is used") 1541 } 1542 if ctx.GlobalIsSet(TxLookupLimitFlag.Name) { 1543 cfg.TxLookupLimit = ctx.GlobalUint64(TxLookupLimitFlag.Name) 1544 } 1545 if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheTrieFlag.Name) { 1546 cfg.TrieCleanCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheTrieFlag.Name) / 100 1547 } 1548 if ctx.GlobalIsSet(CacheTrieJournalFlag.Name) { 1549 cfg.TrieCleanCacheJournal = ctx.GlobalString(CacheTrieJournalFlag.Name) 1550 } 1551 if ctx.GlobalIsSet(CacheTrieRejournalFlag.Name) { 1552 cfg.TrieCleanCacheRejournal = ctx.GlobalDuration(CacheTrieRejournalFlag.Name) 1553 } 1554 if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) { 1555 cfg.TrieDirtyCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100 1556 } 1557 if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheSnapshotFlag.Name) { 1558 cfg.SnapshotCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheSnapshotFlag.Name) / 100 1559 } 1560 if !ctx.GlobalBool(SnapshotFlag.Name) { 1561 // If snap-sync is requested, this flag is also required 1562 if cfg.SyncMode == downloader.SnapSync { 1563 log.Info("Snap sync requested, enabling --snapshot") 1564 } else { 1565 cfg.TrieCleanCache += cfg.SnapshotCache 1566 cfg.SnapshotCache = 0 // Disabled 1567 } 1568 } 1569 if ctx.GlobalIsSet(DocRootFlag.Name) { 1570 cfg.DocRoot = ctx.GlobalString(DocRootFlag.Name) 1571 } 1572 if ctx.GlobalIsSet(VMEnableDebugFlag.Name) { 1573 // TODO(fjl): force-enable this in --dev mode 1574 cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name) 1575 } 1576 1577 if ctx.GlobalIsSet(EWASMInterpreterFlag.Name) { 1578 cfg.EWASMInterpreter = ctx.GlobalString(EWASMInterpreterFlag.Name) 1579 } 1580 1581 if ctx.GlobalIsSet(EVMInterpreterFlag.Name) { 1582 cfg.EVMInterpreter = ctx.GlobalString(EVMInterpreterFlag.Name) 1583 } 1584 if ctx.GlobalIsSet(RPCGlobalGasCapFlag.Name) { 1585 cfg.RPCGasCap = ctx.GlobalUint64(RPCGlobalGasCapFlag.Name) 1586 } 1587 if cfg.RPCGasCap != 0 { 1588 log.Info("Set global gas cap", "cap", cfg.RPCGasCap) 1589 } else { 1590 log.Info("Global gas cap disabled") 1591 } 1592 if ctx.GlobalIsSet(RPCGlobalTxFeeCapFlag.Name) { 1593 cfg.RPCTxFeeCap = ctx.GlobalFloat64(RPCGlobalTxFeeCapFlag.Name) 1594 } 1595 if ctx.GlobalIsSet(NoDiscoverFlag.Name) { 1596 cfg.EthDiscoveryURLs, cfg.SnapDiscoveryURLs = []string{}, []string{} 1597 } else if ctx.GlobalIsSet(DNSDiscoveryFlag.Name) { 1598 urls := ctx.GlobalString(DNSDiscoveryFlag.Name) 1599 if urls == "" { 1600 cfg.EthDiscoveryURLs = []string{} 1601 } else { 1602 cfg.EthDiscoveryURLs = SplitAndTrim(urls) 1603 } 1604 } 1605 // Override any default configs for hard coded networks. 1606 switch { 1607 case ctx.GlobalBool(MainnetFlag.Name): 1608 if !ctx.GlobalIsSet(NetworkIdFlag.Name) { 1609 cfg.NetworkId = 1 1610 } 1611 cfg.Genesis = core.DefaultGenesisBlock() 1612 SetDNSDiscoveryDefaults(cfg, params.MainnetGenesisHash) 1613 case ctx.GlobalBool(RopstenFlag.Name): 1614 if !ctx.GlobalIsSet(NetworkIdFlag.Name) { 1615 cfg.NetworkId = 3 1616 } 1617 cfg.Genesis = core.DefaultRopstenGenesisBlock() 1618 SetDNSDiscoveryDefaults(cfg, params.RopstenGenesisHash) 1619 case ctx.GlobalBool(RinkebyFlag.Name): 1620 if !ctx.GlobalIsSet(NetworkIdFlag.Name) { 1621 cfg.NetworkId = 4 1622 } 1623 cfg.Genesis = core.DefaultRinkebyGenesisBlock() 1624 SetDNSDiscoveryDefaults(cfg, params.RinkebyGenesisHash) 1625 case ctx.GlobalBool(GoerliFlag.Name): 1626 if !ctx.GlobalIsSet(NetworkIdFlag.Name) { 1627 cfg.NetworkId = 5 1628 } 1629 cfg.Genesis = core.DefaultGoerliGenesisBlock() 1630 SetDNSDiscoveryDefaults(cfg, params.GoerliGenesisHash) 1631 case ctx.GlobalBool(YoloV3Flag.Name): 1632 if !ctx.GlobalIsSet(NetworkIdFlag.Name) { 1633 cfg.NetworkId = new(big.Int).SetBytes([]byte("yolov3x")).Uint64() // "yolov3x" 1634 } 1635 cfg.Genesis = core.DefaultYoloV3GenesisBlock() 1636 case ctx.GlobalBool(DeveloperFlag.Name): 1637 if !ctx.GlobalIsSet(NetworkIdFlag.Name) { 1638 cfg.NetworkId = 1337 1639 } 1640 // Create new developer account or reuse existing one 1641 var ( 1642 developer accounts.Account 1643 passphrase string 1644 err error 1645 ) 1646 if list := MakePasswordList(ctx); len(list) > 0 { 1647 // Just take the first value. Although the function returns a possible multiple values and 1648 // some usages iterate through them as attempts, that doesn't make sense in this setting, 1649 // when we're definitely concerned with only one account. 1650 passphrase = list[0] 1651 } 1652 // setEtherbase has been called above, configuring the miner address from command line flags. 1653 if cfg.Miner.Etherbase != (common.Address{}) { 1654 developer = accounts.Account{Address: cfg.Miner.Etherbase} 1655 } else if accs := ks.Accounts(); len(accs) > 0 { 1656 developer = ks.Accounts()[0] 1657 } else { 1658 developer, err = ks.NewAccount(passphrase) 1659 if err != nil { 1660 Fatalf("Failed to create developer account: %v", err) 1661 } 1662 } 1663 if err := ks.Unlock(developer, passphrase); err != nil { 1664 Fatalf("Failed to unlock developer account: %v", err) 1665 } 1666 log.Info("Using developer account", "address", developer.Address) 1667 1668 // Create a new developer genesis block or reuse existing one 1669 cfg.Genesis = core.DeveloperGenesisBlock(uint64(ctx.GlobalInt(DeveloperPeriodFlag.Name)), developer.Address) 1670 if ctx.GlobalIsSet(DataDirFlag.Name) { 1671 // Check if we have an already initialized chain and fall back to 1672 // that if so. Otherwise we need to generate a new genesis spec. 1673 chaindb := MakeChainDatabase(ctx, stack, false) // TODO (MariusVanDerWijden) make this read only 1674 if rawdb.ReadCanonicalHash(chaindb, 0) != (common.Hash{}) { 1675 cfg.Genesis = nil // fallback to db content 1676 } 1677 chaindb.Close() 1678 } 1679 if !ctx.GlobalIsSet(MinerGasPriceFlag.Name) { 1680 cfg.Miner.GasPrice = big.NewInt(1) 1681 } 1682 default: 1683 if cfg.NetworkId == 1 { 1684 SetDNSDiscoveryDefaults(cfg, params.MainnetGenesisHash) 1685 } 1686 } 1687 } 1688 1689 // SetDNSDiscoveryDefaults configures DNS discovery with the given URL if 1690 // no URLs are set. 1691 func SetDNSDiscoveryDefaults(cfg *ethconfig.Config, genesis common.Hash) { 1692 if cfg.EthDiscoveryURLs != nil { 1693 return // already set through flags/config 1694 } 1695 protocol := "all" 1696 if cfg.SyncMode == downloader.LightSync { 1697 protocol = "les" 1698 } 1699 if url := params.KnownDNSNetwork(genesis, protocol); url != "" { 1700 cfg.EthDiscoveryURLs = []string{url} 1701 cfg.SnapDiscoveryURLs = cfg.EthDiscoveryURLs 1702 } 1703 } 1704 1705 // RegisterEthService adds an Ethereum client to the stack. 1706 // The second return value is the full node instance, which may be nil if the 1707 // node is running as a light client. 1708 func RegisterEthService(stack *node.Node, cfg *ethconfig.Config) (ethapi.Backend, *eth.Ethereum) { 1709 if cfg.SyncMode == downloader.LightSync { 1710 backend, err := les.New(stack, cfg) 1711 if err != nil { 1712 Fatalf("Failed to register the Ethereum service: %v", err) 1713 } 1714 stack.RegisterAPIs(tracers.APIs(backend.ApiBackend)) 1715 return backend.ApiBackend, nil 1716 } 1717 backend, err := eth.New(stack, cfg) 1718 if err != nil { 1719 Fatalf("Failed to register the Ethereum service: %v", err) 1720 } 1721 if cfg.LightServ > 0 { 1722 _, err := les.NewLesServer(stack, backend, cfg) 1723 if err != nil { 1724 Fatalf("Failed to create the LES server: %v", err) 1725 } 1726 } 1727 stack.RegisterAPIs(tracers.APIs(backend.APIBackend)) 1728 return backend.APIBackend, backend 1729 } 1730 1731 // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to 1732 // the given node. 1733 func RegisterEthStatsService(stack *node.Node, backend ethapi.Backend, url string) { 1734 if err := ethstats.New(stack, backend, backend.Engine(), url); err != nil { 1735 Fatalf("Failed to register the Ethereum Stats service: %v", err) 1736 } 1737 } 1738 1739 // RegisterGraphQLService is a utility function to construct a new service and register it against a node. 1740 func RegisterGraphQLService(stack *node.Node, backend ethapi.Backend, cfg node.Config) { 1741 if err := graphql.New(stack, backend, cfg.GraphQLCors, cfg.GraphQLVirtualHosts); err != nil { 1742 Fatalf("Failed to register the GraphQL service: %v", err) 1743 } 1744 } 1745 1746 func SetupMetrics(ctx *cli.Context) { 1747 if metrics.Enabled { 1748 log.Info("Enabling metrics collection") 1749 1750 var ( 1751 enableExport = ctx.GlobalBool(MetricsEnableInfluxDBFlag.Name) 1752 endpoint = ctx.GlobalString(MetricsInfluxDBEndpointFlag.Name) 1753 database = ctx.GlobalString(MetricsInfluxDBDatabaseFlag.Name) 1754 username = ctx.GlobalString(MetricsInfluxDBUsernameFlag.Name) 1755 password = ctx.GlobalString(MetricsInfluxDBPasswordFlag.Name) 1756 ) 1757 1758 if enableExport { 1759 tagsMap := SplitTagsFlag(ctx.GlobalString(MetricsInfluxDBTagsFlag.Name)) 1760 1761 log.Info("Enabling metrics export to InfluxDB") 1762 1763 go influxdb.InfluxDBWithTags(metrics.DefaultRegistry, 10*time.Second, endpoint, database, username, password, "geth.", tagsMap) 1764 } 1765 1766 if ctx.GlobalIsSet(MetricsHTTPFlag.Name) { 1767 address := fmt.Sprintf("%s:%d", ctx.GlobalString(MetricsHTTPFlag.Name), ctx.GlobalInt(MetricsPortFlag.Name)) 1768 log.Info("Enabling stand-alone metrics HTTP endpoint", "address", address) 1769 exp.Setup(address) 1770 } 1771 } 1772 } 1773 1774 func SplitTagsFlag(tagsFlag string) map[string]string { 1775 tags := strings.Split(tagsFlag, ",") 1776 tagsMap := map[string]string{} 1777 1778 for _, t := range tags { 1779 if t != "" { 1780 kv := strings.Split(t, "=") 1781 1782 if len(kv) == 2 { 1783 tagsMap[kv[0]] = kv[1] 1784 } 1785 } 1786 } 1787 1788 return tagsMap 1789 } 1790 1791 // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails. 1792 func MakeChainDatabase(ctx *cli.Context, stack *node.Node, readonly bool) ethdb.Database { 1793 var ( 1794 cache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100 1795 handles = MakeDatabaseHandles() 1796 1797 err error 1798 chainDb ethdb.Database 1799 ) 1800 if ctx.GlobalString(SyncModeFlag.Name) == "light" { 1801 name := "lightchaindata" 1802 chainDb, err = stack.OpenDatabase(name, cache, handles, "", readonly) 1803 } else { 1804 name := "chaindata" 1805 chainDb, err = stack.OpenDatabaseWithFreezer(name, cache, handles, ctx.GlobalString(AncientFlag.Name), "", readonly) 1806 } 1807 if err != nil { 1808 Fatalf("Could not open database: %v", err) 1809 } 1810 return chainDb 1811 } 1812 1813 func MakeGenesis(ctx *cli.Context) *core.Genesis { 1814 var genesis *core.Genesis 1815 switch { 1816 case ctx.GlobalBool(MainnetFlag.Name): 1817 genesis = core.DefaultGenesisBlock() 1818 case ctx.GlobalBool(RopstenFlag.Name): 1819 genesis = core.DefaultRopstenGenesisBlock() 1820 case ctx.GlobalBool(RinkebyFlag.Name): 1821 genesis = core.DefaultRinkebyGenesisBlock() 1822 case ctx.GlobalBool(GoerliFlag.Name): 1823 genesis = core.DefaultGoerliGenesisBlock() 1824 case ctx.GlobalBool(YoloV3Flag.Name): 1825 genesis = core.DefaultYoloV3GenesisBlock() 1826 case ctx.GlobalBool(DeveloperFlag.Name): 1827 Fatalf("Developer chains are ephemeral") 1828 } 1829 return genesis 1830 } 1831 1832 // MakeChain creates a chain manager from set command line flags. 1833 func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) { 1834 // expecting the last argument to be the genesis file 1835 genesis, err := getGenesis(ctx.Args().Get(len(ctx.Args()) - 1)) 1836 if err != nil { 1837 Fatalf("Valid genesis file is required as argument: {}", err) 1838 } 1839 1840 chainDb = MakeChainDatabase(ctx, stack, false) // TODO(rjl493456442) support read-only database 1841 config, _, err := core.SetupGenesisBlock(chainDb, genesis) 1842 if err != nil { 1843 Fatalf("%v", err) 1844 } 1845 var engine consensus.Engine 1846 var ethereum *eth.Ethereum 1847 if config.Clique != nil { 1848 engine = clique.New(config.Clique, chainDb) 1849 } else if config.Bor != nil { 1850 ethereum = CreateBorEthereum(ð.Config{ 1851 Genesis: genesis, 1852 HeimdallURL: ctx.GlobalString(HeimdallURLFlag.Name), 1853 WithoutHeimdall: ctx.GlobalBool(WithoutHeimdallFlag.Name), 1854 }) 1855 engine = ethereum.Engine() 1856 } else { 1857 engine = ethash.NewFaker() 1858 if !ctx.GlobalBool(FakePoWFlag.Name) { 1859 engine = ethash.New(ethash.Config{ 1860 CacheDir: stack.ResolvePath(ethconfig.Defaults.Ethash.CacheDir), 1861 CachesInMem: ethconfig.Defaults.Ethash.CachesInMem, 1862 CachesOnDisk: ethconfig.Defaults.Ethash.CachesOnDisk, 1863 CachesLockMmap: ethconfig.Defaults.Ethash.CachesLockMmap, 1864 DatasetDir: stack.ResolvePath(ethconfig.Defaults.Ethash.DatasetDir), 1865 DatasetsInMem: ethconfig.Defaults.Ethash.DatasetsInMem, 1866 DatasetsOnDisk: ethconfig.Defaults.Ethash.DatasetsOnDisk, 1867 DatasetsLockMmap: ethconfig.Defaults.Ethash.DatasetsLockMmap, 1868 }, nil, false) 1869 } 1870 } 1871 if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" { 1872 Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name) 1873 } 1874 cache := &core.CacheConfig{ 1875 TrieCleanLimit: ethconfig.Defaults.TrieCleanCache, 1876 TrieCleanNoPrefetch: ctx.GlobalBool(CacheNoPrefetchFlag.Name), 1877 TrieDirtyLimit: ethconfig.Defaults.TrieDirtyCache, 1878 TrieDirtyDisabled: ctx.GlobalString(GCModeFlag.Name) == "archive", 1879 TrieTimeLimit: ethconfig.Defaults.TrieTimeout, 1880 SnapshotLimit: ethconfig.Defaults.SnapshotCache, 1881 Preimages: ctx.GlobalBool(CachePreimagesFlag.Name), 1882 } 1883 if cache.TrieDirtyDisabled && !cache.Preimages { 1884 cache.Preimages = true 1885 log.Info("Enabling recording of key preimages since archive mode is used") 1886 } 1887 if !ctx.GlobalBool(SnapshotFlag.Name) { 1888 cache.SnapshotLimit = 0 // Disabled 1889 } 1890 if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheTrieFlag.Name) { 1891 cache.TrieCleanLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheTrieFlag.Name) / 100 1892 } 1893 if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) { 1894 cache.TrieDirtyLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100 1895 } 1896 vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)} 1897 1898 // TODO(rjl493456442) disable snapshot generation/wiping if the chain is read only. 1899 // Disable transaction indexing/unindexing by default. 1900 chain, err = core.NewBlockChain(chainDb, cache, config, engine, vmcfg, nil, nil) 1901 if err != nil { 1902 Fatalf("Can't create BlockChain: %v", err) 1903 } 1904 if ethereum != nil { 1905 ethereum.SetBlockchain(chain) 1906 } 1907 return chain, chainDb 1908 } 1909 1910 // MakeConsolePreloads retrieves the absolute paths for the console JavaScript 1911 // scripts to preload before starting. 1912 func MakeConsolePreloads(ctx *cli.Context) []string { 1913 // Skip preloading if there's nothing to preload 1914 if ctx.GlobalString(PreloadJSFlag.Name) == "" { 1915 return nil 1916 } 1917 // Otherwise resolve absolute paths and return them 1918 var preloads []string 1919 1920 for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") { 1921 preloads = append(preloads, strings.TrimSpace(file)) 1922 } 1923 return preloads 1924 } 1925 1926 // MigrateFlags sets the global flag from a local flag when it's set. 1927 // This is a temporary function used for migrating old command/flags to the 1928 // new format. 1929 // 1930 // e.g. geth account new --keystore /tmp/mykeystore --lightkdf 1931 // 1932 // is equivalent after calling this method with: 1933 // 1934 // geth --keystore /tmp/mykeystore --lightkdf account new 1935 // 1936 // This allows the use of the existing configuration functionality. 1937 // When all flags are migrated this function can be removed and the existing 1938 // configuration functionality must be changed that is uses local flags 1939 func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error { 1940 return func(ctx *cli.Context) error { 1941 for _, name := range ctx.FlagNames() { 1942 if ctx.IsSet(name) { 1943 ctx.GlobalSet(name, ctx.String(name)) 1944 } 1945 } 1946 return action(ctx) 1947 } 1948 }