flags.go 30 KB

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