flags.go 68 KB

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