flags.go 31 KB

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