flags.go 26 KB

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