main.go 15 KB

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