flags.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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. "runtime"
  26. "strconv"
  27. "strings"
  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/consensus"
  32. "github.com/ethereum/go-ethereum/consensus/clique"
  33. "github.com/ethereum/go-ethereum/consensus/ethash"
  34. "github.com/ethereum/go-ethereum/core"
  35. "github.com/ethereum/go-ethereum/core/state"
  36. "github.com/ethereum/go-ethereum/core/vm"
  37. "github.com/ethereum/go-ethereum/crypto"
  38. "github.com/ethereum/go-ethereum/dashboard"
  39. "github.com/ethereum/go-ethereum/eth"
  40. "github.com/ethereum/go-ethereum/eth/downloader"
  41. "github.com/ethereum/go-ethereum/eth/gasprice"
  42. "github.com/ethereum/go-ethereum/ethdb"
  43. "github.com/ethereum/go-ethereum/ethstats"
  44. "github.com/ethereum/go-ethereum/les"
  45. "github.com/ethereum/go-ethereum/log"
  46. "github.com/ethereum/go-ethereum/metrics"
  47. "github.com/ethereum/go-ethereum/node"
  48. "github.com/ethereum/go-ethereum/p2p"
  49. "github.com/ethereum/go-ethereum/p2p/discover"
  50. "github.com/ethereum/go-ethereum/p2p/discv5"
  51. "github.com/ethereum/go-ethereum/p2p/nat"
  52. "github.com/ethereum/go-ethereum/p2p/netutil"
  53. "github.com/ethereum/go-ethereum/params"
  54. whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
  55. "gopkg.in/urfave/cli.v1"
  56. )
  57. var (
  58. CommandHelpTemplate = `{{.cmd.Name}}{{if .cmd.Subcommands}} command{{end}}{{if .cmd.Flags}} [command options]{{end}} [arguments...]
  59. {{if .cmd.Description}}{{.cmd.Description}}
  60. {{end}}{{if .cmd.Subcommands}}
  61. SUBCOMMANDS:
  62. {{range .cmd.Subcommands}}{{.cmd.Name}}{{with .cmd.ShortName}}, {{.cmd}}{{end}}{{ "\t" }}{{.cmd.Usage}}
  63. {{end}}{{end}}{{if .categorizedFlags}}
  64. {{range $idx, $categorized := .categorizedFlags}}{{$categorized.Name}} OPTIONS:
  65. {{range $categorized.Flags}}{{"\t"}}{{.}}
  66. {{end}}
  67. {{end}}{{end}}`
  68. )
  69. func init() {
  70. cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
  71. VERSION:
  72. {{.Version}}
  73. COMMANDS:
  74. {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  75. {{end}}{{if .Flags}}
  76. GLOBAL OPTIONS:
  77. {{range .Flags}}{{.}}
  78. {{end}}{{end}}
  79. `
  80. cli.CommandHelpTemplate = CommandHelpTemplate
  81. }
  82. // NewApp creates an app with sane defaults.
  83. func NewApp(gitCommit, usage string) *cli.App {
  84. app := cli.NewApp()
  85. app.Name = filepath.Base(os.Args[0])
  86. app.Author = ""
  87. //app.Authors = nil
  88. app.Email = ""
  89. app.Version = params.Version
  90. if gitCommit != "" {
  91. app.Version += "-" + gitCommit[:8]
  92. }
  93. app.Usage = usage
  94. return app
  95. }
  96. // These are all the command line flags we support.
  97. // If you add to this list, please remember to include the
  98. // flag in the appropriate command definition.
  99. //
  100. // The flags are defined here so their names and help texts
  101. // are the same for all commands.
  102. var (
  103. // General settings
  104. DataDirFlag = DirectoryFlag{
  105. Name: "datadir",
  106. Usage: "Data directory for the databases and keystore",
  107. Value: DirectoryString{node.DefaultDataDir()},
  108. }
  109. KeyStoreDirFlag = DirectoryFlag{
  110. Name: "keystore",
  111. Usage: "Directory for the keystore (default = inside the datadir)",
  112. }
  113. NoUSBFlag = cli.BoolFlag{
  114. Name: "nousb",
  115. Usage: "Disables monitoring for and managing USB hardware wallets",
  116. }
  117. NetworkIdFlag = cli.Uint64Flag{
  118. Name: "networkid",
  119. Usage: "Network identifier (integer, 1=Frontier, 2=Morden (disused), 3=Ropsten, 4=Rinkeby)",
  120. Value: eth.DefaultConfig.NetworkId,
  121. }
  122. TestnetFlag = cli.BoolFlag{
  123. Name: "testnet",
  124. Usage: "Ropsten network: pre-configured proof-of-work test network",
  125. }
  126. RinkebyFlag = cli.BoolFlag{
  127. Name: "rinkeby",
  128. Usage: "Rinkeby network: pre-configured proof-of-authority test network",
  129. }
  130. DeveloperFlag = cli.BoolFlag{
  131. Name: "dev",
  132. Usage: "Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled",
  133. }
  134. DeveloperPeriodFlag = cli.IntFlag{
  135. Name: "dev.period",
  136. Usage: "Block period to use in developer mode (0 = mine only if transaction pending)",
  137. }
  138. IdentityFlag = cli.StringFlag{
  139. Name: "identity",
  140. Usage: "Custom node name",
  141. }
  142. DocRootFlag = DirectoryFlag{
  143. Name: "docroot",
  144. Usage: "Document Root for HTTPClient file scheme",
  145. Value: DirectoryString{homeDir()},
  146. }
  147. FastSyncFlag = cli.BoolFlag{
  148. Name: "fast",
  149. Usage: "Enable fast syncing through state downloads",
  150. }
  151. LightModeFlag = cli.BoolFlag{
  152. Name: "light",
  153. Usage: "Enable light client mode",
  154. }
  155. defaultSyncMode = eth.DefaultConfig.SyncMode
  156. SyncModeFlag = TextMarshalerFlag{
  157. Name: "syncmode",
  158. Usage: `Blockchain sync mode ("fast", "full", or "light")`,
  159. Value: &defaultSyncMode,
  160. }
  161. LightServFlag = cli.IntFlag{
  162. Name: "lightserv",
  163. Usage: "Maximum percentage of time allowed for serving LES requests (0-90)",
  164. Value: 0,
  165. }
  166. LightPeersFlag = cli.IntFlag{
  167. Name: "lightpeers",
  168. Usage: "Maximum number of LES client peers",
  169. Value: 20,
  170. }
  171. LightKDFFlag = cli.BoolFlag{
  172. Name: "lightkdf",
  173. Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
  174. }
  175. // Dashboard settings
  176. DashboardEnabledFlag = cli.BoolFlag{
  177. Name: "dashboard",
  178. Usage: "Enable the dashboard",
  179. }
  180. DashboardAddrFlag = cli.StringFlag{
  181. Name: "dashboard.addr",
  182. Usage: "Dashboard listening interface",
  183. Value: dashboard.DefaultConfig.Host,
  184. }
  185. DashboardPortFlag = cli.IntFlag{
  186. Name: "dashboard.host",
  187. Usage: "Dashboard listening port",
  188. Value: dashboard.DefaultConfig.Port,
  189. }
  190. DashboardRefreshFlag = cli.DurationFlag{
  191. Name: "dashboard.refresh",
  192. Usage: "Dashboard metrics collection refresh rate",
  193. Value: dashboard.DefaultConfig.Refresh,
  194. }
  195. DashboardAssetsFlag = cli.StringFlag{
  196. Name: "dashboard.assets",
  197. Usage: "Developer flag to serve the dashboard from the local file system",
  198. Value: dashboard.DefaultConfig.Assets,
  199. }
  200. // Ethash settings
  201. EthashCacheDirFlag = DirectoryFlag{
  202. Name: "ethash.cachedir",
  203. Usage: "Directory to store the ethash verification caches (default = inside the datadir)",
  204. }
  205. EthashCachesInMemoryFlag = cli.IntFlag{
  206. Name: "ethash.cachesinmem",
  207. Usage: "Number of recent ethash caches to keep in memory (16MB each)",
  208. Value: eth.DefaultConfig.EthashCachesInMem,
  209. }
  210. EthashCachesOnDiskFlag = cli.IntFlag{
  211. Name: "ethash.cachesondisk",
  212. Usage: "Number of recent ethash caches to keep on disk (16MB each)",
  213. Value: eth.DefaultConfig.EthashCachesOnDisk,
  214. }
  215. EthashDatasetDirFlag = DirectoryFlag{
  216. Name: "ethash.dagdir",
  217. Usage: "Directory to store the ethash mining DAGs (default = inside home folder)",
  218. Value: DirectoryString{eth.DefaultConfig.EthashDatasetDir},
  219. }
  220. EthashDatasetsInMemoryFlag = cli.IntFlag{
  221. Name: "ethash.dagsinmem",
  222. Usage: "Number of recent ethash mining DAGs to keep in memory (1+GB each)",
  223. Value: eth.DefaultConfig.EthashDatasetsInMem,
  224. }
  225. EthashDatasetsOnDiskFlag = cli.IntFlag{
  226. Name: "ethash.dagsondisk",
  227. Usage: "Number of recent ethash mining DAGs to keep on disk (1+GB each)",
  228. Value: eth.DefaultConfig.EthashDatasetsOnDisk,
  229. }
  230. // Transaction pool settings
  231. TxPoolNoLocalsFlag = cli.BoolFlag{
  232. Name: "txpool.nolocals",
  233. Usage: "Disables price exemptions for locally submitted transactions",
  234. }
  235. TxPoolJournalFlag = cli.StringFlag{
  236. Name: "txpool.journal",
  237. Usage: "Disk journal for local transaction to survive node restarts",
  238. Value: core.DefaultTxPoolConfig.Journal,
  239. }
  240. TxPoolRejournalFlag = cli.DurationFlag{
  241. Name: "txpool.rejournal",
  242. Usage: "Time interval to regenerate the local transaction journal",
  243. Value: core.DefaultTxPoolConfig.Rejournal,
  244. }
  245. TxPoolPriceLimitFlag = cli.Uint64Flag{
  246. Name: "txpool.pricelimit",
  247. Usage: "Minimum gas price limit to enforce for acceptance into the pool",
  248. Value: eth.DefaultConfig.TxPool.PriceLimit,
  249. }
  250. TxPoolPriceBumpFlag = cli.Uint64Flag{
  251. Name: "txpool.pricebump",
  252. Usage: "Price bump percentage to replace an already existing transaction",
  253. Value: eth.DefaultConfig.TxPool.PriceBump,
  254. }
  255. TxPoolAccountSlotsFlag = cli.Uint64Flag{
  256. Name: "txpool.accountslots",
  257. Usage: "Minimum number of executable transaction slots guaranteed per account",
  258. Value: eth.DefaultConfig.TxPool.AccountSlots,
  259. }
  260. TxPoolGlobalSlotsFlag = cli.Uint64Flag{
  261. Name: "txpool.globalslots",
  262. Usage: "Maximum number of executable transaction slots for all accounts",
  263. Value: eth.DefaultConfig.TxPool.GlobalSlots,
  264. }
  265. TxPoolAccountQueueFlag = cli.Uint64Flag{
  266. Name: "txpool.accountqueue",
  267. Usage: "Maximum number of non-executable transaction slots permitted per account",
  268. Value: eth.DefaultConfig.TxPool.AccountQueue,
  269. }
  270. TxPoolGlobalQueueFlag = cli.Uint64Flag{
  271. Name: "txpool.globalqueue",
  272. Usage: "Maximum number of non-executable transaction slots for all accounts",
  273. Value: eth.DefaultConfig.TxPool.GlobalQueue,
  274. }
  275. TxPoolLifetimeFlag = cli.DurationFlag{
  276. Name: "txpool.lifetime",
  277. Usage: "Maximum amount of time non-executable transaction are queued",
  278. Value: eth.DefaultConfig.TxPool.Lifetime,
  279. }
  280. // Performance tuning settings
  281. CacheFlag = cli.IntFlag{
  282. Name: "cache",
  283. Usage: "Megabytes of memory allocated to internal caching (min 16MB / database forced)",
  284. Value: 128,
  285. }
  286. TrieCacheGenFlag = cli.IntFlag{
  287. Name: "trie-cache-gens",
  288. Usage: "Number of trie node generations to keep in memory",
  289. Value: int(state.MaxTrieCacheGen),
  290. }
  291. // Miner settings
  292. MiningEnabledFlag = cli.BoolFlag{
  293. Name: "mine",
  294. Usage: "Enable mining",
  295. }
  296. MinerThreadsFlag = cli.IntFlag{
  297. Name: "minerthreads",
  298. Usage: "Number of CPU threads to use for mining",
  299. Value: runtime.NumCPU(),
  300. }
  301. TargetGasLimitFlag = cli.Uint64Flag{
  302. Name: "targetgaslimit",
  303. Usage: "Target gas limit sets the artificial target gas floor for the blocks to mine",
  304. Value: params.GenesisGasLimit.Uint64(),
  305. }
  306. EtherbaseFlag = cli.StringFlag{
  307. Name: "etherbase",
  308. Usage: "Public address for block mining rewards (default = first account created)",
  309. Value: "0",
  310. }
  311. GasPriceFlag = BigFlag{
  312. Name: "gasprice",
  313. Usage: "Minimal gas price to accept for mining a transactions",
  314. Value: eth.DefaultConfig.GasPrice,
  315. }
  316. ExtraDataFlag = cli.StringFlag{
  317. Name: "extradata",
  318. Usage: "Block extra data set by the miner (default = client version)",
  319. }
  320. // Account settings
  321. UnlockedAccountFlag = cli.StringFlag{
  322. Name: "unlock",
  323. Usage: "Comma separated list of accounts to unlock",
  324. Value: "",
  325. }
  326. PasswordFileFlag = cli.StringFlag{
  327. Name: "password",
  328. Usage: "Password file to use for non-interactive password input",
  329. Value: "",
  330. }
  331. VMEnableDebugFlag = cli.BoolFlag{
  332. Name: "vmdebug",
  333. Usage: "Record information useful for VM and contract debugging",
  334. }
  335. // Logging and debug settings
  336. EthStatsURLFlag = cli.StringFlag{
  337. Name: "ethstats",
  338. Usage: "Reporting URL of a ethstats service (nodename:secret@host:port)",
  339. }
  340. MetricsEnabledFlag = cli.BoolFlag{
  341. Name: metrics.MetricsEnabledFlag,
  342. Usage: "Enable metrics collection and reporting",
  343. }
  344. FakePoWFlag = cli.BoolFlag{
  345. Name: "fakepow",
  346. Usage: "Disables proof-of-work verification",
  347. }
  348. NoCompactionFlag = cli.BoolFlag{
  349. Name: "nocompaction",
  350. Usage: "Disables db compaction after import",
  351. }
  352. // RPC settings
  353. RPCEnabledFlag = cli.BoolFlag{
  354. Name: "rpc",
  355. Usage: "Enable the HTTP-RPC server",
  356. }
  357. RPCListenAddrFlag = cli.StringFlag{
  358. Name: "rpcaddr",
  359. Usage: "HTTP-RPC server listening interface",
  360. Value: node.DefaultHTTPHost,
  361. }
  362. RPCPortFlag = cli.IntFlag{
  363. Name: "rpcport",
  364. Usage: "HTTP-RPC server listening port",
  365. Value: node.DefaultHTTPPort,
  366. }
  367. RPCCORSDomainFlag = cli.StringFlag{
  368. Name: "rpccorsdomain",
  369. Usage: "Comma separated list of domains from which to accept cross origin requests (browser enforced)",
  370. Value: "",
  371. }
  372. RPCApiFlag = cli.StringFlag{
  373. Name: "rpcapi",
  374. Usage: "API's offered over the HTTP-RPC interface",
  375. Value: "",
  376. }
  377. IPCDisabledFlag = cli.BoolFlag{
  378. Name: "ipcdisable",
  379. Usage: "Disable the IPC-RPC server",
  380. }
  381. IPCPathFlag = DirectoryFlag{
  382. Name: "ipcpath",
  383. Usage: "Filename for IPC socket/pipe within the datadir (explicit paths escape it)",
  384. }
  385. WSEnabledFlag = cli.BoolFlag{
  386. Name: "ws",
  387. Usage: "Enable the WS-RPC server",
  388. }
  389. WSListenAddrFlag = cli.StringFlag{
  390. Name: "wsaddr",
  391. Usage: "WS-RPC server listening interface",
  392. Value: node.DefaultWSHost,
  393. }
  394. WSPortFlag = cli.IntFlag{
  395. Name: "wsport",
  396. Usage: "WS-RPC server listening port",
  397. Value: node.DefaultWSPort,
  398. }
  399. WSApiFlag = cli.StringFlag{
  400. Name: "wsapi",
  401. Usage: "API's offered over the WS-RPC interface",
  402. Value: "",
  403. }
  404. WSAllowedOriginsFlag = cli.StringFlag{
  405. Name: "wsorigins",
  406. Usage: "Origins from which to accept websockets requests",
  407. Value: "",
  408. }
  409. ExecFlag = cli.StringFlag{
  410. Name: "exec",
  411. Usage: "Execute JavaScript statement",
  412. }
  413. PreloadJSFlag = cli.StringFlag{
  414. Name: "preload",
  415. Usage: "Comma separated list of JavaScript files to preload into the console",
  416. }
  417. // Network Settings
  418. MaxPeersFlag = cli.IntFlag{
  419. Name: "maxpeers",
  420. Usage: "Maximum number of network peers (network disabled if set to 0)",
  421. Value: 25,
  422. }
  423. MaxPendingPeersFlag = cli.IntFlag{
  424. Name: "maxpendpeers",
  425. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  426. Value: 0,
  427. }
  428. ListenPortFlag = cli.IntFlag{
  429. Name: "port",
  430. Usage: "Network listening port",
  431. Value: 30303,
  432. }
  433. BootnodesFlag = cli.StringFlag{
  434. Name: "bootnodes",
  435. Usage: "Comma separated enode URLs for P2P discovery bootstrap (set v4+v5 instead for light servers)",
  436. Value: "",
  437. }
  438. BootnodesV4Flag = cli.StringFlag{
  439. Name: "bootnodesv4",
  440. Usage: "Comma separated enode URLs for P2P v4 discovery bootstrap (light server, full nodes)",
  441. Value: "",
  442. }
  443. BootnodesV5Flag = cli.StringFlag{
  444. Name: "bootnodesv5",
  445. Usage: "Comma separated enode URLs for P2P v5 discovery bootstrap (light server, light nodes)",
  446. Value: "",
  447. }
  448. NodeKeyFileFlag = cli.StringFlag{
  449. Name: "nodekey",
  450. Usage: "P2P node key file",
  451. }
  452. NodeKeyHexFlag = cli.StringFlag{
  453. Name: "nodekeyhex",
  454. Usage: "P2P node key as hex (for testing)",
  455. }
  456. NATFlag = cli.StringFlag{
  457. Name: "nat",
  458. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  459. Value: "any",
  460. }
  461. NoDiscoverFlag = cli.BoolFlag{
  462. Name: "nodiscover",
  463. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  464. }
  465. DiscoveryV5Flag = cli.BoolFlag{
  466. Name: "v5disc",
  467. Usage: "Enables the experimental RLPx V5 (Topic Discovery) mechanism",
  468. }
  469. NetrestrictFlag = cli.StringFlag{
  470. Name: "netrestrict",
  471. Usage: "Restricts network communication to the given IP networks (CIDR masks)",
  472. }
  473. // ATM the url is left to the user and deployment to
  474. JSpathFlag = cli.StringFlag{
  475. Name: "jspath",
  476. Usage: "JavaScript root path for `loadScript`",
  477. Value: ".",
  478. }
  479. // Gas price oracle settings
  480. GpoBlocksFlag = cli.IntFlag{
  481. Name: "gpoblocks",
  482. Usage: "Number of recent blocks to check for gas prices",
  483. Value: eth.DefaultConfig.GPO.Blocks,
  484. }
  485. GpoPercentileFlag = cli.IntFlag{
  486. Name: "gpopercentile",
  487. Usage: "Suggested gas price is the given percentile of a set of recent transaction gas prices",
  488. Value: eth.DefaultConfig.GPO.Percentile,
  489. }
  490. WhisperEnabledFlag = cli.BoolFlag{
  491. Name: "shh",
  492. Usage: "Enable Whisper",
  493. }
  494. WhisperMaxMessageSizeFlag = cli.IntFlag{
  495. Name: "shh.maxmessagesize",
  496. Usage: "Max message size accepted",
  497. Value: int(whisper.DefaultMaxMessageSize),
  498. }
  499. WhisperMinPOWFlag = cli.Float64Flag{
  500. Name: "shh.pow",
  501. Usage: "Minimum POW accepted",
  502. Value: whisper.DefaultMinimumPoW,
  503. }
  504. )
  505. // MakeDataDir retrieves the currently requested data directory, terminating
  506. // if none (or the empty string) is specified. If the node is starting a testnet,
  507. // the a subdirectory of the specified datadir will be used.
  508. func MakeDataDir(ctx *cli.Context) string {
  509. if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
  510. if ctx.GlobalBool(TestnetFlag.Name) {
  511. return filepath.Join(path, "testnet")
  512. }
  513. if ctx.GlobalBool(RinkebyFlag.Name) {
  514. return filepath.Join(path, "rinkeby")
  515. }
  516. return path
  517. }
  518. Fatalf("Cannot determine default data directory, please set manually (--datadir)")
  519. return ""
  520. }
  521. // setNodeKey creates a node key from set command line flags, either loading it
  522. // from a file or as a specified hex value. If neither flags were provided, this
  523. // method returns nil and an emphemeral key is to be generated.
  524. func setNodeKey(ctx *cli.Context, cfg *p2p.Config) {
  525. var (
  526. hex = ctx.GlobalString(NodeKeyHexFlag.Name)
  527. file = ctx.GlobalString(NodeKeyFileFlag.Name)
  528. key *ecdsa.PrivateKey
  529. err error
  530. )
  531. switch {
  532. case file != "" && hex != "":
  533. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  534. case file != "":
  535. if key, err = crypto.LoadECDSA(file); err != nil {
  536. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  537. }
  538. cfg.PrivateKey = key
  539. case hex != "":
  540. if key, err = crypto.HexToECDSA(hex); err != nil {
  541. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  542. }
  543. cfg.PrivateKey = key
  544. }
  545. }
  546. // setNodeUserIdent creates the user identifier from CLI flags.
  547. func setNodeUserIdent(ctx *cli.Context, cfg *node.Config) {
  548. if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
  549. cfg.UserIdent = identity
  550. }
  551. }
  552. // setBootstrapNodes creates a list of bootstrap nodes from the command line
  553. // flags, reverting to pre-configured ones if none have been specified.
  554. func setBootstrapNodes(ctx *cli.Context, cfg *p2p.Config) {
  555. urls := params.MainnetBootnodes
  556. switch {
  557. case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV4Flag.Name):
  558. if ctx.GlobalIsSet(BootnodesV4Flag.Name) {
  559. urls = strings.Split(ctx.GlobalString(BootnodesV4Flag.Name), ",")
  560. } else {
  561. urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
  562. }
  563. case ctx.GlobalBool(TestnetFlag.Name):
  564. urls = params.TestnetBootnodes
  565. case ctx.GlobalBool(RinkebyFlag.Name):
  566. urls = params.RinkebyBootnodes
  567. }
  568. cfg.BootstrapNodes = make([]*discover.Node, 0, len(urls))
  569. for _, url := range urls {
  570. node, err := discover.ParseNode(url)
  571. if err != nil {
  572. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  573. continue
  574. }
  575. cfg.BootstrapNodes = append(cfg.BootstrapNodes, node)
  576. }
  577. }
  578. // setBootstrapNodesV5 creates a list of bootstrap nodes from the command line
  579. // flags, reverting to pre-configured ones if none have been specified.
  580. func setBootstrapNodesV5(ctx *cli.Context, cfg *p2p.Config) {
  581. urls := params.DiscoveryV5Bootnodes
  582. switch {
  583. case ctx.GlobalIsSet(BootnodesFlag.Name) || ctx.GlobalIsSet(BootnodesV5Flag.Name):
  584. if ctx.GlobalIsSet(BootnodesV5Flag.Name) {
  585. urls = strings.Split(ctx.GlobalString(BootnodesV5Flag.Name), ",")
  586. } else {
  587. urls = strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",")
  588. }
  589. case ctx.GlobalBool(RinkebyFlag.Name):
  590. urls = params.RinkebyV5Bootnodes
  591. case cfg.BootstrapNodesV5 != nil:
  592. return // already set, don't apply defaults.
  593. }
  594. cfg.BootstrapNodesV5 = make([]*discv5.Node, 0, len(urls))
  595. for _, url := range urls {
  596. node, err := discv5.ParseNode(url)
  597. if err != nil {
  598. log.Error("Bootstrap URL invalid", "enode", url, "err", err)
  599. continue
  600. }
  601. cfg.BootstrapNodesV5 = append(cfg.BootstrapNodesV5, node)
  602. }
  603. }
  604. // setListenAddress creates a TCP listening address string from set command
  605. // line flags.
  606. func setListenAddress(ctx *cli.Context, cfg *p2p.Config) {
  607. if ctx.GlobalIsSet(ListenPortFlag.Name) {
  608. cfg.ListenAddr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
  609. }
  610. }
  611. // setDiscoveryV5Address creates a UDP listening address string from set command
  612. // line flags for the V5 discovery protocol.
  613. func setDiscoveryV5Address(ctx *cli.Context, cfg *p2p.Config) {
  614. if ctx.GlobalIsSet(ListenPortFlag.Name) {
  615. cfg.DiscoveryV5Addr = fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name)+1)
  616. }
  617. }
  618. // setNAT creates a port mapper from command line flags.
  619. func setNAT(ctx *cli.Context, cfg *p2p.Config) {
  620. if ctx.GlobalIsSet(NATFlag.Name) {
  621. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  622. if err != nil {
  623. Fatalf("Option %s: %v", NATFlag.Name, err)
  624. }
  625. cfg.NAT = natif
  626. }
  627. }
  628. // splitAndTrim splits input separated by a comma
  629. // and trims excessive white space from the substrings.
  630. func splitAndTrim(input string) []string {
  631. result := strings.Split(input, ",")
  632. for i, r := range result {
  633. result[i] = strings.TrimSpace(r)
  634. }
  635. return result
  636. }
  637. // setHTTP creates the HTTP RPC listener interface string from the set
  638. // command line flags, returning empty if the HTTP endpoint is disabled.
  639. func setHTTP(ctx *cli.Context, cfg *node.Config) {
  640. if ctx.GlobalBool(RPCEnabledFlag.Name) && cfg.HTTPHost == "" {
  641. cfg.HTTPHost = "127.0.0.1"
  642. if ctx.GlobalIsSet(RPCListenAddrFlag.Name) {
  643. cfg.HTTPHost = ctx.GlobalString(RPCListenAddrFlag.Name)
  644. }
  645. }
  646. if ctx.GlobalIsSet(RPCPortFlag.Name) {
  647. cfg.HTTPPort = ctx.GlobalInt(RPCPortFlag.Name)
  648. }
  649. if ctx.GlobalIsSet(RPCCORSDomainFlag.Name) {
  650. cfg.HTTPCors = splitAndTrim(ctx.GlobalString(RPCCORSDomainFlag.Name))
  651. }
  652. if ctx.GlobalIsSet(RPCApiFlag.Name) {
  653. cfg.HTTPModules = splitAndTrim(ctx.GlobalString(RPCApiFlag.Name))
  654. }
  655. }
  656. // setWS creates the WebSocket RPC listener interface string from the set
  657. // command line flags, returning empty if the HTTP endpoint is disabled.
  658. func setWS(ctx *cli.Context, cfg *node.Config) {
  659. if ctx.GlobalBool(WSEnabledFlag.Name) && cfg.WSHost == "" {
  660. cfg.WSHost = "127.0.0.1"
  661. if ctx.GlobalIsSet(WSListenAddrFlag.Name) {
  662. cfg.WSHost = ctx.GlobalString(WSListenAddrFlag.Name)
  663. }
  664. }
  665. if ctx.GlobalIsSet(WSPortFlag.Name) {
  666. cfg.WSPort = ctx.GlobalInt(WSPortFlag.Name)
  667. }
  668. if ctx.GlobalIsSet(WSAllowedOriginsFlag.Name) {
  669. cfg.WSOrigins = splitAndTrim(ctx.GlobalString(WSAllowedOriginsFlag.Name))
  670. }
  671. if ctx.GlobalIsSet(WSApiFlag.Name) {
  672. cfg.WSModules = splitAndTrim(ctx.GlobalString(WSApiFlag.Name))
  673. }
  674. }
  675. // setIPC creates an IPC path configuration from the set command line flags,
  676. // returning an empty string if IPC was explicitly disabled, or the set path.
  677. func setIPC(ctx *cli.Context, cfg *node.Config) {
  678. checkExclusive(ctx, IPCDisabledFlag, IPCPathFlag)
  679. switch {
  680. case ctx.GlobalBool(IPCDisabledFlag.Name):
  681. cfg.IPCPath = ""
  682. case ctx.GlobalIsSet(IPCPathFlag.Name):
  683. cfg.IPCPath = ctx.GlobalString(IPCPathFlag.Name)
  684. }
  685. }
  686. // makeDatabaseHandles raises out the number of allowed file handles per process
  687. // for Geth and returns half of the allowance to assign to the database.
  688. func makeDatabaseHandles() int {
  689. if err := raiseFdLimit(2048); err != nil {
  690. Fatalf("Failed to raise file descriptor allowance: %v", err)
  691. }
  692. limit, err := getFdLimit()
  693. if err != nil {
  694. Fatalf("Failed to retrieve file descriptor allowance: %v", err)
  695. }
  696. if limit > 2048 { // cap database file descriptors even if more is available
  697. limit = 2048
  698. }
  699. return limit / 2 // Leave half for networking and other stuff
  700. }
  701. // MakeAddress converts an account specified directly as a hex encoded string or
  702. // a key index in the key store to an internal account representation.
  703. func MakeAddress(ks *keystore.KeyStore, account string) (accounts.Account, error) {
  704. // If the specified account is a valid address, return it
  705. if common.IsHexAddress(account) {
  706. return accounts.Account{Address: common.HexToAddress(account)}, nil
  707. }
  708. // Otherwise try to interpret the account as a keystore index
  709. index, err := strconv.Atoi(account)
  710. if err != nil || index < 0 {
  711. return accounts.Account{}, fmt.Errorf("invalid account address or index %q", account)
  712. }
  713. accs := ks.Accounts()
  714. if len(accs) <= index {
  715. return accounts.Account{}, fmt.Errorf("index %d higher than number of accounts %d", index, len(accs))
  716. }
  717. return accs[index], nil
  718. }
  719. // setEtherbase retrieves the etherbase either from the directly specified
  720. // command line flags or from the keystore if CLI indexed.
  721. func setEtherbase(ctx *cli.Context, ks *keystore.KeyStore, cfg *eth.Config) {
  722. if ctx.GlobalIsSet(EtherbaseFlag.Name) {
  723. account, err := MakeAddress(ks, ctx.GlobalString(EtherbaseFlag.Name))
  724. if err != nil {
  725. Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
  726. }
  727. cfg.Etherbase = account.Address
  728. return
  729. }
  730. accounts := ks.Accounts()
  731. if (cfg.Etherbase == common.Address{}) {
  732. if len(accounts) > 0 {
  733. cfg.Etherbase = accounts[0].Address
  734. } else {
  735. log.Warn("No etherbase set and no accounts found as default")
  736. }
  737. }
  738. }
  739. // MakePasswordList reads password lines from the file specified by the global --password flag.
  740. func MakePasswordList(ctx *cli.Context) []string {
  741. path := ctx.GlobalString(PasswordFileFlag.Name)
  742. if path == "" {
  743. return nil
  744. }
  745. text, err := ioutil.ReadFile(path)
  746. if err != nil {
  747. Fatalf("Failed to read password file: %v", err)
  748. }
  749. lines := strings.Split(string(text), "\n")
  750. // Sanitise DOS line endings.
  751. for i := range lines {
  752. lines[i] = strings.TrimRight(lines[i], "\r")
  753. }
  754. return lines
  755. }
  756. func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) {
  757. setNodeKey(ctx, cfg)
  758. setNAT(ctx, cfg)
  759. setListenAddress(ctx, cfg)
  760. setDiscoveryV5Address(ctx, cfg)
  761. setBootstrapNodes(ctx, cfg)
  762. setBootstrapNodesV5(ctx, cfg)
  763. if ctx.GlobalIsSet(MaxPeersFlag.Name) {
  764. cfg.MaxPeers = ctx.GlobalInt(MaxPeersFlag.Name)
  765. }
  766. if ctx.GlobalIsSet(MaxPendingPeersFlag.Name) {
  767. cfg.MaxPendingPeers = ctx.GlobalInt(MaxPendingPeersFlag.Name)
  768. }
  769. if ctx.GlobalIsSet(NoDiscoverFlag.Name) || ctx.GlobalBool(LightModeFlag.Name) {
  770. cfg.NoDiscovery = true
  771. }
  772. // if we're running a light client or server, force enable the v5 peer discovery
  773. // unless it is explicitly disabled with --nodiscover note that explicitly specifying
  774. // --v5disc overrides --nodiscover, in which case the later only disables v4 discovery
  775. forceV5Discovery := (ctx.GlobalBool(LightModeFlag.Name) || ctx.GlobalInt(LightServFlag.Name) > 0) && !ctx.GlobalBool(NoDiscoverFlag.Name)
  776. if ctx.GlobalIsSet(DiscoveryV5Flag.Name) {
  777. cfg.DiscoveryV5 = ctx.GlobalBool(DiscoveryV5Flag.Name)
  778. } else if forceV5Discovery {
  779. cfg.DiscoveryV5 = true
  780. }
  781. if netrestrict := ctx.GlobalString(NetrestrictFlag.Name); netrestrict != "" {
  782. list, err := netutil.ParseNetlist(netrestrict)
  783. if err != nil {
  784. Fatalf("Option %q: %v", NetrestrictFlag.Name, err)
  785. }
  786. cfg.NetRestrict = list
  787. }
  788. if ctx.GlobalBool(DeveloperFlag.Name) {
  789. // --dev mode can't use p2p networking.
  790. cfg.MaxPeers = 0
  791. cfg.ListenAddr = ":0"
  792. cfg.DiscoveryV5Addr = ":0"
  793. cfg.NoDiscovery = true
  794. cfg.DiscoveryV5 = false
  795. }
  796. }
  797. // SetNodeConfig applies node-related command line flags to the config.
  798. func SetNodeConfig(ctx *cli.Context, cfg *node.Config) {
  799. SetP2PConfig(ctx, &cfg.P2P)
  800. setIPC(ctx, cfg)
  801. setHTTP(ctx, cfg)
  802. setWS(ctx, cfg)
  803. setNodeUserIdent(ctx, cfg)
  804. switch {
  805. case ctx.GlobalIsSet(DataDirFlag.Name):
  806. cfg.DataDir = ctx.GlobalString(DataDirFlag.Name)
  807. case ctx.GlobalBool(DeveloperFlag.Name):
  808. cfg.DataDir = "" // unless explicitly requested, use memory databases
  809. case ctx.GlobalBool(TestnetFlag.Name):
  810. cfg.DataDir = filepath.Join(node.DefaultDataDir(), "testnet")
  811. case ctx.GlobalBool(RinkebyFlag.Name):
  812. cfg.DataDir = filepath.Join(node.DefaultDataDir(), "rinkeby")
  813. }
  814. if ctx.GlobalIsSet(KeyStoreDirFlag.Name) {
  815. cfg.KeyStoreDir = ctx.GlobalString(KeyStoreDirFlag.Name)
  816. }
  817. if ctx.GlobalIsSet(LightKDFFlag.Name) {
  818. cfg.UseLightweightKDF = ctx.GlobalBool(LightKDFFlag.Name)
  819. }
  820. if ctx.GlobalIsSet(NoUSBFlag.Name) {
  821. cfg.NoUSB = ctx.GlobalBool(NoUSBFlag.Name)
  822. }
  823. }
  824. func setGPO(ctx *cli.Context, cfg *gasprice.Config) {
  825. if ctx.GlobalIsSet(GpoBlocksFlag.Name) {
  826. cfg.Blocks = ctx.GlobalInt(GpoBlocksFlag.Name)
  827. }
  828. if ctx.GlobalIsSet(GpoPercentileFlag.Name) {
  829. cfg.Percentile = ctx.GlobalInt(GpoPercentileFlag.Name)
  830. }
  831. }
  832. func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) {
  833. if ctx.GlobalIsSet(TxPoolNoLocalsFlag.Name) {
  834. cfg.NoLocals = ctx.GlobalBool(TxPoolNoLocalsFlag.Name)
  835. }
  836. if ctx.GlobalIsSet(TxPoolJournalFlag.Name) {
  837. cfg.Journal = ctx.GlobalString(TxPoolJournalFlag.Name)
  838. }
  839. if ctx.GlobalIsSet(TxPoolRejournalFlag.Name) {
  840. cfg.Rejournal = ctx.GlobalDuration(TxPoolRejournalFlag.Name)
  841. }
  842. if ctx.GlobalIsSet(TxPoolPriceLimitFlag.Name) {
  843. cfg.PriceLimit = ctx.GlobalUint64(TxPoolPriceLimitFlag.Name)
  844. }
  845. if ctx.GlobalIsSet(TxPoolPriceBumpFlag.Name) {
  846. cfg.PriceBump = ctx.GlobalUint64(TxPoolPriceBumpFlag.Name)
  847. }
  848. if ctx.GlobalIsSet(TxPoolAccountSlotsFlag.Name) {
  849. cfg.AccountSlots = ctx.GlobalUint64(TxPoolAccountSlotsFlag.Name)
  850. }
  851. if ctx.GlobalIsSet(TxPoolGlobalSlotsFlag.Name) {
  852. cfg.GlobalSlots = ctx.GlobalUint64(TxPoolGlobalSlotsFlag.Name)
  853. }
  854. if ctx.GlobalIsSet(TxPoolAccountQueueFlag.Name) {
  855. cfg.AccountQueue = ctx.GlobalUint64(TxPoolAccountQueueFlag.Name)
  856. }
  857. if ctx.GlobalIsSet(TxPoolGlobalQueueFlag.Name) {
  858. cfg.GlobalQueue = ctx.GlobalUint64(TxPoolGlobalQueueFlag.Name)
  859. }
  860. if ctx.GlobalIsSet(TxPoolLifetimeFlag.Name) {
  861. cfg.Lifetime = ctx.GlobalDuration(TxPoolLifetimeFlag.Name)
  862. }
  863. }
  864. func setEthash(ctx *cli.Context, cfg *eth.Config) {
  865. if ctx.GlobalIsSet(EthashCacheDirFlag.Name) {
  866. cfg.EthashCacheDir = ctx.GlobalString(EthashCacheDirFlag.Name)
  867. }
  868. if ctx.GlobalIsSet(EthashDatasetDirFlag.Name) {
  869. cfg.EthashDatasetDir = ctx.GlobalString(EthashDatasetDirFlag.Name)
  870. }
  871. if ctx.GlobalIsSet(EthashCachesInMemoryFlag.Name) {
  872. cfg.EthashCachesInMem = ctx.GlobalInt(EthashCachesInMemoryFlag.Name)
  873. }
  874. if ctx.GlobalIsSet(EthashCachesOnDiskFlag.Name) {
  875. cfg.EthashCachesOnDisk = ctx.GlobalInt(EthashCachesOnDiskFlag.Name)
  876. }
  877. if ctx.GlobalIsSet(EthashDatasetsInMemoryFlag.Name) {
  878. cfg.EthashDatasetsInMem = ctx.GlobalInt(EthashDatasetsInMemoryFlag.Name)
  879. }
  880. if ctx.GlobalIsSet(EthashDatasetsOnDiskFlag.Name) {
  881. cfg.EthashDatasetsOnDisk = ctx.GlobalInt(EthashDatasetsOnDiskFlag.Name)
  882. }
  883. }
  884. func checkExclusive(ctx *cli.Context, flags ...cli.Flag) {
  885. set := make([]string, 0, 1)
  886. for _, flag := range flags {
  887. if ctx.GlobalIsSet(flag.GetName()) {
  888. set = append(set, "--"+flag.GetName())
  889. }
  890. }
  891. if len(set) > 1 {
  892. Fatalf("flags %v can't be used at the same time", strings.Join(set, ", "))
  893. }
  894. }
  895. // SetShhConfig applies shh-related command line flags to the config.
  896. func SetShhConfig(ctx *cli.Context, stack *node.Node, cfg *whisper.Config) {
  897. if ctx.GlobalIsSet(WhisperMaxMessageSizeFlag.Name) {
  898. cfg.MaxMessageSize = uint32(ctx.GlobalUint(WhisperMaxMessageSizeFlag.Name))
  899. }
  900. if ctx.GlobalIsSet(WhisperMinPOWFlag.Name) {
  901. cfg.MinimumAcceptedPOW = ctx.GlobalFloat64(WhisperMinPOWFlag.Name)
  902. }
  903. }
  904. // SetEthConfig applies eth-related command line flags to the config.
  905. func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
  906. // Avoid conflicting network flags
  907. checkExclusive(ctx, DeveloperFlag, TestnetFlag, RinkebyFlag)
  908. checkExclusive(ctx, FastSyncFlag, LightModeFlag, SyncModeFlag)
  909. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  910. setEtherbase(ctx, ks, cfg)
  911. setGPO(ctx, &cfg.GPO)
  912. setTxPool(ctx, &cfg.TxPool)
  913. setEthash(ctx, cfg)
  914. switch {
  915. case ctx.GlobalIsSet(SyncModeFlag.Name):
  916. cfg.SyncMode = *GlobalTextMarshaler(ctx, SyncModeFlag.Name).(*downloader.SyncMode)
  917. case ctx.GlobalBool(FastSyncFlag.Name):
  918. cfg.SyncMode = downloader.FastSync
  919. case ctx.GlobalBool(LightModeFlag.Name):
  920. cfg.SyncMode = downloader.LightSync
  921. }
  922. if ctx.GlobalIsSet(LightServFlag.Name) {
  923. cfg.LightServ = ctx.GlobalInt(LightServFlag.Name)
  924. }
  925. if ctx.GlobalIsSet(LightPeersFlag.Name) {
  926. cfg.LightPeers = ctx.GlobalInt(LightPeersFlag.Name)
  927. }
  928. if ctx.GlobalIsSet(NetworkIdFlag.Name) {
  929. cfg.NetworkId = ctx.GlobalUint64(NetworkIdFlag.Name)
  930. }
  931. if ctx.GlobalIsSet(CacheFlag.Name) {
  932. cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name)
  933. }
  934. cfg.DatabaseHandles = makeDatabaseHandles()
  935. if ctx.GlobalIsSet(MinerThreadsFlag.Name) {
  936. cfg.MinerThreads = ctx.GlobalInt(MinerThreadsFlag.Name)
  937. }
  938. if ctx.GlobalIsSet(DocRootFlag.Name) {
  939. cfg.DocRoot = ctx.GlobalString(DocRootFlag.Name)
  940. }
  941. if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  942. cfg.ExtraData = []byte(ctx.GlobalString(ExtraDataFlag.Name))
  943. }
  944. if ctx.GlobalIsSet(GasPriceFlag.Name) {
  945. cfg.GasPrice = GlobalBig(ctx, GasPriceFlag.Name)
  946. }
  947. if ctx.GlobalIsSet(VMEnableDebugFlag.Name) {
  948. // TODO(fjl): force-enable this in --dev mode
  949. cfg.EnablePreimageRecording = ctx.GlobalBool(VMEnableDebugFlag.Name)
  950. }
  951. // Override any default configs for hard coded networks.
  952. switch {
  953. case ctx.GlobalBool(TestnetFlag.Name):
  954. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  955. cfg.NetworkId = 3
  956. }
  957. cfg.Genesis = core.DefaultTestnetGenesisBlock()
  958. case ctx.GlobalBool(RinkebyFlag.Name):
  959. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  960. cfg.NetworkId = 4
  961. }
  962. cfg.Genesis = core.DefaultRinkebyGenesisBlock()
  963. case ctx.GlobalBool(DeveloperFlag.Name):
  964. // Create new developer account or reuse existing one
  965. var (
  966. developer accounts.Account
  967. err error
  968. )
  969. if accs := ks.Accounts(); len(accs) > 0 {
  970. developer = ks.Accounts()[0]
  971. } else {
  972. developer, err = ks.NewAccount("")
  973. if err != nil {
  974. Fatalf("Failed to create developer account: %v", err)
  975. }
  976. }
  977. if err := ks.Unlock(developer, ""); err != nil {
  978. Fatalf("Failed to unlock developer account: %v", err)
  979. }
  980. log.Info("Using developer account", "address", developer.Address)
  981. cfg.Genesis = core.DeveloperGenesisBlock(uint64(ctx.GlobalInt(DeveloperPeriodFlag.Name)), developer.Address)
  982. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  983. cfg.GasPrice = big.NewInt(1)
  984. }
  985. }
  986. // TODO(fjl): move trie cache generations into config
  987. if gen := ctx.GlobalInt(TrieCacheGenFlag.Name); gen > 0 {
  988. state.MaxTrieCacheGen = uint16(gen)
  989. }
  990. }
  991. // SetDashboardConfig applies dashboard related command line flags to the config.
  992. func SetDashboardConfig(ctx *cli.Context, cfg *dashboard.Config) {
  993. cfg.Host = ctx.GlobalString(DashboardAddrFlag.Name)
  994. cfg.Port = ctx.GlobalInt(DashboardPortFlag.Name)
  995. cfg.Refresh = ctx.GlobalDuration(DashboardRefreshFlag.Name)
  996. cfg.Assets = ctx.GlobalString(DashboardAssetsFlag.Name)
  997. }
  998. // RegisterEthService adds an Ethereum client to the stack.
  999. func RegisterEthService(stack *node.Node, cfg *eth.Config) {
  1000. var err error
  1001. if cfg.SyncMode == downloader.LightSync {
  1002. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1003. return les.New(ctx, cfg)
  1004. })
  1005. } else {
  1006. err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1007. fullNode, err := eth.New(ctx, cfg)
  1008. if fullNode != nil && cfg.LightServ > 0 {
  1009. ls, _ := les.NewLesServer(fullNode, cfg)
  1010. fullNode.AddLesServer(ls)
  1011. }
  1012. return fullNode, err
  1013. })
  1014. }
  1015. if err != nil {
  1016. Fatalf("Failed to register the Ethereum service: %v", err)
  1017. }
  1018. }
  1019. // RegisterDashboardService adds a dashboard to the stack.
  1020. func RegisterDashboardService(stack *node.Node, cfg *dashboard.Config) {
  1021. stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1022. return dashboard.New(cfg)
  1023. })
  1024. }
  1025. // RegisterShhService configures Whisper and adds it to the given node.
  1026. func RegisterShhService(stack *node.Node, cfg *whisper.Config) {
  1027. if err := stack.Register(func(n *node.ServiceContext) (node.Service, error) {
  1028. return whisper.New(cfg), nil
  1029. }); err != nil {
  1030. Fatalf("Failed to register the Whisper service: %v", err)
  1031. }
  1032. }
  1033. // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
  1034. // th egiven node.
  1035. func RegisterEthStatsService(stack *node.Node, url string) {
  1036. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  1037. // Retrieve both eth and les services
  1038. var ethServ *eth.Ethereum
  1039. ctx.Service(&ethServ)
  1040. var lesServ *les.LightEthereum
  1041. ctx.Service(&lesServ)
  1042. return ethstats.New(url, ethServ, lesServ)
  1043. }); err != nil {
  1044. Fatalf("Failed to register the Ethereum Stats service: %v", err)
  1045. }
  1046. }
  1047. // SetupNetwork configures the system for either the main net or some test network.
  1048. func SetupNetwork(ctx *cli.Context) {
  1049. // TODO(fjl): move target gas limit into config
  1050. params.TargetGasLimit = new(big.Int).SetUint64(ctx.GlobalUint64(TargetGasLimitFlag.Name))
  1051. }
  1052. // MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
  1053. func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
  1054. var (
  1055. cache = ctx.GlobalInt(CacheFlag.Name)
  1056. handles = makeDatabaseHandles()
  1057. )
  1058. name := "chaindata"
  1059. if ctx.GlobalBool(LightModeFlag.Name) {
  1060. name = "lightchaindata"
  1061. }
  1062. chainDb, err := stack.OpenDatabase(name, cache, handles)
  1063. if err != nil {
  1064. Fatalf("Could not open database: %v", err)
  1065. }
  1066. return chainDb
  1067. }
  1068. func MakeGenesis(ctx *cli.Context) *core.Genesis {
  1069. var genesis *core.Genesis
  1070. switch {
  1071. case ctx.GlobalBool(TestnetFlag.Name):
  1072. genesis = core.DefaultTestnetGenesisBlock()
  1073. case ctx.GlobalBool(RinkebyFlag.Name):
  1074. genesis = core.DefaultRinkebyGenesisBlock()
  1075. case ctx.GlobalBool(DeveloperFlag.Name):
  1076. Fatalf("Developer chains are ephemeral")
  1077. }
  1078. return genesis
  1079. }
  1080. // MakeChain creates a chain manager from set command line flags.
  1081. func MakeChain(ctx *cli.Context, stack *node.Node) (chain *core.BlockChain, chainDb ethdb.Database) {
  1082. var err error
  1083. chainDb = MakeChainDatabase(ctx, stack)
  1084. config, _, err := core.SetupGenesisBlock(chainDb, MakeGenesis(ctx))
  1085. if err != nil {
  1086. Fatalf("%v", err)
  1087. }
  1088. var engine consensus.Engine
  1089. if config.Clique != nil {
  1090. engine = clique.New(config.Clique, chainDb)
  1091. } else {
  1092. engine = ethash.NewFaker()
  1093. if !ctx.GlobalBool(FakePoWFlag.Name) {
  1094. engine = ethash.New(
  1095. stack.ResolvePath(eth.DefaultConfig.EthashCacheDir), eth.DefaultConfig.EthashCachesInMem, eth.DefaultConfig.EthashCachesOnDisk,
  1096. stack.ResolvePath(eth.DefaultConfig.EthashDatasetDir), eth.DefaultConfig.EthashDatasetsInMem, eth.DefaultConfig.EthashDatasetsOnDisk,
  1097. )
  1098. }
  1099. }
  1100. vmcfg := vm.Config{EnablePreimageRecording: ctx.GlobalBool(VMEnableDebugFlag.Name)}
  1101. chain, err = core.NewBlockChain(chainDb, config, engine, vmcfg)
  1102. if err != nil {
  1103. Fatalf("Can't create BlockChain: %v", err)
  1104. }
  1105. return chain, chainDb
  1106. }
  1107. // MakeConsolePreloads retrieves the absolute paths for the console JavaScript
  1108. // scripts to preload before starting.
  1109. func MakeConsolePreloads(ctx *cli.Context) []string {
  1110. // Skip preloading if there's nothing to preload
  1111. if ctx.GlobalString(PreloadJSFlag.Name) == "" {
  1112. return nil
  1113. }
  1114. // Otherwise resolve absolute paths and return them
  1115. preloads := []string{}
  1116. assets := ctx.GlobalString(JSpathFlag.Name)
  1117. for _, file := range strings.Split(ctx.GlobalString(PreloadJSFlag.Name), ",") {
  1118. preloads = append(preloads, common.AbsolutePath(assets, strings.TrimSpace(file)))
  1119. }
  1120. return preloads
  1121. }
  1122. // MigrateFlags sets the global flag from a local flag when it's set.
  1123. // This is a temporary function used for migrating old command/flags to the
  1124. // new format.
  1125. //
  1126. // e.g. geth account new --keystore /tmp/mykeystore --lightkdf
  1127. //
  1128. // is equivalent after calling this method with:
  1129. //
  1130. // geth --keystore /tmp/mykeystore --lightkdf account new
  1131. //
  1132. // This allows the use of the existing configuration functionality.
  1133. // When all flags are migrated this function can be removed and the existing
  1134. // configuration functionality must be changed that is uses local flags
  1135. func MigrateFlags(action func(ctx *cli.Context) error) func(*cli.Context) error {
  1136. return func(ctx *cli.Context) error {
  1137. for _, name := range ctx.FlagNames() {
  1138. if ctx.IsSet(name) {
  1139. ctx.GlobalSet(name, ctx.String(name))
  1140. }
  1141. }
  1142. return action(ctx)
  1143. }
  1144. }