flags.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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"
  23. "math/big"
  24. "os"
  25. "path/filepath"
  26. "runtime"
  27. "strconv"
  28. "strings"
  29. "github.com/ethereum/ethash"
  30. "github.com/ethereum/go-ethereum/accounts"
  31. "github.com/ethereum/go-ethereum/common"
  32. "github.com/ethereum/go-ethereum/core"
  33. "github.com/ethereum/go-ethereum/core/state"
  34. "github.com/ethereum/go-ethereum/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, 0=Olympic (disused), 1=Frontier, 2=Morden (disused), 3=Ropsten)",
  110. Value: eth.NetworkId,
  111. }
  112. OlympicFlag = cli.BoolFlag{
  113. Name: "olympic",
  114. Usage: "Olympic network: pre-configured pre-release test network",
  115. }
  116. TestNetFlag = cli.BoolFlag{
  117. Name: "testnet",
  118. Usage: "Ropsten network: pre-configured test network",
  119. }
  120. DevModeFlag = cli.BoolFlag{
  121. Name: "dev",
  122. Usage: "Developer mode: pre-configured private network with several debugging flags",
  123. }
  124. IdentityFlag = cli.StringFlag{
  125. Name: "identity",
  126. Usage: "Custom node name",
  127. }
  128. NatspecEnabledFlag = cli.BoolFlag{
  129. Name: "natspec",
  130. Usage: "Enable NatSpec confirmation notice",
  131. }
  132. DocRootFlag = DirectoryFlag{
  133. Name: "docroot",
  134. Usage: "Document Root for HTTPClient file scheme",
  135. Value: DirectoryString{homeDir()},
  136. }
  137. FastSyncFlag = cli.BoolFlag{
  138. Name: "fast",
  139. Usage: "Enable fast syncing through state downloads",
  140. }
  141. LightModeFlag = cli.BoolFlag{
  142. Name: "light",
  143. Usage: "Enable light client mode",
  144. }
  145. LightServFlag = cli.IntFlag{
  146. Name: "lightserv",
  147. Usage: "Maximum percentage of time allowed for serving LES requests (0-90)",
  148. Value: 0,
  149. }
  150. LightPeersFlag = cli.IntFlag{
  151. Name: "lightpeers",
  152. Usage: "Maximum number of LES client peers",
  153. Value: 20,
  154. }
  155. LightKDFFlag = cli.BoolFlag{
  156. Name: "lightkdf",
  157. Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
  158. }
  159. // Performance tuning settings
  160. CacheFlag = cli.IntFlag{
  161. Name: "cache",
  162. Usage: "Megabytes of memory allocated to internal caching (min 16MB / database forced)",
  163. Value: 128,
  164. }
  165. TrieCacheGenFlag = cli.IntFlag{
  166. Name: "trie-cache-gens",
  167. Usage: "Number of trie node generations to keep in memory",
  168. Value: int(state.MaxTrieCacheGen),
  169. }
  170. // Miner settings
  171. MiningEnabledFlag = cli.BoolFlag{
  172. Name: "mine",
  173. Usage: "Enable mining",
  174. }
  175. MinerThreadsFlag = cli.IntFlag{
  176. Name: "minerthreads",
  177. Usage: "Number of CPU threads to use for mining",
  178. Value: runtime.NumCPU(),
  179. }
  180. TargetGasLimitFlag = cli.StringFlag{
  181. Name: "targetgaslimit",
  182. Usage: "Target gas limit sets the artificial target gas floor for the blocks to mine",
  183. Value: params.GenesisGasLimit.String(),
  184. }
  185. AutoDAGFlag = cli.BoolFlag{
  186. Name: "autodag",
  187. Usage: "Enable automatic DAG pregeneration",
  188. }
  189. EtherbaseFlag = cli.StringFlag{
  190. Name: "etherbase",
  191. Usage: "Public address for block mining rewards (default = first account created)",
  192. Value: "0",
  193. }
  194. GasPriceFlag = cli.StringFlag{
  195. Name: "gasprice",
  196. Usage: "Minimal gas price to accept for mining a transactions",
  197. Value: new(big.Int).Mul(big.NewInt(20), common.Shannon).String(),
  198. }
  199. ExtraDataFlag = cli.StringFlag{
  200. Name: "extradata",
  201. Usage: "Block extra data set by the miner (default = client version)",
  202. }
  203. // Account settings
  204. UnlockedAccountFlag = cli.StringFlag{
  205. Name: "unlock",
  206. Usage: "Comma separated list of accounts to unlock",
  207. Value: "",
  208. }
  209. PasswordFileFlag = cli.StringFlag{
  210. Name: "password",
  211. Usage: "Password file to use for non-inteactive password input",
  212. Value: "",
  213. }
  214. VMForceJitFlag = cli.BoolFlag{
  215. Name: "forcejit",
  216. Usage: "Force the JIT VM to take precedence",
  217. }
  218. VMJitCacheFlag = cli.IntFlag{
  219. Name: "jitcache",
  220. Usage: "Amount of cached JIT VM programs",
  221. Value: 64,
  222. }
  223. VMEnableJitFlag = cli.BoolFlag{
  224. Name: "jitvm",
  225. Usage: "Enable the JIT VM",
  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.StringSliceFlag{
  328. Name: "bootnodes",
  329. Usage: "Comma separated enode URLs for P2P discovery bootstrap",
  330. Value: nil,
  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 = ctx.GlobalStringSlice(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 = ctx.GlobalStringSlice(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, OlympicFlag}
  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. }
  707. // Override any default configs in dev mode or the test net
  708. switch {
  709. case ctx.GlobalBool(OlympicFlag.Name):
  710. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  711. ethConf.NetworkId = 1
  712. }
  713. ethConf.Genesis = core.OlympicGenesisBlock()
  714. case ctx.GlobalBool(TestNetFlag.Name):
  715. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  716. ethConf.NetworkId = 3
  717. }
  718. ethConf.Genesis = core.DefaultTestnetGenesisBlock()
  719. case ctx.GlobalBool(DevModeFlag.Name):
  720. ethConf.Genesis = core.OlympicGenesisBlock()
  721. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  722. ethConf.GasPrice = new(big.Int)
  723. }
  724. ethConf.PowTest = true
  725. }
  726. // Override any global options pertaining to the Ethereum protocol
  727. if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  728. state.MaxTrieCacheGen = uint16(gen)
  729. }
  730. if ethConf.LightMode {
  731. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  732. return les.New(ctx, ethConf)
  733. }); err != nil {
  734. Fatalf("Failed to register the Ethereum light node service: %v", err)
  735. }
  736. } else {
  737. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  738. fullNode, err := eth.New(ctx, ethConf)
  739. if fullNode != nil && ethConf.LightServ > 0 {
  740. ls, _ := les.NewLesServer(fullNode, ethConf)
  741. fullNode.AddLesServer(ls)
  742. }
  743. return fullNode, err
  744. }); err != nil {
  745. Fatalf("Failed to register the Ethereum full node service: %v", err)
  746. }
  747. }
  748. }
  749. // RegisterShhService configures Whisper and adds it to the given node.
  750. func RegisterShhService(stack *node.Node) {
  751. if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  752. Fatalf("Failed to register the Whisper service: %v", err)
  753. }
  754. }
  755. // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  756. // th egiven node.
  757. func RegisterEthStatsService(stack *node.Node, url string) {
  758. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  759. // Retrieve both eth and les services
  760. var ethServ *eth.Ethereum
  761. ctx.Service(&ethServ)
  762. var lesServ *les.LightEthereum
  763. ctx.Service(&lesServ)
  764. return ethstats.New(url, ethServ, lesServ)
  765. }); err != nil {
  766. Fatalf("Failed to register the Ethereum Stats service: %v", err)
  767. }
  768. }
  769. // SetupNetwork configures the system for either the main net or some test network.
  770. func SetupNetwork(ctx *cli.Context) {
  771. switch {
  772. case ctx.GlobalBool(OlympicFlag.Name):
  773. params.DurationLimit = big.NewInt(8)
  774. params.GenesisGasLimit = big.NewInt(3141592)
  775. params.MinGasLimit = big.NewInt(125000)
  776. params.MaximumExtraDataSize = big.NewInt(1024)
  777. NetworkIdFlag.Value = 0
  778. core.BlockReward = big.NewInt(1.5e+18)
  779. core.ExpDiffPeriod = big.NewInt(math.MaxInt64)
  780. }
  781. params.TargetGasLimit = common.String2Big(ctx.GlobalString(TargetGasLimitFlag.Name))
  782. }
  783. // MakeChainConfig reads the chain configuration from the database in ctx.Datadir.
  784. func MakeChainConfig(ctx *cli.Context, stack *node.Node) *params.ChainConfig {
  785. db := MakeChainDatabase(ctx, stack)
  786. defer db.Close()
  787. return MakeChainConfigFromDb(ctx, db)
  788. }
  789. // MakeChainConfigFromDb reads the chain configuration from the given database.
  790. func MakeChainConfigFromDb(ctx *cli.Context, db ethdb.Database) *params.ChainConfig {
  791. // If the chain is already initialized, use any existing chain configs
  792. config := new(params.ChainConfig)
  793. genesis := core.GetBlock(db, core.GetCanonicalHash(db, 0), 0)
  794. if genesis != nil {
  795. storedConfig, err := core.GetChainConfig(db, genesis.Hash())
  796. switch err {
  797. case nil:
  798. config = storedConfig
  799. case core.ChainConfigNotFoundErr:
  800. // No configs found, use empty, will populate below
  801. default:
  802. Fatalf("Could not make chain configuration: %v", err)
  803. }
  804. }
  805. // set chain id in case it's zero.
  806. if config.ChainId == nil {
  807. config.ChainId = new(big.Int)
  808. }
  809. // Check whether we are allowed to set default config params or not:
  810. // - If no genesis is set, we're running either mainnet or testnet (private nets use `geth init`)
  811. // - If a genesis is already set, ensure we have a configuration for it (mainnet or testnet)
  812. defaults := genesis == nil ||
  813. (genesis.Hash() == params.MainNetGenesisHash && !ctx.GlobalBool(TestNetFlag.Name)) ||
  814. (genesis.Hash() == params.TestNetGenesisHash && ctx.GlobalBool(TestNetFlag.Name))
  815. if defaults {
  816. if ctx.GlobalBool(TestNetFlag.Name) {
  817. config = params.TestnetChainConfig
  818. } else {
  819. // Homestead fork
  820. config.HomesteadBlock = params.MainNetHomesteadBlock
  821. // DAO fork
  822. config.DAOForkBlock = params.MainNetDAOForkBlock
  823. config.DAOForkSupport = true
  824. // DoS reprice fork
  825. config.EIP150Block = params.MainNetHomesteadGasRepriceBlock
  826. config.EIP150Hash = params.MainNetHomesteadGasRepriceHash
  827. // DoS state cleanup fork
  828. config.EIP155Block = params.MainNetSpuriousDragon
  829. config.EIP158Block = params.MainNetSpuriousDragon
  830. config.ChainId = params.MainNetChainID
  831. }
  832. }
  833. return config
  834. }
  835. func ChainDbName(ctx *cli.Context) string {
  836. if ctx.GlobalBool(LightModeFlag.Name) {
  837. return "lightchaindata"
  838. } else {
  839. return "chaindata"
  840. }
  841. }
  842. // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  843. func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  844. var (
  845. cache = ctx.GlobalInt(CacheFlag.Name)
  846. handles = MakeDatabaseHandles()
  847. name = ChainDbName(ctx)
  848. )
  849. chainDb, err := stack.OpenDatabase(name, cache, handles)
  850. if err != nil {
  851. Fatalf("Could not open database: %v", err)
  852. }
  853. return chainDb
  854. }
  855. // MakeChain creates a chain manager from set command line flags.
  856. func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  857. var err error
  858. chainDb = MakeChainDatabase(ctx, stack)
  859. if ctx.GlobalBool(OlympicFlag.Name) {
  860. _, err := core.WriteOlympicGenesisBlock(chainDb)
  861. if err != nil {
  862. glog.Fatalln(err)
  863. }
  864. }
  865. if ctx.GlobalBool(TestNetFlag.Name) {
  866. _, err := core.WriteTestNetGenesisBlock(chainDb)
  867. if err != nil {
  868. glog.Fatalln(err)
  869. }
  870. }
  871. chainConfig := MakeChainConfigFromDb(ctx, chainDb)
  872. pow := pow.PoW(core.FakePow{})
  873. if !ctx.GlobalBool(FakePoWFlag.Name) {
  874. pow = ethash.New()
  875. }
  876. chain, err = core.NewBlockChain(chainDb, chainConfig, pow, new(event.TypeMux))
  877. if err != nil {
  878. Fatalf("Could not start chainmanager: %v", err)
  879. }
  880. return chain, chainDb
  881. }
  882. // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  883. // scripts to preload before starting.
  884. func MakeConsolePreloads(ctx *cli.Context) []string {
  885. // Skip preloading if there's nothing to preload
  886. if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  887. return nil
  888. }
  889. // Otherwise resolve absolute paths and return them
  890. preloads := []string{}
  891. assets := ctx.GlobalString(JSpathFlag.Name)
  892. for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  893. preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  894. }
  895. return preloads
  896. }