flags.go 28 KB

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