main.go 11 KB

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