main.go 14 KB

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