flags.go 64 KB

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