flags.go 30 KB

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