flags.go 29 KB

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