flags.go 56 KB

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