main.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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/flags"
  37. "github.com/ethereum/go-ethereum/les"
  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.GraphQLListenAddrFlag,
  169. utils.GraphQLPortFlag,
  170. utils.GraphQLCORSDomainFlag,
  171. utils.GraphQLVirtualHostsFlag,
  172. utils.HTTPApiFlag,
  173. utils.LegacyRPCApiFlag,
  174. utils.WSEnabledFlag,
  175. utils.WSListenAddrFlag,
  176. utils.LegacyWSListenAddrFlag,
  177. utils.WSPortFlag,
  178. utils.LegacyWSPortFlag,
  179. utils.WSApiFlag,
  180. utils.LegacyWSApiFlag,
  181. utils.WSAllowedOriginsFlag,
  182. utils.LegacyWSAllowedOriginsFlag,
  183. utils.IPCDisabledFlag,
  184. utils.IPCPathFlag,
  185. utils.InsecureUnlockAllowedFlag,
  186. utils.RPCGlobalGasCap,
  187. utils.RPCGlobalTxFeeCap,
  188. }
  189. whisperFlags = []cli.Flag{
  190. utils.WhisperEnabledFlag,
  191. utils.WhisperMaxMessageSizeFlag,
  192. utils.WhisperMinPOWFlag,
  193. utils.WhisperRestrictConnectionBetweenLightClientsFlag,
  194. }
  195. metricsFlags = []cli.Flag{
  196. utils.MetricsEnabledFlag,
  197. utils.MetricsEnabledExpensiveFlag,
  198. utils.MetricsHTTPFlag,
  199. utils.MetricsPortFlag,
  200. utils.MetricsEnableInfluxDBFlag,
  201. utils.MetricsInfluxDBEndpointFlag,
  202. utils.MetricsInfluxDBDatabaseFlag,
  203. utils.MetricsInfluxDBUsernameFlag,
  204. utils.MetricsInfluxDBPasswordFlag,
  205. utils.MetricsInfluxDBTagsFlag,
  206. }
  207. )
  208. func init() {
  209. // Initialize the CLI app and start Geth
  210. app.Action = geth
  211. app.HideVersion = true // we have a command to print the version
  212. app.Copyright = "Copyright 2013-2020 The go-ethereum Authors"
  213. app.Commands = []cli.Command{
  214. // See chaincmd.go:
  215. initCommand,
  216. importCommand,
  217. exportCommand,
  218. importPreimagesCommand,
  219. exportPreimagesCommand,
  220. copydbCommand,
  221. removedbCommand,
  222. dumpCommand,
  223. dumpGenesisCommand,
  224. inspectCommand,
  225. // See accountcmd.go:
  226. accountCommand,
  227. walletCommand,
  228. // See consolecmd.go:
  229. consoleCommand,
  230. attachCommand,
  231. javascriptCommand,
  232. // See misccmd.go:
  233. makecacheCommand,
  234. makedagCommand,
  235. versionCommand,
  236. licenseCommand,
  237. // See config.go
  238. dumpConfigCommand,
  239. // See retesteth.go
  240. retestethCommand,
  241. // See cmd/utils/flags_legacy.go
  242. utils.ShowDeprecated,
  243. }
  244. sort.Sort(cli.CommandsByName(app.Commands))
  245. app.Flags = append(app.Flags, nodeFlags...)
  246. app.Flags = append(app.Flags, rpcFlags...)
  247. app.Flags = append(app.Flags, consoleFlags...)
  248. app.Flags = append(app.Flags, debug.Flags...)
  249. app.Flags = append(app.Flags, debug.DeprecatedFlags...)
  250. app.Flags = append(app.Flags, whisperFlags...)
  251. app.Flags = append(app.Flags, metricsFlags...)
  252. app.Before = func(ctx *cli.Context) error {
  253. return debug.Setup(ctx)
  254. }
  255. app.After = func(ctx *cli.Context) error {
  256. debug.Exit()
  257. prompt.Stdin.Close() // Resets terminal mode.
  258. return nil
  259. }
  260. }
  261. func main() {
  262. if err := app.Run(os.Args); err != nil {
  263. fmt.Fprintln(os.Stderr, err)
  264. os.Exit(1)
  265. }
  266. }
  267. // prepare manipulates memory cache allowance and setups metric system.
  268. // This function should be called before launching devp2p stack.
  269. func prepare(ctx *cli.Context) {
  270. // If we're running a known preset, log it for convenience.
  271. switch {
  272. case ctx.GlobalIsSet(utils.LegacyTestnetFlag.Name):
  273. log.Info("Starting Geth on Ropsten testnet...")
  274. log.Warn("The --testnet flag is ambiguous! Please specify one of --goerli, --rinkeby, or --ropsten.")
  275. log.Warn("The generic --testnet flag is deprecated and will be removed in the future!")
  276. case ctx.GlobalIsSet(utils.RopstenFlag.Name):
  277. log.Info("Starting Geth on Ropsten testnet...")
  278. case ctx.GlobalIsSet(utils.RinkebyFlag.Name):
  279. log.Info("Starting Geth on Rinkeby testnet...")
  280. case ctx.GlobalIsSet(utils.GoerliFlag.Name):
  281. log.Info("Starting Geth on Görli testnet...")
  282. case ctx.GlobalIsSet(utils.DeveloperFlag.Name):
  283. log.Info("Starting Geth in ephemeral dev mode...")
  284. case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name):
  285. log.Info("Starting Geth on Ethereum mainnet...")
  286. }
  287. // If we're a full node on mainnet without --cache specified, bump default cache allowance
  288. if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
  289. // Make sure we're not on any supported preconfigured testnet either
  290. 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) {
  291. // Nope, we're really on mainnet. Bump that cache up!
  292. log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
  293. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
  294. }
  295. }
  296. // If we're running a light client on any network, drop the cache to some meaningfully low amount
  297. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
  298. log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
  299. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
  300. }
  301. // Cap the cache allowance and tune the garbage collector
  302. mem, err := gopsutil.VirtualMemory()
  303. if err == nil {
  304. if 32<<(^uintptr(0)>>63) == 32 && mem.Total > 2*1024*1024*1024 {
  305. log.Warn("Lowering memory allowance on 32bit arch", "available", mem.Total/1024/1024, "addressable", 2*1024)
  306. mem.Total = 2 * 1024 * 1024 * 1024
  307. }
  308. allowance := int(mem.Total / 1024 / 1024 / 3)
  309. if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance {
  310. log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance)
  311. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance))
  312. }
  313. }
  314. // Ensure Go's GC ignores the database cache for trigger percentage
  315. cache := ctx.GlobalInt(utils.CacheFlag.Name)
  316. gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024)))
  317. log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc))
  318. godebug.SetGCPercent(int(gogc))
  319. // Start metrics export if enabled
  320. utils.SetupMetrics(ctx)
  321. // Start system runtime metrics collection
  322. go metrics.CollectProcessMetrics(3 * time.Second)
  323. }
  324. // geth is the main entry point into the system if no special subcommand is ran.
  325. // It creates a default node based on the command line arguments and runs it in
  326. // blocking mode, waiting for it to be shut down.
  327. func geth(ctx *cli.Context) error {
  328. if args := ctx.Args(); len(args) > 0 {
  329. return fmt.Errorf("invalid command: %q", args[0])
  330. }
  331. prepare(ctx)
  332. node := makeFullNode(ctx)
  333. defer node.Close()
  334. startNode(ctx, node)
  335. node.Wait()
  336. return nil
  337. }
  338. // startNode boots up the system node and all registered protocols, after which
  339. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  340. // miner.
  341. func startNode(ctx *cli.Context, stack *node.Node) {
  342. debug.Memsize.Add("node", stack)
  343. // Start up the node itself
  344. utils.StartNode(stack)
  345. // Unlock any account specifically requested
  346. unlockAccounts(ctx, stack)
  347. // Register wallet event handlers to open and auto-derive wallets
  348. events := make(chan accounts.WalletEvent, 16)
  349. stack.AccountManager().Subscribe(events)
  350. // Create a client to interact with local geth node.
  351. rpcClient, err := stack.Attach()
  352. if err != nil {
  353. utils.Fatalf("Failed to attach to self: %v", err)
  354. }
  355. ethClient := ethclient.NewClient(rpcClient)
  356. // Set contract backend for ethereum service if local node
  357. // is serving LES requests.
  358. if ctx.GlobalInt(utils.LegacyLightServFlag.Name) > 0 || ctx.GlobalInt(utils.LightServeFlag.Name) > 0 {
  359. var ethService *eth.Ethereum
  360. if err := stack.Service(&ethService); err != nil {
  361. utils.Fatalf("Failed to retrieve ethereum service: %v", err)
  362. }
  363. ethService.SetContractBackend(ethClient)
  364. }
  365. // Set contract backend for les service if local node is
  366. // running as a light client.
  367. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  368. var lesService *les.LightEthereum
  369. if err := stack.Service(&lesService); err != nil {
  370. utils.Fatalf("Failed to retrieve light ethereum service: %v", err)
  371. }
  372. lesService.SetContractBackend(ethClient)
  373. }
  374. go func() {
  375. // Open any wallets already attached
  376. for _, wallet := range stack.AccountManager().Wallets() {
  377. if err := wallet.Open(""); err != nil {
  378. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  379. }
  380. }
  381. // Listen for wallet event till termination
  382. for event := range events {
  383. switch event.Kind {
  384. case accounts.WalletArrived:
  385. if err := event.Wallet.Open(""); err != nil {
  386. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  387. }
  388. case accounts.WalletOpened:
  389. status, _ := event.Wallet.Status()
  390. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  391. var derivationPaths []accounts.DerivationPath
  392. if event.Wallet.URL().Scheme == "ledger" {
  393. derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
  394. }
  395. derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
  396. event.Wallet.SelfDerive(derivationPaths, ethClient)
  397. case accounts.WalletDropped:
  398. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  399. event.Wallet.Close()
  400. }
  401. }
  402. }()
  403. // Spawn a standalone goroutine for status synchronization monitoring,
  404. // close the node when synchronization is complete if user required.
  405. if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
  406. go func() {
  407. sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
  408. defer sub.Unsubscribe()
  409. for {
  410. event := <-sub.Chan()
  411. if event == nil {
  412. continue
  413. }
  414. done, ok := event.Data.(downloader.DoneEvent)
  415. if !ok {
  416. continue
  417. }
  418. if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
  419. log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
  420. "age", common.PrettyAge(timestamp))
  421. stack.Stop()
  422. }
  423. }
  424. }()
  425. }
  426. // Start auxiliary services if enabled
  427. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
  428. // Mining only makes sense if a full Ethereum node is running
  429. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  430. utils.Fatalf("Light clients do not support mining")
  431. }
  432. var ethereum *eth.Ethereum
  433. if err := stack.Service(&ethereum); err != nil {
  434. utils.Fatalf("Ethereum service not running: %v", err)
  435. }
  436. // Set the gas price to the limits from the CLI and start mining
  437. gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
  438. if ctx.GlobalIsSet(utils.LegacyMinerGasPriceFlag.Name) && !ctx.GlobalIsSet(utils.MinerGasPriceFlag.Name) {
  439. gasprice = utils.GlobalBig(ctx, utils.LegacyMinerGasPriceFlag.Name)
  440. }
  441. ethereum.TxPool().SetGasPrice(gasprice)
  442. threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name)
  443. if ctx.GlobalIsSet(utils.LegacyMinerThreadsFlag.Name) && !ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) {
  444. threads = ctx.GlobalInt(utils.LegacyMinerThreadsFlag.Name)
  445. log.Warn("The flag --minerthreads is deprecated and will be removed in the future, please use --miner.threads")
  446. }
  447. if err := ethereum.StartMining(threads); err != nil {
  448. utils.Fatalf("Failed to start mining: %v", err)
  449. }
  450. }
  451. }
  452. // unlockAccounts unlocks any account specifically requested.
  453. func unlockAccounts(ctx *cli.Context, stack *node.Node) {
  454. var unlocks []string
  455. inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  456. for _, input := range inputs {
  457. if trimmed := strings.TrimSpace(input); trimmed != "" {
  458. unlocks = append(unlocks, trimmed)
  459. }
  460. }
  461. // Short circuit if there is no account to unlock.
  462. if len(unlocks) == 0 {
  463. return
  464. }
  465. // If insecure account unlocking is not allowed if node's APIs are exposed to external.
  466. // Print warning log to user and skip unlocking.
  467. if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
  468. utils.Fatalf("Account unlock with HTTP access is forbidden!")
  469. }
  470. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  471. passwords := utils.MakePasswordList(ctx)
  472. for i, account := range unlocks {
  473. unlockAccount(ks, account, i, passwords)
  474. }
  475. }