main.go 14 KB

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