main.go 10.0 KB

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