flags.go 28 KB

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