main.go 16 KB

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