flags.go 67 KB

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