main.go 12 KB

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