flags.go 69 KB

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