flags.go 29 KB

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