flags.go 76 KB

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