main.go 16 KB

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