flags.go 67 KB

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