flags.go 24 KB

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