main.go 9.4 KB

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