main.go 15 KB

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