main.go 10 KB

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