main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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/console"
  32. "github.com/ethereum/go-ethereum/eth"
  33. "github.com/ethereum/go-ethereum/ethclient"
  34. "github.com/ethereum/go-ethereum/internal/debug"
  35. "github.com/ethereum/go-ethereum/log"
  36. "github.com/ethereum/go-ethereum/metrics"
  37. "github.com/ethereum/go-ethereum/node"
  38. "gopkg.in/urfave/cli.v1"
  39. )
  40. const (
  41. clientIdentifier = "geth" // Client identifier to advertise over the network
  42. )
  43. var (
  44. // Git SHA1 commit hash of the release (set via linker flags)
  45. gitCommit = ""
  46. // The app that holds all commands and flags.
  47. app = utils.NewApp(gitCommit, "the go-ethereum command line interface")
  48. // flags that configure the node
  49. nodeFlags = []cli.Flag{
  50. utils.IdentityFlag,
  51. utils.UnlockedAccountFlag,
  52. utils.PasswordFileFlag,
  53. utils.BootnodesFlag,
  54. utils.BootnodesV4Flag,
  55. utils.BootnodesV5Flag,
  56. utils.DataDirFlag,
  57. utils.KeyStoreDirFlag,
  58. utils.NoUSBFlag,
  59. utils.DashboardEnabledFlag,
  60. utils.DashboardAddrFlag,
  61. utils.DashboardPortFlag,
  62. utils.DashboardRefreshFlag,
  63. utils.EthashCacheDirFlag,
  64. utils.EthashCachesInMemoryFlag,
  65. utils.EthashCachesOnDiskFlag,
  66. utils.EthashDatasetDirFlag,
  67. utils.EthashDatasetsInMemoryFlag,
  68. utils.EthashDatasetsOnDiskFlag,
  69. utils.TxPoolLocalsFlag,
  70. utils.TxPoolNoLocalsFlag,
  71. utils.TxPoolJournalFlag,
  72. utils.TxPoolRejournalFlag,
  73. utils.TxPoolPriceLimitFlag,
  74. utils.TxPoolPriceBumpFlag,
  75. utils.TxPoolAccountSlotsFlag,
  76. utils.TxPoolGlobalSlotsFlag,
  77. utils.TxPoolAccountQueueFlag,
  78. utils.TxPoolGlobalQueueFlag,
  79. utils.TxPoolLifetimeFlag,
  80. utils.ULCModeConfigFlag,
  81. utils.OnlyAnnounceModeFlag,
  82. utils.ULCTrustedNodesFlag,
  83. utils.ULCMinTrustedFractionFlag,
  84. utils.SyncModeFlag,
  85. utils.GCModeFlag,
  86. utils.LightServFlag,
  87. utils.LightPeersFlag,
  88. utils.LightKDFFlag,
  89. utils.WhitelistFlag,
  90. utils.CacheFlag,
  91. utils.CacheDatabaseFlag,
  92. utils.CacheTrieFlag,
  93. utils.CacheGCFlag,
  94. utils.TrieCacheGenFlag,
  95. utils.ListenPortFlag,
  96. utils.MaxPeersFlag,
  97. utils.MaxPendingPeersFlag,
  98. utils.MiningEnabledFlag,
  99. utils.MinerThreadsFlag,
  100. utils.MinerLegacyThreadsFlag,
  101. utils.MinerNotifyFlag,
  102. utils.MinerGasTargetFlag,
  103. utils.MinerLegacyGasTargetFlag,
  104. utils.MinerGasLimitFlag,
  105. utils.MinerGasPriceFlag,
  106. utils.MinerLegacyGasPriceFlag,
  107. utils.MinerEtherbaseFlag,
  108. utils.MinerLegacyEtherbaseFlag,
  109. utils.MinerExtraDataFlag,
  110. utils.MinerLegacyExtraDataFlag,
  111. utils.MinerRecommitIntervalFlag,
  112. utils.MinerNoVerfiyFlag,
  113. utils.NATFlag,
  114. utils.NoDiscoverFlag,
  115. utils.DiscoveryV5Flag,
  116. utils.NetrestrictFlag,
  117. utils.NodeKeyFileFlag,
  118. utils.NodeKeyHexFlag,
  119. utils.DeveloperFlag,
  120. utils.DeveloperPeriodFlag,
  121. utils.TestnetFlag,
  122. utils.RinkebyFlag,
  123. utils.VMEnableDebugFlag,
  124. utils.NetworkIdFlag,
  125. utils.ConstantinopleOverrideFlag,
  126. utils.RPCCORSDomainFlag,
  127. utils.RPCVirtualHostsFlag,
  128. utils.EthStatsURLFlag,
  129. utils.MetricsEnabledFlag,
  130. utils.FakePoWFlag,
  131. utils.NoCompactionFlag,
  132. utils.GpoBlocksFlag,
  133. utils.GpoPercentileFlag,
  134. utils.EWASMInterpreterFlag,
  135. utils.EVMInterpreterFlag,
  136. configFileFlag,
  137. }
  138. rpcFlags = []cli.Flag{
  139. utils.RPCEnabledFlag,
  140. utils.RPCListenAddrFlag,
  141. utils.RPCPortFlag,
  142. utils.GraphQLEnabledFlag,
  143. utils.GraphQLListenAddrFlag,
  144. utils.GraphQLPortFlag,
  145. utils.GraphQLCORSDomainFlag,
  146. utils.GraphQLVirtualHostsFlag,
  147. utils.RPCApiFlag,
  148. utils.WSEnabledFlag,
  149. utils.WSListenAddrFlag,
  150. utils.WSPortFlag,
  151. utils.WSApiFlag,
  152. utils.WSAllowedOriginsFlag,
  153. utils.IPCDisabledFlag,
  154. utils.IPCPathFlag,
  155. }
  156. whisperFlags = []cli.Flag{
  157. utils.WhisperEnabledFlag,
  158. utils.WhisperMaxMessageSizeFlag,
  159. utils.WhisperMinPOWFlag,
  160. utils.WhisperRestrictConnectionBetweenLightClientsFlag,
  161. }
  162. metricsFlags = []cli.Flag{
  163. utils.MetricsEnableInfluxDBFlag,
  164. utils.MetricsInfluxDBEndpointFlag,
  165. utils.MetricsInfluxDBDatabaseFlag,
  166. utils.MetricsInfluxDBUsernameFlag,
  167. utils.MetricsInfluxDBPasswordFlag,
  168. utils.MetricsInfluxDBHostTagFlag,
  169. }
  170. )
  171. func init() {
  172. // Initialize the CLI app and start Geth
  173. app.Action = geth
  174. app.HideVersion = true // we have a command to print the version
  175. app.Copyright = "Copyright 2013-2019 The go-ethereum Authors"
  176. app.Commands = []cli.Command{
  177. // See chaincmd.go:
  178. initCommand,
  179. importCommand,
  180. exportCommand,
  181. importPreimagesCommand,
  182. exportPreimagesCommand,
  183. copydbCommand,
  184. removedbCommand,
  185. dumpCommand,
  186. // See monitorcmd.go:
  187. monitorCommand,
  188. // See accountcmd.go:
  189. accountCommand,
  190. walletCommand,
  191. // See consolecmd.go:
  192. consoleCommand,
  193. attachCommand,
  194. javascriptCommand,
  195. // See misccmd.go:
  196. makecacheCommand,
  197. makedagCommand,
  198. versionCommand,
  199. bugCommand,
  200. licenseCommand,
  201. // See config.go
  202. dumpConfigCommand,
  203. }
  204. sort.Sort(cli.CommandsByName(app.Commands))
  205. app.Flags = append(app.Flags, nodeFlags...)
  206. app.Flags = append(app.Flags, rpcFlags...)
  207. app.Flags = append(app.Flags, consoleFlags...)
  208. app.Flags = append(app.Flags, debug.Flags...)
  209. app.Flags = append(app.Flags, whisperFlags...)
  210. app.Flags = append(app.Flags, metricsFlags...)
  211. app.Before = func(ctx *cli.Context) error {
  212. logdir := ""
  213. if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
  214. logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs")
  215. }
  216. if err := debug.Setup(ctx, logdir); err != nil {
  217. return err
  218. }
  219. // Cap the cache allowance and tune the garbage collector
  220. var mem gosigar.Mem
  221. if err := mem.Get(); err == nil {
  222. allowance := int(mem.Total / 1024 / 1024 / 3)
  223. if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
  224. log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
  225. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
  226. }
  227. }
  228. // Ensure Go's GC ignores the database cache for trigger percentage
  229. cache := ctx.GlobalInt(utils.CacheFlag.Name)
  230. gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
  231. log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
  232. godebug.SetGCPercent(int(gogc))
  233. // Start metrics export if enabled
  234. utils.SetupMetrics(ctx)
  235. // Start system runtime metrics collection
  236. go metrics.CollectProcessMetrics(3 * time.Second)
  237. return nil
  238. }
  239. app.After = func(ctx *cli.Context) error {
  240. debug.Exit()
  241. console.Stdin.Close() // Resets terminal mode.
  242. return nil
  243. }
  244. }
  245. func main() {
  246. if err := app.Run(os.Args); err != nil {
  247. fmt.Fprintln(os.Stderr, err)
  248. os.Exit(1)
  249. }
  250. }
  251. // geth is the main entry point into the system if no special subcommand is ran.
  252. // It creates a default node based on the command line arguments and runs it in
  253. // blocking mode, waiting for it to be shut down.
  254. func geth(ctx *cli.Context) error {
  255. if args := ctx.Args(); len(args) > 0 {
  256. return fmt.Errorf("invalid command: %q", args[0])
  257. }
  258. node := makeFullNode(ctx)
  259. startNode(ctx, node)
  260. node.Wait()
  261. return nil
  262. }
  263. // startNode boots up the system node and all registered protocols, after which
  264. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  265. // miner.
  266. func startNode(ctx *cli.Context, stack *node.Node) {
  267. debug.Memsize.Add("node", stack)
  268. // Start up the node itself
  269. utils.StartNode(stack)
  270. // Unlock any account specifically requested
  271. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  272. passwords := utils.MakePasswordList(ctx)
  273. unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  274. for i, account := range unlocks {
  275. if trimmed := strings.TrimSpace(account); trimmed != "" {
  276. unlockAccount(ctx, ks, trimmed, i, passwords)
  277. }
  278. }
  279. // Register wallet event handlers to open and auto-derive wallets
  280. events := make(chan accounts.WalletEvent, 16)
  281. stack.AccountManager().Subscribe(events)
  282. go func() {
  283. // Create a chain state reader for self-derivation
  284. rpcClient, err := stack.Attach()
  285. if err != nil {
  286. utils.Fatalf("Failed to attach to self: %v", err)
  287. }
  288. stateReader := ethclient.NewClient(rpcClient)
  289. // Open any wallets already attached
  290. for _, wallet := range stack.AccountManager().Wallets() {
  291. if err := wallet.Open(""); err != nil {
  292. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  293. }
  294. }
  295. // Listen for wallet event till termination
  296. for event := range events {
  297. switch event.Kind {
  298. case accounts.WalletArrived:
  299. if err := event.Wallet.Open(""); err != nil {
  300. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  301. }
  302. case accounts.WalletOpened:
  303. status, _ := event.Wallet.Status()
  304. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  305. derivationPath := accounts.DefaultBaseDerivationPath
  306. if event.Wallet.URL().Scheme == "ledger" {
  307. derivationPath = accounts.DefaultLedgerBaseDerivationPath
  308. }
  309. event.Wallet.SelfDerive(derivationPath, stateReader)
  310. case accounts.WalletDropped:
  311. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  312. event.Wallet.Close()
  313. }
  314. }
  315. }()
  316. // Start auxiliary services if enabled
  317. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
  318. // Mining only makes sense if a full Ethereum node is running
  319. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  320. utils.Fatalf("Light clients do not support mining")
  321. }
  322. var ethereum *eth.Ethereum
  323. if err := stack.Service(&ethereum); err != nil {
  324. utils.Fatalf("Ethereum service not running: %v", err)
  325. }
  326. // Set the gas price to the limits from the CLI and start mining
  327. gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name)
  328. if ctx.IsSet(utils.MinerGasPriceFlag.Name) {
  329. gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
  330. }
  331. ethereum.TxPool().SetGasPrice(gasprice)
  332. threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name)
  333. if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
  334. threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name)
  335. }
  336. if err := ethereum.StartMining(threads); err != nil {
  337. utils.Fatalf("Failed to start mining: %v", err)
  338. }
  339. }
  340. }