main.go 14 KB

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