flags.go 66 KB

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