flags.go 53 KB

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