flags.go 66 KB

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