flags.go 40 KB

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