flags.go 66 KB

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