flags.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. GpoBlocksFlag = cli.IntFlag{
  398. Name: "gpoblocks",
  399. Usage: "Number of recent blocks to check for gas prices",
  400. Value: 10,
  401. }
  402. GpoPercentileFlag = cli.IntFlag{
  403. Name: "gpopercentile",
  404. Usage: "Suggested gas price is the given percentile of a set of recent transaction gas prices",
  405. Value: 50,
  406. }
  407. )
  408. // MakeDataDir retrieves the currently requested data directory, terminating
  409. // if none (or the empty string) is specified. If the node is starting a testnet,
  410. // the a subdirectory of the specified datadir will be used.
  411. func MakeDataDir(ctx *cli.Context) string {
  412. if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
  413. // TODO: choose a different location outside of the regular datadir.
  414. if ctx.GlobalBool(TestNetFlag.Name) {
  415. return filepath.Join(path, "testnet")
  416. }
  417. return path
  418. }
  419. Fatalf("Cannot determine default data directory, please set manually (--datadir)")
  420. return ""
  421. }
  422. // MakeEthashCacheDir returns the directory to use for storing the ethash cache
  423. // dumps.
  424. func MakeEthashCacheDir(ctx *cli.Context) string {
  425. if ctx.GlobalIsSet(EthashCacheDirFlag.Name) && ctx.GlobalString(EthashCacheDirFlag.Name) == "" {
  426. return ""
  427. }
  428. if !ctx.GlobalIsSet(EthashCacheDirFlag.Name) {
  429. return "ethash"
  430. }
  431. return ctx.GlobalString(EthashCacheDirFlag.Name)
  432. }
  433. // MakeEthashDatasetDir returns the directory to use for storing the full ethash
  434. // dataset dumps.
  435. func MakeEthashDatasetDir(ctx *cli.Context) string {
  436. if !ctx.GlobalIsSet(EthashDatasetDirFlag.Name) {
  437. home := os.Getenv("HOME")
  438. if home == "" {
  439. if user, err := user.Current(); err == nil {
  440. home = user.HomeDir
  441. }
  442. }
  443. if runtime.GOOS == "windows" {
  444. return filepath.Join(home, "AppData", "Ethash")
  445. }
  446. return filepath.Join(home, ".ethash")
  447. }
  448. return ctx.GlobalString(EthashDatasetDirFlag.Name)
  449. }
  450. // MakeIPCPath creates an IPC path configuration from the set command line flags,
  451. // returning an empty string if IPC was explicitly disabled, or the set path.
  452. func MakeIPCPath(ctx *cli.Context) string {
  453. if ctx.GlobalBool(IPCDisabledFlag.Name) {
  454. return ""
  455. }
  456. return ctx.GlobalString(IPCPathFlag.Name)
  457. }
  458. // MakeNodeKey creates a node key from set command line flags, either loading it
  459. // from a file or as a specified hex value. If neither flags were provided, this
  460. // method returns nil and an emphemeral key is to be generated.
  461. func MakeNodeKey(ctx *cli.Context) *ecdsa.PrivateKey {
  462. var (
  463. hex = ctx.GlobalString(NodeKeyHexFlag.Name)
  464. file = ctx.GlobalString(NodeKeyFileFlag.Name)
  465. key *ecdsa.PrivateKey
  466. err error
  467. )
  468. switch {
  469. case file != "" && hex != "":
  470. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  471. case file != "":
  472. if key, err = crypto.LoadECDSA(file); err != nil {
  473. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  474. }
  475. case hex != "":
  476. if key, err = crypto.HexToECDSA(hex); err != nil {
  477. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  478. }
  479. }
  480. return key
  481. }
  482. // makeNodeUserIdent creates the user identifier from CLI flags.
  483. func makeNodeUserIdent(ctx *cli.Context) string {
  484. var comps []string
  485. if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
  486. comps = append(comps, identity)
  487. }
  488. if ctx.GlobalBool(VMEnableJitFlag.Name) {
  489. comps = append(comps, "JIT")
  490. }
  491. return strings.Join(comps, "/")
  492. }
  493. // MakeBootstrapNodes creates a list of bootstrap nodes from the command line
  494. // flags, reverting to pre-configured ones if none have been specified.
  495. func MakeBootstrapNodes(ctx *cli.Context) []*discover.Node {
  496. urls := params.MainnetBootnodes
  497. if ctx.GlobalIsSet(BootnodesFlag.Name) {
  498. urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
  499. } else if ctx.GlobalBool(TestNetFlag.Name) {
  500. urls = params.TestnetBootnodes
  501. }
  502. bootnodes := make([]*discover.Node, 0, len(urls))
  503. for _, url := range urls {
  504. node, err := discover.ParseNode(url)
  505. if err != nil {
  506. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  507. continue
  508. }
  509. bootnodes = append(bootnodes, node)
  510. }
  511. return bootnodes
  512. }
  513. // MakeBootstrapNodesV5 creates a list of bootstrap nodes from the command line
  514. // flags, reverting to pre-configured ones if none have been specified.
  515. func MakeBootstrapNodesV5(ctx *cli.Context) []*discv5.Node {
  516. urls := params.DiscoveryV5Bootnodes
  517. if ctx.GlobalIsSet(BootnodesFlag.Name) {
  518. urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
  519. }
  520. bootnodes := make([]*discv5.Node, 0, len(urls))
  521. for _, url := range urls {
  522. node, err := discv5.ParseNode(url)
  523. if err != nil {
  524. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  525. continue
  526. }
  527. bootnodes = append(bootnodes, node)
  528. }
  529. return bootnodes
  530. }
  531. // MakeListenAddress creates a TCP listening address string from set command
  532. // line flags.
  533. func MakeListenAddress(ctx *cli.Context) string {
  534. return fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
  535. }
  536. // MakeDiscoveryV5Address creates a UDP listening address string from set command
  537. // line flags for the V5 discovery protocol.
  538. func MakeDiscoveryV5Address(ctx *cli.Context) string {
  539. return fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name)+1)
  540. }
  541. // MakeNAT creates a port mapper from set command line flags.
  542. func MakeNAT(ctx *cli.Context) nat.Interface {
  543. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  544. if err != nil {
  545. Fatalf("Option %s: %v", NATFlag.Name, err)
  546. }
  547. return natif
  548. }
  549. // MakeRPCModules splits input separated by a comma and trims excessive white
  550. // space from the substrings.
  551. func MakeRPCModules(input string) []string {
  552. result := strings.Split(input, ",")
  553. for i, r := range result {
  554. result[i] = strings.TrimSpace(r)
  555. }
  556. return result
  557. }
  558. // MakeHTTPRpcHost creates the HTTP RPC listener interface string from the set
  559. // command line flags, returning empty if the HTTP endpoint is disabled.
  560. func MakeHTTPRpcHost(ctx *cli.Context) string {
  561. if !ctx.GlobalBool(RPCEnabledFlag.Name) {
  562. return ""
  563. }
  564. return ctx.GlobalString(RPCListenAddrFlag.Name)
  565. }
  566. // MakeWSRpcHost creates the WebSocket RPC listener interface string from the set
  567. // command line flags, returning empty if the HTTP endpoint is disabled.
  568. func MakeWSRpcHost(ctx *cli.Context) string {
  569. if !ctx.GlobalBool(WSEnabledFlag.Name) {
  570. return ""
  571. }
  572. return ctx.GlobalString(WSListenAddrFlag.Name)
  573. }
  574. // MakeDatabaseHandles raises out the number of allowed file handles per process
  575. // for Geth and returns half of the allowance to assign to the database.
  576. func MakeDatabaseHandles() int {
  577. if err := raiseFdLimit(2048); err != nil {
  578. Fatalf("Failed to raise file descriptor allowance: %v", err)
  579. }
  580. limit, err := getFdLimit()
  581. if err != nil {
  582. Fatalf("Failed to retrieve file descriptor allowance: %v", err)
  583. }
  584. if limit > 2048 { // cap database file descriptors even if more is available
  585. limit = 2048
  586. }
  587. return limit / 2 // Leave half for networking and other stuff
  588. }
  589. // MakeAddress converts an account specified directly as a hex encoded string or
  590. // a key index in the key store to an internal account representation.
  591. func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) {
  592. // If the specified account is a valid address, return it
  593. if common.IsHexAddress(account) {
  594. return accounts.Account{Address: common.HexToAddress(account)}, nil
  595. }
  596. // Otherwise try to interpret the account as a keystore index
  597. index, err := strconv.Atoi(account)
  598. if err != nil || index < 0 {
  599. return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account)
  600. }
  601. accs := ks.Accounts()
  602. if len(accs) <= index {
  603. return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs))
  604. }
  605. return accs[index], nil
  606. }
  607. // MakeEtherbase retrieves the etherbase either from the directly specified
  608. // command line flags or from the keystore if CLI indexed.
  609. func MakeEtherbase(ks *keystore.KeyStore, ctx *cli.Context) common.Address {
  610. accounts := ks.Accounts()
  611. if !ctx.GlobalIsSet(EtherbaseFlag.Name) && len(accounts) == 0 {
  612. log.Warn("No etherbase set and no accounts found as default")
  613. return common.Address{}
  614. }
  615. etherbase := ctx.GlobalString(EtherbaseFlag.Name)
  616. if etherbase == "" {
  617. return common.Address{}
  618. }
  619. // If the specified etherbase is a valid address, return it
  620. account, err := MakeAddress(ks, etherbase)
  621. if err != nil {
  622. Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
  623. }
  624. return account.Address
  625. }
  626. // MakeMinerExtra resolves extradata for the miner from the set command line flags
  627. // or returns a default one composed on the client, runtime and OS metadata.
  628. func MakeMinerExtra(extra []byte, ctx *cli.Context) []byte {
  629. if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  630. return []byte(ctx.GlobalString(ExtraDataFlag.Name))
  631. }
  632. return extra
  633. }
  634. // MakePasswordList reads password lines from the file specified by --password.
  635. func MakePasswordList(ctx *cli.Context) []string {
  636. path := ctx.GlobalString(PasswordFileFlag.Name)
  637. if path == "" {
  638. return nil
  639. }
  640. text, err := ioutil.ReadFile(path)
  641. if err != nil {
  642. Fatalf("Failed to read password file: %v", err)
  643. }
  644. lines := strings.Split(string(text), "\n")
  645. // Sanitise DOS line endings.
  646. for i := range lines {
  647. lines[i] = strings.TrimRight(lines[i], "\r")
  648. }
  649. return lines
  650. }
  651. // MakeNode configures a node with no services from command line flags.
  652. func MakeNode(ctx *cli.Context, name, gitCommit string) *node.Node {
  653. vsn := params.Version
  654. if gitCommit != "" {
  655. vsn += "-" + gitCommit[:8]
  656. }
  657. // if we're running a light client or server, force enable the v5 peer discovery unless it is explicitly disabled with --nodiscover
  658. // note that explicitly specifying --v5disc overrides --nodiscover, in which case the later only disables v4 discovery
  659. forceV5Discovery := (ctx.GlobalBool(LightModeFlag.Name) || ctx.GlobalInt(LightServFlag.Name) > 0) && !ctx.GlobalBool(NoDiscoverFlag.Name)
  660. config := &node.Config{
  661. DataDir: MakeDataDir(ctx),
  662. KeyStoreDir: ctx.GlobalString(KeyStoreDirFlag.Name),
  663. UseLightweightKDF: ctx.GlobalBool(LightKDFFlag.Name),
  664. PrivateKey: MakeNodeKey(ctx),
  665. Name: name,
  666. Version: vsn,
  667. UserIdent: makeNodeUserIdent(ctx),
  668. NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name) || ctx.GlobalBool(LightModeFlag.Name), // always disable v4 discovery in light client mode
  669. DiscoveryV5: ctx.GlobalBool(DiscoveryV5Flag.Name) || forceV5Discovery,
  670. DiscoveryV5Addr: MakeDiscoveryV5Address(ctx),
  671. BootstrapNodes: MakeBootstrapNodes(ctx),
  672. BootstrapNodesV5: MakeBootstrapNodesV5(ctx),
  673. ListenAddr: MakeListenAddress(ctx),
  674. NAT: MakeNAT(ctx),
  675. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  676. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  677. IPCPath: MakeIPCPath(ctx),
  678. HTTPHost: MakeHTTPRpcHost(ctx),
  679. HTTPPort: ctx.GlobalInt(RPCPortFlag.Name),
  680. HTTPCors: ctx.GlobalString(RPCCORSDomainFlag.Name),
  681. HTTPModules: MakeRPCModules(ctx.GlobalString(RPCApiFlag.Name)),
  682. WSHost: MakeWSRpcHost(ctx),
  683. WSPort: ctx.GlobalInt(WSPortFlag.Name),
  684. WSOrigins: ctx.GlobalString(WSAllowedOriginsFlag.Name),
  685. WSModules: MakeRPCModules(ctx.GlobalString(WSApiFlag.Name)),
  686. }
  687. if ctx.GlobalBool(DevModeFlag.Name) {
  688. if !ctx.GlobalIsSet(DataDirFlag.Name) {
  689. config.DataDir = filepath.Join(os.TempDir(), "/ethereum_dev_mode")
  690. }
  691. // --dev mode does not need p2p networking.
  692. config.MaxPeers = 0
  693. config.ListenAddr = ":0"
  694. }
  695. if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" {
  696. list, err := netutil.ParseNetlist(netrestrict)
  697. if err != nil {
  698. Fatalf("Option %q: %v", NetrestrictFlag.Name, err)
  699. }
  700. config.NetRestrict = list
  701. }
  702. stack, err := node.New(config)
  703. if err != nil {
  704. Fatalf("Failed to create the protocol stack: %v", err)
  705. }
  706. return stack
  707. }
  708. // RegisterEthService configures eth.Ethereum from command line flags and adds it to the
  709. // given node.
  710. func RegisterEthService(ctx *cli.Context, stack *node.Node, extra []byte) {
  711. // Avoid conflicting network flags
  712. networks, netFlags := 0, []cli.BoolFlag{DevModeFlag, TestNetFlag}
  713. for _, flag := range netFlags {
  714. if ctx.GlobalBool(flag.Name) {
  715. networks++
  716. }
  717. }
  718. if networks > 1 {
  719. Fatalf("The %v flags are mutually exclusive", netFlags)
  720. }
  721. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  722. ethConf := &eth.Config{
  723. Etherbase: MakeEtherbase(ks, ctx),
  724. FastSync: ctx.GlobalBool(FastSyncFlag.Name),
  725. LightMode: ctx.GlobalBool(LightModeFlag.Name),
  726. LightServ: ctx.GlobalInt(LightServFlag.Name),
  727. LightPeers: ctx.GlobalInt(LightPeersFlag.Name),
  728. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  729. DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
  730. DatabaseHandles: MakeDatabaseHandles(),
  731. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  732. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  733. ExtraData: MakeMinerExtra(extra, ctx),
  734. DocRoot: ctx.GlobalString(DocRootFlag.Name),
  735. GasPrice: GlobalBig(ctx, GasPriceFlag.Name),
  736. GpoBlocks: ctx.GlobalInt(GpoBlocksFlag.Name),
  737. GpoPercentile: ctx.GlobalInt(GpoPercentileFlag.Name),
  738. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  739. EthashCacheDir: MakeEthashCacheDir(ctx),
  740. EthashCachesInMem: ctx.GlobalInt(EthashCachesInMemoryFlag.Name),
  741. EthashCachesOnDisk: ctx.GlobalInt(EthashCachesOnDiskFlag.Name),
  742. EthashDatasetDir: MakeEthashDatasetDir(ctx),
  743. EthashDatasetsInMem: ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name),
  744. EthashDatasetsOnDisk: ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name),
  745. EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name),
  746. }
  747. // Override any default configs in dev mode or the test net
  748. switch {
  749. case ctx.GlobalBool(TestNetFlag.Name):
  750. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  751. ethConf.NetworkId = 3
  752. }
  753. ethConf.Genesis = core.DefaultTestnetGenesisBlock()
  754. case ctx.GlobalBool(DevModeFlag.Name):
  755. ethConf.Genesis = core.DevGenesisBlock()
  756. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  757. ethConf.GasPrice = new(big.Int)
  758. }
  759. ethConf.PowTest = true
  760. }
  761. // Override any global options pertaining to the Ethereum protocol
  762. if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  763. state.MaxTrieCacheGen = uint16(gen)
  764. }
  765. if ethConf.LightMode {
  766. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  767. return les.New(ctx, ethConf)
  768. }); err != nil {
  769. Fatalf("Failed to register the Ethereum light node service: %v", err)
  770. }
  771. } else {
  772. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  773. fullNode, err := eth.New(ctx, ethConf)
  774. if fullNode != nil && ethConf.LightServ > 0 {
  775. ls, _ := les.NewLesServer(fullNode, ethConf)
  776. fullNode.AddLesServer(ls)
  777. }
  778. return fullNode, err
  779. }); err != nil {
  780. Fatalf("Failed to register the Ethereum full node service: %v", err)
  781. }
  782. }
  783. }
  784. // RegisterShhService configures Whisper and adds it to the given node.
  785. func RegisterShhService(stack *node.Node) {
  786. if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  787. Fatalf("Failed to register the Whisper service: %v", err)
  788. }
  789. }
  790. // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  791. // th egiven node.
  792. func RegisterEthStatsService(stack *node.Node, url string) {
  793. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  794. // Retrieve both eth and les services
  795. var ethServ *eth.Ethereum
  796. ctx.Service(&ethServ)
  797. var lesServ *les.LightEthereum
  798. ctx.Service(&lesServ)
  799. return ethstats.New(url, ethServ, lesServ)
  800. }); err != nil {
  801. Fatalf("Failed to register the Ethereum Stats service: %v", err)
  802. }
  803. }
  804. // SetupNetwork configures the system for either the main net or some test network.
  805. func SetupNetwork(ctx *cli.Context) {
  806. params.TargetGasLimit = new(big.Int).SetUint64(ctx.GlobalUint64(TargetGasLimitFlag.Name))
  807. }
  808. func ChainDbName(ctx *cli.Context) string {
  809. if ctx.GlobalBool(LightModeFlag.Name) {
  810. return "lightchaindata"
  811. } else {
  812. return "chaindata"
  813. }
  814. }
  815. // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  816. func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  817. var (
  818. cache = ctx.GlobalInt(CacheFlag.Name)
  819. handles = MakeDatabaseHandles()
  820. name = ChainDbName(ctx)
  821. )
  822. chainDb, err := stack.OpenDatabase(name, cache, handles)
  823. if err != nil {
  824. Fatalf("Could not open database: %v", err)
  825. }
  826. return chainDb
  827. }
  828. func MakeGenesis(ctx *cli.Context) *core.Genesis {
  829. var genesis *core.Genesis
  830. switch {
  831. case ctx.GlobalBool(TestNetFlag.Name):
  832. genesis = core.DefaultTestnetGenesisBlock()
  833. case ctx.GlobalBool(DevModeFlag.Name):
  834. genesis = core.DevGenesisBlock()
  835. }
  836. return genesis
  837. }
  838. // MakeChain creates a chain manager from set command line flags.
  839. func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  840. var err error
  841. chainDb = MakeChainDatabase(ctx, stack)
  842. engine := ethash.NewFaker()
  843. if !ctx.GlobalBool(FakePoWFlag.Name) {
  844. engine = ethash.New("", 1, 0, "", 1, 0)
  845. }
  846. config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx))
  847. if err != nil {
  848. Fatalf("%v", err)
  849. }
  850. vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
  851. chain, err = core.NewBlockChain(chainDb, config, engine, new(event.TypeMux), vmcfg)
  852. if err != nil {
  853. Fatalf("Can't create BlockChain: %v", err)
  854. }
  855. return chain, chainDb
  856. }
  857. // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  858. // scripts to preload before starting.
  859. func MakeConsolePreloads(ctx *cli.Context) []string {
  860. // Skip preloading if there's nothing to preload
  861. if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  862. return nil
  863. }
  864. // Otherwise resolve absolute paths and return them
  865. preloads := []string{}
  866. assets := ctx.GlobalString(JSpathFlag.Name)
  867. for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  868. preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  869. }
  870. return preloads
  871. }