flags.go 25 KB

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