main.go 15 KB

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