flags.go 68 KB

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