main.go 12 KB

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