main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. // Copyright 2014 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. // geth is the official command-line client for Ethereum.
  17. package main
  18. import (
  19. "fmt"
  20. "math"
  21. "os"
  22. "runtime"
  23. godebug "runtime/debug"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "time"
  28. "github.com/elastic/gosigar"
  29. "github.com/ethereum/go-ethereum/accounts"
  30. "github.com/ethereum/go-ethereum/accounts/keystore"
  31. "github.com/ethereum/go-ethereum/cmd/utils"
  32. "github.com/ethereum/go-ethereum/common"
  33. "github.com/ethereum/go-ethereum/console"
  34. "github.com/ethereum/go-ethereum/eth"
  35. "github.com/ethereum/go-ethereum/eth/downloader"
  36. "github.com/ethereum/go-ethereum/ethclient"
  37. "github.com/ethereum/go-ethereum/internal/debug"
  38. "github.com/ethereum/go-ethereum/les"
  39. "github.com/ethereum/go-ethereum/log"
  40. "github.com/ethereum/go-ethereum/metrics"
  41. "github.com/ethereum/go-ethereum/node"
  42. cli "gopkg.in/urfave/cli.v1"
  43. )
  44. const (
  45. clientIdentifier = "geth" // Client identifier to advertise over the network
  46. )
  47. var (
  48. // Git SHA1 commit hash of the release (set via linker flags)
  49. gitCommit = ""
  50. gitDate = ""
  51. // The app that holds all commands and flags.
  52. app = utils.NewApp(gitCommit, gitDate, "the go-ethereum command line interface")
  53. // flags that configure the node
  54. nodeFlags = []cli.Flag{
  55. utils.IdentityFlag,
  56. utils.UnlockedAccountFlag,
  57. utils.PasswordFileFlag,
  58. utils.BootnodesFlag,
  59. utils.BootnodesV4Flag,
  60. utils.BootnodesV5Flag,
  61. utils.DataDirFlag,
  62. utils.AncientFlag,
  63. utils.KeyStoreDirFlag,
  64. utils.ExternalSignerFlag,
  65. utils.NoUSBFlag,
  66. utils.SmartCardDaemonPathFlag,
  67. utils.OverrideIstanbulFlag,
  68. utils.DashboardEnabledFlag,
  69. utils.DashboardAddrFlag,
  70. utils.DashboardPortFlag,
  71. utils.DashboardRefreshFlag,
  72. utils.EthashCacheDirFlag,
  73. utils.EthashCachesInMemoryFlag,
  74. utils.EthashCachesOnDiskFlag,
  75. utils.EthashDatasetDirFlag,
  76. utils.EthashDatasetsInMemoryFlag,
  77. utils.EthashDatasetsOnDiskFlag,
  78. utils.TxPoolLocalsFlag,
  79. utils.TxPoolNoLocalsFlag,
  80. utils.TxPoolJournalFlag,
  81. utils.TxPoolRejournalFlag,
  82. utils.TxPoolPriceLimitFlag,
  83. utils.TxPoolPriceBumpFlag,
  84. utils.TxPoolAccountSlotsFlag,
  85. utils.TxPoolGlobalSlotsFlag,
  86. utils.TxPoolAccountQueueFlag,
  87. utils.TxPoolGlobalQueueFlag,
  88. utils.TxPoolLifetimeFlag,
  89. utils.SyncModeFlag,
  90. utils.ExitWhenSyncedFlag,
  91. utils.GCModeFlag,
  92. utils.LightServeFlag,
  93. utils.LightLegacyServFlag,
  94. utils.LightIngressFlag,
  95. utils.LightEgressFlag,
  96. utils.LightMaxPeersFlag,
  97. utils.LightLegacyPeersFlag,
  98. utils.LightKDFFlag,
  99. utils.UltraLightServersFlag,
  100. utils.UltraLightFractionFlag,
  101. utils.UltraLightOnlyAnnounceFlag,
  102. utils.WhitelistFlag,
  103. utils.CacheFlag,
  104. utils.CacheDatabaseFlag,
  105. utils.CacheTrieFlag,
  106. utils.CacheGCFlag,
  107. utils.CacheNoPrefetchFlag,
  108. utils.ListenPortFlag,
  109. utils.MaxPeersFlag,
  110. utils.MaxPendingPeersFlag,
  111. utils.MiningEnabledFlag,
  112. utils.MinerThreadsFlag,
  113. utils.MinerLegacyThreadsFlag,
  114. utils.MinerNotifyFlag,
  115. utils.MinerGasTargetFlag,
  116. utils.MinerLegacyGasTargetFlag,
  117. utils.MinerGasLimitFlag,
  118. utils.MinerGasPriceFlag,
  119. utils.MinerLegacyGasPriceFlag,
  120. utils.MinerEtherbaseFlag,
  121. utils.MinerLegacyEtherbaseFlag,
  122. utils.MinerExtraDataFlag,
  123. utils.MinerLegacyExtraDataFlag,
  124. utils.MinerRecommitIntervalFlag,
  125. utils.MinerNoVerfiyFlag,
  126. utils.NATFlag,
  127. utils.NoDiscoverFlag,
  128. utils.DiscoveryV5Flag,
  129. utils.NetrestrictFlag,
  130. utils.NodeKeyFileFlag,
  131. utils.NodeKeyHexFlag,
  132. utils.DeveloperFlag,
  133. utils.DeveloperPeriodFlag,
  134. utils.TestnetFlag,
  135. utils.RinkebyFlag,
  136. utils.GoerliFlag,
  137. utils.VMEnableDebugFlag,
  138. utils.NetworkIdFlag,
  139. utils.EthStatsURLFlag,
  140. utils.FakePoWFlag,
  141. utils.NoCompactionFlag,
  142. utils.GpoBlocksFlag,
  143. utils.GpoPercentileFlag,
  144. utils.EWASMInterpreterFlag,
  145. utils.EVMInterpreterFlag,
  146. configFileFlag,
  147. }
  148. rpcFlags = []cli.Flag{
  149. utils.RPCEnabledFlag,
  150. utils.RPCListenAddrFlag,
  151. utils.RPCPortFlag,
  152. utils.RPCCORSDomainFlag,
  153. utils.RPCVirtualHostsFlag,
  154. utils.GraphQLEnabledFlag,
  155. utils.GraphQLListenAddrFlag,
  156. utils.GraphQLPortFlag,
  157. utils.GraphQLCORSDomainFlag,
  158. utils.GraphQLVirtualHostsFlag,
  159. utils.RPCApiFlag,
  160. utils.WSEnabledFlag,
  161. utils.WSListenAddrFlag,
  162. utils.WSPortFlag,
  163. utils.WSApiFlag,
  164. utils.WSAllowedOriginsFlag,
  165. utils.IPCDisabledFlag,
  166. utils.IPCPathFlag,
  167. utils.InsecureUnlockAllowedFlag,
  168. utils.RPCGlobalGasCap,
  169. }
  170. whisperFlags = []cli.Flag{
  171. utils.WhisperEnabledFlag,
  172. utils.WhisperMaxMessageSizeFlag,
  173. utils.WhisperMinPOWFlag,
  174. utils.WhisperRestrictConnectionBetweenLightClientsFlag,
  175. }
  176. metricsFlags = []cli.Flag{
  177. utils.MetricsEnabledFlag,
  178. utils.MetricsEnabledExpensiveFlag,
  179. utils.MetricsEnableInfluxDBFlag,
  180. utils.MetricsInfluxDBEndpointFlag,
  181. utils.MetricsInfluxDBDatabaseFlag,
  182. utils.MetricsInfluxDBUsernameFlag,
  183. utils.MetricsInfluxDBPasswordFlag,
  184. utils.MetricsInfluxDBTagsFlag,
  185. }
  186. )
  187. func init() {
  188. // Initialize the CLI app and start Geth
  189. app.Action = geth
  190. app.HideVersion = true // we have a command to print the version
  191. app.Copyright = "Copyright 2013-2019 The go-ethereum Authors"
  192. app.Commands = []cli.Command{
  193. // See chaincmd.go:
  194. initCommand,
  195. importCommand,
  196. exportCommand,
  197. importPreimagesCommand,
  198. exportPreimagesCommand,
  199. copydbCommand,
  200. removedbCommand,
  201. dumpCommand,
  202. inspectCommand,
  203. // See accountcmd.go:
  204. accountCommand,
  205. walletCommand,
  206. // See consolecmd.go:
  207. consoleCommand,
  208. attachCommand,
  209. javascriptCommand,
  210. // See misccmd.go:
  211. makecacheCommand,
  212. makedagCommand,
  213. versionCommand,
  214. licenseCommand,
  215. // See config.go
  216. dumpConfigCommand,
  217. // See retesteth.go
  218. retestethCommand,
  219. }
  220. sort.Sort(cli.CommandsByName(app.Commands))
  221. app.Flags = append(app.Flags, nodeFlags...)
  222. app.Flags = append(app.Flags, rpcFlags...)
  223. app.Flags = append(app.Flags, consoleFlags...)
  224. app.Flags = append(app.Flags, debug.Flags...)
  225. app.Flags = append(app.Flags, whisperFlags...)
  226. app.Flags = append(app.Flags, metricsFlags...)
  227. app.Before = func(ctx *cli.Context) error {
  228. logdir := ""
  229. if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
  230. logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs")
  231. }
  232. if err := debug.Setup(ctx, logdir); err != nil {
  233. return err
  234. }
  235. return nil
  236. }
  237. app.After = func(ctx *cli.Context) error {
  238. debug.Exit()
  239. console.Stdin.Close() // Resets terminal mode.
  240. return nil
  241. }
  242. }
  243. func main() {
  244. if err := app.Run(os.Args); err != nil {
  245. fmt.Fprintln(os.Stderr, err)
  246. os.Exit(1)
  247. }
  248. }
  249. // prepare manipulates memory cache allowance and setups metric system.
  250. // This function should be called before launching devp2p stack.
  251. func prepare(ctx *cli.Context) {
  252. // If we're a full node on mainnet without --cache specified, bump default cache allowance
  253. if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
  254. // Make sure we're not on any supported preconfigured testnet either
  255. if !ctx.GlobalIsSet(utils.TestnetFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
  256. // Nope, we're really on mainnet. Bump that cache up!
  257. log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
  258. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
  259. }
  260. }
  261. // If we're running a light client on any network, drop the cache to some meaningfully low amount
  262. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
  263. log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
  264. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
  265. }
  266. // Cap the cache allowance and tune the garbage collector
  267. var mem gosigar.Mem
  268. // Workaround until OpenBSD support lands into gosigar
  269. // Check https://github.com/elastic/gosigar#supported-platforms
  270. if runtime.GOOS != "openbsd" {
  271. if err := mem.Get(); err == nil {
  272. allowance := int(mem.Total / 1024 / 1024 / 3)
  273. if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
  274. log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
  275. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
  276. }
  277. }
  278. }
  279. // Ensure Go's GC ignores the database cache for trigger percentage
  280. cache := ctx.GlobalInt(utils.CacheFlag.Name)
  281. gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
  282. log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
  283. godebug.SetGCPercent(int(gogc))
  284. // Start metrics export if enabled
  285. utils.SetupMetrics(ctx)
  286. // Start system runtime metrics collection
  287. go metrics.CollectProcessMetrics(3 * time.Second)
  288. }
  289. // geth is the main entry point into the system if no special subcommand is ran.
  290. // It creates a default node based on the command line arguments and runs it in
  291. // blocking mode, waiting for it to be shut down.
  292. func geth(ctx *cli.Context) error {
  293. if args := ctx.Args(); len(args) > 0 {
  294. return fmt.Errorf("invalid command: %q", args[0])
  295. }
  296. prepare(ctx)
  297. node := makeFullNode(ctx)
  298. defer node.Close()
  299. startNode(ctx, node)
  300. node.Wait()
  301. return nil
  302. }
  303. // startNode boots up the system node and all registered protocols, after which
  304. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  305. // miner.
  306. func startNode(ctx *cli.Context, stack *node.Node) {
  307. debug.Memsize.Add("node", stack)
  308. // Start up the node itself
  309. utils.StartNode(stack)
  310. // Unlock any account specifically requested
  311. unlockAccounts(ctx, stack)
  312. // Register wallet event handlers to open and auto-derive wallets
  313. events := make(chan accounts.WalletEvent, 16)
  314. stack.AccountManager().Subscribe(events)
  315. // Create a client to interact with local geth node.
  316. rpcClient, err := stack.Attach()
  317. if err != nil {
  318. utils.Fatalf("Failed to attach to self: %v", err)
  319. }
  320. ethClient := ethclient.NewClient(rpcClient)
  321. // Set contract backend for ethereum service if local node
  322. // is serving LES requests.
  323. if ctx.GlobalInt(utils.LightLegacyServFlag.Name) > 0 || ctx.GlobalInt(utils.LightServeFlag.Name) > 0 {
  324. var ethService *eth.Ethereum
  325. if err := stack.Service(&ethService); err != nil {
  326. utils.Fatalf("Failed to retrieve ethereum service: %v", err)
  327. }
  328. ethService.SetContractBackend(ethClient)
  329. }
  330. // Set contract backend for les service if local node is
  331. // running as a light client.
  332. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  333. var lesService *les.LightEthereum
  334. if err := stack.Service(&lesService); err != nil {
  335. utils.Fatalf("Failed to retrieve light ethereum service: %v", err)
  336. }
  337. lesService.SetContractBackend(ethClient)
  338. }
  339. go func() {
  340. // Open any wallets already attached
  341. for _, wallet := range stack.AccountManager().Wallets() {
  342. if err := wallet.Open(""); err != nil {
  343. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  344. }
  345. }
  346. // Listen for wallet event till termination
  347. for event := range events {
  348. switch event.Kind {
  349. case accounts.WalletArrived:
  350. if err := event.Wallet.Open(""); err != nil {
  351. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  352. }
  353. case accounts.WalletOpened:
  354. status, _ := event.Wallet.Status()
  355. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  356. var derivationPaths []accounts.DerivationPath
  357. if event.Wallet.URL().Scheme == "ledger" {
  358. derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
  359. }
  360. derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
  361. event.Wallet.SelfDerive(derivationPaths, ethClient)
  362. case accounts.WalletDropped:
  363. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  364. event.Wallet.Close()
  365. }
  366. }
  367. }()
  368. // Spawn a standalone goroutine for status synchronization monitoring,
  369. // close the node when synchronization is complete if user required.
  370. if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
  371. go func() {
  372. sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
  373. defer sub.Unsubscribe()
  374. for {
  375. event := <-sub.Chan()
  376. if event == nil {
  377. continue
  378. }
  379. done, ok := event.Data.(downloader.DoneEvent)
  380. if !ok {
  381. continue
  382. }
  383. if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
  384. log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
  385. "age", common.PrettyAge(timestamp))
  386. stack.Stop()
  387. }
  388. }
  389. }()
  390. }
  391. // Start auxiliary services if enabled
  392. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
  393. // Mining only makes sense if a full Ethereum node is running
  394. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  395. utils.Fatalf("Light clients do not support mining")
  396. }
  397. var ethereum *eth.Ethereum
  398. if err := stack.Service(&ethereum); err != nil {
  399. utils.Fatalf("Ethereum service not running: %v", err)
  400. }
  401. // Set the gas price to the limits from the CLI and start mining
  402. gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
  403. if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
  404. gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
  405. }
  406. ethereum.TxPool().SetGasPrice(gasprice)
  407. threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
  408. if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
  409. threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
  410. }
  411. if err := ethereum.StartMining(threads); err != nil {
  412. utils.Fatalf("Failed to start mining: %v", err)
  413. }
  414. }
  415. }
  416. // unlockAccounts unlocks any account specifically requested.
  417. func unlockAccounts(ctx *cli.Context, stack *node.Node) {
  418. var unlocks []string
  419. inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  420. for _, input := range inputs {
  421. if trimmed := strings.TrimSpace(input); trimmed != "" {
  422. unlocks = append(unlocks, trimmed)
  423. }
  424. }
  425. // Short circuit if there is no account to unlock.
  426. if len(unlocks) == 0 {
  427. return
  428. }
  429. // If insecure account unlocking is not allowed if node's APIs are exposed to external.
  430. // Print warning log to user and skip unlocking.
  431. if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
  432. utils.Fatalf("Account unlock with HTTP access is forbidden!")
  433. }
  434. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  435. passwords := utils.MakePasswordList(ctx)
  436. for i, account := range unlocks {
  437. unlockAccount(ks, account, i, passwords)
  438. }
  439. }