flags.go 66 KB

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