flags.go 60 KB

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