flags.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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/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/ethdb"
  38. "github.com/ethereum/go-ethereum/ethstats"
  39. "github.com/ethereum/go-ethereum/event"
  40. "github.com/ethereum/go-ethereum/les"
  41. "github.com/ethereum/go-ethereum/log"
  42. "github.com/ethereum/go-ethereum/metrics"
  43. "github.com/ethereum/go-ethereum/node"
  44. "github.com/ethereum/go-ethereum/p2p/discover"
  45. "github.com/ethereum/go-ethereum/p2p/discv5"
  46. "github.com/ethereum/go-ethereum/p2p/nat"
  47. "github.com/ethereum/go-ethereum/p2p/netutil"
  48. "github.com/ethereum/go-ethereum/params"
  49. "github.com/ethereum/go-ethereum/pow"
  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 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. ChainConfig: MakeChainConfig(ctx, stack),
  745. FastSync: ctx.GlobalBool(FastSyncFlag.Name),
  746. LightMode: ctx.GlobalBool(LightModeFlag.Name),
  747. LightServ: ctx.GlobalInt(LightServFlag.Name),
  748. LightPeers: ctx.GlobalInt(LightPeersFlag.Name),
  749. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  750. DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
  751. DatabaseHandles: MakeDatabaseHandles(),
  752. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  753. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  754. ExtraData: MakeMinerExtra(extra, ctx),
  755. DocRoot: ctx.GlobalString(DocRootFlag.Name),
  756. GasPrice: GlobalBig(ctx, GasPriceFlag.Name),
  757. GpoMinGasPrice: GlobalBig(ctx, GpoMinGasPriceFlag.Name),
  758. GpoMaxGasPrice: GlobalBig(ctx, GpoMaxGasPriceFlag.Name),
  759. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  760. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  761. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  762. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  763. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  764. EthashCacheDir: MakeEthashCacheDir(ctx),
  765. EthashCachesInMem: ctx.GlobalInt(EthashCachesInMemoryFlag.Name),
  766. EthashCachesOnDisk: ctx.GlobalInt(EthashCachesOnDiskFlag.Name),
  767. EthashDatasetDir: MakeEthashDatasetDir(ctx),
  768. EthashDatasetsInMem: ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name),
  769. EthashDatasetsOnDisk: ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name),
  770. EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name),
  771. }
  772. // Override any default configs in dev mode or the test net
  773. switch {
  774. case ctx.GlobalBool(TestNetFlag.Name):
  775. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  776. ethConf.NetworkId = 3
  777. }
  778. ethConf.Genesis = core.DefaultTestnetGenesisBlock()
  779. case ctx.GlobalBool(DevModeFlag.Name):
  780. ethConf.Genesis = core.DevGenesisBlock()
  781. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  782. ethConf.GasPrice = new(big.Int)
  783. }
  784. ethConf.PowTest = true
  785. }
  786. // Override any global options pertaining to the Ethereum protocol
  787. if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  788. state.MaxTrieCacheGen = uint16(gen)
  789. }
  790. if ethConf.LightMode {
  791. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  792. return les.New(ctx, ethConf)
  793. }); err != nil {
  794. Fatalf("Failed to register the Ethereum light node service: %v", err)
  795. }
  796. } else {
  797. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  798. fullNode, err := eth.New(ctx, ethConf)
  799. if fullNode != nil && ethConf.LightServ > 0 {
  800. ls, _ := les.NewLesServer(fullNode, ethConf)
  801. fullNode.AddLesServer(ls)
  802. }
  803. return fullNode, err
  804. }); err != nil {
  805. Fatalf("Failed to register the Ethereum full node service: %v", err)
  806. }
  807. }
  808. }
  809. // RegisterShhService configures Whisper and adds it to the given node.
  810. func RegisterShhService(stack *node.Node) {
  811. if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  812. Fatalf("Failed to register the Whisper service: %v", err)
  813. }
  814. }
  815. // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  816. // th egiven node.
  817. func RegisterEthStatsService(stack *node.Node, url string) {
  818. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  819. // Retrieve both eth and les services
  820. var ethServ *eth.Ethereum
  821. ctx.Service(&ethServ)
  822. var lesServ *les.LightEthereum
  823. ctx.Service(&lesServ)
  824. return ethstats.New(url, ethServ, lesServ)
  825. }); err != nil {
  826. Fatalf("Failed to register the Ethereum Stats service: %v", err)
  827. }
  828. }
  829. // SetupNetwork configures the system for either the main net or some test network.
  830. func SetupNetwork(ctx *cli.Context) {
  831. params.TargetGasLimit = new(big.Int).SetUint64(ctx.GlobalUint64(TargetGasLimitFlag.Name))
  832. }
  833. // MakeChainConfig reads the chain configuration from the database in ctx.Datadir.
  834. func MakeChainConfig(ctx *cli.Context, stack *node.Node) *params.ChainConfig {
  835. db := MakeChainDatabase(ctx, stack)
  836. defer db.Close()
  837. return MakeChainConfigFromDb(ctx, db)
  838. }
  839. // MakeChainConfigFromDb reads the chain configuration from the given database.
  840. func MakeChainConfigFromDb(ctx *cli.Context, db ethdb.Database) *params.ChainConfig {
  841. // If the chain is already initialized, use any existing chain configs
  842. config := new(params.ChainConfig)
  843. genesis := core.GetBlock(db, core.GetCanonicalHash(db, 0), 0)
  844. if genesis != nil {
  845. storedConfig, err := core.GetChainConfig(db, genesis.Hash())
  846. switch err {
  847. case nil:
  848. config = storedConfig
  849. case core.ChainConfigNotFoundErr:
  850. // No configs found, use empty, will populate below
  851. default:
  852. Fatalf("Could not make chain configuration: %v", err)
  853. }
  854. }
  855. // set chain id in case it's zero.
  856. if config.ChainId == nil {
  857. config.ChainId = new(big.Int)
  858. }
  859. // Check whether we are allowed to set default config params or not:
  860. // - If no genesis is set, we're running either mainnet or testnet (private nets use `geth init`)
  861. // - If a genesis is already set, ensure we have a configuration for it (mainnet or testnet)
  862. defaults := genesis == nil ||
  863. (genesis.Hash() == params.MainNetGenesisHash && !ctx.GlobalBool(TestNetFlag.Name)) ||
  864. (genesis.Hash() == params.TestNetGenesisHash && ctx.GlobalBool(TestNetFlag.Name))
  865. if defaults {
  866. if ctx.GlobalBool(TestNetFlag.Name) {
  867. config = params.TestnetChainConfig
  868. } else if ctx.GlobalBool(DevModeFlag.Name) {
  869. config = params.AllProtocolChanges
  870. } else {
  871. // Homestead fork
  872. config.HomesteadBlock = params.MainNetHomesteadBlock
  873. // DAO fork
  874. config.DAOForkBlock = params.MainNetDAOForkBlock
  875. config.DAOForkSupport = true
  876. // DoS reprice fork
  877. config.EIP150Block = params.MainNetHomesteadGasRepriceBlock
  878. config.EIP150Hash = params.MainNetHomesteadGasRepriceHash
  879. // DoS state cleanup fork
  880. config.EIP155Block = params.MainNetSpuriousDragon
  881. config.EIP158Block = params.MainNetSpuriousDragon
  882. config.ChainId = params.MainNetChainID
  883. }
  884. }
  885. return config
  886. }
  887. func ChainDbName(ctx *cli.Context) string {
  888. if ctx.GlobalBool(LightModeFlag.Name) {
  889. return "lightchaindata"
  890. } else {
  891. return "chaindata"
  892. }
  893. }
  894. // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  895. func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  896. var (
  897. cache = ctx.GlobalInt(CacheFlag.Name)
  898. handles = MakeDatabaseHandles()
  899. name = ChainDbName(ctx)
  900. )
  901. chainDb, err := stack.OpenDatabase(name, cache, handles)
  902. if err != nil {
  903. Fatalf("Could not open database: %v", err)
  904. }
  905. return chainDb
  906. }
  907. // MakeChain creates a chain manager from set command line flags.
  908. func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  909. var err error
  910. chainDb = MakeChainDatabase(ctx, stack)
  911. if ctx.GlobalBool(TestNetFlag.Name) {
  912. _, err := core.WriteTestNetGenesisBlock(chainDb)
  913. if err != nil {
  914. Fatalf("Failed to write testnet genesis: %v", err)
  915. }
  916. }
  917. chainConfig := MakeChainConfigFromDb(ctx, chainDb)
  918. seal := pow.PoW(pow.FakePow{})
  919. if !ctx.GlobalBool(FakePoWFlag.Name) {
  920. seal = pow.NewFullEthash("", 1, 0, "", 1, 0)
  921. }
  922. chain, err = core.NewBlockChain(chainDb, chainConfig, seal, new(event.TypeMux), vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)})
  923. if err != nil {
  924. Fatalf("Could not start chainmanager: %v", err)
  925. }
  926. return chain, chainDb
  927. }
  928. // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  929. // scripts to preload before starting.
  930. func MakeConsolePreloads(ctx *cli.Context) []string {
  931. // Skip preloading if there's nothing to preload
  932. if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  933. return nil
  934. }
  935. // Otherwise resolve absolute paths and return them
  936. preloads := []string{}
  937. assets := ctx.GlobalString(JSpathFlag.Name)
  938. for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  939. preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  940. }
  941. return preloads
  942. }