flags.go 25 KB

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