flags.go 46 KB

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