main.go 14 KB

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