main.go 16 KB

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