flags.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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. "os"
  24. "path/filepath"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "github.com/codegangsta/cli"
  29. "github.com/ethereum/ethash"
  30. "github.com/ethereum/go-ethereum/accounts"
  31. "github.com/ethereum/go-ethereum/common"
  32. "github.com/ethereum/go-ethereum/core"
  33. "github.com/ethereum/go-ethereum/core/state"
  34. "github.com/ethereum/go-ethereum/core/vm"
  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/rpc"
  47. "github.com/ethereum/go-ethereum/whisper"
  48. )
  49. func init() {
  50. cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
  51. VERSION:
  52. {{.Version}}
  53. COMMANDS:
  54. {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  55. {{end}}{{if .Flags}}
  56. GLOBAL OPTIONS:
  57. {{range .Flags}}{{.}}
  58. {{end}}{{end}}
  59. `
  60. cli.CommandHelpTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...]
  61. {{if .Description}}{{.Description}}
  62. {{end}}{{if .Subcommands}}
  63. SUBCOMMANDS:
  64. {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  65. {{end}}{{end}}{{if .Flags}}
  66. OPTIONS:
  67. {{range .Flags}}{{.}}
  68. {{end}}{{end}}
  69. `
  70. }
  71. // NewApp creates an app with sane defaults.
  72. func NewApp(version, usage string) *cli.App {
  73. app := cli.NewApp()
  74. app.Name = filepath.Base(os.Args[0])
  75. app.Author = ""
  76. //app.Authors = nil
  77. app.Email = ""
  78. app.Version = version
  79. app.Usage = usage
  80. return app
  81. }
  82. // These are all the command line flags we support.
  83. // If you add to this list, please remember to include the
  84. // flag in the appropriate command definition.
  85. //
  86. // The flags are defined here so their names and help texts
  87. // are the same for all commands.
  88. var (
  89. // General settings
  90. DataDirFlag = DirectoryFlag{
  91. Name: "datadir",
  92. Usage: "Data directory for the databases and keystore",
  93. Value: DirectoryString{common.DefaultDataDir()},
  94. }
  95. NetworkIdFlag = cli.IntFlag{
  96. Name: "networkid",
  97. Usage: "Network identifier (integer, 0=Olympic, 1=Frontier, 2=Morden)",
  98. Value: eth.NetworkId,
  99. }
  100. OlympicFlag = cli.BoolFlag{
  101. Name: "olympic",
  102. Usage: "Olympic network: pre-configured pre-release test network",
  103. }
  104. TestNetFlag = cli.BoolFlag{
  105. Name: "testnet",
  106. Usage: "Morden network: pre-configured test network with modified starting nonces (replay protection)",
  107. }
  108. DevModeFlag = cli.BoolFlag{
  109. Name: "dev",
  110. Usage: "Developer mode: pre-configured private network with several debugging flags",
  111. }
  112. GenesisFileFlag = cli.StringFlag{
  113. Name: "genesis",
  114. Usage: "Insert/overwrite the genesis block (JSON format)",
  115. }
  116. IdentityFlag = cli.StringFlag{
  117. Name: "identity",
  118. Usage: "Custom node name",
  119. }
  120. NatspecEnabledFlag = cli.BoolFlag{
  121. Name: "natspec",
  122. Usage: "Enable NatSpec confirmation notice",
  123. }
  124. DocRootFlag = DirectoryFlag{
  125. Name: "docroot",
  126. Usage: "Document Root for HTTPClient file scheme",
  127. Value: DirectoryString{common.HomeDir()},
  128. }
  129. CacheFlag = cli.IntFlag{
  130. Name: "cache",
  131. Usage: "Megabytes of memory allocated to internal caching (min 16MB / database forced)",
  132. Value: 0,
  133. }
  134. BlockchainVersionFlag = cli.IntFlag{
  135. Name: "blockchainversion",
  136. Usage: "Blockchain version (integer)",
  137. Value: core.BlockChainVersion,
  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. // Miner settings
  148. // TODO: refactor CPU vs GPU mining flags
  149. MiningEnabledFlag = cli.BoolFlag{
  150. Name: "mine",
  151. Usage: "Enable mining",
  152. }
  153. MinerThreadsFlag = cli.IntFlag{
  154. Name: "minerthreads",
  155. Usage: "Number of CPU threads to use for mining",
  156. Value: runtime.NumCPU(),
  157. }
  158. MiningGPUFlag = cli.StringFlag{
  159. Name: "minergpus",
  160. Usage: "List of GPUs to use for mining (e.g. '0,1' will use the first two GPUs found)",
  161. }
  162. AutoDAGFlag = cli.BoolFlag{
  163. Name: "autodag",
  164. Usage: "Enable automatic DAG pregeneration",
  165. }
  166. EtherbaseFlag = cli.StringFlag{
  167. Name: "etherbase",
  168. Usage: "Public address for block mining rewards (default = first account created)",
  169. Value: "0",
  170. }
  171. GasPriceFlag = cli.StringFlag{
  172. Name: "gasprice",
  173. Usage: "Minimal gas price to accept for mining a transactions",
  174. Value: new(big.Int).Mul(big.NewInt(20), common.Shannon).String(),
  175. }
  176. ExtraDataFlag = cli.StringFlag{
  177. Name: "extradata",
  178. Usage: "Block extra data set by the miner (default = client version)",
  179. }
  180. // Account settings
  181. UnlockedAccountFlag = cli.StringFlag{
  182. Name: "unlock",
  183. Usage: "Comma separated list of accounts to unlock",
  184. Value: "",
  185. }
  186. PasswordFileFlag = cli.StringFlag{
  187. Name: "password",
  188. Usage: "Password file to use for non-inteactive password input",
  189. Value: "",
  190. }
  191. // vm flags
  192. VMDebugFlag = cli.BoolFlag{
  193. Name: "vmdebug",
  194. Usage: "Virtual Machine debug output",
  195. }
  196. VMForceJitFlag = cli.BoolFlag{
  197. Name: "forcejit",
  198. Usage: "Force the JIT VM to take precedence",
  199. }
  200. VMJitCacheFlag = cli.IntFlag{
  201. Name: "jitcache",
  202. Usage: "Amount of cached JIT VM programs",
  203. Value: 64,
  204. }
  205. VMEnableJitFlag = cli.BoolFlag{
  206. Name: "jitvm",
  207. Usage: "Enable the JIT VM",
  208. }
  209. // logging and debug settings
  210. MetricsEnabledFlag = cli.BoolFlag{
  211. Name: metrics.MetricsEnabledFlag,
  212. Usage: "Enable metrics collection and reporting",
  213. }
  214. // RPC settings
  215. RPCEnabledFlag = cli.BoolFlag{
  216. Name: "rpc",
  217. Usage: "Enable the HTTP-RPC server",
  218. }
  219. RPCListenAddrFlag = cli.StringFlag{
  220. Name: "rpcaddr",
  221. Usage: "HTTP-RPC server listening interface",
  222. Value: common.DefaultHTTPHost,
  223. }
  224. RPCPortFlag = cli.IntFlag{
  225. Name: "rpcport",
  226. Usage: "HTTP-RPC server listening port",
  227. Value: common.DefaultHTTPPort,
  228. }
  229. RPCCORSDomainFlag = cli.StringFlag{
  230. Name: "rpccorsdomain",
  231. Usage: "Domains from which to accept cross origin requests (browser enforced)",
  232. Value: "",
  233. }
  234. RPCApiFlag = cli.StringFlag{
  235. Name: "rpcapi",
  236. Usage: "API's offered over the HTTP-RPC interface",
  237. Value: rpc.DefaultHTTPApis,
  238. }
  239. IPCDisabledFlag = cli.BoolFlag{
  240. Name: "ipcdisable",
  241. Usage: "Disable the IPC-RPC server",
  242. }
  243. IPCApiFlag = cli.StringFlag{
  244. Name: "ipcapi",
  245. Usage: "API's offered over the IPC-RPC interface",
  246. Value: rpc.DefaultIPCApis,
  247. }
  248. IPCPathFlag = DirectoryFlag{
  249. Name: "ipcpath",
  250. Usage: "Filename for IPC socket/pipe within the datadir (explicit paths escape it)",
  251. Value: DirectoryString{common.DefaultIPCSocket},
  252. }
  253. WSEnabledFlag = cli.BoolFlag{
  254. Name: "ws",
  255. Usage: "Enable the WS-RPC server",
  256. }
  257. WSListenAddrFlag = cli.StringFlag{
  258. Name: "wsaddr",
  259. Usage: "WS-RPC server listening interface",
  260. Value: common.DefaultWSHost,
  261. }
  262. WSPortFlag = cli.IntFlag{
  263. Name: "wsport",
  264. Usage: "WS-RPC server listening port",
  265. Value: common.DefaultWSPort,
  266. }
  267. WSApiFlag = cli.StringFlag{
  268. Name: "wsapi",
  269. Usage: "API's offered over the WS-RPC interface",
  270. Value: rpc.DefaultHTTPApis,
  271. }
  272. WSAllowedDomainsFlag = cli.StringFlag{
  273. Name: "wsdomains",
  274. Usage: "Domains from which to accept websockets requests (can be spoofed)",
  275. Value: "",
  276. }
  277. ExecFlag = cli.StringFlag{
  278. Name: "exec",
  279. Usage: "Execute JavaScript statement (only in combination with console/attach)",
  280. }
  281. // Network Settings
  282. MaxPeersFlag = cli.IntFlag{
  283. Name: "maxpeers",
  284. Usage: "Maximum number of network peers (network disabled if set to 0)",
  285. Value: 25,
  286. }
  287. MaxPendingPeersFlag = cli.IntFlag{
  288. Name: "maxpendpeers",
  289. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  290. Value: 0,
  291. }
  292. ListenPortFlag = cli.IntFlag{
  293. Name: "port",
  294. Usage: "Network listening port",
  295. Value: 30303,
  296. }
  297. BootnodesFlag = cli.StringFlag{
  298. Name: "bootnodes",
  299. Usage: "Comma separated enode URLs for P2P discovery bootstrap",
  300. Value: "",
  301. }
  302. NodeKeyFileFlag = cli.StringFlag{
  303. Name: "nodekey",
  304. Usage: "P2P node key file",
  305. }
  306. NodeKeyHexFlag = cli.StringFlag{
  307. Name: "nodekeyhex",
  308. Usage: "P2P node key as hex (for testing)",
  309. }
  310. NATFlag = cli.StringFlag{
  311. Name: "nat",
  312. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  313. Value: "any",
  314. }
  315. NoDiscoverFlag = cli.BoolFlag{
  316. Name: "nodiscover",
  317. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  318. }
  319. WhisperEnabledFlag = cli.BoolFlag{
  320. Name: "shh",
  321. Usage: "Enable Whisper",
  322. }
  323. // ATM the url is left to the user and deployment to
  324. JSpathFlag = cli.StringFlag{
  325. Name: "jspath",
  326. Usage: "JavaScript root path for `loadScript` and document root for `admin.httpGet`",
  327. Value: ".",
  328. }
  329. SolcPathFlag = cli.StringFlag{
  330. Name: "solc",
  331. Usage: "Solidity compiler command to be used",
  332. Value: "solc",
  333. }
  334. // Gas price oracle settings
  335. GpoMinGasPriceFlag = cli.StringFlag{
  336. Name: "gpomin",
  337. Usage: "Minimum suggested gas price",
  338. Value: new(big.Int).Mul(big.NewInt(20), common.Shannon).String(),
  339. }
  340. GpoMaxGasPriceFlag = cli.StringFlag{
  341. Name: "gpomax",
  342. Usage: "Maximum suggested gas price",
  343. Value: new(big.Int).Mul(big.NewInt(500), common.Shannon).String(),
  344. }
  345. GpoFullBlockRatioFlag = cli.IntFlag{
  346. Name: "gpofull",
  347. Usage: "Full block threshold for gas price calculation (%)",
  348. Value: 80,
  349. }
  350. GpobaseStepDownFlag = cli.IntFlag{
  351. Name: "gpobasedown",
  352. Usage: "Suggested gas price base step down ratio (1/1000)",
  353. Value: 10,
  354. }
  355. GpobaseStepUpFlag = cli.IntFlag{
  356. Name: "gpobaseup",
  357. Usage: "Suggested gas price base step up ratio (1/1000)",
  358. Value: 100,
  359. }
  360. GpobaseCorrectionFactorFlag = cli.IntFlag{
  361. Name: "gpobasecf",
  362. Usage: "Suggested gas price base correction factor (%)",
  363. Value: 110,
  364. }
  365. )
  366. // MustMakeDataDir retrieves the currently requested data directory, terminating
  367. // if none (or the empty string) is specified. If the node is starting a testnet,
  368. // the a subdirectory of the specified datadir will be used.
  369. func MustMakeDataDir(ctx *cli.Context) string {
  370. if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
  371. if ctx.GlobalBool(TestNetFlag.Name) {
  372. return filepath.Join(path, "/testnet")
  373. }
  374. return path
  375. }
  376. Fatalf("Cannot determine default data directory, please set manually (--datadir)")
  377. return ""
  378. }
  379. // MakeIPCPath creates an IPC path configuration from the set command line flags,
  380. // returning an empty string if IPC was explicitly disabled, or the set path.
  381. func MakeIPCPath(ctx *cli.Context) string {
  382. if ctx.GlobalBool(IPCDisabledFlag.Name) {
  383. return ""
  384. }
  385. return ctx.GlobalString(IPCPathFlag.Name)
  386. }
  387. // MakeNodeKey creates a node key from set command line flags, either loading it
  388. // from a file or as a specified hex value. If neither flags were provided, this
  389. // method returns nil and an emphemeral key is to be generated.
  390. func MakeNodeKey(ctx *cli.Context) *ecdsa.PrivateKey {
  391. var (
  392. hex = ctx.GlobalString(NodeKeyHexFlag.Name)
  393. file = ctx.GlobalString(NodeKeyFileFlag.Name)
  394. key *ecdsa.PrivateKey
  395. err error
  396. )
  397. switch {
  398. case file != "" && hex != "":
  399. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  400. case file != "":
  401. if key, err = crypto.LoadECDSA(file); err != nil {
  402. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  403. }
  404. case hex != "":
  405. if key, err = crypto.HexToECDSA(hex); err != nil {
  406. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  407. }
  408. }
  409. return key
  410. }
  411. // MakeNodeName creates a node name from a base set and the command line flags.
  412. func MakeNodeName(client, version string, ctx *cli.Context) string {
  413. name := common.MakeName(client, version)
  414. if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
  415. name += "/" + identity
  416. }
  417. if ctx.GlobalBool(VMEnableJitFlag.Name) {
  418. name += "/JIT"
  419. }
  420. return name
  421. }
  422. // MakeBootstrapNodes creates a list of bootstrap nodes from the command line
  423. // flags, reverting to pre-configured ones if none have been specified.
  424. func MakeBootstrapNodes(ctx *cli.Context) []*discover.Node {
  425. // Return pre-configured nodes if none were manually requested
  426. if !ctx.GlobalIsSet(BootnodesFlag.Name) {
  427. if ctx.GlobalBool(TestNetFlag.Name) {
  428. return TestNetBootNodes
  429. }
  430. return FrontierBootNodes
  431. }
  432. // Otherwise parse and use the CLI bootstrap nodes
  433. bootnodes := []*discover.Node{}
  434. for _, url := range strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",") {
  435. node, err := discover.ParseNode(url)
  436. if err != nil {
  437. glog.V(logger.Error).Infof("Bootstrap URL %s: %v\n", url, err)
  438. continue
  439. }
  440. bootnodes = append(bootnodes, node)
  441. }
  442. return bootnodes
  443. }
  444. // MakeListenAddress creates a TCP listening address string from set command
  445. // line flags.
  446. func MakeListenAddress(ctx *cli.Context) string {
  447. return fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
  448. }
  449. // MakeNAT creates a port mapper from set command line flags.
  450. func MakeNAT(ctx *cli.Context) nat.Interface {
  451. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  452. if err != nil {
  453. Fatalf("Option %s: %v", NATFlag.Name, err)
  454. }
  455. return natif
  456. }
  457. // MakeHTTPRpcHost creates the HTTP RPC listener interface string from the set
  458. // command line flags, returning empty if the HTTP endpoint is disabled.
  459. func MakeHTTPRpcHost(ctx *cli.Context) string {
  460. if !ctx.GlobalBool(RPCEnabledFlag.Name) {
  461. return ""
  462. }
  463. return ctx.GlobalString(RPCListenAddrFlag.Name)
  464. }
  465. // MakeWSRpcHost creates the WebSocket RPC listener interface string from the set
  466. // command line flags, returning empty if the HTTP endpoint is disabled.
  467. func MakeWSRpcHost(ctx *cli.Context) string {
  468. if !ctx.GlobalBool(WSEnabledFlag.Name) {
  469. return ""
  470. }
  471. return ctx.GlobalString(WSListenAddrFlag.Name)
  472. }
  473. // MakeGenesisBlock loads up a genesis block from an input file specified in the
  474. // command line, or returns the empty string if none set.
  475. func MakeGenesisBlock(ctx *cli.Context) string {
  476. genesis := ctx.GlobalString(GenesisFileFlag.Name)
  477. if genesis == "" {
  478. return ""
  479. }
  480. data, err := ioutil.ReadFile(genesis)
  481. if err != nil {
  482. Fatalf("Failed to load custom genesis file: %v", err)
  483. }
  484. return string(data)
  485. }
  486. // MakeAccountManager creates an account manager from set command line flags.
  487. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  488. // Create the keystore crypto primitive, light if requested
  489. scryptN := crypto.StandardScryptN
  490. scryptP := crypto.StandardScryptP
  491. if ctx.GlobalBool(LightKDFFlag.Name) {
  492. scryptN = crypto.LightScryptN
  493. scryptP = crypto.LightScryptP
  494. }
  495. // Assemble an account manager using the configured datadir
  496. var (
  497. datadir = MustMakeDataDir(ctx)
  498. keystore = crypto.NewKeyStorePassphrase(filepath.Join(datadir, "keystore"), scryptN, scryptP)
  499. )
  500. return accounts.NewManager(keystore)
  501. }
  502. // MakeAddress converts an account specified directly as a hex encoded string or
  503. // a key index in the key store to an internal account representation.
  504. func MakeAddress(accman *accounts.Manager, account string) (a common.Address, err error) {
  505. // If the specified account is a valid address, return it
  506. if common.IsHexAddress(account) {
  507. return common.HexToAddress(account), nil
  508. }
  509. // Otherwise try to interpret the account as a keystore index
  510. index, err := strconv.Atoi(account)
  511. if err != nil {
  512. return a, fmt.Errorf("invalid account address or index %q", account)
  513. }
  514. hex, err := accman.AddressByIndex(index)
  515. if err != nil {
  516. return a, fmt.Errorf("can't get account #%d (%v)", index, err)
  517. }
  518. return common.HexToAddress(hex), nil
  519. }
  520. // MakeEtherbase retrieves the etherbase either from the directly specified
  521. // command line flags or from the keystore if CLI indexed.
  522. func MakeEtherbase(accman *accounts.Manager, ctx *cli.Context) common.Address {
  523. accounts, _ := accman.Accounts()
  524. if !ctx.GlobalIsSet(EtherbaseFlag.Name) && len(accounts) == 0 {
  525. glog.V(logger.Error).Infoln("WARNING: No etherbase set and no accounts found as default")
  526. return common.Address{}
  527. }
  528. etherbase := ctx.GlobalString(EtherbaseFlag.Name)
  529. if etherbase == "" {
  530. return common.Address{}
  531. }
  532. // If the specified etherbase is a valid address, return it
  533. addr, err := MakeAddress(accman, etherbase)
  534. if err != nil {
  535. Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
  536. }
  537. return addr
  538. }
  539. // MakeMinerExtra resolves extradata for the miner from the set command line flags
  540. // or returns a default one composed on the client, runtime and OS metadata.
  541. func MakeMinerExtra(extra []byte, ctx *cli.Context) []byte {
  542. if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  543. return []byte(ctx.GlobalString(ExtraDataFlag.Name))
  544. }
  545. return extra
  546. }
  547. // MakePasswordList loads up a list of password from a file specified by the
  548. // command line flags.
  549. func MakePasswordList(ctx *cli.Context) []string {
  550. if path := ctx.GlobalString(PasswordFileFlag.Name); path != "" {
  551. blob, err := ioutil.ReadFile(path)
  552. if err != nil {
  553. Fatalf("Failed to read password file: %v", err)
  554. }
  555. return strings.Split(string(blob), "\n")
  556. }
  557. return nil
  558. }
  559. // MakeSystemNode sets up a local node, configures the services to launch and
  560. // assembles the P2P protocol stack.
  561. func MakeSystemNode(name, version string, extra []byte, ctx *cli.Context) *node.Node {
  562. // Avoid conflicting network flags
  563. networks, netFlags := 0, []cli.BoolFlag{DevModeFlag, TestNetFlag, OlympicFlag}
  564. for _, flag := range netFlags {
  565. if ctx.GlobalBool(flag.Name) {
  566. networks++
  567. }
  568. }
  569. if networks > 1 {
  570. Fatalf("The %v flags are mutually exclusive", netFlags)
  571. }
  572. // Configure the node's service container
  573. stackConf := &node.Config{
  574. DataDir: MustMakeDataDir(ctx),
  575. PrivateKey: MakeNodeKey(ctx),
  576. Name: MakeNodeName(name, version, ctx),
  577. NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name),
  578. BootstrapNodes: MakeBootstrapNodes(ctx),
  579. ListenAddr: MakeListenAddress(ctx),
  580. NAT: MakeNAT(ctx),
  581. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  582. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  583. IPCPath: MakeIPCPath(ctx),
  584. HTTPHost: MakeHTTPRpcHost(ctx),
  585. HTTPPort: ctx.GlobalInt(RPCPortFlag.Name),
  586. HTTPCors: ctx.GlobalString(RPCCORSDomainFlag.Name),
  587. HTTPModules: strings.Split(ctx.GlobalString(RPCApiFlag.Name), ","),
  588. WSHost: MakeWSRpcHost(ctx),
  589. WSPort: ctx.GlobalInt(WSPortFlag.Name),
  590. WSDomains: ctx.GlobalString(WSAllowedDomainsFlag.Name),
  591. WSModules: strings.Split(ctx.GlobalString(WSApiFlag.Name), ","),
  592. }
  593. // Configure the Ethereum service
  594. accman := MakeAccountManager(ctx)
  595. ethConf := &eth.Config{
  596. Genesis: MakeGenesisBlock(ctx),
  597. FastSync: ctx.GlobalBool(FastSyncFlag.Name),
  598. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  599. DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
  600. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  601. AccountManager: accman,
  602. Etherbase: MakeEtherbase(accman, ctx),
  603. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  604. ExtraData: MakeMinerExtra(extra, ctx),
  605. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  606. DocRoot: ctx.GlobalString(DocRootFlag.Name),
  607. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  608. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  609. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  610. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  611. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  612. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  613. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  614. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  615. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  616. }
  617. // Configure the Whisper service
  618. shhEnable := ctx.GlobalBool(WhisperEnabledFlag.Name)
  619. // Override any default configs in dev mode or the test net
  620. switch {
  621. case ctx.GlobalBool(OlympicFlag.Name):
  622. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  623. ethConf.NetworkId = 1
  624. }
  625. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  626. ethConf.Genesis = core.OlympicGenesisBlock()
  627. }
  628. case ctx.GlobalBool(TestNetFlag.Name):
  629. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  630. ethConf.NetworkId = 2
  631. }
  632. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  633. ethConf.Genesis = core.TestNetGenesisBlock()
  634. }
  635. state.StartingNonce = 1048576 // (2**20)
  636. case ctx.GlobalBool(DevModeFlag.Name):
  637. // Override the base network stack configs
  638. if !ctx.GlobalIsSet(DataDirFlag.Name) {
  639. stackConf.DataDir = filepath.Join(os.TempDir(), "/ethereum_dev_mode")
  640. }
  641. if !ctx.GlobalIsSet(MaxPeersFlag.Name) {
  642. stackConf.MaxPeers = 0
  643. }
  644. if !ctx.GlobalIsSet(ListenPortFlag.Name) {
  645. stackConf.ListenAddr = ":0"
  646. }
  647. // Override the Ethereum protocol configs
  648. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  649. ethConf.Genesis = core.OlympicGenesisBlock()
  650. }
  651. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  652. ethConf.GasPrice = new(big.Int)
  653. }
  654. if !ctx.GlobalIsSet(WhisperEnabledFlag.Name) {
  655. shhEnable = true
  656. }
  657. if !ctx.GlobalIsSet(VMDebugFlag.Name) {
  658. vm.Debug = true
  659. }
  660. ethConf.PowTest = true
  661. }
  662. // Assemble and return the protocol stack
  663. stack, err := node.New(stackConf)
  664. if err != nil {
  665. Fatalf("Failed to create the protocol stack: %v", err)
  666. }
  667. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  668. return eth.New(ctx, ethConf)
  669. }); err != nil {
  670. Fatalf("Failed to register the Ethereum service: %v", err)
  671. }
  672. if shhEnable {
  673. if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  674. Fatalf("Failed to register the Whisper service: %v", err)
  675. }
  676. }
  677. return stack
  678. }
  679. // SetupNetwork configures the system for either the main net or some test network.
  680. func SetupNetwork(ctx *cli.Context) {
  681. switch {
  682. case ctx.GlobalBool(OlympicFlag.Name):
  683. params.DurationLimit = big.NewInt(8)
  684. params.GenesisGasLimit = big.NewInt(3141592)
  685. params.MinGasLimit = big.NewInt(125000)
  686. params.MaximumExtraDataSize = big.NewInt(1024)
  687. NetworkIdFlag.Value = 0
  688. core.BlockReward = big.NewInt(1.5e+18)
  689. core.ExpDiffPeriod = big.NewInt(math.MaxInt64)
  690. }
  691. }
  692. // SetupVM configured the VM package's global settings
  693. func SetupVM(ctx *cli.Context) {
  694. vm.EnableJit = ctx.GlobalBool(VMEnableJitFlag.Name)
  695. vm.ForceJit = ctx.GlobalBool(VMForceJitFlag.Name)
  696. vm.SetJITCacheSize(ctx.GlobalInt(VMJitCacheFlag.Name))
  697. if ctx.GlobalIsSet(VMDebugFlag.Name) {
  698. vm.Debug = ctx.GlobalBool(VMDebugFlag.Name)
  699. }
  700. }
  701. // MakeChain creates a chain manager from set command line flags.
  702. func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database) {
  703. datadir := MustMakeDataDir(ctx)
  704. cache := ctx.GlobalInt(CacheFlag.Name)
  705. var err error
  706. if chainDb, err = ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache); err != nil {
  707. Fatalf("Could not open database: %v", err)
  708. }
  709. if ctx.GlobalBool(OlympicFlag.Name) {
  710. _, err := core.WriteTestNetGenesisBlock(chainDb)
  711. if err != nil {
  712. glog.Fatalln(err)
  713. }
  714. }
  715. eventMux := new(event.TypeMux)
  716. pow := ethash.New()
  717. //genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  718. chain, err = core.NewBlockChain(chainDb, pow, eventMux)
  719. if err != nil {
  720. Fatalf("Could not start chainmanager: %v", err)
  721. }
  722. return chain, chainDb
  723. }