flags.go 67 KB

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