flags.go 30 KB

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