main.go 16 KB

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