flags.go 28 KB

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