flags.go 27 KB

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