flags.go 31 KB

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