flags.go 64 KB

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