main.go 14 KB

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