flags.go 27 KB

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