main.go 14 KB

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