flags.go 58 KB

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