flags.go 70 KB

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