main.go 14 KB

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