main.go 13 KB

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