flags.go 28 KB

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