main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. "os"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/ethereum/go-ethereum/accounts"
  26. "github.com/ethereum/go-ethereum/accounts/keystore"
  27. "github.com/ethereum/go-ethereum/cmd/utils"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/console/prompt"
  30. "github.com/ethereum/go-ethereum/eth"
  31. "github.com/ethereum/go-ethereum/eth/downloader"
  32. "github.com/ethereum/go-ethereum/ethclient"
  33. "github.com/ethereum/go-ethereum/internal/debug"
  34. "github.com/ethereum/go-ethereum/internal/ethapi"
  35. "github.com/ethereum/go-ethereum/internal/flags"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/metrics"
  38. "github.com/ethereum/go-ethereum/node"
  39. "gopkg.in/urfave/cli.v1"
  40. )
  41. const (
  42. clientIdentifier = "geth" // Client identifier to advertise over the network
  43. )
  44. var (
  45. // Git SHA1 commit hash of the release (set via linker flags)
  46. gitCommit = ""
  47. gitDate = ""
  48. // The app that holds all commands and flags.
  49. app = flags.NewApp(gitCommit, gitDate, "the go-ethereum command line interface")
  50. // flags that configure the node
  51. nodeFlags = []cli.Flag{
  52. utils.IdentityFlag,
  53. utils.UnlockedAccountFlag,
  54. utils.PasswordFileFlag,
  55. utils.BootnodesFlag,
  56. utils.DataDirFlag,
  57. utils.AncientFlag,
  58. utils.MinFreeDiskSpaceFlag,
  59. utils.KeyStoreDirFlag,
  60. utils.ExternalSignerFlag,
  61. utils.NoUSBFlag,
  62. utils.DirectBroadcastFlag,
  63. utils.DisableSnapProtocolFlag,
  64. utils.DiffSyncFlag,
  65. utils.RangeLimitFlag,
  66. utils.USBFlag,
  67. utils.SmartCardDaemonPathFlag,
  68. utils.OverrideBerlinFlag,
  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.TxPoolReannounceTimeFlag,
  89. utils.SyncModeFlag,
  90. utils.ExitWhenSyncedFlag,
  91. utils.GCModeFlag,
  92. utils.SnapshotFlag,
  93. utils.TxLookupLimitFlag,
  94. utils.LightServeFlag,
  95. utils.LightIngressFlag,
  96. utils.LightEgressFlag,
  97. utils.LightMaxPeersFlag,
  98. utils.LightNoPruneFlag,
  99. utils.LightKDFFlag,
  100. utils.UltraLightServersFlag,
  101. utils.UltraLightFractionFlag,
  102. utils.UltraLightOnlyAnnounceFlag,
  103. utils.LightNoSyncServeFlag,
  104. utils.WhitelistFlag,
  105. utils.BloomFilterSizeFlag,
  106. utils.TriesInMemoryFlag,
  107. utils.CacheFlag,
  108. utils.CacheDatabaseFlag,
  109. utils.CacheTrieFlag,
  110. utils.CacheTrieJournalFlag,
  111. utils.CacheTrieRejournalFlag,
  112. utils.CacheGCFlag,
  113. utils.CacheSnapshotFlag,
  114. utils.CachePreimagesFlag,
  115. utils.PersistDiffFlag,
  116. utils.DiffBlockFlag,
  117. utils.ListenPortFlag,
  118. utils.MaxPeersFlag,
  119. utils.MaxPendingPeersFlag,
  120. utils.MiningEnabledFlag,
  121. utils.MinerThreadsFlag,
  122. utils.MinerNotifyFlag,
  123. utils.MinerGasTargetFlag,
  124. utils.MinerGasLimitFlag,
  125. utils.MinerGasPriceFlag,
  126. utils.MinerEtherbaseFlag,
  127. utils.MinerExtraDataFlag,
  128. utils.MinerRecommitIntervalFlag,
  129. utils.MinerDelayLeftoverFlag,
  130. utils.MinerNoVerfiyFlag,
  131. utils.NATFlag,
  132. utils.NoDiscoverFlag,
  133. utils.DiscoveryV5Flag,
  134. utils.NetrestrictFlag,
  135. utils.NodeKeyFileFlag,
  136. utils.NodeKeyHexFlag,
  137. utils.DNSDiscoveryFlag,
  138. utils.MainnetFlag,
  139. utils.DeveloperFlag,
  140. utils.DeveloperPeriodFlag,
  141. utils.RopstenFlag,
  142. utils.RinkebyFlag,
  143. utils.GoerliFlag,
  144. utils.YoloV3Flag,
  145. utils.VMEnableDebugFlag,
  146. utils.NetworkIdFlag,
  147. utils.EthStatsURLFlag,
  148. utils.FakePoWFlag,
  149. utils.NoCompactionFlag,
  150. utils.GpoBlocksFlag,
  151. utils.GpoPercentileFlag,
  152. utils.GpoMaxGasPriceFlag,
  153. utils.EWASMInterpreterFlag,
  154. utils.EVMInterpreterFlag,
  155. utils.MinerNotifyFullFlag,
  156. configFileFlag,
  157. utils.CatalystFlag,
  158. }
  159. rpcFlags = []cli.Flag{
  160. utils.HTTPEnabledFlag,
  161. utils.HTTPListenAddrFlag,
  162. utils.HTTPPortFlag,
  163. utils.HTTPCORSDomainFlag,
  164. utils.HTTPVirtualHostsFlag,
  165. utils.LegacyRPCEnabledFlag,
  166. utils.LegacyRPCListenAddrFlag,
  167. utils.LegacyRPCPortFlag,
  168. utils.LegacyRPCCORSDomainFlag,
  169. utils.LegacyRPCVirtualHostsFlag,
  170. utils.LegacyRPCApiFlag,
  171. utils.GraphQLEnabledFlag,
  172. utils.GraphQLCORSDomainFlag,
  173. utils.GraphQLVirtualHostsFlag,
  174. utils.HTTPApiFlag,
  175. utils.HTTPPathPrefixFlag,
  176. utils.WSEnabledFlag,
  177. utils.WSListenAddrFlag,
  178. utils.WSPortFlag,
  179. utils.WSApiFlag,
  180. utils.WSAllowedOriginsFlag,
  181. utils.WSPathPrefixFlag,
  182. utils.IPCDisabledFlag,
  183. utils.IPCPathFlag,
  184. utils.InsecureUnlockAllowedFlag,
  185. utils.RPCGlobalGasCapFlag,
  186. utils.RPCGlobalTxFeeCapFlag,
  187. utils.AllowUnprotectedTxs,
  188. }
  189. metricsFlags = []cli.Flag{
  190. utils.MetricsEnabledFlag,
  191. utils.MetricsEnabledExpensiveFlag,
  192. utils.MetricsHTTPFlag,
  193. utils.MetricsPortFlag,
  194. utils.MetricsEnableInfluxDBFlag,
  195. utils.MetricsInfluxDBEndpointFlag,
  196. utils.MetricsInfluxDBDatabaseFlag,
  197. utils.MetricsInfluxDBUsernameFlag,
  198. utils.MetricsInfluxDBPasswordFlag,
  199. utils.MetricsInfluxDBTagsFlag,
  200. }
  201. )
  202. func init() {
  203. // Initialize the CLI app and start Geth
  204. app.Action = geth
  205. app.HideVersion = true // we have a command to print the version
  206. app.Copyright = "Copyright 2013-2020 The go-ethereum Authors and BSC Authors"
  207. app.Commands = []cli.Command{
  208. // See chaincmd.go:
  209. initCommand,
  210. initNetworkCommand,
  211. importCommand,
  212. exportCommand,
  213. importPreimagesCommand,
  214. exportPreimagesCommand,
  215. removedbCommand,
  216. dumpCommand,
  217. dumpGenesisCommand,
  218. // See accountcmd.go:
  219. accountCommand,
  220. walletCommand,
  221. // See consolecmd.go:
  222. consoleCommand,
  223. attachCommand,
  224. javascriptCommand,
  225. // See misccmd.go:
  226. makecacheCommand,
  227. makedagCommand,
  228. versionCommand,
  229. versionCheckCommand,
  230. licenseCommand,
  231. // See config.go
  232. dumpConfigCommand,
  233. // see dbcmd.go
  234. dbCommand,
  235. // See cmd/utils/flags_legacy.go
  236. utils.ShowDeprecated,
  237. // See snapshot.go
  238. snapshotCommand,
  239. }
  240. sort.Sort(cli.CommandsByName(app.Commands))
  241. app.Flags = append(app.Flags, nodeFlags...)
  242. app.Flags = append(app.Flags, rpcFlags...)
  243. app.Flags = append(app.Flags, consoleFlags...)
  244. app.Flags = append(app.Flags, debug.Flags...)
  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. // Start metrics export if enabled
  294. utils.SetupMetrics(ctx)
  295. // Start system runtime metrics collection
  296. go metrics.CollectProcessMetrics(3 * time.Second)
  297. }
  298. // geth is the main entry point into the system if no special subcommand is ran.
  299. // It creates a default node based on the command line arguments and runs it in
  300. // blocking mode, waiting for it to be shut down.
  301. func geth(ctx *cli.Context) error {
  302. if args := ctx.Args(); len(args) > 0 {
  303. return fmt.Errorf("invalid command: %q", args[0])
  304. }
  305. prepare(ctx)
  306. stack, backend := makeFullNode(ctx)
  307. defer stack.Close()
  308. startNode(ctx, stack, backend)
  309. stack.Wait()
  310. return nil
  311. }
  312. // startNode boots up the system node and all registered protocols, after which
  313. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  314. // miner.
  315. func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend) {
  316. debug.Memsize.Add("node", stack)
  317. // Start up the node itself
  318. utils.StartNode(ctx, stack)
  319. // Unlock any account specifically requested
  320. unlockAccounts(ctx, stack)
  321. // Register wallet event handlers to open and auto-derive wallets
  322. events := make(chan accounts.WalletEvent, 16)
  323. stack.AccountManager().Subscribe(events)
  324. // Create a client to interact with local geth node.
  325. rpcClient, err := stack.Attach()
  326. if err != nil {
  327. utils.Fatalf("Failed to attach to self: %v", err)
  328. }
  329. ethClient := ethclient.NewClient(rpcClient)
  330. go func() {
  331. // Open any wallets already attached
  332. for _, wallet := range stack.AccountManager().Wallets() {
  333. if err := wallet.Open(""); err != nil {
  334. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  335. }
  336. }
  337. // Listen for wallet event till termination
  338. for event := range events {
  339. switch event.Kind {
  340. case accounts.WalletArrived:
  341. if err := event.Wallet.Open(""); err != nil {
  342. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  343. }
  344. case accounts.WalletOpened:
  345. status, _ := event.Wallet.Status()
  346. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  347. var derivationPaths []accounts.DerivationPath
  348. if event.Wallet.URL().Scheme == "ledger" {
  349. derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
  350. }
  351. derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
  352. event.Wallet.SelfDerive(derivationPaths, ethClient)
  353. case accounts.WalletDropped:
  354. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  355. event.Wallet.Close()
  356. }
  357. }
  358. }()
  359. // Spawn a standalone goroutine for status synchronization monitoring,
  360. // close the node when synchronization is complete if user required.
  361. if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
  362. go func() {
  363. sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
  364. defer sub.Unsubscribe()
  365. for {
  366. event := <-sub.Chan()
  367. if event == nil {
  368. continue
  369. }
  370. done, ok := event.Data.(downloader.DoneEvent)
  371. if !ok {
  372. continue
  373. }
  374. if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
  375. log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
  376. "age", common.PrettyAge(timestamp))
  377. stack.Close()
  378. }
  379. }
  380. }()
  381. }
  382. // Start auxiliary services if enabled
  383. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
  384. // Mining only makes sense if a full Ethereum node is running
  385. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  386. utils.Fatalf("Light clients do not support mining")
  387. }
  388. ethBackend, ok := backend.(*eth.EthAPIBackend)
  389. if !ok {
  390. utils.Fatalf("Ethereum service not running: %v", err)
  391. }
  392. // Set the gas price to the limits from the CLI and start mining
  393. gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
  394. ethBackend.TxPool().SetGasPrice(gasprice)
  395. // start mining
  396. threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name)
  397. if err := ethBackend.StartMining(threads); err != nil {
  398. utils.Fatalf("Failed to start mining: %v", err)
  399. }
  400. }
  401. }
  402. // unlockAccounts unlocks any account specifically requested.
  403. func unlockAccounts(ctx *cli.Context, stack *node.Node) {
  404. var unlocks []string
  405. inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  406. for _, input := range inputs {
  407. if trimmed := strings.TrimSpace(input); trimmed != "" {
  408. unlocks = append(unlocks, trimmed)
  409. }
  410. }
  411. // Short circuit if there is no account to unlock.
  412. if len(unlocks) == 0 {
  413. return
  414. }
  415. // If insecure account unlocking is not allowed if node's APIs are exposed to external.
  416. // Print warning log to user and skip unlocking.
  417. if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
  418. utils.Fatalf("Account unlock with HTTP access is forbidden!")
  419. }
  420. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  421. passwords := utils.MakePasswordList(ctx)
  422. for i, account := range unlocks {
  423. unlockAccount(ks, account, i, passwords)
  424. }
  425. }