main.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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/ethereum/go-ethereum/accounts"
  28. "github.com/ethereum/go-ethereum/accounts/keystore"
  29. "github.com/ethereum/go-ethereum/cmd/utils"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/console/prompt"
  32. "github.com/ethereum/go-ethereum/eth"
  33. "github.com/ethereum/go-ethereum/eth/downloader"
  34. "github.com/ethereum/go-ethereum/ethclient"
  35. "github.com/ethereum/go-ethereum/internal/debug"
  36. "github.com/ethereum/go-ethereum/internal/ethapi"
  37. "github.com/ethereum/go-ethereum/internal/flags"
  38. "github.com/ethereum/go-ethereum/log"
  39. "github.com/ethereum/go-ethereum/metrics"
  40. "github.com/ethereum/go-ethereum/node"
  41. gopsutil "github.com/shirou/gopsutil/mem"
  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 = flags.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.LegacyBootnodesV4Flag,
  60. utils.LegacyBootnodesV5Flag,
  61. utils.DataDirFlag,
  62. utils.AncientFlag,
  63. utils.KeyStoreDirFlag,
  64. utils.ExternalSignerFlag,
  65. utils.NoUSBFlag,
  66. utils.SmartCardDaemonPathFlag,
  67. utils.EthashCacheDirFlag,
  68. utils.EthashCachesInMemoryFlag,
  69. utils.EthashCachesOnDiskFlag,
  70. utils.EthashCachesLockMmapFlag,
  71. utils.EthashDatasetDirFlag,
  72. utils.EthashDatasetsInMemoryFlag,
  73. utils.EthashDatasetsOnDiskFlag,
  74. utils.EthashDatasetsLockMmapFlag,
  75. utils.TxPoolLocalsFlag,
  76. utils.TxPoolNoLocalsFlag,
  77. utils.TxPoolJournalFlag,
  78. utils.TxPoolRejournalFlag,
  79. utils.TxPoolPriceLimitFlag,
  80. utils.TxPoolPriceBumpFlag,
  81. utils.TxPoolAccountSlotsFlag,
  82. utils.TxPoolGlobalSlotsFlag,
  83. utils.TxPoolAccountQueueFlag,
  84. utils.TxPoolGlobalQueueFlag,
  85. utils.TxPoolLifetimeFlag,
  86. utils.SyncModeFlag,
  87. utils.ExitWhenSyncedFlag,
  88. utils.GCModeFlag,
  89. utils.SnapshotFlag,
  90. utils.TxLookupLimitFlag,
  91. utils.LightServeFlag,
  92. utils.LegacyLightServFlag,
  93. utils.LightIngressFlag,
  94. utils.LightEgressFlag,
  95. utils.LightMaxPeersFlag,
  96. utils.LegacyLightPeersFlag,
  97. utils.LightNoPruneFlag,
  98. utils.LightKDFFlag,
  99. utils.UltraLightServersFlag,
  100. utils.UltraLightFractionFlag,
  101. utils.UltraLightOnlyAnnounceFlag,
  102. utils.WhitelistFlag,
  103. utils.CacheFlag,
  104. utils.CacheDatabaseFlag,
  105. utils.CacheTrieFlag,
  106. utils.CacheTrieJournalFlag,
  107. utils.CacheTrieRejournalFlag,
  108. utils.CacheGCFlag,
  109. utils.CacheSnapshotFlag,
  110. utils.CacheNoPrefetchFlag,
  111. utils.ListenPortFlag,
  112. utils.MaxPeersFlag,
  113. utils.MaxPendingPeersFlag,
  114. utils.MiningEnabledFlag,
  115. utils.MinerThreadsFlag,
  116. utils.LegacyMinerThreadsFlag,
  117. utils.MinerNotifyFlag,
  118. utils.MinerGasTargetFlag,
  119. utils.LegacyMinerGasTargetFlag,
  120. utils.MinerGasLimitFlag,
  121. utils.MinerGasPriceFlag,
  122. utils.LegacyMinerGasPriceFlag,
  123. utils.MinerEtherbaseFlag,
  124. utils.LegacyMinerEtherbaseFlag,
  125. utils.MinerExtraDataFlag,
  126. utils.LegacyMinerExtraDataFlag,
  127. utils.MinerRecommitIntervalFlag,
  128. utils.MinerNoVerfiyFlag,
  129. utils.NATFlag,
  130. utils.NoDiscoverFlag,
  131. utils.DiscoveryV5Flag,
  132. utils.NetrestrictFlag,
  133. utils.NodeKeyFileFlag,
  134. utils.NodeKeyHexFlag,
  135. utils.DNSDiscoveryFlag,
  136. utils.DeveloperFlag,
  137. utils.DeveloperPeriodFlag,
  138. utils.LegacyTestnetFlag,
  139. utils.RopstenFlag,
  140. utils.RinkebyFlag,
  141. utils.GoerliFlag,
  142. utils.YoloV1Flag,
  143. utils.VMEnableDebugFlag,
  144. utils.NetworkIdFlag,
  145. utils.EthStatsURLFlag,
  146. utils.FakePoWFlag,
  147. utils.NoCompactionFlag,
  148. utils.GpoBlocksFlag,
  149. utils.LegacyGpoBlocksFlag,
  150. utils.GpoPercentileFlag,
  151. utils.LegacyGpoPercentileFlag,
  152. utils.EWASMInterpreterFlag,
  153. utils.EVMInterpreterFlag,
  154. configFileFlag,
  155. }
  156. rpcFlags = []cli.Flag{
  157. utils.HTTPEnabledFlag,
  158. utils.HTTPListenAddrFlag,
  159. utils.HTTPPortFlag,
  160. utils.HTTPCORSDomainFlag,
  161. utils.HTTPVirtualHostsFlag,
  162. utils.LegacyRPCEnabledFlag,
  163. utils.LegacyRPCListenAddrFlag,
  164. utils.LegacyRPCPortFlag,
  165. utils.LegacyRPCCORSDomainFlag,
  166. utils.LegacyRPCVirtualHostsFlag,
  167. utils.GraphQLEnabledFlag,
  168. utils.GraphQLCORSDomainFlag,
  169. utils.GraphQLVirtualHostsFlag,
  170. utils.HTTPApiFlag,
  171. utils.LegacyRPCApiFlag,
  172. utils.WSEnabledFlag,
  173. utils.WSListenAddrFlag,
  174. utils.LegacyWSListenAddrFlag,
  175. utils.WSPortFlag,
  176. utils.LegacyWSPortFlag,
  177. utils.WSApiFlag,
  178. utils.LegacyWSApiFlag,
  179. utils.WSAllowedOriginsFlag,
  180. utils.LegacyWSAllowedOriginsFlag,
  181. utils.IPCDisabledFlag,
  182. utils.IPCPathFlag,
  183. utils.InsecureUnlockAllowedFlag,
  184. utils.RPCGlobalGasCap,
  185. utils.RPCGlobalTxFeeCap,
  186. }
  187. whisperFlags = []cli.Flag{
  188. utils.WhisperEnabledFlag,
  189. utils.WhisperMaxMessageSizeFlag,
  190. utils.WhisperMinPOWFlag,
  191. utils.WhisperRestrictConnectionBetweenLightClientsFlag,
  192. }
  193. metricsFlags = []cli.Flag{
  194. utils.MetricsEnabledFlag,
  195. utils.MetricsEnabledExpensiveFlag,
  196. utils.MetricsHTTPFlag,
  197. utils.MetricsPortFlag,
  198. utils.MetricsEnableInfluxDBFlag,
  199. utils.MetricsInfluxDBEndpointFlag,
  200. utils.MetricsInfluxDBDatabaseFlag,
  201. utils.MetricsInfluxDBUsernameFlag,
  202. utils.MetricsInfluxDBPasswordFlag,
  203. utils.MetricsInfluxDBTagsFlag,
  204. }
  205. )
  206. func init() {
  207. // Initialize the CLI app and start Geth
  208. app.Action = geth
  209. app.HideVersion = true // we have a command to print the version
  210. app.Copyright = "Copyright 2013-2020 The go-ethereum Authors"
  211. app.Commands = []cli.Command{
  212. // See chaincmd.go:
  213. initCommand,
  214. importCommand,
  215. exportCommand,
  216. importPreimagesCommand,
  217. exportPreimagesCommand,
  218. copydbCommand,
  219. removedbCommand,
  220. dumpCommand,
  221. dumpGenesisCommand,
  222. inspectCommand,
  223. // See accountcmd.go:
  224. accountCommand,
  225. walletCommand,
  226. // See consolecmd.go:
  227. consoleCommand,
  228. attachCommand,
  229. javascriptCommand,
  230. // See misccmd.go:
  231. makecacheCommand,
  232. makedagCommand,
  233. versionCommand,
  234. licenseCommand,
  235. // See config.go
  236. dumpConfigCommand,
  237. // See retesteth.go
  238. retestethCommand,
  239. // See cmd/utils/flags_legacy.go
  240. utils.ShowDeprecated,
  241. }
  242. sort.Sort(cli.CommandsByName(app.Commands))
  243. app.Flags = append(app.Flags, nodeFlags...)
  244. app.Flags = append(app.Flags, rpcFlags...)
  245. app.Flags = append(app.Flags, consoleFlags...)
  246. app.Flags = append(app.Flags, debug.Flags...)
  247. app.Flags = append(app.Flags, debug.DeprecatedFlags...)
  248. app.Flags = append(app.Flags, whisperFlags...)
  249. app.Flags = append(app.Flags, metricsFlags...)
  250. app.Before = func(ctx *cli.Context) error {
  251. return debug.Setup(ctx)
  252. }
  253. app.After = func(ctx *cli.Context) error {
  254. debug.Exit()
  255. prompt.Stdin.Close() // Resets terminal mode.
  256. return nil
  257. }
  258. }
  259. func main() {
  260. if err := app.Run(os.Args); err != nil {
  261. fmt.Fprintln(os.Stderr, err)
  262. os.Exit(1)
  263. }
  264. }
  265. // prepare manipulates memory cache allowance and setups metric system.
  266. // This function should be called before launching devp2p stack.
  267. func prepare(ctx *cli.Context) {
  268. // If we're running a known preset, log it for convenience.
  269. switch {
  270. case ctx.GlobalIsSet(utils.LegacyTestnetFlag.Name):
  271. log.Info("Starting Geth on Ropsten testnet...")
  272. log.Warn("The --testnet flag is ambiguous! Please specify one of --goerli, --rinkeby, or --ropsten.")
  273. log.Warn("The generic --testnet flag is deprecated and will be removed in the future!")
  274. case ctx.GlobalIsSet(utils.RopstenFlag.Name):
  275. log.Info("Starting Geth on Ropsten testnet...")
  276. case ctx.GlobalIsSet(utils.RinkebyFlag.Name):
  277. log.Info("Starting Geth on Rinkeby testnet...")
  278. case ctx.GlobalIsSet(utils.GoerliFlag.Name):
  279. log.Info("Starting Geth on Görli testnet...")
  280. case ctx.GlobalIsSet(utils.DeveloperFlag.Name):
  281. log.Info("Starting Geth in ephemeral dev mode...")
  282. case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name):
  283. log.Info("Starting Geth on Ethereum mainnet...")
  284. }
  285. // If we're a full node on mainnet without --cache specified, bump default cache allowance
  286. if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
  287. // Make sure we're not on any supported preconfigured testnet either
  288. if !ctx.GlobalIsSet(utils.LegacyTestnetFlag.Name) && !ctx.GlobalIsSet(utils.RopstenFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
  289. // Nope, we're really on mainnet. Bump that cache up!
  290. log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
  291. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
  292. }
  293. }
  294. // If we're running a light client on any network, drop the cache to some meaningfully low amount
  295. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
  296. log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
  297. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
  298. }
  299. // Cap the cache allowance and tune the garbage collector
  300. mem, err := gopsutil.VirtualMemory()
  301. if err == nil {
  302. if 32<<(^uintptr(0)>>63) == 32 && mem.Total > 2*1024*1024*1024 {
  303. log.Warn("Lowering memory allowance on 32bit arch", "available", mem.Total/1024/1024, "addressable", 2*1024)
  304. mem.Total = 2 * 1024 * 1024 * 1024
  305. }
  306. allowance := int(mem.Total / 1024 / 1024 / 3)
  307. if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
  308. log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
  309. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
  310. }
  311. }
  312. // Ensure Go's GC ignores the database cache for trigger percentage
  313. cache := ctx.GlobalInt(utils.CacheFlag.Name)
  314. gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
  315. log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
  316. godebug.SetGCPercent(int(gogc))
  317. // Start metrics export if enabled
  318. utils.SetupMetrics(ctx)
  319. // Start system runtime metrics collection
  320. go metrics.CollectProcessMetrics(3 * time.Second)
  321. }
  322. // geth is the main entry point into the system if no special subcommand is ran.
  323. // It creates a default node based on the command line arguments and runs it in
  324. // blocking mode, waiting for it to be shut down.
  325. func geth(ctx *cli.Context) error {
  326. if args := ctx.Args(); len(args) > 0 {
  327. return fmt.Errorf("invalid command: %q", args[0])
  328. }
  329. prepare(ctx)
  330. stack, backend := makeFullNode(ctx)
  331. defer stack.Close()
  332. startNode(ctx, stack, backend)
  333. stack.Wait()
  334. return nil
  335. }
  336. // startNode boots up the system node and all registered protocols, after which
  337. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  338. // miner.
  339. func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend) {
  340. debug.Memsize.Add("node", stack)
  341. // Start up the node itself
  342. utils.StartNode(stack)
  343. // Unlock any account specifically requested
  344. unlockAccounts(ctx, stack)
  345. // Register wallet event handlers to open and auto-derive wallets
  346. events := make(chan accounts.WalletEvent, 16)
  347. stack.AccountManager().Subscribe(events)
  348. // Create a client to interact with local geth node.
  349. rpcClient, err := stack.Attach()
  350. if err != nil {
  351. utils.Fatalf("Failed to attach to self: %v", err)
  352. }
  353. ethClient := ethclient.NewClient(rpcClient)
  354. go func() {
  355. // Open any wallets already attached
  356. for _, wallet := range stack.AccountManager().Wallets() {
  357. if err := wallet.Open(""); err != nil {
  358. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  359. }
  360. }
  361. // Listen for wallet event till termination
  362. for event := range events {
  363. switch event.Kind {
  364. case accounts.WalletArrived:
  365. if err := event.Wallet.Open(""); err != nil {
  366. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  367. }
  368. case accounts.WalletOpened:
  369. status, _ := event.Wallet.Status()
  370. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  371. var derivationPaths []accounts.DerivationPath
  372. if event.Wallet.URL().Scheme == "ledger" {
  373. derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
  374. }
  375. derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
  376. event.Wallet.SelfDerive(derivationPaths, ethClient)
  377. case accounts.WalletDropped:
  378. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  379. event.Wallet.Close()
  380. }
  381. }
  382. }()
  383. // Spawn a standalone goroutine for status synchronization monitoring,
  384. // close the node when synchronization is complete if user required.
  385. if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
  386. go func() {
  387. sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
  388. defer sub.Unsubscribe()
  389. for {
  390. event := <-sub.Chan()
  391. if event == nil {
  392. continue
  393. }
  394. done, ok := event.Data.(downloader.DoneEvent)
  395. if !ok {
  396. continue
  397. }
  398. if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
  399. log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
  400. "age", common.PrettyAge(timestamp))
  401. stack.Close()
  402. }
  403. }
  404. }()
  405. }
  406. // Start auxiliary services if enabled
  407. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
  408. // Mining only makes sense if a full Ethereum node is running
  409. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  410. utils.Fatalf("Light clients do not support mining")
  411. }
  412. ethBackend, ok := backend.(*eth.EthAPIBackend)
  413. if !ok {
  414. utils.Fatalf("Ethereum service not running: %v", err)
  415. }
  416. // Set the gas price to the limits from the CLI and start mining
  417. gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
  418. if ctx.GlobalIsSet(utils.LegacyMinerGasPriceFlag.Name) && !ctx.GlobalIsSet(utils.MinerGasPriceFlag.Name) {
  419. gasprice = utils.GlobalBig(ctx, utils.LegacyMinerGasPriceFlag.Name)
  420. }
  421. ethBackend.TxPool().SetGasPrice(gasprice)
  422. // start mining
  423. threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name)
  424. if ctx.GlobalIsSet(utils.LegacyMinerThreadsFlag.Name) && !ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
  425. threads = ctx.GlobalInt(utils.LegacyMinerThreadsFlag.Name)
  426. log.Warn("The flag --minerthreads is deprecated and will be removed in the future, please use --miner.threads")
  427. }
  428. if err := ethBackend.StartMining(threads); err != nil {
  429. utils.Fatalf("Failed to start mining: %v", err)
  430. }
  431. }
  432. }
  433. // unlockAccounts unlocks any account specifically requested.
  434. func unlockAccounts(ctx *cli.Context, stack *node.Node) {
  435. var unlocks []string
  436. inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  437. for _, input := range inputs {
  438. if trimmed := strings.TrimSpace(input); trimmed != "" {
  439. unlocks = append(unlocks, trimmed)
  440. }
  441. }
  442. // Short circuit if there is no account to unlock.
  443. if len(unlocks) == 0 {
  444. return
  445. }
  446. // If insecure account unlocking is not allowed if node's APIs are exposed to external.
  447. // Print warning log to user and skip unlocking.
  448. if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
  449. utils.Fatalf("Account unlock with HTTP access is forbidden!")
  450. }
  451. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  452. passwords := utils.MakePasswordList(ctx)
  453. for i, account := range unlocks {
  454. unlockAccount(ks, account, i, passwords)
  455. }
  456. }