flags.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  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.Uint64(),
  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. }
  568. cfg.BootstrapNodes = make([]*discover.Node, 0, len(urls))
  569. for _, url := range urls {
  570. node, err := discover.ParseNode(url)
  571. if err != nil {
  572. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  573. continue
  574. }
  575. cfg.BootstrapNodes = append(cfg.BootstrapNodes, node)
  576. }
  577. }
  578. // setBootstrapNodesV5 creates a list of bootstrap nodes from the command line
  579. // flags, reverting to pre-configured ones if none have been specified.
  580. func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) {
  581. urls := params.DiscoveryV5Bootnodes
  582. switch {
  583. case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV5Flag.Name):
  584. if ctx.GlobalIsSet(BootnodesV5Flag.Name) {
  585. urls = strings.Split(ctx.GlobalString(BootnodesV5Flag.Name), ",")
  586. } else {
  587. urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
  588. }
  589. case ctx.GlobalBool(RinkebyFlag.Name):
  590. urls = params.RinkebyV5Bootnodes
  591. case cfg.BootstrapNodesV5 != nil:
  592. return // already set, don't apply defaults.
  593. }
  594. cfg.BootstrapNodesV5 = make([]*discv5.Node, 0, len(urls))
  595. for _, url := range urls {
  596. node, err := discv5.ParseNode(url)
  597. if err != nil {
  598. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  599. continue
  600. }
  601. cfg.BootstrapNodesV5 = append(cfg.BootstrapNodesV5, node)
  602. }
  603. }
  604. // setListenAddress creates a TCP listening address string from set command
  605. // line flags.
  606. func setListenAddress(ctx *cli.Context, cfg *p2p.Config) {
  607. if ctx.GlobalIsSet(ListenPortFlag.Name) {
  608. cfg.ListenAddr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
  609. }
  610. }
  611. // setDiscoveryV5Address creates a UDP listening address string from set command
  612. // line flags for the V5 discovery protocol.
  613. func setDiscoveryV5Address(ctx *cli.Context, cfg *p2p.Config) {
  614. if ctx.GlobalIsSet(ListenPortFlag.Name) {
  615. cfg.DiscoveryV5Addr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name)+1)
  616. }
  617. }
  618. // setNAT creates a port mapper from command line flags.
  619. func setNAT(ctx *cli.Context, cfg *p2p.Config) {
  620. if ctx.GlobalIsSet(NATFlag.Name) {
  621. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  622. if err != nil {
  623. Fatalf("Option %s: %v", NATFlag.Name, err)
  624. }
  625. cfg.NAT = natif
  626. }
  627. }
  628. // splitAndTrim splits input separated by a comma
  629. // and trims excessive white space from the substrings.
  630. func splitAndTrim(input string) []string {
  631. result := strings.Split(input, ",")
  632. for i, r := range result {
  633. result[i] = strings.TrimSpace(r)
  634. }
  635. return result
  636. }
  637. // setHTTP creates the HTTP RPC listener interface string from the set
  638. // command line flags, returning empty if the HTTP endpoint is disabled.
  639. func setHTTP(ctx *cli.Context, cfg *node.Config) {
  640. if ctx.GlobalBool(RPCEnabledFlag.Name) && cfg.HTTPHost == "" {
  641. cfg.HTTPHost = "127.0.0.1"
  642. if ctx.GlobalIsSet(RPCListenAddrFlag.Name) {
  643. cfg.HTTPHost = ctx.GlobalString(RPCListenAddrFlag.Name)
  644. }
  645. }
  646. if ctx.GlobalIsSet(RPCPortFlag.Name) {
  647. cfg.HTTPPort = ctx.GlobalInt(RPCPortFlag.Name)
  648. }
  649. if ctx.GlobalIsSet(RPCCORSDomainFlag.Name) {
  650. cfg.HTTPCors = splitAndTrim(ctx.GlobalString(RPCCORSDomainFlag.Name))
  651. }
  652. if ctx.GlobalIsSet(RPCApiFlag.Name) {
  653. cfg.HTTPModules = splitAndTrim(ctx.GlobalString(RPCApiFlag.Name))
  654. }
  655. }
  656. // setWS creates the WebSocket RPC listener interface string from the set
  657. // command line flags, returning empty if the HTTP endpoint is disabled.
  658. func setWS(ctx *cli.Context, cfg *node.Config) {
  659. if ctx.GlobalBool(WSEnabledFlag.Name) && cfg.WSHost == "" {
  660. cfg.WSHost = "127.0.0.1"
  661. if ctx.GlobalIsSet(WSListenAddrFlag.Name) {
  662. cfg.WSHost = ctx.GlobalString(WSListenAddrFlag.Name)
  663. }
  664. }
  665. if ctx.GlobalIsSet(WSPortFlag.Name) {
  666. cfg.WSPort = ctx.GlobalInt(WSPortFlag.Name)
  667. }
  668. if ctx.GlobalIsSet(WSAllowedOriginsFlag.Name) {
  669. cfg.WSOrigins = splitAndTrim(ctx.GlobalString(WSAllowedOriginsFlag.Name))
  670. }
  671. if ctx.GlobalIsSet(WSApiFlag.Name) {
  672. cfg.WSModules = splitAndTrim(ctx.GlobalString(WSApiFlag.Name))
  673. }
  674. }
  675. // setIPC creates an IPC path configuration from the set command line flags,
  676. // returning an empty string if IPC was explicitly disabled, or the set path.
  677. func setIPC(ctx *cli.Context, cfg *node.Config) {
  678. checkExclusive(ctx, IPCDisabledFlag, IPCPathFlag)
  679. switch {
  680. case ctx.GlobalBool(IPCDisabledFlag.Name):
  681. cfg.IPCPath = ""
  682. case ctx.GlobalIsSet(IPCPathFlag.Name):
  683. cfg.IPCPath = ctx.GlobalString(IPCPathFlag.Name)
  684. }
  685. }
  686. // makeDatabaseHandles raises out the number of allowed file handles per process
  687. // for Geth and returns half of the allowance to assign to the database.
  688. func makeDatabaseHandles() int {
  689. if err := raiseFdLimit(2048); err != nil {
  690. Fatalf("Failed to raise file descriptor allowance: %v", err)
  691. }
  692. limit, err := getFdLimit()
  693. if err != nil {
  694. Fatalf("Failed to retrieve file descriptor allowance: %v", err)
  695. }
  696. if limit > 2048 { // cap database file descriptors even if more is available
  697. limit = 2048
  698. }
  699. return limit / 2 // Leave half for networking and other stuff
  700. }
  701. // MakeAddress converts an account specified directly as a hex encoded string or
  702. // a key index in the key store to an internal account representation.
  703. func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) {
  704. // If the specified account is a valid address, return it
  705. if common.IsHexAddress(account) {
  706. return accounts.Account{Address: common.HexToAddress(account)}, nil
  707. }
  708. // Otherwise try to interpret the account as a keystore index
  709. index, err := strconv.Atoi(account)
  710. if err != nil || index < 0 {
  711. return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account)
  712. }
  713. accs := ks.Accounts()
  714. if len(accs) <= index {
  715. return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs))
  716. }
  717. return accs[index], nil
  718. }
  719. // setEtherbase retrieves the etherbase either from the directly specified
  720. // command line flags or from the keystore if CLI indexed.
  721. func setEtherbase(ctx *cli.Context, ks *keystore.KeyStore, cfg *eth.Config) {
  722. if ctx.GlobalIsSet(EtherbaseFlag.Name) {
  723. account, err := MakeAddress(ks, ctx.GlobalString(EtherbaseFlag.Name))
  724. if err != nil {
  725. Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
  726. }
  727. cfg.Etherbase = account.Address
  728. return
  729. }
  730. accounts := ks.Accounts()
  731. if (cfg.Etherbase == common.Address{}) {
  732. if len(accounts) > 0 {
  733. cfg.Etherbase = accounts[0].Address
  734. } else {
  735. log.Warn("No etherbase set and no accounts found as default")
  736. }
  737. }
  738. }
  739. // MakePasswordList reads password lines from the file specified by the global --password flag.
  740. func MakePasswordList(ctx *cli.Context) []string {
  741. path := ctx.GlobalString(PasswordFileFlag.Name)
  742. if path == "" {
  743. return nil
  744. }
  745. text, err := ioutil.ReadFile(path)
  746. if err != nil {
  747. Fatalf("Failed to read password file: %v", err)
  748. }
  749. lines := strings.Split(string(text), "\n")
  750. // Sanitise DOS line endings.
  751. for i := range lines {
  752. lines[i] = strings.TrimRight(lines[i], "\r")
  753. }
  754. return lines
  755. }
  756. func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) {
  757. setNodeKey(ctx, cfg)
  758. setNAT(ctx, cfg)
  759. setListenAddress(ctx, cfg)
  760. setDiscoveryV5Address(ctx, cfg)
  761. setBootstrapNodes(ctx, cfg)
  762. setBootstrapNodesV5(ctx, cfg)
  763. if ctx.GlobalIsSet(MaxPeersFlag.Name) {
  764. cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name)
  765. }
  766. if ctx.GlobalIsSet(MaxPendingPeersFlag.Name) {
  767. cfg.MaxPendingPeers = ctx.GlobalInt(MaxPendingPeersFlag.Name)
  768. }
  769. if ctx.GlobalIsSet(NoDiscoverFlag.Name) || ctx.GlobalBool(LightModeFlag.Name) {
  770. cfg.NoDiscovery = true
  771. }
  772. // if we're running a light client or server, force enable the v5 peer discovery
  773. // unless it is explicitly disabled with --nodiscover note that explicitly specifying
  774. // --v5disc overrides --nodiscover, in which case the later only disables v4 discovery
  775. forceV5Discovery := (ctx.GlobalBool(LightModeFlag.Name) || ctx.GlobalInt(LightServFlag.Name) > 0) && !ctx.GlobalBool(NoDiscoverFlag.Name)
  776. if ctx.GlobalIsSet(DiscoveryV5Flag.Name) {
  777. cfg.DiscoveryV5 = ctx.GlobalBool(DiscoveryV5Flag.Name)
  778. } else if forceV5Discovery {
  779. cfg.DiscoveryV5 = true
  780. }
  781. if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" {
  782. list, err := netutil.ParseNetlist(netrestrict)
  783. if err != nil {
  784. Fatalf("Option %q: %v", NetrestrictFlag.Name, err)
  785. }
  786. cfg.NetRestrict = list
  787. }
  788. if ctx.GlobalBool(DeveloperFlag.Name) {
  789. // --dev mode can't use p2p networking.
  790. cfg.MaxPeers = 0
  791. cfg.ListenAddr = ":0"
  792. cfg.DiscoveryV5Addr = ":0"
  793. cfg.NoDiscovery = true
  794. cfg.DiscoveryV5 = false
  795. }
  796. }
  797. // SetNodeConfig applies node-related command line flags to the config.
  798. func SetNodeConfig(ctx *cli.Context, cfg *node.Config) {
  799. SetP2PConfig(ctx, &cfg.P2P)
  800. setIPC(ctx, cfg)
  801. setHTTP(ctx, cfg)
  802. setWS(ctx, cfg)
  803. setNodeUserIdent(ctx, cfg)
  804. switch {
  805. case ctx.GlobalIsSet(DataDirFlag.Name):
  806. cfg.DataDir = ctx.GlobalString(DataDirFlag.Name)
  807. case ctx.GlobalBool(DeveloperFlag.Name):
  808. cfg.DataDir = "" // unless explicitly requested, use memory databases
  809. case ctx.GlobalBool(TestnetFlag.Name):
  810. cfg.DataDir = filepath.Join(node.DefaultDataDir(), "testnet")
  811. case ctx.GlobalBool(RinkebyFlag.Name):
  812. cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby")
  813. }
  814. if ctx.GlobalIsSet(KeyStoreDirFlag.Name) {
  815. cfg.KeyStoreDir = ctx.GlobalString(KeyStoreDirFlag.Name)
  816. }
  817. if ctx.GlobalIsSet(LightKDFFlag.Name) {
  818. cfg.UseLightweightKDF = ctx.GlobalBool(LightKDFFlag.Name)
  819. }
  820. if ctx.GlobalIsSet(NoUSBFlag.Name) {
  821. cfg.NoUSB = ctx.GlobalBool(NoUSBFlag.Name)
  822. }
  823. }
  824. func setGPO(ctx *cli.Context, cfg *gasprice.Config) {
  825. if ctx.GlobalIsSet(GpoBlocksFlag.Name) {
  826. cfg.Blocks = ctx.GlobalInt(GpoBlocksFlag.Name)
  827. }
  828. if ctx.GlobalIsSet(GpoPercentileFlag.Name) {
  829. cfg.Percentile = ctx.GlobalInt(GpoPercentileFlag.Name)
  830. }
  831. }
  832. func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) {
  833. if ctx.GlobalIsSet(TxPoolNoLocalsFlag.Name) {
  834. cfg.NoLocals = ctx.GlobalBool(TxPoolNoLocalsFlag.Name)
  835. }
  836. if ctx.GlobalIsSet(TxPoolJournalFlag.Name) {
  837. cfg.Journal = ctx.GlobalString(TxPoolJournalFlag.Name)
  838. }
  839. if ctx.GlobalIsSet(TxPoolRejournalFlag.Name) {
  840. cfg.Rejournal = ctx.GlobalDuration(TxPoolRejournalFlag.Name)
  841. }
  842. if ctx.GlobalIsSet(TxPoolPriceLimitFlag.Name) {
  843. cfg.PriceLimit = ctx.GlobalUint64(TxPoolPriceLimitFlag.Name)
  844. }
  845. if ctx.GlobalIsSet(TxPoolPriceBumpFlag.Name) {
  846. cfg.PriceBump = ctx.GlobalUint64(TxPoolPriceBumpFlag.Name)
  847. }
  848. if ctx.GlobalIsSet(TxPoolAccountSlotsFlag.Name) {
  849. cfg.AccountSlots = ctx.GlobalUint64(TxPoolAccountSlotsFlag.Name)
  850. }
  851. if ctx.GlobalIsSet(TxPoolGlobalSlotsFlag.Name) {
  852. cfg.GlobalSlots = ctx.GlobalUint64(TxPoolGlobalSlotsFlag.Name)
  853. }
  854. if ctx.GlobalIsSet(TxPoolAccountQueueFlag.Name) {
  855. cfg.AccountQueue = ctx.GlobalUint64(TxPoolAccountQueueFlag.Name)
  856. }
  857. if ctx.GlobalIsSet(TxPoolGlobalQueueFlag.Name) {
  858. cfg.GlobalQueue = ctx.GlobalUint64(TxPoolGlobalQueueFlag.Name)
  859. }
  860. if ctx.GlobalIsSet(TxPoolLifetimeFlag.Name) {
  861. cfg.Lifetime = ctx.GlobalDuration(TxPoolLifetimeFlag.Name)
  862. }
  863. }
  864. func setEthash(ctx *cli.Context, cfg *eth.Config) {
  865. if ctx.GlobalIsSet(EthashCacheDirFlag.Name) {
  866. cfg.Ethash.CacheDir = ctx.GlobalString(EthashCacheDirFlag.Name)
  867. }
  868. if ctx.GlobalIsSet(EthashDatasetDirFlag.Name) {
  869. cfg.Ethash.DatasetDir = ctx.GlobalString(EthashDatasetDirFlag.Name)
  870. }
  871. if ctx.GlobalIsSet(EthashCachesInMemoryFlag.Name) {
  872. cfg.Ethash.CachesInMem = ctx.GlobalInt(EthashCachesInMemoryFlag.Name)
  873. }
  874. if ctx.GlobalIsSet(EthashCachesOnDiskFlag.Name) {
  875. cfg.Ethash.CachesOnDisk = ctx.GlobalInt(EthashCachesOnDiskFlag.Name)
  876. }
  877. if ctx.GlobalIsSet(EthashDatasetsInMemoryFlag.Name) {
  878. cfg.Ethash.DatasetsInMem = ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name)
  879. }
  880. if ctx.GlobalIsSet(EthashDatasetsOnDiskFlag.Name) {
  881. cfg.Ethash.DatasetsOnDisk = ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name)
  882. }
  883. }
  884. // checkExclusive verifies that only a single isntance of the provided flags was
  885. // set by the user. Each flag might optionally be followed by a string type to
  886. // specialize it further.
  887. func checkExclusive(ctx *cli.Context, args ...interface{}) {
  888. set := make([]string, 0, 1)
  889. for i := 0; i < len(args); i++ {
  890. // Make sure the next argument is a flag and skip if not set
  891. flag, ok := args[i].(cli.Flag)
  892. if !ok {
  893. panic(fmt.Sprintf("invalid argument, not cli.Flag type: %T", args[i]))
  894. }
  895. // Check if next arg extends current and expand its name if so
  896. name := flag.GetName()
  897. if i+1 < len(args) {
  898. switch option := args[i+1].(type) {
  899. case string:
  900. // Extended flag, expand the name and shift the arguments
  901. if ctx.GlobalString(flag.GetName()) == option {
  902. name += "=" + option
  903. }
  904. i++
  905. case cli.Flag:
  906. default:
  907. panic(fmt.Sprintf("invalid argument, not cli.Flag or string extension: %T", args[i+1]))
  908. }
  909. }
  910. // Mark the flag if it's set
  911. if ctx.GlobalIsSet(flag.GetName()) {
  912. set = append(set, "--"+name)
  913. }
  914. }
  915. if len(set) > 1 {
  916. Fatalf("Flags %v can't be used at the same time", strings.Join(set, ", "))
  917. }
  918. }
  919. // SetShhConfig applies shh-related command line flags to the config.
  920. func SetShhConfig(ctx *cli.Context, stack *node.Node, cfg *whisper.Config) {
  921. if ctx.GlobalIsSet(WhisperMaxMessageSizeFlag.Name) {
  922. cfg.MaxMessageSize = uint32(ctx.GlobalUint(WhisperMaxMessageSizeFlag.Name))
  923. }
  924. if ctx.GlobalIsSet(WhisperMinPOWFlag.Name) {
  925. cfg.MinimumAcceptedPOW = ctx.GlobalFloat64(WhisperMinPOWFlag.Name)
  926. }
  927. }
  928. // SetEthConfig applies eth-related command line flags to the config.
  929. func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
  930. // Avoid conflicting network flags
  931. checkExclusive(ctx, DeveloperFlag, TestnetFlag, RinkebyFlag)
  932. checkExclusive(ctx, FastSyncFlag, LightModeFlag, SyncModeFlag)
  933. checkExclusive(ctx, LightServFlag, LightModeFlag)
  934. checkExclusive(ctx, LightServFlag, SyncModeFlag, "light")
  935. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  936. setEtherbase(ctx, ks, cfg)
  937. setGPO(ctx, &cfg.GPO)
  938. setTxPool(ctx, &cfg.TxPool)
  939. setEthash(ctx, cfg)
  940. switch {
  941. case ctx.GlobalIsSet(SyncModeFlag.Name):
  942. cfg.SyncMode = *GlobalTextMarshaler(ctx, SyncModeFlag.Name).(*downloader.SyncMode)
  943. case ctx.GlobalBool(FastSyncFlag.Name):
  944. cfg.SyncMode = downloader.FastSync
  945. case ctx.GlobalBool(LightModeFlag.Name):
  946. cfg.SyncMode = downloader.LightSync
  947. }
  948. if ctx.GlobalIsSet(LightServFlag.Name) {
  949. cfg.LightServ = ctx.GlobalInt(LightServFlag.Name)
  950. }
  951. if ctx.GlobalIsSet(LightPeersFlag.Name) {
  952. cfg.LightPeers = ctx.GlobalInt(LightPeersFlag.Name)
  953. }
  954. if ctx.GlobalIsSet(NetworkIdFlag.Name) {
  955. cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name)
  956. }
  957. if ctx.GlobalIsSet(CacheFlag.Name) {
  958. cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name)
  959. }
  960. cfg.DatabaseHandles = makeDatabaseHandles()
  961. if ctx.GlobalIsSet(MinerThreadsFlag.Name) {
  962. cfg.MinerThreads = ctx.GlobalInt(MinerThreadsFlag.Name)
  963. }
  964. if ctx.GlobalIsSet(DocRootFlag.Name) {
  965. cfg.DocRoot = ctx.GlobalString(DocRootFlag.Name)
  966. }
  967. if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  968. cfg.ExtraData = []byte(ctx.GlobalString(ExtraDataFlag.Name))
  969. }
  970. if ctx.GlobalIsSet(GasPriceFlag.Name) {
  971. cfg.GasPrice = GlobalBig(ctx, GasPriceFlag.Name)
  972. }
  973. if ctx.GlobalIsSet(VMEnableDebugFlag.Name) {
  974. // TODO(fjl): force-enable this in --dev mode
  975. cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name)
  976. }
  977. // Override any default configs for hard coded networks.
  978. switch {
  979. case ctx.GlobalBool(TestnetFlag.Name):
  980. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  981. cfg.NetworkId = 3
  982. }
  983. cfg.Genesis = core.DefaultTestnetGenesisBlock()
  984. case ctx.GlobalBool(RinkebyFlag.Name):
  985. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  986. cfg.NetworkId = 4
  987. }
  988. cfg.Genesis = core.DefaultRinkebyGenesisBlock()
  989. case ctx.GlobalBool(DeveloperFlag.Name):
  990. // Create new developer account or reuse existing one
  991. var (
  992. developer accounts.Account
  993. err error
  994. )
  995. if accs := ks.Accounts(); len(accs) > 0 {
  996. developer = ks.Accounts()[0]
  997. } else {
  998. developer, err = ks.NewAccount("")
  999. if err != nil {
  1000. Fatalf("Failed to create developer account: %v", err)
  1001. }
  1002. }
  1003. if err := ks.Unlock(developer, ""); err != nil {
  1004. Fatalf("Failed to unlock developer account: %v", err)
  1005. }
  1006. log.Info("Using developer account", "address", developer.Address)
  1007. cfg.Genesis = core.DeveloperGenesisBlock(uint64(ctx.GlobalInt(DeveloperPeriodFlag.Name)), developer.Address)
  1008. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  1009. cfg.GasPrice = big.NewInt(1)
  1010. }
  1011. }
  1012. // TODO(fjl): move trie cache generations into config
  1013. if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  1014. state.MaxTrieCacheGen = uint16(gen)
  1015. }
  1016. }
  1017. // SetDashboardConfig applies dashboard related command line flags to the config.
  1018. func SetDashboardConfig(ctx *cli.Context, cfg *dashboard.Config) {
  1019. cfg.Host = ctx.GlobalString(DashboardAddrFlag.Name)
  1020. cfg.Port = ctx.GlobalInt(DashboardPortFlag.Name)
  1021. cfg.Refresh = ctx.GlobalDuration(DashboardRefreshFlag.Name)
  1022. cfg.Assets = ctx.GlobalString(DashboardAssetsFlag.Name)
  1023. }
  1024. // RegisterEthService adds an Ethereum client to the stack.
  1025. func RegisterEthService(stack *node.Node, cfg *eth.Config) {
  1026. var err error
  1027. if cfg.SyncMode == downloader.LightSync {
  1028. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1029. return les.New(ctx, cfg)
  1030. })
  1031. } else {
  1032. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1033. fullNode, err := eth.New(ctx, cfg)
  1034. if fullNode != nil && cfg.LightServ > 0 {
  1035. ls, _ := les.NewLesServer(fullNode, cfg)
  1036. fullNode.AddLesServer(ls)
  1037. }
  1038. return fullNode, err
  1039. })
  1040. }
  1041. if err != nil {
  1042. Fatalf("Failed to register the Ethereum service: %v", err)
  1043. }
  1044. }
  1045. // RegisterDashboardService adds a dashboard to the stack.
  1046. func RegisterDashboardService(stack *node.Node, cfg *dashboard.Config) {
  1047. stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1048. return dashboard.New(cfg)
  1049. })
  1050. }
  1051. // RegisterShhService configures Whisper and adds it to the given node.
  1052. func RegisterShhService(stack *node.Node, cfg *whisper.Config) {
  1053. if err := stack.Register(func(n *node.ServiceContext) (node.Service, error) {
  1054. return whisper.New(cfg), nil
  1055. }); err != nil {
  1056. Fatalf("Failed to register the Whisper service: %v", err)
  1057. }
  1058. }
  1059. // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  1060. // th egiven node.
  1061. func RegisterEthStatsService(stack *node.Node, url string) {
  1062. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1063. // Retrieve both eth and les services
  1064. var ethServ *eth.Ethereum
  1065. ctx.Service(&ethServ)
  1066. var lesServ *les.LightEthereum
  1067. ctx.Service(&lesServ)
  1068. return ethstats.New(url, ethServ, lesServ)
  1069. }); err != nil {
  1070. Fatalf("Failed to register the Ethereum Stats service: %v", err)
  1071. }
  1072. }
  1073. // SetupNetwork configures the system for either the main net or some test network.
  1074. func SetupNetwork(ctx *cli.Context) {
  1075. // TODO(fjl): move target gas limit into config
  1076. params.TargetGasLimit = new(big.Int).SetUint64(ctx.GlobalUint64(TargetGasLimitFlag.Name))
  1077. }
  1078. // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  1079. func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  1080. var (
  1081. cache = ctx.GlobalInt(CacheFlag.Name)
  1082. handles = makeDatabaseHandles()
  1083. )
  1084. name := "chaindata"
  1085. if ctx.GlobalBool(LightModeFlag.Name) {
  1086. name = "lightchaindata"
  1087. }
  1088. chainDb, err := stack.OpenDatabase(name, cache, handles)
  1089. if err != nil {
  1090. Fatalf("Could not open database: %v", err)
  1091. }
  1092. return chainDb
  1093. }
  1094. func MakeGenesis(ctx *cli.Context) *core.Genesis {
  1095. var genesis *core.Genesis
  1096. switch {
  1097. case ctx.GlobalBool(TestnetFlag.Name):
  1098. genesis = core.DefaultTestnetGenesisBlock()
  1099. case ctx.GlobalBool(RinkebyFlag.Name):
  1100. genesis = core.DefaultRinkebyGenesisBlock()
  1101. case ctx.GlobalBool(DeveloperFlag.Name):
  1102. Fatalf("Developer chains are ephemeral")
  1103. }
  1104. return genesis
  1105. }
  1106. // MakeChain creates a chain manager from set command line flags.
  1107. func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  1108. var err error
  1109. chainDb = MakeChainDatabase(ctx, stack)
  1110. config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx))
  1111. if err != nil {
  1112. Fatalf("%v", err)
  1113. }
  1114. var engine consensus.Engine
  1115. if config.Clique != nil {
  1116. engine = clique.New(config.Clique, chainDb)
  1117. } else {
  1118. engine = ethash.NewFaker()
  1119. if !ctx.GlobalBool(FakePoWFlag.Name) {
  1120. engine = ethash.New(ethash.Config{
  1121. CacheDir: stack.ResolvePath(eth.DefaultConfig.Ethash.CacheDir),
  1122. CachesInMem: eth.DefaultConfig.Ethash.CachesInMem,
  1123. CachesOnDisk: eth.DefaultConfig.Ethash.CachesOnDisk,
  1124. DatasetDir: stack.ResolvePath(eth.DefaultConfig.Ethash.DatasetDir),
  1125. DatasetsInMem: eth.DefaultConfig.Ethash.DatasetsInMem,
  1126. DatasetsOnDisk: eth.DefaultConfig.Ethash.DatasetsOnDisk,
  1127. })
  1128. }
  1129. }
  1130. vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
  1131. chain, err = core.NewBlockChain(chainDb, config, engine, vmcfg)
  1132. if err != nil {
  1133. Fatalf("Can't create BlockChain: %v", err)
  1134. }
  1135. return chain, chainDb
  1136. }
  1137. // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  1138. // scripts to preload before starting.
  1139. func MakeConsolePreloads(ctx *cli.Context) []string {
  1140. // Skip preloading if there's nothing to preload
  1141. if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  1142. return nil
  1143. }
  1144. // Otherwise resolve absolute paths and return them
  1145. preloads := []string{}
  1146. assets := ctx.GlobalString(JSpathFlag.Name)
  1147. for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  1148. preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  1149. }
  1150. return preloads
  1151. }
  1152. // MigrateFlags sets the global flag from a local flag when it's set.
  1153. // This is a temporary function used for migrating old command/flags to the
  1154. // new format.
  1155. //
  1156. // e.g. geth account new --keystore /tmp/mykeystore --lightkdf
  1157. //
  1158. // is equivalent after calling this method with:
  1159. //
  1160. // geth --keystore /tmp/mykeystore --lightkdf account new
  1161. //
  1162. // This allows the use of the existing configuration functionality.
  1163. // When all flags are migrated this function can be removed and the existing
  1164. // configuration functionality must be changed that is uses local flags
  1165. func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error {
  1166. return func(ctx *cli.Context) error {
  1167. for _, name := range ctx.FlagNames() {
  1168. if ctx.IsSet(name) {
  1169. ctx.GlobalSet(name, ctx.String(name))
  1170. }
  1171. }
  1172. return action(ctx)
  1173. }
  1174. }