flags.go 27 KB

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