flags.go 30 KB

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