main.go 14 KB

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