flags.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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.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. // Return pre-configured nodes if none were manually requested
  465. if !ctx.GlobalIsSet(BootnodesFlag.Name) {
  466. if ctx.GlobalBool(TestNetFlag.Name) {
  467. return params.TestnetBootnodes
  468. }
  469. return params.MainnetBootnodes
  470. }
  471. // Otherwise parse and use the CLI bootstrap nodes
  472. bootnodes := []*discover.Node{}
  473. for _, url := range strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",") {
  474. node, err := discover.ParseNode(url)
  475. if err != nil {
  476. glog.V(logger.Error).Infof("Bootstrap URL %s: %v\n", url, err)
  477. continue
  478. }
  479. bootnodes = append(bootnodes, node)
  480. }
  481. return bootnodes
  482. }
  483. // MakeBootstrapNodesV5 creates a list of bootstrap nodes from the command line
  484. // flags, reverting to pre-configured ones if none have been specified.
  485. func MakeBootstrapNodesV5(ctx *cli.Context) []*discv5.Node {
  486. // Return pre-configured nodes if none were manually requested
  487. if !ctx.GlobalIsSet(BootnodesFlag.Name) {
  488. return params.DiscoveryV5Bootnodes
  489. }
  490. // Otherwise parse and use the CLI bootstrap nodes
  491. bootnodes := []*discv5.Node{}
  492. for _, url := range strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",") {
  493. node, err := discv5.ParseNode(url)
  494. if err != nil {
  495. glog.V(logger.Error).Infof("Bootstrap URL %s: %v\n", url, err)
  496. continue
  497. }
  498. bootnodes = append(bootnodes, node)
  499. }
  500. return bootnodes
  501. }
  502. // MakeListenAddress creates a TCP listening address string from set command
  503. // line flags.
  504. func MakeListenAddress(ctx *cli.Context) string {
  505. return fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
  506. }
  507. // MakeDiscoveryV5Address creates a UDP listening address string from set command
  508. // line flags for the V5 discovery protocol.
  509. func MakeDiscoveryV5Address(ctx *cli.Context) string {
  510. return fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name)+1)
  511. }
  512. // MakeNAT creates a port mapper from set command line flags.
  513. func MakeNAT(ctx *cli.Context) nat.Interface {
  514. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  515. if err != nil {
  516. Fatalf("Option %s: %v", NATFlag.Name, err)
  517. }
  518. return natif
  519. }
  520. // MakeRPCModules splits input separated by a comma and trims excessive white
  521. // space from the substrings.
  522. func MakeRPCModules(input string) []string {
  523. result := strings.Split(input, ",")
  524. for i, r := range result {
  525. result[i] = strings.TrimSpace(r)
  526. }
  527. return result
  528. }
  529. // MakeHTTPRpcHost creates the HTTP RPC listener interface string from the set
  530. // command line flags, returning empty if the HTTP endpoint is disabled.
  531. func MakeHTTPRpcHost(ctx *cli.Context) string {
  532. if !ctx.GlobalBool(RPCEnabledFlag.Name) {
  533. return ""
  534. }
  535. return ctx.GlobalString(RPCListenAddrFlag.Name)
  536. }
  537. // MakeWSRpcHost creates the WebSocket RPC listener interface string from the set
  538. // command line flags, returning empty if the HTTP endpoint is disabled.
  539. func MakeWSRpcHost(ctx *cli.Context) string {
  540. if !ctx.GlobalBool(WSEnabledFlag.Name) {
  541. return ""
  542. }
  543. return ctx.GlobalString(WSListenAddrFlag.Name)
  544. }
  545. // MakeDatabaseHandles raises out the number of allowed file handles per process
  546. // for Geth and returns half of the allowance to assign to the database.
  547. func MakeDatabaseHandles() int {
  548. if err := raiseFdLimit(2048); err != nil {
  549. Fatalf("Failed to raise file descriptor allowance: %v", err)
  550. }
  551. limit, err := getFdLimit()
  552. if err != nil {
  553. Fatalf("Failed to retrieve file descriptor allowance: %v", err)
  554. }
  555. if limit > 2048 { // cap database file descriptors even if more is available
  556. limit = 2048
  557. }
  558. return limit / 2 // Leave half for networking and other stuff
  559. }
  560. // MakeAddress converts an account specified directly as a hex encoded string or
  561. // a key index in the key store to an internal account representation.
  562. func MakeAddress(accman *accounts.Manager, account string) (accounts.Account, error) {
  563. // If the specified account is a valid address, return it
  564. if common.IsHexAddress(account) {
  565. return accounts.Account{Address: common.HexToAddress(account)}, nil
  566. }
  567. // Otherwise try to interpret the account as a keystore index
  568. index, err := strconv.Atoi(account)
  569. if err != nil {
  570. return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account)
  571. }
  572. return accman.AccountByIndex(index)
  573. }
  574. // MakeEtherbase retrieves the etherbase either from the directly specified
  575. // command line flags or from the keystore if CLI indexed.
  576. func MakeEtherbase(accman *accounts.Manager, ctx *cli.Context) common.Address {
  577. accounts := accman.Accounts()
  578. if !ctx.GlobalIsSet(EtherbaseFlag.Name) && len(accounts) == 0 {
  579. glog.V(logger.Error).Infoln("WARNING: No etherbase set and no accounts found as default")
  580. return common.Address{}
  581. }
  582. etherbase := ctx.GlobalString(EtherbaseFlag.Name)
  583. if etherbase == "" {
  584. return common.Address{}
  585. }
  586. // If the specified etherbase is a valid address, return it
  587. account, err := MakeAddress(accman, etherbase)
  588. if err != nil {
  589. Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
  590. }
  591. return account.Address
  592. }
  593. // MakeMinerExtra resolves extradata for the miner from the set command line flags
  594. // or returns a default one composed on the client, runtime and OS metadata.
  595. func MakeMinerExtra(extra []byte, ctx *cli.Context) []byte {
  596. if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  597. return []byte(ctx.GlobalString(ExtraDataFlag.Name))
  598. }
  599. return extra
  600. }
  601. // MakePasswordList reads password lines from the file specified by --password.
  602. func MakePasswordList(ctx *cli.Context) []string {
  603. path := ctx.GlobalString(PasswordFileFlag.Name)
  604. if path == "" {
  605. return nil
  606. }
  607. text, err := ioutil.ReadFile(path)
  608. if err != nil {
  609. Fatalf("Failed to read password file: %v", err)
  610. }
  611. lines := strings.Split(string(text), "\n")
  612. // Sanitise DOS line endings.
  613. for i := range lines {
  614. lines[i] = strings.TrimRight(lines[i], "\r")
  615. }
  616. return lines
  617. }
  618. // MakeNode configures a node with no services from command line flags.
  619. func MakeNode(ctx *cli.Context, name, gitCommit string) *node.Node {
  620. vsn := params.Version
  621. if gitCommit != "" {
  622. vsn += "-" + gitCommit[:8]
  623. }
  624. config := &node.Config{
  625. DataDir: MakeDataDir(ctx),
  626. KeyStoreDir: ctx.GlobalString(KeyStoreDirFlag.Name),
  627. UseLightweightKDF: ctx.GlobalBool(LightKDFFlag.Name),
  628. PrivateKey: MakeNodeKey(ctx),
  629. Name: name,
  630. Version: vsn,
  631. UserIdent: makeNodeUserIdent(ctx),
  632. NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name) || ctx.GlobalBool(LightModeFlag.Name),
  633. DiscoveryV5: ctx.GlobalBool(DiscoveryV5Flag.Name) || ctx.GlobalBool(LightModeFlag.Name) || ctx.GlobalInt(LightServFlag.Name) > 0,
  634. DiscoveryV5Addr: MakeDiscoveryV5Address(ctx),
  635. BootstrapNodes: MakeBootstrapNodes(ctx),
  636. BootstrapNodesV5: MakeBootstrapNodesV5(ctx),
  637. ListenAddr: MakeListenAddress(ctx),
  638. NAT: MakeNAT(ctx),
  639. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  640. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  641. IPCPath: MakeIPCPath(ctx),
  642. HTTPHost: MakeHTTPRpcHost(ctx),
  643. HTTPPort: ctx.GlobalInt(RPCPortFlag.Name),
  644. HTTPCors: ctx.GlobalString(RPCCORSDomainFlag.Name),
  645. HTTPModules: MakeRPCModules(ctx.GlobalString(RPCApiFlag.Name)),
  646. WSHost: MakeWSRpcHost(ctx),
  647. WSPort: ctx.GlobalInt(WSPortFlag.Name),
  648. WSOrigins: ctx.GlobalString(WSAllowedOriginsFlag.Name),
  649. WSModules: MakeRPCModules(ctx.GlobalString(WSApiFlag.Name)),
  650. }
  651. if ctx.GlobalBool(DevModeFlag.Name) {
  652. if !ctx.GlobalIsSet(DataDirFlag.Name) {
  653. config.DataDir = filepath.Join(os.TempDir(), "/ethereum_dev_mode")
  654. }
  655. // --dev mode does not need p2p networking.
  656. config.MaxPeers = 0
  657. config.ListenAddr = ":0"
  658. }
  659. if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" {
  660. list, err := netutil.ParseNetlist(netrestrict)
  661. if err != nil {
  662. Fatalf("Option %q: %v", NetrestrictFlag.Name, err)
  663. }
  664. config.NetRestrict = list
  665. }
  666. stack, err := node.New(config)
  667. if err != nil {
  668. Fatalf("Failed to create the protocol stack: %v", err)
  669. }
  670. return stack
  671. }
  672. // RegisterEthService configures eth.Ethereum from command line flags and adds it to the
  673. // given node.
  674. func RegisterEthService(ctx *cli.Context, stack *node.Node, extra []byte) {
  675. // Avoid conflicting network flags
  676. networks, netFlags := 0, []cli.BoolFlag{DevModeFlag, TestNetFlag, OlympicFlag}
  677. for _, flag := range netFlags {
  678. if ctx.GlobalBool(flag.Name) {
  679. networks++
  680. }
  681. }
  682. if networks > 1 {
  683. Fatalf("The %v flags are mutually exclusive", netFlags)
  684. }
  685. ethConf := &eth.Config{
  686. Etherbase: MakeEtherbase(stack.AccountManager(), ctx),
  687. ChainConfig: MakeChainConfig(ctx, stack),
  688. FastSync: ctx.GlobalBool(FastSyncFlag.Name),
  689. LightMode: ctx.GlobalBool(LightModeFlag.Name),
  690. LightServ: ctx.GlobalInt(LightServFlag.Name),
  691. LightPeers: ctx.GlobalInt(LightPeersFlag.Name),
  692. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  693. DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
  694. DatabaseHandles: MakeDatabaseHandles(),
  695. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  696. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  697. ExtraData: MakeMinerExtra(extra, ctx),
  698. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  699. DocRoot: ctx.GlobalString(DocRootFlag.Name),
  700. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  701. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  702. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  703. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  704. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  705. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  706. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  707. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  708. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  709. }
  710. // Override any default configs in dev mode or the test net
  711. switch {
  712. case ctx.GlobalBool(OlympicFlag.Name):
  713. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  714. ethConf.NetworkId = 1
  715. }
  716. ethConf.Genesis = core.OlympicGenesisBlock()
  717. case ctx.GlobalBool(TestNetFlag.Name):
  718. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  719. ethConf.NetworkId = 3
  720. }
  721. ethConf.Genesis = core.DefaultTestnetGenesisBlock()
  722. case ctx.GlobalBool(DevModeFlag.Name):
  723. ethConf.Genesis = core.OlympicGenesisBlock()
  724. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  725. ethConf.GasPrice = new(big.Int)
  726. }
  727. ethConf.PowTest = true
  728. }
  729. // Override any global options pertaining to the Ethereum protocol
  730. if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  731. state.MaxTrieCacheGen = uint16(gen)
  732. }
  733. if ethConf.LightMode {
  734. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  735. return les.New(ctx, ethConf)
  736. }); err != nil {
  737. Fatalf("Failed to register the Ethereum light node service: %v", err)
  738. }
  739. } else {
  740. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  741. fullNode, err := eth.New(ctx, ethConf)
  742. if fullNode != nil && ethConf.LightServ > 0 {
  743. ls, _ := les.NewLesServer(fullNode, ethConf)
  744. fullNode.AddLesServer(ls)
  745. }
  746. return fullNode, err
  747. }); err != nil {
  748. Fatalf("Failed to register the Ethereum full node service: %v", err)
  749. }
  750. }
  751. }
  752. // RegisterShhService configures Whisper and adds it to the given node.
  753. func RegisterShhService(stack *node.Node) {
  754. if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  755. Fatalf("Failed to register the Whisper service: %v", err)
  756. }
  757. }
  758. // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  759. // th egiven node.
  760. func RegisterEthStatsService(stack *node.Node, url string) {
  761. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  762. // Retrieve both eth and les services
  763. var ethServ *eth.Ethereum
  764. ctx.Service(&ethServ)
  765. var lesServ *les.LightEthereum
  766. ctx.Service(&lesServ)
  767. return ethstats.New(url, ethServ, lesServ)
  768. }); err != nil {
  769. Fatalf("Failed to register the Ethereum Stats service: %v", err)
  770. }
  771. }
  772. // SetupNetwork configures the system for either the main net or some test network.
  773. func SetupNetwork(ctx *cli.Context) {
  774. switch {
  775. case ctx.GlobalBool(OlympicFlag.Name):
  776. params.DurationLimit = big.NewInt(8)
  777. params.GenesisGasLimit = big.NewInt(3141592)
  778. params.MinGasLimit = big.NewInt(125000)
  779. params.MaximumExtraDataSize = big.NewInt(1024)
  780. NetworkIdFlag.Value = 0
  781. core.BlockReward = big.NewInt(1.5e+18)
  782. core.ExpDiffPeriod = big.NewInt(math.MaxInt64)
  783. }
  784. params.TargetGasLimit = common.String2Big(ctx.GlobalString(TargetGasLimitFlag.Name))
  785. }
  786. // MakeChainConfig reads the chain configuration from the database in ctx.Datadir.
  787. func MakeChainConfig(ctx *cli.Context, stack *node.Node) *params.ChainConfig {
  788. db := MakeChainDatabase(ctx, stack)
  789. defer db.Close()
  790. return MakeChainConfigFromDb(ctx, db)
  791. }
  792. // MakeChainConfigFromDb reads the chain configuration from the given database.
  793. func MakeChainConfigFromDb(ctx *cli.Context, db ethdb.Database) *params.ChainConfig {
  794. // If the chain is already initialized, use any existing chain configs
  795. config := new(params.ChainConfig)
  796. genesis := core.GetBlock(db, core.GetCanonicalHash(db, 0), 0)
  797. if genesis != nil {
  798. storedConfig, err := core.GetChainConfig(db, genesis.Hash())
  799. switch err {
  800. case nil:
  801. config = storedConfig
  802. case core.ChainConfigNotFoundErr:
  803. // No configs found, use empty, will populate below
  804. default:
  805. Fatalf("Could not make chain configuration: %v", err)
  806. }
  807. }
  808. // set chain id in case it's zero.
  809. if config.ChainId == nil {
  810. config.ChainId = new(big.Int)
  811. }
  812. // Check whether we are allowed to set default config params or not:
  813. // - If no genesis is set, we're running either mainnet or testnet (private nets use `geth init`)
  814. // - If a genesis is already set, ensure we have a configuration for it (mainnet or testnet)
  815. defaults := genesis == nil ||
  816. (genesis.Hash() == params.MainNetGenesisHash && !ctx.GlobalBool(TestNetFlag.Name)) ||
  817. (genesis.Hash() == params.TestNetGenesisHash && ctx.GlobalBool(TestNetFlag.Name))
  818. if defaults {
  819. if ctx.GlobalBool(TestNetFlag.Name) {
  820. config = params.TestnetChainConfig
  821. } else {
  822. // Homestead fork
  823. config.HomesteadBlock = params.MainNetHomesteadBlock
  824. // DAO fork
  825. config.DAOForkBlock = params.MainNetDAOForkBlock
  826. config.DAOForkSupport = true
  827. // DoS reprice fork
  828. config.EIP150Block = params.MainNetHomesteadGasRepriceBlock
  829. config.EIP150Hash = params.MainNetHomesteadGasRepriceHash
  830. // DoS state cleanup fork
  831. config.EIP155Block = params.MainNetSpuriousDragon
  832. config.EIP158Block = params.MainNetSpuriousDragon
  833. config.ChainId = params.MainNetChainID
  834. }
  835. }
  836. return config
  837. }
  838. func ChainDbName(ctx *cli.Context) string {
  839. if ctx.GlobalBool(LightModeFlag.Name) {
  840. return "lightchaindata"
  841. } else {
  842. return "chaindata"
  843. }
  844. }
  845. // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  846. func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  847. var (
  848. cache = ctx.GlobalInt(CacheFlag.Name)
  849. handles = MakeDatabaseHandles()
  850. name = ChainDbName(ctx)
  851. )
  852. chainDb, err := stack.OpenDatabase(name, cache, handles)
  853. if err != nil {
  854. Fatalf("Could not open database: %v", err)
  855. }
  856. return chainDb
  857. }
  858. // MakeChain creates a chain manager from set command line flags.
  859. func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  860. var err error
  861. chainDb = MakeChainDatabase(ctx, stack)
  862. if ctx.GlobalBool(OlympicFlag.Name) {
  863. _, err := core.WriteTestNetGenesisBlock(chainDb)
  864. if err != nil {
  865. glog.Fatalln(err)
  866. }
  867. }
  868. chainConfig := MakeChainConfigFromDb(ctx, chainDb)
  869. pow := pow.PoW(core.FakePow{})
  870. if !ctx.GlobalBool(FakePoWFlag.Name) {
  871. pow = ethash.New()
  872. }
  873. chain, err = core.NewBlockChain(chainDb, chainConfig, pow, new(event.TypeMux))
  874. if err != nil {
  875. Fatalf("Could not start chainmanager: %v", err)
  876. }
  877. return chain, chainDb
  878. }
  879. // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  880. // scripts to preload before starting.
  881. func MakeConsolePreloads(ctx *cli.Context) []string {
  882. // Skip preloading if there's nothing to preload
  883. if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  884. return nil
  885. }
  886. // Otherwise resolve absolute paths and return them
  887. preloads := []string{}
  888. assets := ctx.GlobalString(JSpathFlag.Name)
  889. for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  890. preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  891. }
  892. return preloads
  893. }