flags.go 65 KB

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