flags.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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) (a common.Address, err error) {
  494. // If the specified account is a valid address, return it
  495. if common.IsHexAddress(account) {
  496. return common.HexToAddress(account), nil
  497. }
  498. // Otherwise try to interpret the account as a keystore index
  499. index, err := strconv.Atoi(account)
  500. if err != nil {
  501. return a, fmt.Errorf("invalid account address or index %q", account)
  502. }
  503. hex, err := accman.AddressByIndex(index)
  504. if err != nil {
  505. return a, fmt.Errorf("can't get account #%d (%v)", index, err)
  506. }
  507. return common.HexToAddress(hex), nil
  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. accounts, _ := accman.Accounts()
  513. if !ctx.GlobalIsSet(EtherbaseFlag.Name) && len(accounts) == 0 {
  514. glog.V(logger.Error).Infoln("WARNING: No etherbase set and no accounts found as default")
  515. return common.Address{}
  516. }
  517. etherbase := ctx.GlobalString(EtherbaseFlag.Name)
  518. if etherbase == "" {
  519. return common.Address{}
  520. }
  521. // If the specified etherbase is a valid address, return it
  522. addr, err := MakeAddress(accman, etherbase)
  523. if err != nil {
  524. Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
  525. }
  526. return addr
  527. }
  528. // MakeMinerExtra resolves extradata for the miner from the set command line flags
  529. // or returns a default one composed on the client, runtime and OS metadata.
  530. func MakeMinerExtra(extra []byte, ctx *cli.Context) []byte {
  531. if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  532. return []byte(ctx.GlobalString(ExtraDataFlag.Name))
  533. }
  534. return extra
  535. }
  536. // MakePasswordList loads up a list of password from a file specified by the
  537. // command line flags.
  538. func MakePasswordList(ctx *cli.Context) []string {
  539. if path := ctx.GlobalString(PasswordFileFlag.Name); path != "" {
  540. blob, err := ioutil.ReadFile(path)
  541. if err != nil {
  542. Fatalf("Failed to read password file: %v", err)
  543. }
  544. return strings.Split(string(blob), "\n")
  545. }
  546. return nil
  547. }
  548. // MakeSystemNode sets up a local node, configures the services to launch and
  549. // assembles the P2P protocol stack.
  550. func MakeSystemNode(name, version string, extra []byte, ctx *cli.Context) *node.Node {
  551. // Avoid conflicting network flags
  552. networks, netFlags := 0, []cli.BoolFlag{DevModeFlag, TestNetFlag, OlympicFlag}
  553. for _, flag := range netFlags {
  554. if ctx.GlobalBool(flag.Name) {
  555. networks++
  556. }
  557. }
  558. if networks > 1 {
  559. Fatalf("The %v flags are mutually exclusive", netFlags)
  560. }
  561. // Configure the node's service container
  562. stackConf := &node.Config{
  563. DataDir: MustMakeDataDir(ctx),
  564. PrivateKey: MakeNodeKey(ctx),
  565. Name: MakeNodeName(name, version, ctx),
  566. NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name),
  567. BootstrapNodes: MakeBootstrapNodes(ctx),
  568. ListenAddr: MakeListenAddress(ctx),
  569. NAT: MakeNAT(ctx),
  570. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  571. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  572. }
  573. // Configure the Ethereum service
  574. accman := MakeAccountManager(ctx)
  575. ethConf := &eth.Config{
  576. Genesis: MakeGenesisBlock(ctx),
  577. FastSync: ctx.GlobalBool(FastSyncFlag.Name),
  578. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  579. DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
  580. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  581. AccountManager: accman,
  582. Etherbase: MakeEtherbase(accman, ctx),
  583. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  584. ExtraData: MakeMinerExtra(extra, ctx),
  585. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  586. DocRoot: ctx.GlobalString(DocRootFlag.Name),
  587. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  588. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  589. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  590. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  591. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  592. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  593. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  594. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  595. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  596. }
  597. // Configure the Whisper service
  598. shhEnable := ctx.GlobalBool(WhisperEnabledFlag.Name)
  599. // Override any default configs in dev mode or the test net
  600. switch {
  601. case ctx.GlobalBool(OlympicFlag.Name):
  602. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  603. ethConf.NetworkId = 1
  604. }
  605. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  606. ethConf.Genesis = core.OlympicGenesisBlock()
  607. }
  608. case ctx.GlobalBool(TestNetFlag.Name):
  609. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  610. ethConf.NetworkId = 2
  611. }
  612. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  613. ethConf.Genesis = core.TestNetGenesisBlock()
  614. }
  615. state.StartingNonce = 1048576 // (2**20)
  616. case ctx.GlobalBool(DevModeFlag.Name):
  617. // Override the base network stack configs
  618. if !ctx.GlobalIsSet(DataDirFlag.Name) {
  619. stackConf.DataDir = filepath.Join(os.TempDir(), "/ethereum_dev_mode")
  620. }
  621. if !ctx.GlobalIsSet(MaxPeersFlag.Name) {
  622. stackConf.MaxPeers = 0
  623. }
  624. if !ctx.GlobalIsSet(ListenPortFlag.Name) {
  625. stackConf.ListenAddr = ":0"
  626. }
  627. // Override the Ethereum protocol configs
  628. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  629. ethConf.Genesis = core.OlympicGenesisBlock()
  630. }
  631. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  632. ethConf.GasPrice = new(big.Int)
  633. }
  634. if !ctx.GlobalIsSet(WhisperEnabledFlag.Name) {
  635. shhEnable = true
  636. }
  637. if !ctx.GlobalIsSet(VMDebugFlag.Name) {
  638. vm.Debug = true
  639. }
  640. ethConf.PowTest = true
  641. }
  642. // Assemble and return the protocol stack
  643. stack, err := node.New(stackConf)
  644. if err != nil {
  645. Fatalf("Failed to create the protocol stack: %v", err)
  646. }
  647. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  648. return eth.New(ctx, ethConf)
  649. }); err != nil {
  650. Fatalf("Failed to register the Ethereum service: %v", err)
  651. }
  652. if shhEnable {
  653. if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  654. Fatalf("Failed to register the Whisper service: %v", err)
  655. }
  656. }
  657. return stack
  658. }
  659. // SetupLogger configures glog from the logging-related command line flags.
  660. func SetupLogger(ctx *cli.Context) {
  661. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  662. glog.CopyStandardLogTo("INFO")
  663. glog.SetToStderr(true)
  664. if ctx.GlobalIsSet(LogFileFlag.Name) {
  665. logger.New("", ctx.GlobalString(LogFileFlag.Name), ctx.GlobalInt(VerbosityFlag.Name))
  666. }
  667. if ctx.GlobalIsSet(VMDebugFlag.Name) {
  668. vm.Debug = ctx.GlobalBool(VMDebugFlag.Name)
  669. }
  670. }
  671. // SetupNetwork configures the system for either the main net or some test network.
  672. func SetupNetwork(ctx *cli.Context) {
  673. switch {
  674. case ctx.GlobalBool(OlympicFlag.Name):
  675. params.DurationLimit = big.NewInt(8)
  676. params.GenesisGasLimit = big.NewInt(3141592)
  677. params.MinGasLimit = big.NewInt(125000)
  678. params.MaximumExtraDataSize = big.NewInt(1024)
  679. NetworkIdFlag.Value = 0
  680. core.BlockReward = big.NewInt(1.5e+18)
  681. core.ExpDiffPeriod = big.NewInt(math.MaxInt64)
  682. }
  683. }
  684. // SetupVM configured the VM package's global settings
  685. func SetupVM(ctx *cli.Context) {
  686. vm.EnableJit = ctx.GlobalBool(VMEnableJitFlag.Name)
  687. vm.ForceJit = ctx.GlobalBool(VMForceJitFlag.Name)
  688. vm.SetJITCacheSize(ctx.GlobalInt(VMJitCacheFlag.Name))
  689. }
  690. // MakeChain creates a chain manager from set command line flags.
  691. func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database) {
  692. datadir := MustMakeDataDir(ctx)
  693. cache := ctx.GlobalInt(CacheFlag.Name)
  694. var err error
  695. if chainDb, err = ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache); err != nil {
  696. Fatalf("Could not open database: %v", err)
  697. }
  698. if ctx.GlobalBool(OlympicFlag.Name) {
  699. _, err := core.WriteTestNetGenesisBlock(chainDb)
  700. if err != nil {
  701. glog.Fatalln(err)
  702. }
  703. }
  704. eventMux := new(event.TypeMux)
  705. pow := ethash.New()
  706. //genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  707. chain, err = core.NewBlockChain(chainDb, pow, eventMux)
  708. if err != nil {
  709. Fatalf("Could not start chainmanager: %v", err)
  710. }
  711. return chain, chainDb
  712. }
  713. func IpcSocketPath(ctx *cli.Context) (ipcpath string) {
  714. if runtime.GOOS == "windows" {
  715. ipcpath = common.DefaultIpcPath()
  716. if ctx.GlobalIsSet(IPCPathFlag.Name) {
  717. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  718. }
  719. } else {
  720. ipcpath = common.DefaultIpcPath()
  721. if ctx.GlobalIsSet(DataDirFlag.Name) {
  722. ipcpath = filepath.Join(ctx.GlobalString(DataDirFlag.Name), "geth.ipc")
  723. }
  724. if ctx.GlobalIsSet(IPCPathFlag.Name) {
  725. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  726. }
  727. }
  728. return
  729. }
  730. // StartIPC starts a IPC JSON-RPC API server.
  731. func StartIPC(stack *node.Node, ctx *cli.Context) error {
  732. config := comms.IpcConfig{
  733. Endpoint: IpcSocketPath(ctx),
  734. }
  735. initializer := func(conn net.Conn) (comms.Stopper, shared.EthereumApi, error) {
  736. var ethereum *eth.Ethereum
  737. if err := stack.Service(&ethereum); err != nil {
  738. return nil, nil, err
  739. }
  740. fe := useragent.NewRemoteFrontend(conn, ethereum.AccountManager())
  741. xeth := xeth.New(stack, fe)
  742. apis, err := api.ParseApiString(ctx.GlobalString(IPCApiFlag.Name), codec.JSON, xeth, stack)
  743. if err != nil {
  744. return nil, nil, err
  745. }
  746. return xeth, api.Merge(apis...), nil
  747. }
  748. return comms.StartIpc(config, codec.JSON, initializer)
  749. }
  750. // StartRPC starts a HTTP JSON-RPC API server.
  751. func StartRPC(stack *node.Node, ctx *cli.Context) error {
  752. config := comms.HttpConfig{
  753. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  754. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  755. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  756. }
  757. xeth := xeth.New(stack, nil)
  758. codec := codec.JSON
  759. apis, err := api.ParseApiString(ctx.GlobalString(RpcApiFlag.Name), codec, xeth, stack)
  760. if err != nil {
  761. return err
  762. }
  763. return comms.StartHttp(config, codec, api.Merge(apis...))
  764. }
  765. func StartPProf(ctx *cli.Context) {
  766. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  767. go func() {
  768. log.Println(http.ListenAndServe(address, nil))
  769. }()
  770. }