main.go 12 KB

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