flags.go 30 KB

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