main.go 14 KB

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