flags.go 30 KB

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