flags.go 42 KB

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