flags.go 26 KB

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