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