main.go 10 KB

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