flags.go 30 KB

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