flags.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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 contains internal helper functions for go-ethereum commands.
  17. package utils
  18. import (
  19. "crypto/ecdsa"
  20. "fmt"
  21. "io/ioutil"
  22. "math/big"
  23. "os"
  24. "path/filepath"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "github.com/ethereum/go-ethereum/accounts"
  29. "github.com/ethereum/go-ethereum/accounts/keystore"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/consensus/ethash"
  32. "github.com/ethereum/go-ethereum/core"
  33. "github.com/ethereum/go-ethereum/core/state"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/crypto"
  36. "github.com/ethereum/go-ethereum/eth"
  37. "github.com/ethereum/go-ethereum/eth/downloader"
  38. "github.com/ethereum/go-ethereum/eth/gasprice"
  39. "github.com/ethereum/go-ethereum/ethdb"
  40. "github.com/ethereum/go-ethereum/ethstats"
  41. "github.com/ethereum/go-ethereum/event"
  42. "github.com/ethereum/go-ethereum/les"
  43. "github.com/ethereum/go-ethereum/log"
  44. "github.com/ethereum/go-ethereum/metrics"
  45. "github.com/ethereum/go-ethereum/node"
  46. "github.com/ethereum/go-ethereum/p2p"
  47. "github.com/ethereum/go-ethereum/p2p/discover"
  48. "github.com/ethereum/go-ethereum/p2p/discv5"
  49. "github.com/ethereum/go-ethereum/p2p/nat"
  50. "github.com/ethereum/go-ethereum/p2p/netutil"
  51. "github.com/ethereum/go-ethereum/params"
  52. whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
  53. "gopkg.in/urfave/cli.v1"
  54. )
  55. func init() {
  56. cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
  57. VERSION:
  58. {{.Version}}
  59. COMMANDS:
  60. {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  61. {{end}}{{if .Flags}}
  62. GLOBAL OPTIONS:
  63. {{range .Flags}}{{.}}
  64. {{end}}{{end}}
  65. `
  66. cli.CommandHelpTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...]
  67. {{if .Description}}{{.Description}}
  68. {{end}}{{if .Subcommands}}
  69. SUBCOMMANDS:
  70. {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  71. {{end}}{{end}}{{if .Flags}}
  72. OPTIONS:
  73. {{range .Flags}}{{.}}
  74. {{end}}{{end}}
  75. `
  76. }
  77. // NewApp creates an app with sane defaults.
  78. func NewApp(gitCommit, usage string) *cli.App {
  79. app := cli.NewApp()
  80. app.Name = filepath.Base(os.Args[0])
  81. app.Author = ""
  82. //app.Authors = nil
  83. app.Email = ""
  84. app.Version = params.Version
  85. if gitCommit != "" {
  86. app.Version += "-" + gitCommit[:8]
  87. }
  88. app.Usage = usage
  89. return app
  90. }
  91. // These are all the command line flags we support.
  92. // If you add to this list, please remember to include the
  93. // flag in the appropriate command definition.
  94. //
  95. // The flags are defined here so their names and help texts
  96. // are the same for all commands.
  97. var (
  98. // General settings
  99. DataDirFlag = DirectoryFlag{
  100. Name: "datadir",
  101. Usage: "Data directory for the databases and keystore",
  102. Value: DirectoryString{node.DefaultDataDir()},
  103. }
  104. KeyStoreDirFlag = DirectoryFlag{
  105. Name: "keystore",
  106. Usage: "Directory for the keystore (default = inside the datadir)",
  107. }
  108. NoUSBFlag = cli.BoolFlag{
  109. Name: "nousb",
  110. Usage: "Disables monitoring for and managine USB hardware wallets",
  111. }
  112. EthashCacheDirFlag = DirectoryFlag{
  113. Name: "ethash.cachedir",
  114. Usage: "Directory to store the ethash verification caches (default = inside the datadir)",
  115. }
  116. EthashCachesInMemoryFlag = cli.IntFlag{
  117. Name: "ethash.cachesinmem",
  118. Usage: "Number of recent ethash caches to keep in memory (16MB each)",
  119. Value: eth.DefaultConfig.EthashCachesInMem,
  120. }
  121. EthashCachesOnDiskFlag = cli.IntFlag{
  122. Name: "ethash.cachesondisk",
  123. Usage: "Number of recent ethash caches to keep on disk (16MB each)",
  124. Value: eth.DefaultConfig.EthashCachesOnDisk,
  125. }
  126. EthashDatasetDirFlag = DirectoryFlag{
  127. Name: "ethash.dagdir",
  128. Usage: "Directory to store the ethash mining DAGs (default = inside home folder)",
  129. Value: DirectoryString{eth.DefaultConfig.EthashDatasetDir},
  130. }
  131. EthashDatasetsInMemoryFlag = cli.IntFlag{
  132. Name: "ethash.dagsinmem",
  133. Usage: "Number of recent ethash mining DAGs to keep in memory (1+GB each)",
  134. Value: eth.DefaultConfig.EthashDatasetsInMem,
  135. }
  136. EthashDatasetsOnDiskFlag = cli.IntFlag{
  137. Name: "ethash.dagsondisk",
  138. Usage: "Number of recent ethash mining DAGs to keep on disk (1+GB each)",
  139. Value: eth.DefaultConfig.EthashDatasetsOnDisk,
  140. }
  141. NetworkIdFlag = cli.Uint64Flag{
  142. Name: "networkid",
  143. Usage: "Network identifier (integer, 1=Frontier, 2=Morden (disused), 3=Ropsten)",
  144. Value: eth.DefaultConfig.NetworkId,
  145. }
  146. TestNetFlag = cli.BoolFlag{
  147. Name: "testnet",
  148. Usage: "Ropsten network: pre-configured proof-of-work test network",
  149. }
  150. DevModeFlag = cli.BoolFlag{
  151. Name: "dev",
  152. Usage: "Developer mode: pre-configured private network with several debugging flags",
  153. }
  154. IdentityFlag = cli.StringFlag{
  155. Name: "identity",
  156. Usage: "Custom node name",
  157. }
  158. DocRootFlag = DirectoryFlag{
  159. Name: "docroot",
  160. Usage: "Document Root for HTTPClient file scheme",
  161. Value: DirectoryString{homeDir()},
  162. }
  163. FastSyncFlag = cli.BoolFlag{
  164. Name: "fast",
  165. Usage: "Enable fast syncing through state downloads",
  166. }
  167. LightModeFlag = cli.BoolFlag{
  168. Name: "light",
  169. Usage: "Enable light client mode",
  170. }
  171. defaultSyncMode = eth.DefaultConfig.SyncMode
  172. SyncModeFlag = TextMarshalerFlag{
  173. Name: "syncmode",
  174. Usage: `Blockchain sync mode ("fast", "full", or "light")`,
  175. Value: &defaultSyncMode,
  176. }
  177. LightServFlag = cli.IntFlag{
  178. Name: "lightserv",
  179. Usage: "Maximum percentage of time allowed for serving LES requests (0-90)",
  180. Value: 0,
  181. }
  182. LightPeersFlag = cli.IntFlag{
  183. Name: "lightpeers",
  184. Usage: "Maximum number of LES client peers",
  185. Value: 20,
  186. }
  187. LightKDFFlag = cli.BoolFlag{
  188. Name: "lightkdf",
  189. Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
  190. }
  191. // Performance tuning settings
  192. CacheFlag = cli.IntFlag{
  193. Name: "cache",
  194. Usage: "Megabytes of memory allocated to internal caching (min 16MB / database forced)",
  195. Value: 128,
  196. }
  197. TrieCacheGenFlag = cli.IntFlag{
  198. Name: "trie-cache-gens",
  199. Usage: "Number of trie node generations to keep in memory",
  200. Value: int(state.MaxTrieCacheGen),
  201. }
  202. // Miner settings
  203. MiningEnabledFlag = cli.BoolFlag{
  204. Name: "mine",
  205. Usage: "Enable mining",
  206. }
  207. MinerThreadsFlag = cli.IntFlag{
  208. Name: "minerthreads",
  209. Usage: "Number of CPU threads to use for mining",
  210. Value: runtime.NumCPU(),
  211. }
  212. TargetGasLimitFlag = cli.Uint64Flag{
  213. Name: "targetgaslimit",
  214. Usage: "Target gas limit sets the artificial target gas floor for the blocks to mine",
  215. Value: params.GenesisGasLimit.Uint64(),
  216. }
  217. EtherbaseFlag = cli.StringFlag{
  218. Name: "etherbase",
  219. Usage: "Public address for block mining rewards (default = first account created)",
  220. Value: "0",
  221. }
  222. GasPriceFlag = BigFlag{
  223. Name: "gasprice",
  224. Usage: "Minimal gas price to accept for mining a transactions",
  225. Value: big.NewInt(20 * params.Shannon),
  226. }
  227. ExtraDataFlag = cli.StringFlag{
  228. Name: "extradata",
  229. Usage: "Block extra data set by the miner (default = client version)",
  230. }
  231. // Account settings
  232. UnlockedAccountFlag = cli.StringFlag{
  233. Name: "unlock",
  234. Usage: "Comma separated list of accounts to unlock",
  235. Value: "",
  236. }
  237. PasswordFileFlag = cli.StringFlag{
  238. Name: "password",
  239. Usage: "Password file to use for non-inteactive password input",
  240. Value: "",
  241. }
  242. VMEnableDebugFlag = cli.BoolFlag{
  243. Name: "vmdebug",
  244. Usage: "Record information useful for VM and contract debugging",
  245. }
  246. // Logging and debug settings
  247. EthStatsURLFlag = cli.StringFlag{
  248. Name: "ethstats",
  249. Usage: "Reporting URL of a ethstats service (nodename:secret@host:port)",
  250. }
  251. MetricsEnabledFlag = cli.BoolFlag{
  252. Name: metrics.MetricsEnabledFlag,
  253. Usage: "Enable metrics collection and reporting",
  254. }
  255. FakePoWFlag = cli.BoolFlag{
  256. Name: "fakepow",
  257. Usage: "Disables proof-of-work verification",
  258. }
  259. NoCompactionFlag = cli.BoolFlag{
  260. Name: "nocompaction",
  261. Usage: "Disables db compaction after import",
  262. }
  263. // RPC settings
  264. RPCEnabledFlag = cli.BoolFlag{
  265. Name: "rpc",
  266. Usage: "Enable the HTTP-RPC server",
  267. }
  268. RPCListenAddrFlag = cli.StringFlag{
  269. Name: "rpcaddr",
  270. Usage: "HTTP-RPC server listening interface",
  271. Value: node.DefaultHTTPHost,
  272. }
  273. RPCPortFlag = cli.IntFlag{
  274. Name: "rpcport",
  275. Usage: "HTTP-RPC server listening port",
  276. Value: node.DefaultHTTPPort,
  277. }
  278. RPCCORSDomainFlag = cli.StringFlag{
  279. Name: "rpccorsdomain",
  280. Usage: "Comma separated list of domains from which to accept cross origin requests (browser enforced)",
  281. Value: "",
  282. }
  283. RPCApiFlag = cli.StringFlag{
  284. Name: "rpcapi",
  285. Usage: "API's offered over the HTTP-RPC interface",
  286. Value: "",
  287. }
  288. IPCDisabledFlag = cli.BoolFlag{
  289. Name: "ipcdisable",
  290. Usage: "Disable the IPC-RPC server",
  291. }
  292. IPCPathFlag = DirectoryFlag{
  293. Name: "ipcpath",
  294. Usage: "Filename for IPC socket/pipe within the datadir (explicit paths escape it)",
  295. }
  296. WSEnabledFlag = cli.BoolFlag{
  297. Name: "ws",
  298. Usage: "Enable the WS-RPC server",
  299. }
  300. WSListenAddrFlag = cli.StringFlag{
  301. Name: "wsaddr",
  302. Usage: "WS-RPC server listening interface",
  303. Value: node.DefaultWSHost,
  304. }
  305. WSPortFlag = cli.IntFlag{
  306. Name: "wsport",
  307. Usage: "WS-RPC server listening port",
  308. Value: node.DefaultWSPort,
  309. }
  310. WSApiFlag = cli.StringFlag{
  311. Name: "wsapi",
  312. Usage: "API's offered over the WS-RPC interface",
  313. Value: "",
  314. }
  315. WSAllowedOriginsFlag = cli.StringFlag{
  316. Name: "wsorigins",
  317. Usage: "Origins from which to accept websockets requests",
  318. Value: "",
  319. }
  320. ExecFlag = cli.StringFlag{
  321. Name: "exec",
  322. Usage: "Execute JavaScript statement",
  323. }
  324. PreloadJSFlag = cli.StringFlag{
  325. Name: "preload",
  326. Usage: "Comma separated list of JavaScript files to preload into the console",
  327. }
  328. // Network Settings
  329. MaxPeersFlag = cli.IntFlag{
  330. Name: "maxpeers",
  331. Usage: "Maximum number of network peers (network disabled if set to 0)",
  332. Value: 25,
  333. }
  334. MaxPendingPeersFlag = cli.IntFlag{
  335. Name: "maxpendpeers",
  336. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  337. Value: 0,
  338. }
  339. ListenPortFlag = cli.IntFlag{
  340. Name: "port",
  341. Usage: "Network listening port",
  342. Value: 30303,
  343. }
  344. BootnodesFlag = cli.StringFlag{
  345. Name: "bootnodes",
  346. Usage: "Comma separated enode URLs for P2P discovery bootstrap",
  347. Value: "",
  348. }
  349. NodeKeyFileFlag = cli.StringFlag{
  350. Name: "nodekey",
  351. Usage: "P2P node key file",
  352. }
  353. NodeKeyHexFlag = cli.StringFlag{
  354. Name: "nodekeyhex",
  355. Usage: "P2P node key as hex (for testing)",
  356. }
  357. NATFlag = cli.StringFlag{
  358. Name: "nat",
  359. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  360. Value: "any",
  361. }
  362. NoDiscoverFlag = cli.BoolFlag{
  363. Name: "nodiscover",
  364. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  365. }
  366. DiscoveryV5Flag = cli.BoolFlag{
  367. Name: "v5disc",
  368. Usage: "Enables the experimental RLPx V5 (Topic Discovery) mechanism",
  369. }
  370. NetrestrictFlag = cli.StringFlag{
  371. Name: "netrestrict",
  372. Usage: "Restricts network communication to the given IP networks (CIDR masks)",
  373. }
  374. WhisperEnabledFlag = cli.BoolFlag{
  375. Name: "shh",
  376. Usage: "Enable Whisper",
  377. }
  378. // ATM the url is left to the user and deployment to
  379. JSpathFlag = cli.StringFlag{
  380. Name: "jspath",
  381. Usage: "JavaScript root path for `loadScript`",
  382. Value: ".",
  383. }
  384. // Gas price oracle settings
  385. GpoBlocksFlag = cli.IntFlag{
  386. Name: "gpoblocks",
  387. Usage: "Number of recent blocks to check for gas prices",
  388. Value: eth.DefaultConfig.GPO.Blocks,
  389. }
  390. GpoPercentileFlag = cli.IntFlag{
  391. Name: "gpopercentile",
  392. Usage: "Suggested gas price is the given percentile of a set of recent transaction gas prices",
  393. Value: eth.DefaultConfig.GPO.Percentile,
  394. }
  395. )
  396. // MakeDataDir retrieves the currently requested data directory, terminating
  397. // if none (or the empty string) is specified. If the node is starting a testnet,
  398. // the a subdirectory of the specified datadir will be used.
  399. func MakeDataDir(ctx *cli.Context) string {
  400. if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
  401. // TODO: choose a different location outside of the regular datadir.
  402. if ctx.GlobalBool(TestNetFlag.Name) {
  403. return filepath.Join(path, "testnet")
  404. }
  405. return path
  406. }
  407. Fatalf("Cannot determine default data directory, please set manually (--datadir)")
  408. return ""
  409. }
  410. // setNodeKey creates a node key from set command line flags, either loading it
  411. // from a file or as a specified hex value. If neither flags were provided, this
  412. // method returns nil and an emphemeral key is to be generated.
  413. func setNodeKey(ctx *cli.Context, cfg *p2p.Config) {
  414. var (
  415. hex = ctx.GlobalString(NodeKeyHexFlag.Name)
  416. file = ctx.GlobalString(NodeKeyFileFlag.Name)
  417. key *ecdsa.PrivateKey
  418. err error
  419. )
  420. switch {
  421. case file != "" && hex != "":
  422. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  423. case file != "":
  424. if key, err = crypto.LoadECDSA(file); err != nil {
  425. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  426. }
  427. cfg.PrivateKey = key
  428. case hex != "":
  429. if key, err = crypto.HexToECDSA(hex); err != nil {
  430. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  431. }
  432. cfg.PrivateKey = key
  433. }
  434. }
  435. // setNodeUserIdent creates the user identifier from CLI flags.
  436. func setNodeUserIdent(ctx *cli.Context, cfg *node.Config) {
  437. if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
  438. cfg.UserIdent = identity
  439. }
  440. }
  441. // setBootstrapNodes creates a list of bootstrap nodes from the command line
  442. // flags, reverting to pre-configured ones if none have been specified.
  443. func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) {
  444. urls := params.MainnetBootnodes
  445. if ctx.GlobalIsSet(BootnodesFlag.Name) {
  446. urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
  447. } else if ctx.GlobalBool(TestNetFlag.Name) {
  448. urls = params.TestnetBootnodes
  449. }
  450. cfg.BootstrapNodes = make([]*discover.Node, 0, len(urls))
  451. for _, url := range urls {
  452. node, err := discover.ParseNode(url)
  453. if err != nil {
  454. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  455. continue
  456. }
  457. cfg.BootstrapNodes = append(cfg.BootstrapNodes, node)
  458. }
  459. }
  460. // setBootstrapNodesV5 creates a list of bootstrap nodes from the command line
  461. // flags, reverting to pre-configured ones if none have been specified.
  462. func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) {
  463. urls := params.DiscoveryV5Bootnodes
  464. if ctx.GlobalIsSet(BootnodesFlag.Name) {
  465. urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
  466. } else if cfg.BootstrapNodesV5 == nil {
  467. return // already set, don't apply defaults.
  468. }
  469. cfg.BootstrapNodesV5 = make([]*discv5.Node, 0, len(urls))
  470. for _, url := range urls {
  471. node, err := discv5.ParseNode(url)
  472. if err != nil {
  473. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  474. continue
  475. }
  476. cfg.BootstrapNodesV5 = append(cfg.BootstrapNodesV5, node)
  477. }
  478. }
  479. // setListenAddress creates a TCP listening address string from set command
  480. // line flags.
  481. func setListenAddress(ctx *cli.Context, cfg *p2p.Config) {
  482. if ctx.GlobalIsSet(ListenPortFlag.Name) {
  483. cfg.ListenAddr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
  484. }
  485. }
  486. // setDiscoveryV5Address creates a UDP listening address string from set command
  487. // line flags for the V5 discovery protocol.
  488. func setDiscoveryV5Address(ctx *cli.Context, cfg *p2p.Config) {
  489. if ctx.GlobalIsSet(ListenPortFlag.Name) {
  490. cfg.DiscoveryV5Addr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name)+1)
  491. }
  492. }
  493. // setNAT creates a port mapper from command line flags.
  494. func setNAT(ctx *cli.Context, cfg *p2p.Config) {
  495. if ctx.GlobalIsSet(NATFlag.Name) {
  496. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  497. if err != nil {
  498. Fatalf("Option %s: %v", NATFlag.Name, err)
  499. }
  500. cfg.NAT = natif
  501. }
  502. }
  503. // splitAndTrim splits input separated by a comma
  504. // and trims excessive white space from the substrings.
  505. func splitAndTrim(input string) []string {
  506. result := strings.Split(input, ",")
  507. for i, r := range result {
  508. result[i] = strings.TrimSpace(r)
  509. }
  510. return result
  511. }
  512. // setHTTP creates the HTTP RPC listener interface string from the set
  513. // command line flags, returning empty if the HTTP endpoint is disabled.
  514. func setHTTP(ctx *cli.Context, cfg *node.Config) {
  515. if ctx.GlobalBool(RPCEnabledFlag.Name) && cfg.HTTPHost == "" {
  516. cfg.HTTPHost = "127.0.0.1"
  517. if ctx.GlobalIsSet(RPCListenAddrFlag.Name) {
  518. cfg.HTTPHost = ctx.GlobalString(RPCListenAddrFlag.Name)
  519. }
  520. }
  521. if ctx.GlobalIsSet(RPCPortFlag.Name) {
  522. cfg.HTTPPort = ctx.GlobalInt(RPCPortFlag.Name)
  523. }
  524. if ctx.GlobalIsSet(RPCCORSDomainFlag.Name) {
  525. cfg.HTTPCors = splitAndTrim(ctx.GlobalString(RPCCORSDomainFlag.Name))
  526. }
  527. if ctx.GlobalIsSet(RPCApiFlag.Name) {
  528. cfg.HTTPModules = splitAndTrim(ctx.GlobalString(RPCApiFlag.Name))
  529. }
  530. }
  531. // setWS creates the WebSocket RPC listener interface string from the set
  532. // command line flags, returning empty if the HTTP endpoint is disabled.
  533. func setWS(ctx *cli.Context, cfg *node.Config) {
  534. if ctx.GlobalBool(WSEnabledFlag.Name) && cfg.WSHost == "" {
  535. cfg.WSHost = "127.0.0.1"
  536. if ctx.GlobalIsSet(WSListenAddrFlag.Name) {
  537. cfg.WSHost = ctx.GlobalString(WSListenAddrFlag.Name)
  538. }
  539. }
  540. if ctx.GlobalIsSet(WSPortFlag.Name) {
  541. cfg.WSPort = ctx.GlobalInt(WSPortFlag.Name)
  542. }
  543. if ctx.GlobalIsSet(WSAllowedOriginsFlag.Name) {
  544. cfg.WSOrigins = splitAndTrim(ctx.GlobalString(WSAllowedOriginsFlag.Name))
  545. }
  546. if ctx.GlobalIsSet(WSApiFlag.Name) {
  547. cfg.WSModules = splitAndTrim(ctx.GlobalString(WSApiFlag.Name))
  548. }
  549. }
  550. // setIPC creates an IPC path configuration from the set command line flags,
  551. // returning an empty string if IPC was explicitly disabled, or the set path.
  552. func setIPC(ctx *cli.Context, cfg *node.Config) {
  553. checkExclusive(ctx, IPCDisabledFlag, IPCPathFlag)
  554. switch {
  555. case ctx.GlobalBool(IPCDisabledFlag.Name):
  556. cfg.IPCPath = ""
  557. case ctx.GlobalIsSet(IPCPathFlag.Name):
  558. cfg.IPCPath = ctx.GlobalString(IPCPathFlag.Name)
  559. }
  560. }
  561. // makeDatabaseHandles raises out the number of allowed file handles per process
  562. // for Geth and returns half of the allowance to assign to the database.
  563. func makeDatabaseHandles() int {
  564. if err := raiseFdLimit(2048); err != nil {
  565. Fatalf("Failed to raise file descriptor allowance: %v", err)
  566. }
  567. limit, err := getFdLimit()
  568. if err != nil {
  569. Fatalf("Failed to retrieve file descriptor allowance: %v", err)
  570. }
  571. if limit > 2048 { // cap database file descriptors even if more is available
  572. limit = 2048
  573. }
  574. return limit / 2 // Leave half for networking and other stuff
  575. }
  576. // MakeAddress converts an account specified directly as a hex encoded string or
  577. // a key index in the key store to an internal account representation.
  578. func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) {
  579. // If the specified account is a valid address, return it
  580. if common.IsHexAddress(account) {
  581. return accounts.Account{Address: common.HexToAddress(account)}, nil
  582. }
  583. // Otherwise try to interpret the account as a keystore index
  584. index, err := strconv.Atoi(account)
  585. if err != nil || index < 0 {
  586. return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account)
  587. }
  588. accs := ks.Accounts()
  589. if len(accs) <= index {
  590. return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs))
  591. }
  592. return accs[index], nil
  593. }
  594. // setEtherbase retrieves the etherbase either from the directly specified
  595. // command line flags or from the keystore if CLI indexed.
  596. func setEtherbase(ctx *cli.Context, ks *keystore.KeyStore, cfg *eth.Config) {
  597. if ctx.GlobalIsSet(EtherbaseFlag.Name) {
  598. account, err := MakeAddress(ks, ctx.GlobalString(EtherbaseFlag.Name))
  599. if err != nil {
  600. Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
  601. }
  602. cfg.Etherbase = account.Address
  603. return
  604. }
  605. accounts := ks.Accounts()
  606. if (cfg.Etherbase == common.Address{}) {
  607. if len(accounts) > 0 {
  608. cfg.Etherbase = accounts[0].Address
  609. } else {
  610. log.Warn("No etherbase set and no accounts found as default")
  611. }
  612. }
  613. }
  614. // MakePasswordList reads password lines from the file specified by the global --password flag.
  615. func MakePasswordList(ctx *cli.Context) []string {
  616. path := ctx.GlobalString(PasswordFileFlag.Name)
  617. if path == "" {
  618. return nil
  619. }
  620. text, err := ioutil.ReadFile(path)
  621. if err != nil {
  622. Fatalf("Failed to read password file: %v", err)
  623. }
  624. lines := strings.Split(string(text), "\n")
  625. // Sanitise DOS line endings.
  626. for i := range lines {
  627. lines[i] = strings.TrimRight(lines[i], "\r")
  628. }
  629. return lines
  630. }
  631. func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) {
  632. setNodeKey(ctx, cfg)
  633. setNAT(ctx, cfg)
  634. setListenAddress(ctx, cfg)
  635. setDiscoveryV5Address(ctx, cfg)
  636. setBootstrapNodes(ctx, cfg)
  637. setBootstrapNodesV5(ctx, cfg)
  638. if ctx.GlobalIsSet(MaxPeersFlag.Name) {
  639. cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name)
  640. }
  641. if ctx.GlobalIsSet(MaxPendingPeersFlag.Name) {
  642. cfg.MaxPendingPeers = ctx.GlobalInt(MaxPendingPeersFlag.Name)
  643. }
  644. if ctx.GlobalIsSet(NoDiscoverFlag.Name) || ctx.GlobalBool(LightModeFlag.Name) {
  645. cfg.NoDiscovery = true
  646. }
  647. // if we're running a light client or server, force enable the v5 peer discovery
  648. // unless it is explicitly disabled with --nodiscover note that explicitly specifying
  649. // --v5disc overrides --nodiscover, in which case the later only disables v4 discovery
  650. forceV5Discovery := (ctx.GlobalBool(LightModeFlag.Name) || ctx.GlobalInt(LightServFlag.Name) > 0) && !ctx.GlobalBool(NoDiscoverFlag.Name)
  651. if ctx.GlobalIsSet(DiscoveryV5Flag.Name) {
  652. cfg.DiscoveryV5 = ctx.GlobalBool(DiscoveryV5Flag.Name)
  653. } else if forceV5Discovery {
  654. cfg.DiscoveryV5 = true
  655. }
  656. if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" {
  657. list, err := netutil.ParseNetlist(netrestrict)
  658. if err != nil {
  659. Fatalf("Option %q: %v", NetrestrictFlag.Name, err)
  660. }
  661. cfg.NetRestrict = list
  662. }
  663. if ctx.GlobalBool(DevModeFlag.Name) {
  664. // --dev mode can't use p2p networking.
  665. cfg.MaxPeers = 0
  666. cfg.ListenAddr = ":0"
  667. cfg.NoDiscovery = true
  668. cfg.DiscoveryV5 = false
  669. }
  670. }
  671. // SetNodeConfig applies node-related command line flags to the config.
  672. func SetNodeConfig(ctx *cli.Context, cfg *node.Config) {
  673. SetP2PConfig(ctx, &cfg.P2P)
  674. setIPC(ctx, cfg)
  675. setHTTP(ctx, cfg)
  676. setWS(ctx, cfg)
  677. setNodeUserIdent(ctx, cfg)
  678. switch {
  679. case ctx.GlobalIsSet(DataDirFlag.Name):
  680. cfg.DataDir = ctx.GlobalString(DataDirFlag.Name)
  681. case ctx.GlobalBool(DevModeFlag.Name):
  682. cfg.DataDir = filepath.Join(os.TempDir(), "ethereum_dev_mode")
  683. case ctx.GlobalBool(TestNetFlag.Name):
  684. cfg.DataDir = filepath.Join(node.DefaultDataDir(), "testnet")
  685. }
  686. if ctx.GlobalIsSet(KeyStoreDirFlag.Name) {
  687. cfg.KeyStoreDir = ctx.GlobalString(KeyStoreDirFlag.Name)
  688. }
  689. if ctx.GlobalIsSet(LightKDFFlag.Name) {
  690. cfg.UseLightweightKDF = ctx.GlobalBool(LightKDFFlag.Name)
  691. }
  692. if ctx.GlobalIsSet(NoUSBFlag.Name) {
  693. cfg.NoUSB = ctx.GlobalBool(NoUSBFlag.Name)
  694. }
  695. }
  696. func setGPO(ctx *cli.Context, cfg *gasprice.Config) {
  697. if ctx.GlobalIsSet(GpoBlocksFlag.Name) {
  698. cfg.Blocks = ctx.GlobalInt(GpoBlocksFlag.Name)
  699. }
  700. if ctx.GlobalIsSet(GpoPercentileFlag.Name) {
  701. cfg.Percentile = ctx.GlobalInt(GpoPercentileFlag.Name)
  702. }
  703. }
  704. func setEthash(ctx *cli.Context, cfg *eth.Config) {
  705. if ctx.GlobalIsSet(EthashCacheDirFlag.Name) {
  706. cfg.EthashCacheDir = ctx.GlobalString(EthashCacheDirFlag.Name)
  707. }
  708. if ctx.GlobalIsSet(EthashDatasetDirFlag.Name) {
  709. cfg.EthashDatasetDir = ctx.GlobalString(EthashDatasetDirFlag.Name)
  710. }
  711. if ctx.GlobalIsSet(EthashCachesInMemoryFlag.Name) {
  712. cfg.EthashCachesInMem = ctx.GlobalInt(EthashCachesInMemoryFlag.Name)
  713. }
  714. if ctx.GlobalIsSet(EthashCachesOnDiskFlag.Name) {
  715. cfg.EthashCachesOnDisk = ctx.GlobalInt(EthashCachesOnDiskFlag.Name)
  716. }
  717. if ctx.GlobalIsSet(EthashDatasetsInMemoryFlag.Name) {
  718. cfg.EthashDatasetsInMem = ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name)
  719. }
  720. if ctx.GlobalIsSet(EthashDatasetsOnDiskFlag.Name) {
  721. cfg.EthashDatasetsOnDisk = ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name)
  722. }
  723. }
  724. func checkExclusive(ctx *cli.Context, flags ...cli.Flag) {
  725. set := make([]string, 0, 1)
  726. for _, flag := range flags {
  727. if ctx.GlobalIsSet(flag.GetName()) {
  728. set = append(set, "--"+flag.GetName())
  729. }
  730. }
  731. if len(set) > 1 {
  732. Fatalf("flags %v can't be used at the same time", strings.Join(set, ", "))
  733. }
  734. }
  735. // SetEthConfig applies eth-related command line flags to the config.
  736. func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
  737. // Avoid conflicting network flags
  738. checkExclusive(ctx, DevModeFlag, TestNetFlag)
  739. checkExclusive(ctx, FastSyncFlag, LightModeFlag, SyncModeFlag)
  740. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  741. setEtherbase(ctx, ks, cfg)
  742. setGPO(ctx, &cfg.GPO)
  743. setEthash(ctx, cfg)
  744. switch {
  745. case ctx.GlobalIsSet(SyncModeFlag.Name):
  746. cfg.SyncMode = *GlobalTextMarshaler(ctx, SyncModeFlag.Name).(*downloader.SyncMode)
  747. case ctx.GlobalBool(FastSyncFlag.Name):
  748. cfg.SyncMode = downloader.FastSync
  749. case ctx.GlobalBool(LightModeFlag.Name):
  750. cfg.SyncMode = downloader.LightSync
  751. }
  752. if ctx.GlobalIsSet(LightServFlag.Name) {
  753. cfg.LightServ = ctx.GlobalInt(LightServFlag.Name)
  754. }
  755. if ctx.GlobalIsSet(LightPeersFlag.Name) {
  756. cfg.LightPeers = ctx.GlobalInt(LightPeersFlag.Name)
  757. }
  758. if ctx.GlobalIsSet(NetworkIdFlag.Name) {
  759. cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name)
  760. }
  761. // Ethereum needs to know maxPeers to calculate the light server peer ratio.
  762. // TODO(fjl): ensure Ethereum can get MaxPeers from node.
  763. cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name)
  764. if ctx.GlobalIsSet(CacheFlag.Name) {
  765. cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name)
  766. }
  767. cfg.DatabaseHandles = makeDatabaseHandles()
  768. if ctx.GlobalIsSet(MinerThreadsFlag.Name) {
  769. cfg.MinerThreads = ctx.GlobalInt(MinerThreadsFlag.Name)
  770. }
  771. if ctx.GlobalIsSet(DocRootFlag.Name) {
  772. cfg.DocRoot = ctx.GlobalString(DocRootFlag.Name)
  773. }
  774. if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  775. cfg.ExtraData = []byte(ctx.GlobalString(ExtraDataFlag.Name))
  776. }
  777. if ctx.GlobalIsSet(GasPriceFlag.Name) {
  778. cfg.GasPrice = GlobalBig(ctx, GasPriceFlag.Name)
  779. }
  780. if ctx.GlobalIsSet(VMEnableDebugFlag.Name) {
  781. // TODO(fjl): force-enable this in --dev mode
  782. cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name)
  783. }
  784. // Override any default configs for --dev and --testnet.
  785. switch {
  786. case ctx.GlobalBool(TestNetFlag.Name):
  787. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  788. cfg.NetworkId = 3
  789. }
  790. cfg.Genesis = core.DefaultTestnetGenesisBlock()
  791. case ctx.GlobalBool(DevModeFlag.Name):
  792. cfg.Genesis = core.DevGenesisBlock()
  793. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  794. cfg.GasPrice = new(big.Int)
  795. }
  796. cfg.PowTest = true
  797. }
  798. // TODO(fjl): move trie cache generations into config
  799. if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  800. state.MaxTrieCacheGen = uint16(gen)
  801. }
  802. }
  803. // RegisterEthService adds an Ethereum client to the stack.
  804. func RegisterEthService(stack *node.Node, cfg *eth.Config) {
  805. var err error
  806. if cfg.SyncMode == downloader.LightSync {
  807. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  808. return les.New(ctx, cfg)
  809. })
  810. } else {
  811. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  812. fullNode, err := eth.New(ctx, cfg)
  813. if fullNode != nil && cfg.LightServ > 0 {
  814. ls, _ := les.NewLesServer(fullNode, cfg)
  815. fullNode.AddLesServer(ls)
  816. }
  817. return fullNode, err
  818. })
  819. }
  820. if err != nil {
  821. Fatalf("Failed to register the Ethereum service: %v", err)
  822. }
  823. }
  824. // RegisterShhService configures Whisper and adds it to the given node.
  825. func RegisterShhService(stack *node.Node) {
  826. if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  827. Fatalf("Failed to register the Whisper service: %v", err)
  828. }
  829. }
  830. // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  831. // th egiven node.
  832. func RegisterEthStatsService(stack *node.Node, url string) {
  833. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  834. // Retrieve both eth and les services
  835. var ethServ *eth.Ethereum
  836. ctx.Service(&ethServ)
  837. var lesServ *les.LightEthereum
  838. ctx.Service(&lesServ)
  839. return ethstats.New(url, ethServ, lesServ)
  840. }); err != nil {
  841. Fatalf("Failed to register the Ethereum Stats service: %v", err)
  842. }
  843. }
  844. // SetupNetwork configures the system for either the main net or some test network.
  845. func SetupNetwork(ctx *cli.Context) {
  846. // TODO(fjl): move target gas limit into config
  847. params.TargetGasLimit = new(big.Int).SetUint64(ctx.GlobalUint64(TargetGasLimitFlag.Name))
  848. }
  849. // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  850. func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  851. var (
  852. cache = ctx.GlobalInt(CacheFlag.Name)
  853. handles = makeDatabaseHandles()
  854. )
  855. name := "chaindata"
  856. if ctx.GlobalBool(LightModeFlag.Name) {
  857. name = "lightchaindata"
  858. }
  859. chainDb, err := stack.OpenDatabase(name, cache, handles)
  860. if err != nil {
  861. Fatalf("Could not open database: %v", err)
  862. }
  863. return chainDb
  864. }
  865. func MakeGenesis(ctx *cli.Context) *core.Genesis {
  866. var genesis *core.Genesis
  867. switch {
  868. case ctx.GlobalBool(TestNetFlag.Name):
  869. genesis = core.DefaultTestnetGenesisBlock()
  870. case ctx.GlobalBool(DevModeFlag.Name):
  871. genesis = core.DevGenesisBlock()
  872. }
  873. return genesis
  874. }
  875. // MakeChain creates a chain manager from set command line flags.
  876. func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  877. var err error
  878. chainDb = MakeChainDatabase(ctx, stack)
  879. engine := ethash.NewFaker()
  880. if !ctx.GlobalBool(FakePoWFlag.Name) {
  881. engine = ethash.New("", 1, 0, "", 1, 0)
  882. }
  883. config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx))
  884. if err != nil {
  885. Fatalf("%v", err)
  886. }
  887. vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
  888. chain, err = core.NewBlockChain(chainDb, config, engine, new(event.TypeMux), vmcfg)
  889. if err != nil {
  890. Fatalf("Can't create BlockChain: %v", err)
  891. }
  892. return chain, chainDb
  893. }
  894. // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  895. // scripts to preload before starting.
  896. func MakeConsolePreloads(ctx *cli.Context) []string {
  897. // Skip preloading if there's nothing to preload
  898. if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  899. return nil
  900. }
  901. // Otherwise resolve absolute paths and return them
  902. preloads := []string{}
  903. assets := ctx.GlobalString(JSpathFlag.Name)
  904. for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  905. preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  906. }
  907. return preloads
  908. }
  909. // MigrateFlags sets the global flag from a local flag when it's set.
  910. // This is a temporary function used for migrating old command/flags to the
  911. // new format.
  912. //
  913. // e.g. geth account new --keystore /tmp/mykeystore --lightkdf
  914. //
  915. // is equivalent after calling this method with:
  916. //
  917. // geth --keystore /tmp/mykeystore --lightkdf account new
  918. //
  919. // This allows the use of the existing configuration functionality.
  920. // When all flags are migrated this function can be removed and the existing
  921. // configuration functionality must be changed that is uses local flags
  922. func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error {
  923. return func(ctx *cli.Context) error {
  924. for _, name := range ctx.FlagNames() {
  925. if ctx.IsSet(name) {
  926. ctx.GlobalSet(name, ctx.String(name))
  927. }
  928. }
  929. return action(ctx)
  930. }
  931. }