main.go 14 KB

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