flags.go 48 KB

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