main.go 14 KB

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