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