main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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.RangeLimitFlag,
  64. utils.USBFlag,
  65. utils.SmartCardDaemonPathFlag,
  66. utils.OverrideBerlinFlag,
  67. utils.EthashCacheDirFlag,
  68. utils.EthashCachesInMemoryFlag,
  69. utils.EthashCachesOnDiskFlag,
  70. utils.EthashCachesLockMmapFlag,
  71. utils.EthashDatasetDirFlag,
  72. utils.EthashDatasetsInMemoryFlag,
  73. utils.EthashDatasetsOnDiskFlag,
  74. utils.EthashDatasetsLockMmapFlag,
  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.SnapshotFlag,
  90. utils.TxLookupLimitFlag,
  91. utils.LightServeFlag,
  92. utils.LightIngressFlag,
  93. utils.LightEgressFlag,
  94. utils.LightMaxPeersFlag,
  95. utils.LightNoPruneFlag,
  96. utils.LightKDFFlag,
  97. utils.UltraLightServersFlag,
  98. utils.UltraLightFractionFlag,
  99. utils.UltraLightOnlyAnnounceFlag,
  100. utils.LightNoSyncServeFlag,
  101. utils.WhitelistFlag,
  102. utils.BloomFilterSizeFlag,
  103. utils.CacheFlag,
  104. utils.CacheDatabaseFlag,
  105. utils.CacheTrieFlag,
  106. utils.CacheTrieJournalFlag,
  107. utils.CacheTrieRejournalFlag,
  108. utils.CacheGCFlag,
  109. utils.CacheSnapshotFlag,
  110. utils.CacheNoPrefetchFlag,
  111. utils.CachePreimagesFlag,
  112. utils.ListenPortFlag,
  113. utils.MaxPeersFlag,
  114. utils.MaxPendingPeersFlag,
  115. utils.MiningEnabledFlag,
  116. utils.MinerThreadsFlag,
  117. utils.MinerNotifyFlag,
  118. utils.MinerGasTargetFlag,
  119. utils.MinerGasLimitFlag,
  120. utils.MinerGasPriceFlag,
  121. utils.MinerEtherbaseFlag,
  122. utils.MinerExtraDataFlag,
  123. utils.MinerRecommitIntervalFlag,
  124. utils.MinerDelayLeftoverFlag,
  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.MainnetFlag,
  134. utils.DeveloperFlag,
  135. utils.DeveloperPeriodFlag,
  136. utils.RopstenFlag,
  137. utils.RinkebyFlag,
  138. utils.GoerliFlag,
  139. utils.YoloV3Flag,
  140. utils.VMEnableDebugFlag,
  141. utils.NetworkIdFlag,
  142. utils.EthStatsURLFlag,
  143. utils.FakePoWFlag,
  144. utils.NoCompactionFlag,
  145. utils.GpoBlocksFlag,
  146. utils.GpoPercentileFlag,
  147. utils.GpoMaxGasPriceFlag,
  148. utils.EWASMInterpreterFlag,
  149. utils.EVMInterpreterFlag,
  150. utils.MinerNotifyFullFlag,
  151. configFileFlag,
  152. utils.CatalystFlag,
  153. }
  154. rpcFlags = []cli.Flag{
  155. utils.HTTPEnabledFlag,
  156. utils.HTTPListenAddrFlag,
  157. utils.HTTPPortFlag,
  158. utils.HTTPCORSDomainFlag,
  159. utils.HTTPVirtualHostsFlag,
  160. utils.LegacyRPCEnabledFlag,
  161. utils.LegacyRPCListenAddrFlag,
  162. utils.LegacyRPCPortFlag,
  163. utils.LegacyRPCCORSDomainFlag,
  164. utils.LegacyRPCVirtualHostsFlag,
  165. utils.LegacyRPCApiFlag,
  166. utils.GraphQLEnabledFlag,
  167. utils.GraphQLCORSDomainFlag,
  168. utils.GraphQLVirtualHostsFlag,
  169. utils.HTTPApiFlag,
  170. utils.HTTPPathPrefixFlag,
  171. utils.WSEnabledFlag,
  172. utils.WSListenAddrFlag,
  173. utils.WSPortFlag,
  174. utils.WSApiFlag,
  175. utils.WSAllowedOriginsFlag,
  176. utils.WSPathPrefixFlag,
  177. utils.IPCDisabledFlag,
  178. utils.IPCPathFlag,
  179. utils.InsecureUnlockAllowedFlag,
  180. utils.RPCGlobalGasCapFlag,
  181. utils.RPCGlobalTxFeeCapFlag,
  182. utils.AllowUnprotectedTxs,
  183. }
  184. metricsFlags = []cli.Flag{
  185. utils.MetricsEnabledFlag,
  186. utils.MetricsEnabledExpensiveFlag,
  187. utils.MetricsHTTPFlag,
  188. utils.MetricsPortFlag,
  189. utils.MetricsEnableInfluxDBFlag,
  190. utils.MetricsInfluxDBEndpointFlag,
  191. utils.MetricsInfluxDBDatabaseFlag,
  192. utils.MetricsInfluxDBUsernameFlag,
  193. utils.MetricsInfluxDBPasswordFlag,
  194. utils.MetricsInfluxDBTagsFlag,
  195. }
  196. )
  197. func init() {
  198. // Initialize the CLI app and start Geth
  199. app.Action = geth
  200. app.HideVersion = true // we have a command to print the version
  201. app.Copyright = "Copyright 2013-2020 The go-ethereum Authors and BSC Authors"
  202. app.Commands = []cli.Command{
  203. // See chaincmd.go:
  204. initCommand,
  205. initNetworkCommand,
  206. importCommand,
  207. exportCommand,
  208. importPreimagesCommand,
  209. exportPreimagesCommand,
  210. removedbCommand,
  211. dumpCommand,
  212. dumpGenesisCommand,
  213. // See accountcmd.go:
  214. accountCommand,
  215. walletCommand,
  216. // See consolecmd.go:
  217. consoleCommand,
  218. attachCommand,
  219. javascriptCommand,
  220. // See misccmd.go:
  221. makecacheCommand,
  222. makedagCommand,
  223. versionCommand,
  224. versionCheckCommand,
  225. licenseCommand,
  226. // See config.go
  227. dumpConfigCommand,
  228. // see dbcmd.go
  229. dbCommand,
  230. // See cmd/utils/flags_legacy.go
  231. utils.ShowDeprecated,
  232. // See snapshot.go
  233. snapshotCommand,
  234. }
  235. sort.Sort(cli.CommandsByName(app.Commands))
  236. app.Flags = append(app.Flags, nodeFlags...)
  237. app.Flags = append(app.Flags, rpcFlags...)
  238. app.Flags = append(app.Flags, consoleFlags...)
  239. app.Flags = append(app.Flags, debug.Flags...)
  240. app.Flags = append(app.Flags, metricsFlags...)
  241. app.Before = func(ctx *cli.Context) error {
  242. return debug.Setup(ctx)
  243. }
  244. app.After = func(ctx *cli.Context) error {
  245. debug.Exit()
  246. prompt.Stdin.Close() // Resets terminal mode.
  247. return nil
  248. }
  249. }
  250. func main() {
  251. if err := app.Run(os.Args); err != nil {
  252. fmt.Fprintln(os.Stderr, err)
  253. os.Exit(1)
  254. }
  255. }
  256. // prepare manipulates memory cache allowance and setups metric system.
  257. // This function should be called before launching devp2p stack.
  258. func prepare(ctx *cli.Context) {
  259. // If we're running a known preset, log it for convenience.
  260. switch {
  261. case ctx.GlobalIsSet(utils.RopstenFlag.Name):
  262. log.Info("Starting Geth on Ropsten testnet...")
  263. case ctx.GlobalIsSet(utils.RinkebyFlag.Name):
  264. log.Info("Starting Geth on Rinkeby testnet...")
  265. case ctx.GlobalIsSet(utils.GoerliFlag.Name):
  266. log.Info("Starting Geth on Görli testnet...")
  267. case ctx.GlobalIsSet(utils.YoloV3Flag.Name):
  268. log.Info("Starting Geth on YOLOv3 testnet...")
  269. case ctx.GlobalIsSet(utils.DeveloperFlag.Name):
  270. log.Info("Starting Geth in ephemeral dev mode...")
  271. case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name):
  272. log.Info("Starting Geth on Ethereum mainnet...")
  273. }
  274. // If we're a full node on mainnet without --cache specified, bump default cache allowance
  275. if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) {
  276. // Make sure we're not on any supported preconfigured testnet either
  277. if !ctx.GlobalIsSet(utils.RopstenFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) {
  278. // Nope, we're really on mainnet. Bump that cache up!
  279. log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096)
  280. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096))
  281. }
  282. }
  283. // If we're running a light client on any network, drop the cache to some meaningfully low amount
  284. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) {
  285. log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128)
  286. ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128))
  287. }
  288. // Start metrics export if enabled
  289. utils.SetupMetrics(ctx)
  290. // Start system runtime metrics collection
  291. go metrics.CollectProcessMetrics(3 * time.Second)
  292. }
  293. // geth is the main entry point into the system if no special subcommand is ran.
  294. // It creates a default node based on the command line arguments and runs it in
  295. // blocking mode, waiting for it to be shut down.
  296. func geth(ctx *cli.Context) error {
  297. if args := ctx.Args(); len(args) > 0 {
  298. return fmt.Errorf("invalid command: %q", args[0])
  299. }
  300. prepare(ctx)
  301. stack, backend := makeFullNode(ctx)
  302. defer stack.Close()
  303. startNode(ctx, stack, backend)
  304. stack.Wait()
  305. return nil
  306. }
  307. // startNode boots up the system node and all registered protocols, after which
  308. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  309. // miner.
  310. func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend) {
  311. debug.Memsize.Add("node", stack)
  312. // Start up the node itself
  313. utils.StartNode(ctx, stack)
  314. // Unlock any account specifically requested
  315. unlockAccounts(ctx, stack)
  316. // Register wallet event handlers to open and auto-derive wallets
  317. events := make(chan accounts.WalletEvent, 16)
  318. stack.AccountManager().Subscribe(events)
  319. // Create a client to interact with local geth node.
  320. rpcClient, err := stack.Attach()
  321. if err != nil {
  322. utils.Fatalf("Failed to attach to self: %v", err)
  323. }
  324. ethClient := ethclient.NewClient(rpcClient)
  325. go func() {
  326. // Open any wallets already attached
  327. for _, wallet := range stack.AccountManager().Wallets() {
  328. if err := wallet.Open(""); err != nil {
  329. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  330. }
  331. }
  332. // Listen for wallet event till termination
  333. for event := range events {
  334. switch event.Kind {
  335. case accounts.WalletArrived:
  336. if err := event.Wallet.Open(""); err != nil {
  337. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  338. }
  339. case accounts.WalletOpened:
  340. status, _ := event.Wallet.Status()
  341. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  342. var derivationPaths []accounts.DerivationPath
  343. if event.Wallet.URL().Scheme == "ledger" {
  344. derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
  345. }
  346. derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
  347. event.Wallet.SelfDerive(derivationPaths, ethClient)
  348. case accounts.WalletDropped:
  349. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  350. event.Wallet.Close()
  351. }
  352. }
  353. }()
  354. // Spawn a standalone goroutine for status synchronization monitoring,
  355. // close the node when synchronization is complete if user required.
  356. if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) {
  357. go func() {
  358. sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
  359. defer sub.Unsubscribe()
  360. for {
  361. event := <-sub.Chan()
  362. if event == nil {
  363. continue
  364. }
  365. done, ok := event.Data.(downloader.DoneEvent)
  366. if !ok {
  367. continue
  368. }
  369. if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
  370. log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
  371. "age", common.PrettyAge(timestamp))
  372. stack.Close()
  373. }
  374. }
  375. }()
  376. }
  377. // Start auxiliary services if enabled
  378. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
  379. // Mining only makes sense if a full Ethereum node is running
  380. if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" {
  381. utils.Fatalf("Light clients do not support mining")
  382. }
  383. ethBackend, ok := backend.(*eth.EthAPIBackend)
  384. if !ok {
  385. utils.Fatalf("Ethereum service not running: %v", err)
  386. }
  387. // Set the gas price to the limits from the CLI and start mining
  388. gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
  389. ethBackend.TxPool().SetGasPrice(gasprice)
  390. // start mining
  391. threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name)
  392. if err := ethBackend.StartMining(threads); err != nil {
  393. utils.Fatalf("Failed to start mining: %v", err)
  394. }
  395. }
  396. }
  397. // unlockAccounts unlocks any account specifically requested.
  398. func unlockAccounts(ctx *cli.Context, stack *node.Node) {
  399. var unlocks []string
  400. inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  401. for _, input := range inputs {
  402. if trimmed := strings.TrimSpace(input); trimmed != "" {
  403. unlocks = append(unlocks, trimmed)
  404. }
  405. }
  406. // Short circuit if there is no account to unlock.
  407. if len(unlocks) == 0 {
  408. return
  409. }
  410. // If insecure account unlocking is not allowed if node's APIs are exposed to external.
  411. // Print warning log to user and skip unlocking.
  412. if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
  413. utils.Fatalf("Account unlock with HTTP access is forbidden!")
  414. }
  415. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  416. passwords := utils.MakePasswordList(ctx)
  417. for i, account := range unlocks {
  418. unlockAccount(ks, account, i, passwords)
  419. }
  420. }