main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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.TrieCacheGenFlag,
  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.MetricsEnabledFlag,
  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.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. }
  163. whisperFlags = []cli.Flag{
  164. utils.WhisperEnabledFlag,
  165. utils.WhisperMaxMessageSizeFlag,
  166. utils.WhisperMinPOWFlag,
  167. utils.WhisperRestrictConnectionBetweenLightClientsFlag,
  168. }
  169. metricsFlags = []cli.Flag{
  170. utils.MetricsEnableInfluxDBFlag,
  171. utils.MetricsInfluxDBEndpointFlag,
  172. utils.MetricsInfluxDBDatabaseFlag,
  173. utils.MetricsInfluxDBUsernameFlag,
  174. utils.MetricsInfluxDBPasswordFlag,
  175. utils.MetricsInfluxDBTagsFlag,
  176. }
  177. )
  178. func init() {
  179. // Initialize the CLI app and start Geth
  180. app.Action = geth
  181. app.HideVersion = true // we have a command to print the version
  182. app.Copyright = "Copyright 2013-2019 The go-ethereum Authors"
  183. app.Commands = []cli.Command{
  184. // See chaincmd.go:
  185. initCommand,
  186. importCommand,
  187. exportCommand,
  188. importPreimagesCommand,
  189. exportPreimagesCommand,
  190. copydbCommand,
  191. removedbCommand,
  192. dumpCommand,
  193. // See monitorcmd.go:
  194. monitorCommand,
  195. // See accountcmd.go:
  196. accountCommand,
  197. walletCommand,
  198. // See consolecmd.go:
  199. consoleCommand,
  200. attachCommand,
  201. javascriptCommand,
  202. // See misccmd.go:
  203. makecacheCommand,
  204. makedagCommand,
  205. versionCommand,
  206. bugCommand,
  207. licenseCommand,
  208. // See config.go
  209. dumpConfigCommand,
  210. }
  211. sort.Sort(cli.CommandsByName(app.Commands))
  212. app.Flags = append(app.Flags, nodeFlags...)
  213. app.Flags = append(app.Flags, rpcFlags...)
  214. app.Flags = append(app.Flags, consoleFlags...)
  215. app.Flags = append(app.Flags, debug.Flags...)
  216. app.Flags = append(app.Flags, whisperFlags...)
  217. app.Flags = append(app.Flags, metricsFlags...)
  218. app.Before = func(ctx *cli.Context) error {
  219. logdir := ""
  220. if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
  221. logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs")
  222. }
  223. if err := debug.Setup(ctx, logdir); err != nil {
  224. return err
  225. }
  226. // Cap the cache allowance and tune the garbage collector
  227. var mem gosigar.Mem
  228. if err := mem.Get(); err == nil {
  229. allowance := int(mem.Total / 1024 / 1024 / 3)
  230. if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
  231. log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
  232. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
  233. }
  234. }
  235. // Ensure Go's GC ignores the database cache for trigger percentage
  236. cache := ctx.GlobalInt(utils.CacheFlag.Name)
  237. gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
  238. log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
  239. godebug.SetGCPercent(int(gogc))
  240. // Start metrics export if enabled
  241. utils.SetupMetrics(ctx)
  242. // Start system runtime metrics collection
  243. go metrics.CollectProcessMetrics(3 * time.Second)
  244. return nil
  245. }
  246. app.After = func(ctx *cli.Context) error {
  247. debug.Exit()
  248. console.Stdin.Close() // Resets terminal mode.
  249. return nil
  250. }
  251. }
  252. func main() {
  253. if err := app.Run(os.Args); err != nil {
  254. fmt.Fprintln(os.Stderr, err)
  255. os.Exit(1)
  256. }
  257. }
  258. // geth is the main entry point into the system if no special subcommand is ran.
  259. // It creates a default node based on the command line arguments and runs it in
  260. // blocking mode, waiting for it to be shut down.
  261. func geth(ctx *cli.Context) error {
  262. if args := ctx.Args(); len(args) > 0 {
  263. return fmt.Errorf("invalid command: %q", args[0])
  264. }
  265. node := makeFullNode(ctx)
  266. defer node.Close()
  267. startNode(ctx, node)
  268. node.Wait()
  269. return nil
  270. }
  271. // startNode boots up the system node and all registered protocols, after which
  272. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  273. // miner.
  274. func startNode(ctx *cli.Context, stack *node.Node) {
  275. debug.Memsize.Add("node", stack)
  276. // Start up the node itself
  277. utils.StartNode(stack)
  278. // Unlock any account specifically requested
  279. if keystores := stack.AccountManager().Backends(keystore.KeyStoreType); len(keystores) > 0 {
  280. ks := keystores[0].(*keystore.KeyStore)
  281. passwords := utils.MakePasswordList(ctx)
  282. unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  283. for i, account := range unlocks {
  284. if trimmed := strings.TrimSpace(account); trimmed != "" {
  285. unlockAccount(ctx, ks, trimmed, i, passwords)
  286. }
  287. }
  288. }
  289. // Register wallet event handlers to open and auto-derive wallets
  290. events := make(chan accounts.WalletEvent, 16)
  291. stack.AccountManager().Subscribe(events)
  292. go func() {
  293. // Create a chain state reader for self-derivation
  294. rpcClient, err := stack.Attach()
  295. if err != nil {
  296. utils.Fatalf("Failed to attach to self: %v", err)
  297. }
  298. stateReader := ethclient.NewClient(rpcClient)
  299. // Open any wallets already attached
  300. for _, wallet := range stack.AccountManager().Wallets() {
  301. if err := wallet.Open(""); err != nil {
  302. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  303. }
  304. }
  305. // Listen for wallet event till termination
  306. for event := range events {
  307. switch event.Kind {
  308. case accounts.WalletArrived:
  309. if err := event.Wallet.Open(""); err != nil {
  310. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  311. }
  312. case accounts.WalletOpened:
  313. status, _ := event.Wallet.Status()
  314. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  315. derivationPath := accounts.DefaultBaseDerivationPath
  316. if event.Wallet.URL().Scheme == "ledger" {
  317. derivationPath = accounts.DefaultLedgerBaseDerivationPath
  318. }
  319. event.Wallet.SelfDerive(derivationPath, stateReader)
  320. case accounts.WalletDropped:
  321. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  322. event.Wallet.Close()
  323. }
  324. }
  325. }()
  326. // Spawn a standalone goroutine for status synchronization monitoring,
  327. // close the node when synchronization is complete if user required.
  328. if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
  329. go func() {
  330. sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
  331. defer sub.Unsubscribe()
  332. for {
  333. event := <-sub.Chan()
  334. if event == nil {
  335. continue
  336. }
  337. done, ok := event.Data.(downloader.DoneEvent)
  338. if !ok {
  339. continue
  340. }
  341. if timestamp := time.Unix(done.Latest.Time.Int64(), 0); time.Since(timestamp) < 10*time.Minute {
  342. log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
  343. "age", common.PrettyAge(timestamp))
  344. stack.Stop()
  345. }
  346. }
  347. }()
  348. }
  349. // Start auxiliary services if enabled
  350. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
  351. // Mining only makes sense if a full Ethereum node is running
  352. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  353. utils.Fatalf("Light clients do not support mining")
  354. }
  355. var ethereum *eth.Ethereum
  356. if err := stack.Service(&ethereum); err != nil {
  357. utils.Fatalf("Ethereum service not running: %v", err)
  358. }
  359. // Set the gas price to the limits from the CLI and start mining
  360. gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
  361. if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
  362. gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
  363. }
  364. ethereum.TxPool().SetGasPrice(gasprice)
  365. threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
  366. if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
  367. threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
  368. }
  369. if err := ethereum.StartMining(threads); err != nil {
  370. utils.Fatalf("Failed to start mining: %v", err)
  371. }
  372. }
  373. }