flags.go 70 KB

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