flags.go 33 KB

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