main.go 12 KB

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