flags.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  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. "errors"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "math/big"
  25. "os"
  26. "path/filepath"
  27. "strconv"
  28. "strings"
  29. "text/tabwriter"
  30. "text/template"
  31. "time"
  32. "github.com/ethereum/go-ethereum/accounts"
  33. "github.com/ethereum/go-ethereum/accounts/keystore"
  34. "github.com/ethereum/go-ethereum/common"
  35. "github.com/ethereum/go-ethereum/common/fdlimit"
  36. "github.com/ethereum/go-ethereum/consensus"
  37. "github.com/ethereum/go-ethereum/consensus/clique"
  38. "github.com/ethereum/go-ethereum/consensus/ethash"
  39. "github.com/ethereum/go-ethereum/core"
  40. "github.com/ethereum/go-ethereum/core/vm"
  41. "github.com/ethereum/go-ethereum/crypto"
  42. "github.com/ethereum/go-ethereum/eth"
  43. "github.com/ethereum/go-ethereum/eth/downloader"
  44. "github.com/ethereum/go-ethereum/eth/gasprice"
  45. "github.com/ethereum/go-ethereum/ethdb"
  46. "github.com/ethereum/go-ethereum/ethstats"
  47. "github.com/ethereum/go-ethereum/graphql"
  48. "github.com/ethereum/go-ethereum/les"
  49. "github.com/ethereum/go-ethereum/log"
  50. "github.com/ethereum/go-ethereum/metrics"
  51. "github.com/ethereum/go-ethereum/metrics/influxdb"
  52. "github.com/ethereum/go-ethereum/miner"
  53. "github.com/ethereum/go-ethereum/node"
  54. "github.com/ethereum/go-ethereum/p2p"
  55. "github.com/ethereum/go-ethereum/p2p/discv5"
  56. "github.com/ethereum/go-ethereum/p2p/enode"
  57. "github.com/ethereum/go-ethereum/p2p/nat"
  58. "github.com/ethereum/go-ethereum/p2p/netutil"
  59. "github.com/ethereum/go-ethereum/params"
  60. "github.com/ethereum/go-ethereum/rpc"
  61. whisper "github.com/ethereum/go-ethereum/whisper/whisperv6"
  62. pcsclite "github.com/gballet/go-libpcsclite"
  63. cli "gopkg.in/urfave/cli.v1"
  64. )
  65. var (
  66. CommandHelpTemplate = `{{.cmd.Name}}{{if .cmd.Subcommands}} command{{end}}{{if .cmd.Flags}} [command options]{{end}} [arguments...]
  67. {{if .cmd.Description}}{{.cmd.Description}}
  68. {{end}}{{if .cmd.Subcommands}}
  69. SUBCOMMANDS:
  70. {{range .cmd.Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  71. {{end}}{{end}}{{if .categorizedFlags}}
  72. {{range $idx, $categorized := .categorizedFlags}}{{$categorized.Name}} OPTIONS:
  73. {{range $categorized.Flags}}{{"\t"}}{{.}}
  74. {{end}}
  75. {{end}}{{end}}`
  76. OriginCommandHelpTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...]
  77. {{if .Description}}{{.Description}}
  78. {{end}}{{if .Subcommands}}
  79. SUBCOMMANDS:
  80. {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  81. {{end}}{{end}}{{if .Flags}}
  82. OPTIONS:
  83. {{range $.Flags}}{{"\t"}}{{.}}
  84. {{end}}
  85. {{end}}`
  86. )
  87. func init() {
  88. cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
  89. VERSION:
  90. {{.Version}}
  91. COMMANDS:
  92. {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  93. {{end}}{{if .Flags}}
  94. GLOBAL OPTIONS:
  95. {{range .Flags}}{{.}}
  96. {{end}}{{end}}
  97. `
  98. cli.CommandHelpTemplate = CommandHelpTemplate
  99. cli.HelpPrinter = printHelp
  100. }
  101. // NewApp creates an app with sane defaults.
  102. func NewApp(gitCommit, gitDate, usage string) *cli.App {
  103. app := cli.NewApp()
  104. app.Name = filepath.Base(os.Args[0])
  105. app.Author = ""
  106. app.Email = ""
  107. app.Version = params.VersionWithCommit(gitCommit, gitDate)
  108. app.Usage = usage
  109. return app
  110. }
  111. func printHelp(out io.Writer, templ string, data interface{}) {
  112. funcMap := template.FuncMap{"join": strings.Join}
  113. t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
  114. w := tabwriter.NewWriter(out, 38, 8, 2, ' ', 0)
  115. err := t.Execute(w, data)
  116. if err != nil {
  117. panic(err)
  118. }
  119. w.Flush()
  120. }
  121. // These are all the command line flags we support.
  122. // If you add to this list, please remember to include the
  123. // flag in the appropriate command definition.
  124. //
  125. // The flags are defined here so their names and help texts
  126. // are the same for all commands.
  127. var (
  128. // General settings
  129. DataDirFlag = DirectoryFlag{
  130. Name: "datadir",
  131. Usage: "Data directory for the databases and keystore",
  132. Value: DirectoryString(node.DefaultDataDir()),
  133. }
  134. AncientFlag = DirectoryFlag{
  135. Name: "datadir.ancient",
  136. Usage: "Data directory for ancient chain segments (default = inside chaindata)",
  137. }
  138. KeyStoreDirFlag = DirectoryFlag{
  139. Name: "keystore",
  140. Usage: "Directory for the keystore (default = inside the datadir)",
  141. }
  142. NoUSBFlag = cli.BoolFlag{
  143. Name: "nousb",
  144. Usage: "Disables monitoring for and managing USB hardware wallets",
  145. }
  146. SmartCardDaemonPathFlag = cli.StringFlag{
  147. Name: "pcscdpath",
  148. Usage: "Path to the smartcard daemon (pcscd) socket file",
  149. Value: pcsclite.PCSCDSockName,
  150. }
  151. NetworkIdFlag = cli.Uint64Flag{
  152. Name: "networkid",
  153. Usage: "Network identifier (integer, 1=Frontier, 2=Morden (disused), 3=Ropsten, 4=Rinkeby)",
  154. Value: eth.DefaultConfig.NetworkId,
  155. }
  156. TestnetFlag = cli.BoolFlag{
  157. Name: "testnet",
  158. Usage: "Ropsten network: pre-configured proof-of-work test network",
  159. }
  160. RinkebyFlag = cli.BoolFlag{
  161. Name: "rinkeby",
  162. Usage: "Rinkeby network: pre-configured proof-of-authority test network",
  163. }
  164. GoerliFlag = cli.BoolFlag{
  165. Name: "goerli",
  166. Usage: "Görli network: pre-configured proof-of-authority test network",
  167. }
  168. DeveloperFlag = cli.BoolFlag{
  169. Name: "dev",
  170. Usage: "Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled",
  171. }
  172. DeveloperPeriodFlag = cli.IntFlag{
  173. Name: "dev.period",
  174. Usage: "Block period to use in developer mode (0 = mine only if transaction pending)",
  175. }
  176. IdentityFlag = cli.StringFlag{
  177. Name: "identity",
  178. Usage: "Custom node name",
  179. }
  180. DocRootFlag = DirectoryFlag{
  181. Name: "docroot",
  182. Usage: "Document Root for HTTPClient file scheme",
  183. Value: DirectoryString(homeDir()),
  184. }
  185. ExitWhenSyncedFlag = cli.BoolFlag{
  186. Name: "exitwhensynced",
  187. Usage: "Exits after block synchronisation completes",
  188. }
  189. IterativeOutputFlag = cli.BoolFlag{
  190. Name: "iterative",
  191. Usage: "Print streaming JSON iteratively, delimited by newlines",
  192. }
  193. ExcludeStorageFlag = cli.BoolFlag{
  194. Name: "nostorage",
  195. Usage: "Exclude storage entries (save db lookups)",
  196. }
  197. IncludeIncompletesFlag = cli.BoolFlag{
  198. Name: "incompletes",
  199. Usage: "Include accounts for which we don't have the address (missing preimage)",
  200. }
  201. ExcludeCodeFlag = cli.BoolFlag{
  202. Name: "nocode",
  203. Usage: "Exclude contract code (save db lookups)",
  204. }
  205. defaultSyncMode = eth.DefaultConfig.SyncMode
  206. SyncModeFlag = TextMarshalerFlag{
  207. Name: "syncmode",
  208. Usage: `Blockchain sync mode ("fast", "full", or "light")`,
  209. Value: &defaultSyncMode,
  210. }
  211. GCModeFlag = cli.StringFlag{
  212. Name: "gcmode",
  213. Usage: `Blockchain garbage collection mode ("full", "archive")`,
  214. Value: "full",
  215. }
  216. LightKDFFlag = cli.BoolFlag{
  217. Name: "lightkdf",
  218. Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
  219. }
  220. WhitelistFlag = cli.StringFlag{
  221. Name: "whitelist",
  222. Usage: "Comma separated block number-to-hash mappings to enforce (<number>=<hash>)",
  223. }
  224. OverrideIstanbulFlag = cli.Uint64Flag{
  225. Name: "override.istanbul",
  226. Usage: "Manually specify Istanbul fork-block, overriding the bundled setting",
  227. }
  228. OverrideMuirGlacierFlag = cli.Uint64Flag{
  229. Name: "override.muirglacier",
  230. Usage: "Manually specify Muir Glacier fork-block, overriding the bundled setting",
  231. }
  232. // Light server and client settings
  233. LightLegacyServFlag = cli.IntFlag{ // Deprecated in favor of light.serve, remove in 2021
  234. Name: "lightserv",
  235. Usage: "Maximum percentage of time allowed for serving LES requests (deprecated, use --light.serve)",
  236. Value: eth.DefaultConfig.LightServ,
  237. }
  238. LightServeFlag = cli.IntFlag{
  239. Name: "light.serve",
  240. Usage: "Maximum percentage of time allowed for serving LES requests (multi-threaded processing allows values over 100)",
  241. Value: eth.DefaultConfig.LightServ,
  242. }
  243. LightIngressFlag = cli.IntFlag{
  244. Name: "light.ingress",
  245. Usage: "Incoming bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited)",
  246. Value: eth.DefaultConfig.LightIngress,
  247. }
  248. LightEgressFlag = cli.IntFlag{
  249. Name: "light.egress",
  250. Usage: "Outgoing bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited)",
  251. Value: eth.DefaultConfig.LightEgress,
  252. }
  253. LightLegacyPeersFlag = cli.IntFlag{ // Deprecated in favor of light.maxpeers, remove in 2021
  254. Name: "lightpeers",
  255. Usage: "Maximum number of light clients to serve, or light servers to attach to (deprecated, use --light.maxpeers)",
  256. Value: eth.DefaultConfig.LightPeers,
  257. }
  258. LightMaxPeersFlag = cli.IntFlag{
  259. Name: "light.maxpeers",
  260. Usage: "Maximum number of light clients to serve, or light servers to attach to",
  261. Value: eth.DefaultConfig.LightPeers,
  262. }
  263. UltraLightServersFlag = cli.StringFlag{
  264. Name: "ulc.servers",
  265. Usage: "List of trusted ultra-light servers",
  266. Value: strings.Join(eth.DefaultConfig.UltraLightServers, ","),
  267. }
  268. UltraLightFractionFlag = cli.IntFlag{
  269. Name: "ulc.fraction",
  270. Usage: "Minimum % of trusted ultra-light servers required to announce a new head",
  271. Value: eth.DefaultConfig.UltraLightFraction,
  272. }
  273. UltraLightOnlyAnnounceFlag = cli.BoolFlag{
  274. Name: "ulc.onlyannounce",
  275. Usage: "Ultra light server sends announcements only",
  276. }
  277. // Ethash settings
  278. EthashCacheDirFlag = DirectoryFlag{
  279. Name: "ethash.cachedir",
  280. Usage: "Directory to store the ethash verification caches (default = inside the datadir)",
  281. }
  282. EthashCachesInMemoryFlag = cli.IntFlag{
  283. Name: "ethash.cachesinmem",
  284. Usage: "Number of recent ethash caches to keep in memory (16MB each)",
  285. Value: eth.DefaultConfig.Ethash.CachesInMem,
  286. }
  287. EthashCachesOnDiskFlag = cli.IntFlag{
  288. Name: "ethash.cachesondisk",
  289. Usage: "Number of recent ethash caches to keep on disk (16MB each)",
  290. Value: eth.DefaultConfig.Ethash.CachesOnDisk,
  291. }
  292. EthashDatasetDirFlag = DirectoryFlag{
  293. Name: "ethash.dagdir",
  294. Usage: "Directory to store the ethash mining DAGs",
  295. Value: DirectoryString(eth.DefaultConfig.Ethash.DatasetDir),
  296. }
  297. EthashDatasetsInMemoryFlag = cli.IntFlag{
  298. Name: "ethash.dagsinmem",
  299. Usage: "Number of recent ethash mining DAGs to keep in memory (1+GB each)",
  300. Value: eth.DefaultConfig.Ethash.DatasetsInMem,
  301. }
  302. EthashDatasetsOnDiskFlag = cli.IntFlag{
  303. Name: "ethash.dagsondisk",
  304. Usage: "Number of recent ethash mining DAGs to keep on disk (1+GB each)",
  305. Value: eth.DefaultConfig.Ethash.DatasetsOnDisk,
  306. }
  307. // Transaction pool settings
  308. TxPoolLocalsFlag = cli.StringFlag{
  309. Name: "txpool.locals",
  310. Usage: "Comma separated accounts to treat as locals (no flush, priority inclusion)",
  311. }
  312. TxPoolNoLocalsFlag = cli.BoolFlag{
  313. Name: "txpool.nolocals",
  314. Usage: "Disables price exemptions for locally submitted transactions",
  315. }
  316. TxPoolJournalFlag = cli.StringFlag{
  317. Name: "txpool.journal",
  318. Usage: "Disk journal for local transaction to survive node restarts",
  319. Value: core.DefaultTxPoolConfig.Journal,
  320. }
  321. TxPoolRejournalFlag = cli.DurationFlag{
  322. Name: "txpool.rejournal",
  323. Usage: "Time interval to regenerate the local transaction journal",
  324. Value: core.DefaultTxPoolConfig.Rejournal,
  325. }
  326. TxPoolPriceLimitFlag = cli.Uint64Flag{
  327. Name: "txpool.pricelimit",
  328. Usage: "Minimum gas price limit to enforce for acceptance into the pool",
  329. Value: eth.DefaultConfig.TxPool.PriceLimit,
  330. }
  331. TxPoolPriceBumpFlag = cli.Uint64Flag{
  332. Name: "txpool.pricebump",
  333. Usage: "Price bump percentage to replace an already existing transaction",
  334. Value: eth.DefaultConfig.TxPool.PriceBump,
  335. }
  336. TxPoolAccountSlotsFlag = cli.Uint64Flag{
  337. Name: "txpool.accountslots",
  338. Usage: "Minimum number of executable transaction slots guaranteed per account",
  339. Value: eth.DefaultConfig.TxPool.AccountSlots,
  340. }
  341. TxPoolGlobalSlotsFlag = cli.Uint64Flag{
  342. Name: "txpool.globalslots",
  343. Usage: "Maximum number of executable transaction slots for all accounts",
  344. Value: eth.DefaultConfig.TxPool.GlobalSlots,
  345. }
  346. TxPoolAccountQueueFlag = cli.Uint64Flag{
  347. Name: "txpool.accountqueue",
  348. Usage: "Maximum number of non-executable transaction slots permitted per account",
  349. Value: eth.DefaultConfig.TxPool.AccountQueue,
  350. }
  351. TxPoolGlobalQueueFlag = cli.Uint64Flag{
  352. Name: "txpool.globalqueue",
  353. Usage: "Maximum number of non-executable transaction slots for all accounts",
  354. Value: eth.DefaultConfig.TxPool.GlobalQueue,
  355. }
  356. TxPoolLifetimeFlag = cli.DurationFlag{
  357. Name: "txpool.lifetime",
  358. Usage: "Maximum amount of time non-executable transaction are queued",
  359. Value: eth.DefaultConfig.TxPool.Lifetime,
  360. }
  361. // Performance tuning settings
  362. CacheFlag = cli.IntFlag{
  363. Name: "cache",
  364. Usage: "Megabytes of memory allocated to internal caching (default = 4096 mainnet full node, 128 light mode)",
  365. Value: 1024,
  366. }
  367. CacheDatabaseFlag = cli.IntFlag{
  368. Name: "cache.database",
  369. Usage: "Percentage of cache memory allowance to use for database io",
  370. Value: 50,
  371. }
  372. CacheTrieFlag = cli.IntFlag{
  373. Name: "cache.trie",
  374. Usage: "Percentage of cache memory allowance to use for trie caching (default = 15% full mode, 30% archive mode)",
  375. Value: 15,
  376. }
  377. CacheGCFlag = cli.IntFlag{
  378. Name: "cache.gc",
  379. Usage: "Percentage of cache memory allowance to use for trie pruning (default = 25% full mode, 0% archive mode)",
  380. Value: 25,
  381. }
  382. CacheSnapshotFlag = cli.IntFlag{
  383. Name: "cache.snapshot",
  384. Usage: "Percentage of cache memory allowance to use for snapshot caching (default = 10% full mode, 20% archive mode)",
  385. Value: 10,
  386. }
  387. CacheNoPrefetchFlag = cli.BoolFlag{
  388. Name: "cache.noprefetch",
  389. Usage: "Disable heuristic state prefetch during block import (less CPU and disk IO, more time waiting for data)",
  390. }
  391. // Miner settings
  392. MiningEnabledFlag = cli.BoolFlag{
  393. Name: "mine",
  394. Usage: "Enable mining",
  395. }
  396. MinerThreadsFlag = cli.IntFlag{
  397. Name: "miner.threads",
  398. Usage: "Number of CPU threads to use for mining",
  399. Value: 0,
  400. }
  401. MinerLegacyThreadsFlag = cli.IntFlag{
  402. Name: "minerthreads",
  403. Usage: "Number of CPU threads to use for mining (deprecated, use --miner.threads)",
  404. Value: 0,
  405. }
  406. MinerNotifyFlag = cli.StringFlag{
  407. Name: "miner.notify",
  408. Usage: "Comma separated HTTP URL list to notify of new work packages",
  409. }
  410. MinerGasTargetFlag = cli.Uint64Flag{
  411. Name: "miner.gastarget",
  412. Usage: "Target gas floor for mined blocks",
  413. Value: eth.DefaultConfig.Miner.GasFloor,
  414. }
  415. MinerLegacyGasTargetFlag = cli.Uint64Flag{
  416. Name: "targetgaslimit",
  417. Usage: "Target gas floor for mined blocks (deprecated, use --miner.gastarget)",
  418. Value: eth.DefaultConfig.Miner.GasFloor,
  419. }
  420. MinerGasLimitFlag = cli.Uint64Flag{
  421. Name: "miner.gaslimit",
  422. Usage: "Target gas ceiling for mined blocks",
  423. Value: eth.DefaultConfig.Miner.GasCeil,
  424. }
  425. MinerGasPriceFlag = BigFlag{
  426. Name: "miner.gasprice",
  427. Usage: "Minimum gas price for mining a transaction",
  428. Value: eth.DefaultConfig.Miner.GasPrice,
  429. }
  430. MinerLegacyGasPriceFlag = BigFlag{
  431. Name: "gasprice",
  432. Usage: "Minimum gas price for mining a transaction (deprecated, use --miner.gasprice)",
  433. Value: eth.DefaultConfig.Miner.GasPrice,
  434. }
  435. MinerEtherbaseFlag = cli.StringFlag{
  436. Name: "miner.etherbase",
  437. Usage: "Public address for block mining rewards (default = first account)",
  438. Value: "0",
  439. }
  440. MinerLegacyEtherbaseFlag = cli.StringFlag{
  441. Name: "etherbase",
  442. Usage: "Public address for block mining rewards (default = first account, deprecated, use --miner.etherbase)",
  443. Value: "0",
  444. }
  445. MinerExtraDataFlag = cli.StringFlag{
  446. Name: "miner.extradata",
  447. Usage: "Block extra data set by the miner (default = client version)",
  448. }
  449. MinerLegacyExtraDataFlag = cli.StringFlag{
  450. Name: "extradata",
  451. Usage: "Block extra data set by the miner (default = client version, deprecated, use --miner.extradata)",
  452. }
  453. MinerRecommitIntervalFlag = cli.DurationFlag{
  454. Name: "miner.recommit",
  455. Usage: "Time interval to recreate the block being mined",
  456. Value: eth.DefaultConfig.Miner.Recommit,
  457. }
  458. MinerNoVerfiyFlag = cli.BoolFlag{
  459. Name: "miner.noverify",
  460. Usage: "Disable remote sealing verification",
  461. }
  462. // Account settings
  463. UnlockedAccountFlag = cli.StringFlag{
  464. Name: "unlock",
  465. Usage: "Comma separated list of accounts to unlock",
  466. Value: "",
  467. }
  468. PasswordFileFlag = cli.StringFlag{
  469. Name: "password",
  470. Usage: "Password file to use for non-interactive password input",
  471. Value: "",
  472. }
  473. ExternalSignerFlag = cli.StringFlag{
  474. Name: "signer",
  475. Usage: "External signer (url or path to ipc file)",
  476. Value: "",
  477. }
  478. VMEnableDebugFlag = cli.BoolFlag{
  479. Name: "vmdebug",
  480. Usage: "Record information useful for VM and contract debugging",
  481. }
  482. InsecureUnlockAllowedFlag = cli.BoolFlag{
  483. Name: "allow-insecure-unlock",
  484. Usage: "Allow insecure account unlocking when account-related RPCs are exposed by http",
  485. }
  486. RPCGlobalGasCap = cli.Uint64Flag{
  487. Name: "rpc.gascap",
  488. Usage: "Sets a cap on gas that can be used in eth_call/estimateGas",
  489. }
  490. // Logging and debug settings
  491. EthStatsURLFlag = cli.StringFlag{
  492. Name: "ethstats",
  493. Usage: "Reporting URL of a ethstats service (nodename:secret@host:port)",
  494. }
  495. FakePoWFlag = cli.BoolFlag{
  496. Name: "fakepow",
  497. Usage: "Disables proof-of-work verification",
  498. }
  499. NoCompactionFlag = cli.BoolFlag{
  500. Name: "nocompaction",
  501. Usage: "Disables db compaction after import",
  502. }
  503. // RPC settings
  504. IPCDisabledFlag = cli.BoolFlag{
  505. Name: "ipcdisable",
  506. Usage: "Disable the IPC-RPC server",
  507. }
  508. IPCPathFlag = DirectoryFlag{
  509. Name: "ipcpath",
  510. Usage: "Filename for IPC socket/pipe within the datadir (explicit paths escape it)",
  511. }
  512. RPCEnabledFlag = cli.BoolFlag{
  513. Name: "rpc",
  514. Usage: "Enable the HTTP-RPC server",
  515. }
  516. RPCListenAddrFlag = cli.StringFlag{
  517. Name: "rpcaddr",
  518. Usage: "HTTP-RPC server listening interface",
  519. Value: node.DefaultHTTPHost,
  520. }
  521. RPCPortFlag = cli.IntFlag{
  522. Name: "rpcport",
  523. Usage: "HTTP-RPC server listening port",
  524. Value: node.DefaultHTTPPort,
  525. }
  526. RPCCORSDomainFlag = cli.StringFlag{
  527. Name: "rpccorsdomain",
  528. Usage: "Comma separated list of domains from which to accept cross origin requests (browser enforced)",
  529. Value: "",
  530. }
  531. RPCVirtualHostsFlag = cli.StringFlag{
  532. Name: "rpcvhosts",
  533. Usage: "Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard.",
  534. Value: strings.Join(node.DefaultConfig.HTTPVirtualHosts, ","),
  535. }
  536. RPCApiFlag = cli.StringFlag{
  537. Name: "rpcapi",
  538. Usage: "API's offered over the HTTP-RPC interface",
  539. Value: "",
  540. }
  541. WSEnabledFlag = cli.BoolFlag{
  542. Name: "ws",
  543. Usage: "Enable the WS-RPC server",
  544. }
  545. WSListenAddrFlag = cli.StringFlag{
  546. Name: "wsaddr",
  547. Usage: "WS-RPC server listening interface",
  548. Value: node.DefaultWSHost,
  549. }
  550. WSPortFlag = cli.IntFlag{
  551. Name: "wsport",
  552. Usage: "WS-RPC server listening port",
  553. Value: node.DefaultWSPort,
  554. }
  555. WSApiFlag = cli.StringFlag{
  556. Name: "wsapi",
  557. Usage: "API's offered over the WS-RPC interface",
  558. Value: "",
  559. }
  560. WSAllowedOriginsFlag = cli.StringFlag{
  561. Name: "wsorigins",
  562. Usage: "Origins from which to accept websockets requests",
  563. Value: "",
  564. }
  565. GraphQLEnabledFlag = cli.BoolFlag{
  566. Name: "graphql",
  567. Usage: "Enable the GraphQL server",
  568. }
  569. GraphQLListenAddrFlag = cli.StringFlag{
  570. Name: "graphql.addr",
  571. Usage: "GraphQL server listening interface",
  572. Value: node.DefaultGraphQLHost,
  573. }
  574. GraphQLPortFlag = cli.IntFlag{
  575. Name: "graphql.port",
  576. Usage: "GraphQL server listening port",
  577. Value: node.DefaultGraphQLPort,
  578. }
  579. GraphQLCORSDomainFlag = cli.StringFlag{
  580. Name: "graphql.corsdomain",
  581. Usage: "Comma separated list of domains from which to accept cross origin requests (browser enforced)",
  582. Value: "",
  583. }
  584. GraphQLVirtualHostsFlag = cli.StringFlag{
  585. Name: "graphql.vhosts",
  586. Usage: "Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard.",
  587. Value: strings.Join(node.DefaultConfig.GraphQLVirtualHosts, ","),
  588. }
  589. ExecFlag = cli.StringFlag{
  590. Name: "exec",
  591. Usage: "Execute JavaScript statement",
  592. }
  593. PreloadJSFlag = cli.StringFlag{
  594. Name: "preload",
  595. Usage: "Comma separated list of JavaScript files to preload into the console",
  596. }
  597. // Network Settings
  598. MaxPeersFlag = cli.IntFlag{
  599. Name: "maxpeers",
  600. Usage: "Maximum number of network peers (network disabled if set to 0)",
  601. Value: node.DefaultConfig.P2P.MaxPeers,
  602. }
  603. MaxPendingPeersFlag = cli.IntFlag{
  604. Name: "maxpendpeers",
  605. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  606. Value: node.DefaultConfig.P2P.MaxPendingPeers,
  607. }
  608. ListenPortFlag = cli.IntFlag{
  609. Name: "port",
  610. Usage: "Network listening port",
  611. Value: 30303,
  612. }
  613. BootnodesFlag = cli.StringFlag{
  614. Name: "bootnodes",
  615. Usage: "Comma separated enode URLs for P2P discovery bootstrap (set v4+v5 instead for light servers)",
  616. Value: "",
  617. }
  618. BootnodesV4Flag = cli.StringFlag{
  619. Name: "bootnodesv4",
  620. Usage: "Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes)",
  621. Value: "",
  622. }
  623. BootnodesV5Flag = cli.StringFlag{
  624. Name: "bootnodesv5",
  625. Usage: "Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes)",
  626. Value: "",
  627. }
  628. NodeKeyFileFlag = cli.StringFlag{
  629. Name: "nodekey",
  630. Usage: "P2P node key file",
  631. }
  632. NodeKeyHexFlag = cli.StringFlag{
  633. Name: "nodekeyhex",
  634. Usage: "P2P node key as hex (for testing)",
  635. }
  636. NATFlag = cli.StringFlag{
  637. Name: "nat",
  638. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  639. Value: "any",
  640. }
  641. NoDiscoverFlag = cli.BoolFlag{
  642. Name: "nodiscover",
  643. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  644. }
  645. DiscoveryV5Flag = cli.BoolFlag{
  646. Name: "v5disc",
  647. Usage: "Enables the experimental RLPx V5 (Topic Discovery) mechanism",
  648. }
  649. NetrestrictFlag = cli.StringFlag{
  650. Name: "netrestrict",
  651. Usage: "Restricts network communication to the given IP networks (CIDR masks)",
  652. }
  653. DNSDiscoveryFlag = cli.StringFlag{
  654. Name: "discovery.dns",
  655. Usage: "Sets DNS discovery entry points (use \"\" to disable DNS)",
  656. }
  657. // ATM the url is left to the user and deployment to
  658. JSpathFlag = cli.StringFlag{
  659. Name: "jspath",
  660. Usage: "JavaScript root path for `loadScript`",
  661. Value: ".",
  662. }
  663. // Gas price oracle settings
  664. GpoBlocksFlag = cli.IntFlag{
  665. Name: "gpoblocks",
  666. Usage: "Number of recent blocks to check for gas prices",
  667. Value: eth.DefaultConfig.GPO.Blocks,
  668. }
  669. GpoPercentileFlag = cli.IntFlag{
  670. Name: "gpopercentile",
  671. Usage: "Suggested gas price is the given percentile of a set of recent transaction gas prices",
  672. Value: eth.DefaultConfig.GPO.Percentile,
  673. }
  674. WhisperEnabledFlag = cli.BoolFlag{
  675. Name: "shh",
  676. Usage: "Enable Whisper",
  677. }
  678. WhisperMaxMessageSizeFlag = cli.IntFlag{
  679. Name: "shh.maxmessagesize",
  680. Usage: "Max message size accepted",
  681. Value: int(whisper.DefaultMaxMessageSize),
  682. }
  683. WhisperMinPOWFlag = cli.Float64Flag{
  684. Name: "shh.pow",
  685. Usage: "Minimum POW accepted",
  686. Value: whisper.DefaultMinimumPoW,
  687. }
  688. WhisperRestrictConnectionBetweenLightClientsFlag = cli.BoolFlag{
  689. Name: "shh.restrict-light",
  690. Usage: "Restrict connection between two whisper light clients",
  691. }
  692. // Metrics flags
  693. MetricsEnabledFlag = cli.BoolFlag{
  694. Name: "metrics",
  695. Usage: "Enable metrics collection and reporting",
  696. }
  697. MetricsEnabledExpensiveFlag = cli.BoolFlag{
  698. Name: "metrics.expensive",
  699. Usage: "Enable expensive metrics collection and reporting",
  700. }
  701. MetricsEnableInfluxDBFlag = cli.BoolFlag{
  702. Name: "metrics.influxdb",
  703. Usage: "Enable metrics export/push to an external InfluxDB database",
  704. }
  705. MetricsInfluxDBEndpointFlag = cli.StringFlag{
  706. Name: "metrics.influxdb.endpoint",
  707. Usage: "InfluxDB API endpoint to report metrics to",
  708. Value: "http://localhost:8086",
  709. }
  710. MetricsInfluxDBDatabaseFlag = cli.StringFlag{
  711. Name: "metrics.influxdb.database",
  712. Usage: "InfluxDB database name to push reported metrics to",
  713. Value: "geth",
  714. }
  715. MetricsInfluxDBUsernameFlag = cli.StringFlag{
  716. Name: "metrics.influxdb.username",
  717. Usage: "Username to authorize access to the database",
  718. Value: "test",
  719. }
  720. MetricsInfluxDBPasswordFlag = cli.StringFlag{
  721. Name: "metrics.influxdb.password",
  722. Usage: "Password to authorize access to the database",
  723. Value: "test",
  724. }
  725. // Tags are part of every measurement sent to InfluxDB. Queries on tags are faster in InfluxDB.
  726. // For example `host` tag could be used so that we can group all nodes and average a measurement
  727. // across all of them, but also so that we can select a specific node and inspect its measurements.
  728. // https://docs.influxdata.com/influxdb/v1.4/concepts/key_concepts/#tag-key
  729. MetricsInfluxDBTagsFlag = cli.StringFlag{
  730. Name: "metrics.influxdb.tags",
  731. Usage: "Comma-separated InfluxDB tags (key/values) attached to all measurements",
  732. Value: "host=localhost",
  733. }
  734. EWASMInterpreterFlag = cli.StringFlag{
  735. Name: "vm.ewasm",
  736. Usage: "External ewasm configuration (default = built-in interpreter)",
  737. Value: "",
  738. }
  739. EVMInterpreterFlag = cli.StringFlag{
  740. Name: "vm.evm",
  741. Usage: "External EVM configuration (default = built-in interpreter)",
  742. Value: "",
  743. }
  744. )
  745. // MakeDataDir retrieves the currently requested data directory, terminating
  746. // if none (or the empty string) is specified. If the node is starting a testnet,
  747. // the a subdirectory of the specified datadir will be used.
  748. func MakeDataDir(ctx *cli.Context) string {
  749. if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
  750. if ctx.GlobalBool(TestnetFlag.Name) {
  751. return filepath.Join(path, "testnet")
  752. }
  753. if ctx.GlobalBool(RinkebyFlag.Name) {
  754. return filepath.Join(path, "rinkeby")
  755. }
  756. if ctx.GlobalBool(GoerliFlag.Name) {
  757. return filepath.Join(path, "goerli")
  758. }
  759. return path
  760. }
  761. Fatalf("Cannot determine default data directory, please set manually (--datadir)")
  762. return ""
  763. }
  764. // setNodeKey creates a node key from set command line flags, either loading it
  765. // from a file or as a specified hex value. If neither flags were provided, this
  766. // method returns nil and an emphemeral key is to be generated.
  767. func setNodeKey(ctx *cli.Context, cfg *p2p.Config) {
  768. var (
  769. hex = ctx.GlobalString(NodeKeyHexFlag.Name)
  770. file = ctx.GlobalString(NodeKeyFileFlag.Name)
  771. key *ecdsa.PrivateKey
  772. err error
  773. )
  774. switch {
  775. case file != "" && hex != "":
  776. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  777. case file != "":
  778. if key, err = crypto.LoadECDSA(file); err != nil {
  779. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  780. }
  781. cfg.PrivateKey = key
  782. case hex != "":
  783. if key, err = crypto.HexToECDSA(hex); err != nil {
  784. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  785. }
  786. cfg.PrivateKey = key
  787. }
  788. }
  789. // setNodeUserIdent creates the user identifier from CLI flags.
  790. func setNodeUserIdent(ctx *cli.Context, cfg *node.Config) {
  791. if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
  792. cfg.UserIdent = identity
  793. }
  794. }
  795. // setBootstrapNodes creates a list of bootstrap nodes from the command line
  796. // flags, reverting to pre-configured ones if none have been specified.
  797. func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) {
  798. urls := params.MainnetBootnodes
  799. switch {
  800. case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV4Flag.Name):
  801. if ctx.GlobalIsSet(BootnodesV4Flag.Name) {
  802. urls = splitAndTrim(ctx.GlobalString(BootnodesV4Flag.Name))
  803. } else {
  804. urls = splitAndTrim(ctx.GlobalString(BootnodesFlag.Name))
  805. }
  806. case ctx.GlobalBool(TestnetFlag.Name):
  807. urls = params.TestnetBootnodes
  808. case ctx.GlobalBool(RinkebyFlag.Name):
  809. urls = params.RinkebyBootnodes
  810. case ctx.GlobalBool(GoerliFlag.Name):
  811. urls = params.GoerliBootnodes
  812. case cfg.BootstrapNodes != nil:
  813. return // already set, don't apply defaults.
  814. }
  815. cfg.BootstrapNodes = make([]*enode.Node, 0, len(urls))
  816. for _, url := range urls {
  817. if url != "" {
  818. node, err := enode.Parse(enode.ValidSchemes, url)
  819. if err != nil {
  820. log.Crit("Bootstrap URL invalid", "enode", url, "err", err)
  821. continue
  822. }
  823. cfg.BootstrapNodes = append(cfg.BootstrapNodes, node)
  824. }
  825. }
  826. }
  827. // setBootstrapNodesV5 creates a list of bootstrap nodes from the command line
  828. // flags, reverting to pre-configured ones if none have been specified.
  829. func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) {
  830. urls := params.DiscoveryV5Bootnodes
  831. switch {
  832. case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV5Flag.Name):
  833. if ctx.GlobalIsSet(BootnodesV5Flag.Name) {
  834. urls = splitAndTrim(ctx.GlobalString(BootnodesV5Flag.Name))
  835. } else {
  836. urls = splitAndTrim(ctx.GlobalString(BootnodesFlag.Name))
  837. }
  838. case ctx.GlobalBool(RinkebyFlag.Name):
  839. urls = params.RinkebyBootnodes
  840. case ctx.GlobalBool(GoerliFlag.Name):
  841. urls = params.GoerliBootnodes
  842. case cfg.BootstrapNodesV5 != nil:
  843. return // already set, don't apply defaults.
  844. }
  845. cfg.BootstrapNodesV5 = make([]*discv5.Node, 0, len(urls))
  846. for _, url := range urls {
  847. if url != "" {
  848. node, err := discv5.ParseNode(url)
  849. if err != nil {
  850. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  851. continue
  852. }
  853. cfg.BootstrapNodesV5 = append(cfg.BootstrapNodesV5, node)
  854. }
  855. }
  856. }
  857. // setListenAddress creates a TCP listening address string from set command
  858. // line flags.
  859. func setListenAddress(ctx *cli.Context, cfg *p2p.Config) {
  860. if ctx.GlobalIsSet(ListenPortFlag.Name) {
  861. cfg.ListenAddr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
  862. }
  863. }
  864. // setNAT creates a port mapper from command line flags.
  865. func setNAT(ctx *cli.Context, cfg *p2p.Config) {
  866. if ctx.GlobalIsSet(NATFlag.Name) {
  867. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  868. if err != nil {
  869. Fatalf("Option %s: %v", NATFlag.Name, err)
  870. }
  871. cfg.NAT = natif
  872. }
  873. }
  874. // splitAndTrim splits input separated by a comma
  875. // and trims excessive white space from the substrings.
  876. func splitAndTrim(input string) []string {
  877. result := strings.Split(input, ",")
  878. for i, r := range result {
  879. result[i] = strings.TrimSpace(r)
  880. }
  881. return result
  882. }
  883. // setHTTP creates the HTTP RPC listener interface string from the set
  884. // command line flags, returning empty if the HTTP endpoint is disabled.
  885. func setHTTP(ctx *cli.Context, cfg *node.Config) {
  886. if ctx.GlobalBool(RPCEnabledFlag.Name) && cfg.HTTPHost == "" {
  887. cfg.HTTPHost = "127.0.0.1"
  888. if ctx.GlobalIsSet(RPCListenAddrFlag.Name) {
  889. cfg.HTTPHost = ctx.GlobalString(RPCListenAddrFlag.Name)
  890. }
  891. }
  892. if ctx.GlobalIsSet(RPCPortFlag.Name) {
  893. cfg.HTTPPort = ctx.GlobalInt(RPCPortFlag.Name)
  894. }
  895. if ctx.GlobalIsSet(RPCCORSDomainFlag.Name) {
  896. cfg.HTTPCors = splitAndTrim(ctx.GlobalString(RPCCORSDomainFlag.Name))
  897. }
  898. if ctx.GlobalIsSet(RPCApiFlag.Name) {
  899. cfg.HTTPModules = splitAndTrim(ctx.GlobalString(RPCApiFlag.Name))
  900. }
  901. if ctx.GlobalIsSet(RPCVirtualHostsFlag.Name) {
  902. cfg.HTTPVirtualHosts = splitAndTrim(ctx.GlobalString(RPCVirtualHostsFlag.Name))
  903. }
  904. }
  905. // setGraphQL creates the GraphQL listener interface string from the set
  906. // command line flags, returning empty if the GraphQL endpoint is disabled.
  907. func setGraphQL(ctx *cli.Context, cfg *node.Config) {
  908. if ctx.GlobalBool(GraphQLEnabledFlag.Name) && cfg.GraphQLHost == "" {
  909. cfg.GraphQLHost = "127.0.0.1"
  910. if ctx.GlobalIsSet(GraphQLListenAddrFlag.Name) {
  911. cfg.GraphQLHost = ctx.GlobalString(GraphQLListenAddrFlag.Name)
  912. }
  913. }
  914. cfg.GraphQLPort = ctx.GlobalInt(GraphQLPortFlag.Name)
  915. if ctx.GlobalIsSet(GraphQLCORSDomainFlag.Name) {
  916. cfg.GraphQLCors = splitAndTrim(ctx.GlobalString(GraphQLCORSDomainFlag.Name))
  917. }
  918. if ctx.GlobalIsSet(GraphQLVirtualHostsFlag.Name) {
  919. cfg.GraphQLVirtualHosts = splitAndTrim(ctx.GlobalString(GraphQLVirtualHostsFlag.Name))
  920. }
  921. }
  922. // setWS creates the WebSocket RPC listener interface string from the set
  923. // command line flags, returning empty if the HTTP endpoint is disabled.
  924. func setWS(ctx *cli.Context, cfg *node.Config) {
  925. if ctx.GlobalBool(WSEnabledFlag.Name) && cfg.WSHost == "" {
  926. cfg.WSHost = "127.0.0.1"
  927. if ctx.GlobalIsSet(WSListenAddrFlag.Name) {
  928. cfg.WSHost = ctx.GlobalString(WSListenAddrFlag.Name)
  929. }
  930. }
  931. if ctx.GlobalIsSet(WSPortFlag.Name) {
  932. cfg.WSPort = ctx.GlobalInt(WSPortFlag.Name)
  933. }
  934. if ctx.GlobalIsSet(WSAllowedOriginsFlag.Name) {
  935. cfg.WSOrigins = splitAndTrim(ctx.GlobalString(WSAllowedOriginsFlag.Name))
  936. }
  937. if ctx.GlobalIsSet(WSApiFlag.Name) {
  938. cfg.WSModules = splitAndTrim(ctx.GlobalString(WSApiFlag.Name))
  939. }
  940. }
  941. // setIPC creates an IPC path configuration from the set command line flags,
  942. // returning an empty string if IPC was explicitly disabled, or the set path.
  943. func setIPC(ctx *cli.Context, cfg *node.Config) {
  944. CheckExclusive(ctx, IPCDisabledFlag, IPCPathFlag)
  945. switch {
  946. case ctx.GlobalBool(IPCDisabledFlag.Name):
  947. cfg.IPCPath = ""
  948. case ctx.GlobalIsSet(IPCPathFlag.Name):
  949. cfg.IPCPath = ctx.GlobalString(IPCPathFlag.Name)
  950. }
  951. }
  952. // setLes configures the les server and ultra light client settings from the command line flags.
  953. func setLes(ctx *cli.Context, cfg *eth.Config) {
  954. if ctx.GlobalIsSet(LightLegacyServFlag.Name) {
  955. cfg.LightServ = ctx.GlobalInt(LightLegacyServFlag.Name)
  956. }
  957. if ctx.GlobalIsSet(LightServeFlag.Name) {
  958. cfg.LightServ = ctx.GlobalInt(LightServeFlag.Name)
  959. }
  960. if ctx.GlobalIsSet(LightIngressFlag.Name) {
  961. cfg.LightIngress = ctx.GlobalInt(LightIngressFlag.Name)
  962. }
  963. if ctx.GlobalIsSet(LightEgressFlag.Name) {
  964. cfg.LightEgress = ctx.GlobalInt(LightEgressFlag.Name)
  965. }
  966. if ctx.GlobalIsSet(LightLegacyPeersFlag.Name) {
  967. cfg.LightPeers = ctx.GlobalInt(LightLegacyPeersFlag.Name)
  968. }
  969. if ctx.GlobalIsSet(LightMaxPeersFlag.Name) {
  970. cfg.LightPeers = ctx.GlobalInt(LightMaxPeersFlag.Name)
  971. }
  972. if ctx.GlobalIsSet(UltraLightServersFlag.Name) {
  973. cfg.UltraLightServers = strings.Split(ctx.GlobalString(UltraLightServersFlag.Name), ",")
  974. }
  975. if ctx.GlobalIsSet(UltraLightFractionFlag.Name) {
  976. cfg.UltraLightFraction = ctx.GlobalInt(UltraLightFractionFlag.Name)
  977. }
  978. if cfg.UltraLightFraction <= 0 && cfg.UltraLightFraction > 100 {
  979. log.Error("Ultra light fraction is invalid", "had", cfg.UltraLightFraction, "updated", eth.DefaultConfig.UltraLightFraction)
  980. cfg.UltraLightFraction = eth.DefaultConfig.UltraLightFraction
  981. }
  982. if ctx.GlobalIsSet(UltraLightOnlyAnnounceFlag.Name) {
  983. cfg.UltraLightOnlyAnnounce = ctx.GlobalBool(UltraLightOnlyAnnounceFlag.Name)
  984. }
  985. }
  986. // makeDatabaseHandles raises out the number of allowed file handles per process
  987. // for Geth and returns half of the allowance to assign to the database.
  988. func makeDatabaseHandles() int {
  989. limit, err := fdlimit.Maximum()
  990. if err != nil {
  991. Fatalf("Failed to retrieve file descriptor allowance: %v", err)
  992. }
  993. raised, err := fdlimit.Raise(uint64(limit))
  994. if err != nil {
  995. Fatalf("Failed to raise file descriptor allowance: %v", err)
  996. }
  997. return int(raised / 2) // Leave half for networking and other stuff
  998. }
  999. // MakeAddress converts an account specified directly as a hex encoded string or
  1000. // a key index in the key store to an internal account representation.
  1001. func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) {
  1002. // If the specified account is a valid address, return it
  1003. if common.IsHexAddress(account) {
  1004. return accounts.Account{Address: common.HexToAddress(account)}, nil
  1005. }
  1006. // Otherwise try to interpret the account as a keystore index
  1007. index, err := strconv.Atoi(account)
  1008. if err != nil || index < 0 {
  1009. return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account)
  1010. }
  1011. log.Warn("-------------------------------------------------------------------")
  1012. log.Warn("Referring to accounts by order in the keystore folder is dangerous!")
  1013. log.Warn("This functionality is deprecated and will be removed in the future!")
  1014. log.Warn("Please use explicit addresses! (can search via `geth account list`)")
  1015. log.Warn("-------------------------------------------------------------------")
  1016. accs := ks.Accounts()
  1017. if len(accs) <= index {
  1018. return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs))
  1019. }
  1020. return accs[index], nil
  1021. }
  1022. // setEtherbase retrieves the etherbase either from the directly specified
  1023. // command line flags or from the keystore if CLI indexed.
  1024. func setEtherbase(ctx *cli.Context, ks *keystore.KeyStore, cfg *eth.Config) {
  1025. // Extract the current etherbase, new flag overriding legacy one
  1026. var etherbase string
  1027. if ctx.GlobalIsSet(MinerLegacyEtherbaseFlag.Name) {
  1028. etherbase = ctx.GlobalString(MinerLegacyEtherbaseFlag.Name)
  1029. }
  1030. if ctx.GlobalIsSet(MinerEtherbaseFlag.Name) {
  1031. etherbase = ctx.GlobalString(MinerEtherbaseFlag.Name)
  1032. }
  1033. // Convert the etherbase into an address and configure it
  1034. if etherbase != "" {
  1035. if ks != nil {
  1036. account, err := MakeAddress(ks, etherbase)
  1037. if err != nil {
  1038. Fatalf("Invalid miner etherbase: %v", err)
  1039. }
  1040. cfg.Miner.Etherbase = account.Address
  1041. } else {
  1042. Fatalf("No etherbase configured")
  1043. }
  1044. }
  1045. }
  1046. // MakePasswordList reads password lines from the file specified by the global --password flag.
  1047. func MakePasswordList(ctx *cli.Context) []string {
  1048. path := ctx.GlobalString(PasswordFileFlag.Name)
  1049. if path == "" {
  1050. return nil
  1051. }
  1052. text, err := ioutil.ReadFile(path)
  1053. if err != nil {
  1054. Fatalf("Failed to read password file: %v", err)
  1055. }
  1056. lines := strings.Split(string(text), "\n")
  1057. // Sanitise DOS line endings.
  1058. for i := range lines {
  1059. lines[i] = strings.TrimRight(lines[i], "\r")
  1060. }
  1061. return lines
  1062. }
  1063. func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) {
  1064. setNodeKey(ctx, cfg)
  1065. setNAT(ctx, cfg)
  1066. setListenAddress(ctx, cfg)
  1067. setBootstrapNodes(ctx, cfg)
  1068. setBootstrapNodesV5(ctx, cfg)
  1069. lightClient := ctx.GlobalString(SyncModeFlag.Name) == "light"
  1070. lightServer := (ctx.GlobalInt(LightLegacyServFlag.Name) != 0 || ctx.GlobalInt(LightServeFlag.Name) != 0)
  1071. lightPeers := ctx.GlobalInt(LightLegacyPeersFlag.Name)
  1072. if ctx.GlobalIsSet(LightMaxPeersFlag.Name) {
  1073. lightPeers = ctx.GlobalInt(LightMaxPeersFlag.Name)
  1074. }
  1075. if lightClient && !ctx.GlobalIsSet(LightLegacyPeersFlag.Name) && !ctx.GlobalIsSet(LightMaxPeersFlag.Name) {
  1076. // dynamic default - for clients we use 1/10th of the default for servers
  1077. lightPeers /= 10
  1078. }
  1079. if ctx.GlobalIsSet(MaxPeersFlag.Name) {
  1080. cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name)
  1081. if lightServer && !ctx.GlobalIsSet(LightLegacyPeersFlag.Name) && !ctx.GlobalIsSet(LightMaxPeersFlag.Name) {
  1082. cfg.MaxPeers += lightPeers
  1083. }
  1084. } else {
  1085. if lightServer {
  1086. cfg.MaxPeers += lightPeers
  1087. }
  1088. if lightClient && (ctx.GlobalIsSet(LightLegacyPeersFlag.Name) || ctx.GlobalIsSet(LightMaxPeersFlag.Name)) && cfg.MaxPeers < lightPeers {
  1089. cfg.MaxPeers = lightPeers
  1090. }
  1091. }
  1092. if !(lightClient || lightServer) {
  1093. lightPeers = 0
  1094. }
  1095. ethPeers := cfg.MaxPeers - lightPeers
  1096. if lightClient {
  1097. ethPeers = 0
  1098. }
  1099. log.Info("Maximum peer count", "ETH", ethPeers, "LES", lightPeers, "total", cfg.MaxPeers)
  1100. if ctx.GlobalIsSet(MaxPendingPeersFlag.Name) {
  1101. cfg.MaxPendingPeers = ctx.GlobalInt(MaxPendingPeersFlag.Name)
  1102. }
  1103. if ctx.GlobalIsSet(NoDiscoverFlag.Name) || lightClient {
  1104. cfg.NoDiscovery = true
  1105. }
  1106. // if we're running a light client or server, force enable the v5 peer discovery
  1107. // unless it is explicitly disabled with --nodiscover note that explicitly specifying
  1108. // --v5disc overrides --nodiscover, in which case the later only disables v4 discovery
  1109. forceV5Discovery := (lightClient || lightServer) && !ctx.GlobalBool(NoDiscoverFlag.Name)
  1110. if ctx.GlobalIsSet(DiscoveryV5Flag.Name) {
  1111. cfg.DiscoveryV5 = ctx.GlobalBool(DiscoveryV5Flag.Name)
  1112. } else if forceV5Discovery {
  1113. cfg.DiscoveryV5 = true
  1114. }
  1115. if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" {
  1116. list, err := netutil.ParseNetlist(netrestrict)
  1117. if err != nil {
  1118. Fatalf("Option %q: %v", NetrestrictFlag.Name, err)
  1119. }
  1120. cfg.NetRestrict = list
  1121. }
  1122. if ctx.GlobalBool(DeveloperFlag.Name) {
  1123. // --dev mode can't use p2p networking.
  1124. cfg.MaxPeers = 0
  1125. cfg.ListenAddr = ":0"
  1126. cfg.NoDiscovery = true
  1127. cfg.DiscoveryV5 = false
  1128. }
  1129. }
  1130. // SetNodeConfig applies node-related command line flags to the config.
  1131. func SetNodeConfig(ctx *cli.Context, cfg *node.Config) {
  1132. SetP2PConfig(ctx, &cfg.P2P)
  1133. setIPC(ctx, cfg)
  1134. setHTTP(ctx, cfg)
  1135. setGraphQL(ctx, cfg)
  1136. setWS(ctx, cfg)
  1137. setNodeUserIdent(ctx, cfg)
  1138. setDataDir(ctx, cfg)
  1139. setSmartCard(ctx, cfg)
  1140. if ctx.GlobalIsSet(ExternalSignerFlag.Name) {
  1141. cfg.ExternalSigner = ctx.GlobalString(ExternalSignerFlag.Name)
  1142. }
  1143. if ctx.GlobalIsSet(KeyStoreDirFlag.Name) {
  1144. cfg.KeyStoreDir = ctx.GlobalString(KeyStoreDirFlag.Name)
  1145. }
  1146. if ctx.GlobalIsSet(LightKDFFlag.Name) {
  1147. cfg.UseLightweightKDF = ctx.GlobalBool(LightKDFFlag.Name)
  1148. }
  1149. if ctx.GlobalIsSet(NoUSBFlag.Name) {
  1150. cfg.NoUSB = ctx.GlobalBool(NoUSBFlag.Name)
  1151. }
  1152. if ctx.GlobalIsSet(InsecureUnlockAllowedFlag.Name) {
  1153. cfg.InsecureUnlockAllowed = ctx.GlobalBool(InsecureUnlockAllowedFlag.Name)
  1154. }
  1155. }
  1156. func setSmartCard(ctx *cli.Context, cfg *node.Config) {
  1157. // Skip enabling smartcards if no path is set
  1158. path := ctx.GlobalString(SmartCardDaemonPathFlag.Name)
  1159. if path == "" {
  1160. return
  1161. }
  1162. // Sanity check that the smartcard path is valid
  1163. fi, err := os.Stat(path)
  1164. if err != nil {
  1165. log.Info("Smartcard socket not found, disabling", "err", err)
  1166. return
  1167. }
  1168. if fi.Mode()&os.ModeType != os.ModeSocket {
  1169. log.Error("Invalid smartcard daemon path", "path", path, "type", fi.Mode().String())
  1170. return
  1171. }
  1172. // Smartcard daemon path exists and is a socket, enable it
  1173. cfg.SmartCardDaemonPath = path
  1174. }
  1175. func setDataDir(ctx *cli.Context, cfg *node.Config) {
  1176. switch {
  1177. case ctx.GlobalIsSet(DataDirFlag.Name):
  1178. cfg.DataDir = ctx.GlobalString(DataDirFlag.Name)
  1179. case ctx.GlobalBool(DeveloperFlag.Name):
  1180. cfg.DataDir = "" // unless explicitly requested, use memory databases
  1181. case ctx.GlobalBool(TestnetFlag.Name) && cfg.DataDir == node.DefaultDataDir():
  1182. cfg.DataDir = filepath.Join(node.DefaultDataDir(), "testnet")
  1183. case ctx.GlobalBool(RinkebyFlag.Name) && cfg.DataDir == node.DefaultDataDir():
  1184. cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby")
  1185. case ctx.GlobalBool(GoerliFlag.Name) && cfg.DataDir == node.DefaultDataDir():
  1186. cfg.DataDir = filepath.Join(node.DefaultDataDir(), "goerli")
  1187. }
  1188. }
  1189. func setGPO(ctx *cli.Context, cfg *gasprice.Config) {
  1190. if ctx.GlobalIsSet(GpoBlocksFlag.Name) {
  1191. cfg.Blocks = ctx.GlobalInt(GpoBlocksFlag.Name)
  1192. }
  1193. if ctx.GlobalIsSet(GpoPercentileFlag.Name) {
  1194. cfg.Percentile = ctx.GlobalInt(GpoPercentileFlag.Name)
  1195. }
  1196. }
  1197. func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) {
  1198. if ctx.GlobalIsSet(TxPoolLocalsFlag.Name) {
  1199. locals := strings.Split(ctx.GlobalString(TxPoolLocalsFlag.Name), ",")
  1200. for _, account := range locals {
  1201. if trimmed := strings.TrimSpace(account); !common.IsHexAddress(trimmed) {
  1202. Fatalf("Invalid account in --txpool.locals: %s", trimmed)
  1203. } else {
  1204. cfg.Locals = append(cfg.Locals, common.HexToAddress(account))
  1205. }
  1206. }
  1207. }
  1208. if ctx.GlobalIsSet(TxPoolNoLocalsFlag.Name) {
  1209. cfg.NoLocals = ctx.GlobalBool(TxPoolNoLocalsFlag.Name)
  1210. }
  1211. if ctx.GlobalIsSet(TxPoolJournalFlag.Name) {
  1212. cfg.Journal = ctx.GlobalString(TxPoolJournalFlag.Name)
  1213. }
  1214. if ctx.GlobalIsSet(TxPoolRejournalFlag.Name) {
  1215. cfg.Rejournal = ctx.GlobalDuration(TxPoolRejournalFlag.Name)
  1216. }
  1217. if ctx.GlobalIsSet(TxPoolPriceLimitFlag.Name) {
  1218. cfg.PriceLimit = ctx.GlobalUint64(TxPoolPriceLimitFlag.Name)
  1219. }
  1220. if ctx.GlobalIsSet(TxPoolPriceBumpFlag.Name) {
  1221. cfg.PriceBump = ctx.GlobalUint64(TxPoolPriceBumpFlag.Name)
  1222. }
  1223. if ctx.GlobalIsSet(TxPoolAccountSlotsFlag.Name) {
  1224. cfg.AccountSlots = ctx.GlobalUint64(TxPoolAccountSlotsFlag.Name)
  1225. }
  1226. if ctx.GlobalIsSet(TxPoolGlobalSlotsFlag.Name) {
  1227. cfg.GlobalSlots = ctx.GlobalUint64(TxPoolGlobalSlotsFlag.Name)
  1228. }
  1229. if ctx.GlobalIsSet(TxPoolAccountQueueFlag.Name) {
  1230. cfg.AccountQueue = ctx.GlobalUint64(TxPoolAccountQueueFlag.Name)
  1231. }
  1232. if ctx.GlobalIsSet(TxPoolGlobalQueueFlag.Name) {
  1233. cfg.GlobalQueue = ctx.GlobalUint64(TxPoolGlobalQueueFlag.Name)
  1234. }
  1235. if ctx.GlobalIsSet(TxPoolLifetimeFlag.Name) {
  1236. cfg.Lifetime = ctx.GlobalDuration(TxPoolLifetimeFlag.Name)
  1237. }
  1238. }
  1239. func setEthash(ctx *cli.Context, cfg *eth.Config) {
  1240. if ctx.GlobalIsSet(EthashCacheDirFlag.Name) {
  1241. cfg.Ethash.CacheDir = ctx.GlobalString(EthashCacheDirFlag.Name)
  1242. }
  1243. if ctx.GlobalIsSet(EthashDatasetDirFlag.Name) {
  1244. cfg.Ethash.DatasetDir = ctx.GlobalString(EthashDatasetDirFlag.Name)
  1245. }
  1246. if ctx.GlobalIsSet(EthashCachesInMemoryFlag.Name) {
  1247. cfg.Ethash.CachesInMem = ctx.GlobalInt(EthashCachesInMemoryFlag.Name)
  1248. }
  1249. if ctx.GlobalIsSet(EthashCachesOnDiskFlag.Name) {
  1250. cfg.Ethash.CachesOnDisk = ctx.GlobalInt(EthashCachesOnDiskFlag.Name)
  1251. }
  1252. if ctx.GlobalIsSet(EthashDatasetsInMemoryFlag.Name) {
  1253. cfg.Ethash.DatasetsInMem = ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name)
  1254. }
  1255. if ctx.GlobalIsSet(EthashDatasetsOnDiskFlag.Name) {
  1256. cfg.Ethash.DatasetsOnDisk = ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name)
  1257. }
  1258. }
  1259. func setMiner(ctx *cli.Context, cfg *miner.Config) {
  1260. if ctx.GlobalIsSet(MinerNotifyFlag.Name) {
  1261. cfg.Notify = strings.Split(ctx.GlobalString(MinerNotifyFlag.Name), ",")
  1262. }
  1263. if ctx.GlobalIsSet(MinerLegacyExtraDataFlag.Name) {
  1264. cfg.ExtraData = []byte(ctx.GlobalString(MinerLegacyExtraDataFlag.Name))
  1265. }
  1266. if ctx.GlobalIsSet(MinerExtraDataFlag.Name) {
  1267. cfg.ExtraData = []byte(ctx.GlobalString(MinerExtraDataFlag.Name))
  1268. }
  1269. if ctx.GlobalIsSet(MinerLegacyGasTargetFlag.Name) {
  1270. cfg.GasFloor = ctx.GlobalUint64(MinerLegacyGasTargetFlag.Name)
  1271. }
  1272. if ctx.GlobalIsSet(MinerGasTargetFlag.Name) {
  1273. cfg.GasFloor = ctx.GlobalUint64(MinerGasTargetFlag.Name)
  1274. }
  1275. if ctx.GlobalIsSet(MinerGasLimitFlag.Name) {
  1276. cfg.GasCeil = ctx.GlobalUint64(MinerGasLimitFlag.Name)
  1277. }
  1278. if ctx.GlobalIsSet(MinerLegacyGasPriceFlag.Name) {
  1279. cfg.GasPrice = GlobalBig(ctx, MinerLegacyGasPriceFlag.Name)
  1280. }
  1281. if ctx.GlobalIsSet(MinerGasPriceFlag.Name) {
  1282. cfg.GasPrice = GlobalBig(ctx, MinerGasPriceFlag.Name)
  1283. }
  1284. if ctx.GlobalIsSet(MinerRecommitIntervalFlag.Name) {
  1285. cfg.Recommit = ctx.Duration(MinerRecommitIntervalFlag.Name)
  1286. }
  1287. if ctx.GlobalIsSet(MinerNoVerfiyFlag.Name) {
  1288. cfg.Noverify = ctx.Bool(MinerNoVerfiyFlag.Name)
  1289. }
  1290. }
  1291. func setWhitelist(ctx *cli.Context, cfg *eth.Config) {
  1292. whitelist := ctx.GlobalString(WhitelistFlag.Name)
  1293. if whitelist == "" {
  1294. return
  1295. }
  1296. cfg.Whitelist = make(map[uint64]common.Hash)
  1297. for _, entry := range strings.Split(whitelist, ",") {
  1298. parts := strings.Split(entry, "=")
  1299. if len(parts) != 2 {
  1300. Fatalf("Invalid whitelist entry: %s", entry)
  1301. }
  1302. number, err := strconv.ParseUint(parts[0], 0, 64)
  1303. if err != nil {
  1304. Fatalf("Invalid whitelist block number %s: %v", parts[0], err)
  1305. }
  1306. var hash common.Hash
  1307. if err = hash.UnmarshalText([]byte(parts[1])); err != nil {
  1308. Fatalf("Invalid whitelist hash %s: %v", parts[1], err)
  1309. }
  1310. cfg.Whitelist[number] = hash
  1311. }
  1312. }
  1313. // CheckExclusive verifies that only a single instance of the provided flags was
  1314. // set by the user. Each flag might optionally be followed by a string type to
  1315. // specialize it further.
  1316. func CheckExclusive(ctx *cli.Context, args ...interface{}) {
  1317. set := make([]string, 0, 1)
  1318. for i := 0; i < len(args); i++ {
  1319. // Make sure the next argument is a flag and skip if not set
  1320. flag, ok := args[i].(cli.Flag)
  1321. if !ok {
  1322. panic(fmt.Sprintf("invalid argument, not cli.Flag type: %T", args[i]))
  1323. }
  1324. // Check if next arg extends current and expand its name if so
  1325. name := flag.GetName()
  1326. if i+1 < len(args) {
  1327. switch option := args[i+1].(type) {
  1328. case string:
  1329. // Extended flag check, make sure value set doesn't conflict with passed in option
  1330. if ctx.GlobalString(flag.GetName()) == option {
  1331. name += "=" + option
  1332. set = append(set, "--"+name)
  1333. }
  1334. // shift arguments and continue
  1335. i++
  1336. continue
  1337. case cli.Flag:
  1338. default:
  1339. panic(fmt.Sprintf("invalid argument, not cli.Flag or string extension: %T", args[i+1]))
  1340. }
  1341. }
  1342. // Mark the flag if it's set
  1343. if ctx.GlobalIsSet(flag.GetName()) {
  1344. set = append(set, "--"+name)
  1345. }
  1346. }
  1347. if len(set) > 1 {
  1348. Fatalf("Flags %v can't be used at the same time", strings.Join(set, ", "))
  1349. }
  1350. }
  1351. // SetShhConfig applies shh-related command line flags to the config.
  1352. func SetShhConfig(ctx *cli.Context, stack *node.Node, cfg *whisper.Config) {
  1353. if ctx.GlobalIsSet(WhisperMaxMessageSizeFlag.Name) {
  1354. cfg.MaxMessageSize = uint32(ctx.GlobalUint(WhisperMaxMessageSizeFlag.Name))
  1355. }
  1356. if ctx.GlobalIsSet(WhisperMinPOWFlag.Name) {
  1357. cfg.MinimumAcceptedPOW = ctx.GlobalFloat64(WhisperMinPOWFlag.Name)
  1358. }
  1359. if ctx.GlobalIsSet(WhisperRestrictConnectionBetweenLightClientsFlag.Name) {
  1360. cfg.RestrictConnectionBetweenLightClients = true
  1361. }
  1362. }
  1363. // SetEthConfig applies eth-related command line flags to the config.
  1364. func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
  1365. // Avoid conflicting network flags
  1366. CheckExclusive(ctx, DeveloperFlag, TestnetFlag, RinkebyFlag, GoerliFlag)
  1367. CheckExclusive(ctx, LightLegacyServFlag, LightServeFlag, SyncModeFlag, "light")
  1368. CheckExclusive(ctx, DeveloperFlag, ExternalSignerFlag) // Can't use both ephemeral unlocked and external signer
  1369. var ks *keystore.KeyStore
  1370. if keystores := stack.AccountManager().Backends(keystore.KeyStoreType); len(keystores) > 0 {
  1371. ks = keystores[0].(*keystore.KeyStore)
  1372. }
  1373. setEtherbase(ctx, ks, cfg)
  1374. setGPO(ctx, &cfg.GPO)
  1375. setTxPool(ctx, &cfg.TxPool)
  1376. setEthash(ctx, cfg)
  1377. setMiner(ctx, &cfg.Miner)
  1378. setWhitelist(ctx, cfg)
  1379. setLes(ctx, cfg)
  1380. if ctx.GlobalIsSet(SyncModeFlag.Name) {
  1381. cfg.SyncMode = *GlobalTextMarshaler(ctx, SyncModeFlag.Name).(*downloader.SyncMode)
  1382. }
  1383. if ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1384. cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name)
  1385. }
  1386. if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheDatabaseFlag.Name) {
  1387. cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
  1388. }
  1389. cfg.DatabaseHandles = makeDatabaseHandles()
  1390. if ctx.GlobalIsSet(AncientFlag.Name) {
  1391. cfg.DatabaseFreezer = ctx.GlobalString(AncientFlag.Name)
  1392. }
  1393. if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
  1394. Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
  1395. }
  1396. if ctx.GlobalIsSet(GCModeFlag.Name) {
  1397. cfg.NoPruning = ctx.GlobalString(GCModeFlag.Name) == "archive"
  1398. }
  1399. if ctx.GlobalIsSet(CacheNoPrefetchFlag.Name) {
  1400. cfg.NoPrefetch = ctx.GlobalBool(CacheNoPrefetchFlag.Name)
  1401. }
  1402. if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheTrieFlag.Name) {
  1403. cfg.TrieCleanCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheTrieFlag.Name) / 100
  1404. }
  1405. if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
  1406. cfg.TrieDirtyCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
  1407. }
  1408. if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheSnapshotFlag.Name) {
  1409. cfg.SnapshotCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheSnapshotFlag.Name) / 100
  1410. }
  1411. if ctx.GlobalIsSet(DocRootFlag.Name) {
  1412. cfg.DocRoot = ctx.GlobalString(DocRootFlag.Name)
  1413. }
  1414. if ctx.GlobalIsSet(VMEnableDebugFlag.Name) {
  1415. // TODO(fjl): force-enable this in --dev mode
  1416. cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name)
  1417. }
  1418. if ctx.GlobalIsSet(EWASMInterpreterFlag.Name) {
  1419. cfg.EWASMInterpreter = ctx.GlobalString(EWASMInterpreterFlag.Name)
  1420. }
  1421. if ctx.GlobalIsSet(EVMInterpreterFlag.Name) {
  1422. cfg.EVMInterpreter = ctx.GlobalString(EVMInterpreterFlag.Name)
  1423. }
  1424. if ctx.GlobalIsSet(RPCGlobalGasCap.Name) {
  1425. cfg.RPCGasCap = new(big.Int).SetUint64(ctx.GlobalUint64(RPCGlobalGasCap.Name))
  1426. }
  1427. if ctx.GlobalIsSet(DNSDiscoveryFlag.Name) {
  1428. urls := ctx.GlobalString(DNSDiscoveryFlag.Name)
  1429. if urls == "" {
  1430. cfg.DiscoveryURLs = []string{}
  1431. } else {
  1432. cfg.DiscoveryURLs = splitAndTrim(urls)
  1433. }
  1434. }
  1435. // Override any default configs for hard coded networks.
  1436. switch {
  1437. case ctx.GlobalBool(TestnetFlag.Name):
  1438. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1439. cfg.NetworkId = 3
  1440. }
  1441. cfg.Genesis = core.DefaultTestnetGenesisBlock()
  1442. setDNSDiscoveryDefaults(cfg, params.KnownDNSNetworks[params.TestnetGenesisHash])
  1443. case ctx.GlobalBool(RinkebyFlag.Name):
  1444. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1445. cfg.NetworkId = 4
  1446. }
  1447. cfg.Genesis = core.DefaultRinkebyGenesisBlock()
  1448. setDNSDiscoveryDefaults(cfg, params.KnownDNSNetworks[params.RinkebyGenesisHash])
  1449. case ctx.GlobalBool(GoerliFlag.Name):
  1450. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1451. cfg.NetworkId = 5
  1452. }
  1453. cfg.Genesis = core.DefaultGoerliGenesisBlock()
  1454. setDNSDiscoveryDefaults(cfg, params.KnownDNSNetworks[params.GoerliGenesisHash])
  1455. case ctx.GlobalBool(DeveloperFlag.Name):
  1456. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  1457. cfg.NetworkId = 1337
  1458. }
  1459. // Create new developer account or reuse existing one
  1460. var (
  1461. developer accounts.Account
  1462. err error
  1463. )
  1464. if accs := ks.Accounts(); len(accs) > 0 {
  1465. developer = ks.Accounts()[0]
  1466. } else {
  1467. developer, err = ks.NewAccount("")
  1468. if err != nil {
  1469. Fatalf("Failed to create developer account: %v", err)
  1470. }
  1471. }
  1472. if err := ks.Unlock(developer, ""); err != nil {
  1473. Fatalf("Failed to unlock developer account: %v", err)
  1474. }
  1475. log.Info("Using developer account", "address", developer.Address)
  1476. cfg.Genesis = core.DeveloperGenesisBlock(uint64(ctx.GlobalInt(DeveloperPeriodFlag.Name)), developer.Address)
  1477. if !ctx.GlobalIsSet(MinerGasPriceFlag.Name) && !ctx.GlobalIsSet(MinerLegacyGasPriceFlag.Name) {
  1478. cfg.Miner.GasPrice = big.NewInt(1)
  1479. }
  1480. default:
  1481. if cfg.NetworkId == 1 {
  1482. setDNSDiscoveryDefaults(cfg, params.KnownDNSNetworks[params.MainnetGenesisHash])
  1483. }
  1484. }
  1485. }
  1486. // setDNSDiscoveryDefaults configures DNS discovery with the given URL if
  1487. // no URLs are set.
  1488. func setDNSDiscoveryDefaults(cfg *eth.Config, url string) {
  1489. if cfg.DiscoveryURLs != nil {
  1490. return
  1491. }
  1492. cfg.DiscoveryURLs = []string{url}
  1493. }
  1494. // RegisterEthService adds an Ethereum client to the stack.
  1495. func RegisterEthService(stack *node.Node, cfg *eth.Config) {
  1496. var err error
  1497. if cfg.SyncMode == downloader.LightSync {
  1498. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1499. return les.New(ctx, cfg)
  1500. })
  1501. } else {
  1502. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1503. fullNode, err := eth.New(ctx, cfg)
  1504. if fullNode != nil && cfg.LightServ > 0 {
  1505. ls, _ := les.NewLesServer(fullNode, cfg)
  1506. fullNode.AddLesServer(ls)
  1507. }
  1508. return fullNode, err
  1509. })
  1510. }
  1511. if err != nil {
  1512. Fatalf("Failed to register the Ethereum service: %v", err)
  1513. }
  1514. }
  1515. // RegisterShhService configures Whisper and adds it to the given node.
  1516. func RegisterShhService(stack *node.Node, cfg *whisper.Config) {
  1517. if err := stack.Register(func(n *node.ServiceContext) (node.Service, error) {
  1518. return whisper.New(cfg), nil
  1519. }); err != nil {
  1520. Fatalf("Failed to register the Whisper service: %v", err)
  1521. }
  1522. }
  1523. // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  1524. // the given node.
  1525. func RegisterEthStatsService(stack *node.Node, url string) {
  1526. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1527. // Retrieve both eth and les services
  1528. var ethServ *eth.Ethereum
  1529. ctx.Service(&ethServ)
  1530. var lesServ *les.LightEthereum
  1531. ctx.Service(&lesServ)
  1532. // Let ethstats use whichever is not nil
  1533. return ethstats.New(url, ethServ, lesServ)
  1534. }); err != nil {
  1535. Fatalf("Failed to register the Ethereum Stats service: %v", err)
  1536. }
  1537. }
  1538. // RegisterGraphQLService is a utility function to construct a new service and register it against a node.
  1539. func RegisterGraphQLService(stack *node.Node, endpoint string, cors, vhosts []string, timeouts rpc.HTTPTimeouts) {
  1540. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1541. // Try to construct the GraphQL service backed by a full node
  1542. var ethServ *eth.Ethereum
  1543. if err := ctx.Service(&ethServ); err == nil {
  1544. return graphql.New(ethServ.APIBackend, endpoint, cors, vhosts, timeouts)
  1545. }
  1546. // Try to construct the GraphQL service backed by a light node
  1547. var lesServ *les.LightEthereum
  1548. if err := ctx.Service(&lesServ); err == nil {
  1549. return graphql.New(lesServ.ApiBackend, endpoint, cors, vhosts, timeouts)
  1550. }
  1551. // Well, this should not have happened, bail out
  1552. return nil, errors.New("no Ethereum service")
  1553. }); err != nil {
  1554. Fatalf("Failed to register the GraphQL service: %v", err)
  1555. }
  1556. }
  1557. func SetupMetrics(ctx *cli.Context) {
  1558. if metrics.Enabled {
  1559. log.Info("Enabling metrics collection")
  1560. var (
  1561. enableExport = ctx.GlobalBool(MetricsEnableInfluxDBFlag.Name)
  1562. endpoint = ctx.GlobalString(MetricsInfluxDBEndpointFlag.Name)
  1563. database = ctx.GlobalString(MetricsInfluxDBDatabaseFlag.Name)
  1564. username = ctx.GlobalString(MetricsInfluxDBUsernameFlag.Name)
  1565. password = ctx.GlobalString(MetricsInfluxDBPasswordFlag.Name)
  1566. )
  1567. if enableExport {
  1568. tagsMap := SplitTagsFlag(ctx.GlobalString(MetricsInfluxDBTagsFlag.Name))
  1569. log.Info("Enabling metrics export to InfluxDB")
  1570. go influxdb.InfluxDBWithTags(metrics.DefaultRegistry, 10*time.Second, endpoint, database, username, password, "geth.", tagsMap)
  1571. }
  1572. }
  1573. }
  1574. func SplitTagsFlag(tagsFlag string) map[string]string {
  1575. tags := strings.Split(tagsFlag, ",")
  1576. tagsMap := map[string]string{}
  1577. for _, t := range tags {
  1578. if t != "" {
  1579. kv := strings.Split(t, "=")
  1580. if len(kv) == 2 {
  1581. tagsMap[kv[0]] = kv[1]
  1582. }
  1583. }
  1584. }
  1585. return tagsMap
  1586. }
  1587. // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  1588. func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  1589. var (
  1590. cache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
  1591. handles = makeDatabaseHandles()
  1592. )
  1593. name := "chaindata"
  1594. if ctx.GlobalString(SyncModeFlag.Name) == "light" {
  1595. name = "lightchaindata"
  1596. }
  1597. chainDb, err := stack.OpenDatabaseWithFreezer(name, cache, handles, ctx.GlobalString(AncientFlag.Name), "")
  1598. if err != nil {
  1599. Fatalf("Could not open database: %v", err)
  1600. }
  1601. return chainDb
  1602. }
  1603. func MakeGenesis(ctx *cli.Context) *core.Genesis {
  1604. var genesis *core.Genesis
  1605. switch {
  1606. case ctx.GlobalBool(TestnetFlag.Name):
  1607. genesis = core.DefaultTestnetGenesisBlock()
  1608. case ctx.GlobalBool(RinkebyFlag.Name):
  1609. genesis = core.DefaultRinkebyGenesisBlock()
  1610. case ctx.GlobalBool(GoerliFlag.Name):
  1611. genesis = core.DefaultGoerliGenesisBlock()
  1612. case ctx.GlobalBool(DeveloperFlag.Name):
  1613. Fatalf("Developer chains are ephemeral")
  1614. }
  1615. return genesis
  1616. }
  1617. // MakeChain creates a chain manager from set command line flags.
  1618. func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  1619. var err error
  1620. chainDb = MakeChainDatabase(ctx, stack)
  1621. config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx))
  1622. if err != nil {
  1623. Fatalf("%v", err)
  1624. }
  1625. var engine consensus.Engine
  1626. if config.Clique != nil {
  1627. engine = clique.New(config.Clique, chainDb)
  1628. } else {
  1629. engine = ethash.NewFaker()
  1630. if !ctx.GlobalBool(FakePoWFlag.Name) {
  1631. engine = ethash.New(ethash.Config{
  1632. CacheDir: stack.ResolvePath(eth.DefaultConfig.Ethash.CacheDir),
  1633. CachesInMem: eth.DefaultConfig.Ethash.CachesInMem,
  1634. CachesOnDisk: eth.DefaultConfig.Ethash.CachesOnDisk,
  1635. DatasetDir: stack.ResolvePath(eth.DefaultConfig.Ethash.DatasetDir),
  1636. DatasetsInMem: eth.DefaultConfig.Ethash.DatasetsInMem,
  1637. DatasetsOnDisk: eth.DefaultConfig.Ethash.DatasetsOnDisk,
  1638. }, nil, false)
  1639. }
  1640. }
  1641. if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
  1642. Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
  1643. }
  1644. cache := &core.CacheConfig{
  1645. TrieCleanLimit: eth.DefaultConfig.TrieCleanCache,
  1646. TrieCleanNoPrefetch: ctx.GlobalBool(CacheNoPrefetchFlag.Name),
  1647. TrieDirtyLimit: eth.DefaultConfig.TrieDirtyCache,
  1648. TrieDirtyDisabled: ctx.GlobalString(GCModeFlag.Name) == "archive",
  1649. TrieTimeLimit: eth.DefaultConfig.TrieTimeout,
  1650. SnapshotLimit: eth.DefaultConfig.SnapshotCache,
  1651. }
  1652. if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheTrieFlag.Name) {
  1653. cache.TrieCleanLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheTrieFlag.Name) / 100
  1654. }
  1655. if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheGCFlag.Name) {
  1656. cache.TrieDirtyLimit = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheGCFlag.Name) / 100
  1657. }
  1658. vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
  1659. chain, err = core.NewBlockChain(chainDb, cache, config, engine, vmcfg, nil)
  1660. if err != nil {
  1661. Fatalf("Can't create BlockChain: %v", err)
  1662. }
  1663. return chain, chainDb
  1664. }
  1665. // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  1666. // scripts to preload before starting.
  1667. func MakeConsolePreloads(ctx *cli.Context) []string {
  1668. // Skip preloading if there's nothing to preload
  1669. if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  1670. return nil
  1671. }
  1672. // Otherwise resolve absolute paths and return them
  1673. var preloads []string
  1674. assets := ctx.GlobalString(JSpathFlag.Name)
  1675. for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  1676. preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  1677. }
  1678. return preloads
  1679. }
  1680. // MigrateFlags sets the global flag from a local flag when it's set.
  1681. // This is a temporary function used for migrating old command/flags to the
  1682. // new format.
  1683. //
  1684. // e.g. geth account new --keystore /tmp/mykeystore --lightkdf
  1685. //
  1686. // is equivalent after calling this method with:
  1687. //
  1688. // geth --keystore /tmp/mykeystore --lightkdf account new
  1689. //
  1690. // This allows the use of the existing configuration functionality.
  1691. // When all flags are migrated this function can be removed and the existing
  1692. // configuration functionality must be changed that is uses local flags
  1693. func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error {
  1694. return func(ctx *cli.Context) error {
  1695. for _, name := range ctx.FlagNames() {
  1696. if ctx.IsSet(name) {
  1697. ctx.GlobalSet(name, ctx.String(name))
  1698. }
  1699. }
  1700. return action(ctx)
  1701. }
  1702. }