main.go 10 KB

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