main.go 16 KB

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