flags.go 30 KB

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