flags.go 27 KB

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