flags.go 68 KB

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