flags.go 37 KB

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