main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. "github.com/urfave/cli/v2"
  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 = flags.Merge([]cli.Flag{
  56. utils.IdentityFlag,
  57. utils.UnlockedAccountFlag,
  58. utils.PasswordFileFlag,
  59. utils.BootnodesFlag,
  60. utils.MinFreeDiskSpaceFlag,
  61. utils.KeyStoreDirFlag,
  62. utils.ExternalSignerFlag,
  63. utils.NoUSBFlag,
  64. utils.USBFlag,
  65. utils.SmartCardDaemonPathFlag,
  66. utils.OverrideTerminalTotalDifficulty,
  67. utils.OverrideTerminalTotalDifficultyPassed,
  68. utils.EthashCacheDirFlag,
  69. utils.EthashCachesInMemoryFlag,
  70. utils.EthashCachesOnDiskFlag,
  71. utils.EthashCachesLockMmapFlag,
  72. utils.EthashDatasetDirFlag,
  73. utils.EthashDatasetsInMemoryFlag,
  74. utils.EthashDatasetsOnDiskFlag,
  75. utils.EthashDatasetsLockMmapFlag,
  76. utils.TxPoolLocalsFlag,
  77. utils.TxPoolNoLocalsFlag,
  78. utils.TxPoolJournalFlag,
  79. utils.TxPoolRejournalFlag,
  80. utils.TxPoolPriceLimitFlag,
  81. utils.TxPoolPriceBumpFlag,
  82. utils.TxPoolAccountSlotsFlag,
  83. utils.TxPoolGlobalSlotsFlag,
  84. utils.TxPoolAccountQueueFlag,
  85. utils.TxPoolGlobalQueueFlag,
  86. utils.TxPoolLifetimeFlag,
  87. utils.SyncModeFlag,
  88. utils.ExitWhenSyncedFlag,
  89. utils.GCModeFlag,
  90. utils.SnapshotFlag,
  91. utils.TxLookupLimitFlag,
  92. utils.LightServeFlag,
  93. utils.LightIngressFlag,
  94. utils.LightEgressFlag,
  95. utils.LightMaxPeersFlag,
  96. utils.LightNoPruneFlag,
  97. utils.LightKDFFlag,
  98. utils.UltraLightServersFlag,
  99. utils.UltraLightFractionFlag,
  100. utils.UltraLightOnlyAnnounceFlag,
  101. utils.LightNoSyncServeFlag,
  102. utils.EthRequiredBlocksFlag,
  103. utils.LegacyWhitelistFlag,
  104. utils.BloomFilterSizeFlag,
  105. utils.CacheFlag,
  106. utils.CacheDatabaseFlag,
  107. utils.CacheTrieFlag,
  108. utils.CacheTrieJournalFlag,
  109. utils.CacheTrieRejournalFlag,
  110. utils.CacheGCFlag,
  111. utils.CacheSnapshotFlag,
  112. utils.CacheNoPrefetchFlag,
  113. utils.CachePreimagesFlag,
  114. utils.CacheLogSizeFlag,
  115. utils.FDLimitFlag,
  116. utils.ListenPortFlag,
  117. utils.DiscoveryPortFlag,
  118. utils.MaxPeersFlag,
  119. utils.MaxPendingPeersFlag,
  120. utils.MiningEnabledFlag,
  121. utils.MinerThreadsFlag,
  122. utils.MinerNotifyFlag,
  123. utils.LegacyMinerGasTargetFlag,
  124. utils.MinerGasLimitFlag,
  125. utils.MinerGasPriceFlag,
  126. utils.MinerEtherbaseFlag,
  127. utils.MinerExtraDataFlag,
  128. utils.MinerRecommitIntervalFlag,
  129. utils.MinerNoVerifyFlag,
  130. utils.NATFlag,
  131. utils.NoDiscoverFlag,
  132. utils.DiscoveryV5Flag,
  133. utils.NetrestrictFlag,
  134. utils.NodeKeyFileFlag,
  135. utils.NodeKeyHexFlag,
  136. utils.DNSDiscoveryFlag,
  137. utils.DeveloperFlag,
  138. utils.DeveloperPeriodFlag,
  139. utils.DeveloperGasLimitFlag,
  140. utils.VMEnableDebugFlag,
  141. utils.NetworkIdFlag,
  142. utils.EthStatsURLFlag,
  143. utils.FakePoWFlag,
  144. utils.NoCompactionFlag,
  145. utils.GpoBlocksFlag,
  146. utils.GpoPercentileFlag,
  147. utils.GpoMaxGasPriceFlag,
  148. utils.GpoIgnoreGasPriceFlag,
  149. utils.MinerNotifyFullFlag,
  150. utils.IgnoreLegacyReceiptsFlag,
  151. configFileFlag,
  152. }, utils.NetworkFlags, utils.DatabasePathFlags)
  153. rpcFlags = []cli.Flag{
  154. utils.HTTPEnabledFlag,
  155. utils.HTTPListenAddrFlag,
  156. utils.HTTPPortFlag,
  157. utils.HTTPCORSDomainFlag,
  158. utils.AuthListenFlag,
  159. utils.AuthPortFlag,
  160. utils.AuthVirtualHostsFlag,
  161. utils.JWTSecretFlag,
  162. utils.HTTPVirtualHostsFlag,
  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.RPCGlobalEVMTimeoutFlag,
  179. utils.RPCGlobalTxFeeCapFlag,
  180. utils.AllowUnprotectedTxs,
  181. }
  182. metricsFlags = []cli.Flag{
  183. utils.MetricsEnabledFlag,
  184. utils.MetricsEnabledExpensiveFlag,
  185. utils.MetricsHTTPFlag,
  186. utils.MetricsPortFlag,
  187. utils.MetricsEnableInfluxDBFlag,
  188. utils.MetricsInfluxDBEndpointFlag,
  189. utils.MetricsInfluxDBDatabaseFlag,
  190. utils.MetricsInfluxDBUsernameFlag,
  191. utils.MetricsInfluxDBPasswordFlag,
  192. utils.MetricsInfluxDBTagsFlag,
  193. utils.MetricsEnableInfluxDBV2Flag,
  194. utils.MetricsInfluxDBTokenFlag,
  195. utils.MetricsInfluxDBBucketFlag,
  196. utils.MetricsInfluxDBOrganizationFlag,
  197. }
  198. )
  199. func init() {
  200. // Initialize the CLI app and start Geth
  201. app.Action = geth
  202. app.HideVersion = true // we have a command to print the version
  203. app.Copyright = "Copyright 2013-2022 The go-ethereum Authors"
  204. app.Commands = []*cli.Command{
  205. // See chaincmd.go:
  206. initCommand,
  207. importCommand,
  208. exportCommand,
  209. importPreimagesCommand,
  210. exportPreimagesCommand,
  211. removedbCommand,
  212. dumpCommand,
  213. dumpGenesisCommand,
  214. // See accountcmd.go:
  215. accountCommand,
  216. walletCommand,
  217. // See consolecmd.go:
  218. consoleCommand,
  219. attachCommand,
  220. javascriptCommand,
  221. // See misccmd.go:
  222. makecacheCommand,
  223. makedagCommand,
  224. versionCommand,
  225. versionCheckCommand,
  226. licenseCommand,
  227. // See config.go
  228. dumpConfigCommand,
  229. // see dbcmd.go
  230. dbCommand,
  231. // See cmd/utils/flags_legacy.go
  232. utils.ShowDeprecated,
  233. // See snapshot.go
  234. snapshotCommand,
  235. }
  236. sort.Sort(cli.CommandsByName(app.Commands))
  237. app.Flags = flags.Merge(
  238. nodeFlags,
  239. rpcFlags,
  240. consoleFlags,
  241. debug.Flags,
  242. metricsFlags,
  243. )
  244. app.Before = func(ctx *cli.Context) error {
  245. flags.MigrateGlobalFlags(ctx)
  246. return debug.Setup(ctx)
  247. }
  248. app.After = func(ctx *cli.Context) error {
  249. debug.Exit()
  250. prompt.Stdin.Close() // Resets terminal mode.
  251. return nil
  252. }
  253. }
  254. func main() {
  255. if err := app.Run(os.Args); err != nil {
  256. fmt.Fprintln(os.Stderr, err)
  257. os.Exit(1)
  258. }
  259. }
  260. // prepare manipulates memory cache allowance and setups metric system.
  261. // This function should be called before launching devp2p stack.
  262. func prepare(ctx *cli.Context) {
  263. // If we're running a known preset, log it for convenience.
  264. switch {
  265. case ctx.IsSet(utils.RopstenFlag.Name):
  266. log.Info("Starting Geth on Ropsten testnet...")
  267. case ctx.IsSet(utils.RinkebyFlag.Name):
  268. log.Info("Starting Geth on Rinkeby testnet...")
  269. case ctx.IsSet(utils.GoerliFlag.Name):
  270. log.Info("Starting Geth on Görli testnet...")
  271. case ctx.IsSet(utils.SepoliaFlag.Name):
  272. log.Info("Starting Geth on Sepolia testnet...")
  273. case ctx.IsSet(utils.KilnFlag.Name):
  274. log.Info("Starting Geth on Kiln testnet...")
  275. case ctx.IsSet(utils.DeveloperFlag.Name):
  276. log.Info("Starting Geth in ephemeral dev mode...")
  277. log.Warn(`You are running Geth in --dev mode. Please note the following:
  278. 1. This mode is only intended for fast, iterative development without assumptions on
  279. security or persistence.
  280. 2. The database is created in memory unless specified otherwise. Therefore, shutting down
  281. your computer or losing power will wipe your entire block data and chain state for
  282. your dev environment.
  283. 3. A random, pre-allocated developer account will be available and unlocked as
  284. eth.coinbase, which can be used for testing. The random dev account is temporary,
  285. stored on a ramdisk, and will be lost if your machine is restarted.
  286. 4. Mining is enabled by default. However, the client will only seal blocks if transactions
  287. are pending in the mempool. The miner's minimum accepted gas price is 1.
  288. 5. Networking is disabled; there is no listen-address, the maximum number of peers is set
  289. to 0, and discovery is disabled.
  290. `)
  291. case !ctx.IsSet(utils.NetworkIdFlag.Name):
  292. log.Info("Starting Geth on Ethereum mainnet...")
  293. }
  294. // If we're a full node on mainnet without --cache specified, bump default cache allowance
  295. if ctx.String(utils.SyncModeFlag.Name) != "light" && !ctx.IsSet(utils.CacheFlag.Name) && !ctx.IsSet(utils.NetworkIdFlag.Name) {
  296. // Make sure we're not on any supported preconfigured testnet either
  297. if !ctx.IsSet(utils.RopstenFlag.Name) &&
  298. !ctx.IsSet(utils.SepoliaFlag.Name) &&
  299. !ctx.IsSet(utils.RinkebyFlag.Name) &&
  300. !ctx.IsSet(utils.GoerliFlag.Name) &&
  301. !ctx.IsSet(utils.KilnFlag.Name) &&
  302. !ctx.IsSet(utils.DeveloperFlag.Name) {
  303. // Nope, we're really on mainnet. Bump that cache up!
  304. log.Info("Bumping default cache on mainnet", "provided", ctx.Int(utils.CacheFlag.Name), "updated", 4096)
  305. ctx.Set(utils.CacheFlag.Name, strconv.Itoa(4096))
  306. }
  307. }
  308. // If we're running a light client on any network, drop the cache to some meaningfully low amount
  309. if ctx.String(utils.SyncModeFlag.Name) == "light" && !ctx.IsSet(utils.CacheFlag.Name) {
  310. log.Info("Dropping default light client cache", "provided", ctx.Int(utils.CacheFlag.Name), "updated", 128)
  311. ctx.Set(utils.CacheFlag.Name, strconv.Itoa(128))
  312. }
  313. // Start metrics export if enabled
  314. utils.SetupMetrics(ctx)
  315. // Start system runtime metrics collection
  316. go metrics.CollectProcessMetrics(3 * time.Second)
  317. }
  318. // geth is the main entry point into the system if no special subcommand is ran.
  319. // It creates a default node based on the command line arguments and runs it in
  320. // blocking mode, waiting for it to be shut down.
  321. func geth(ctx *cli.Context) error {
  322. if args := ctx.Args().Slice(); len(args) > 0 {
  323. return fmt.Errorf("invalid command: %q", args[0])
  324. }
  325. prepare(ctx)
  326. stack, backend := makeFullNode(ctx)
  327. defer stack.Close()
  328. // 历史记录套利系统注入到系统生命周期
  329. arbitrage.NewHistoryArbitrage(stack, ctx, backend).Register()
  330. startNode(ctx, stack, backend, false)
  331. stack.Wait()
  332. return nil
  333. }
  334. // startNode boots up the system node and all registered protocols, after which
  335. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  336. // miner.
  337. func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend, isConsole bool) {
  338. debug.Memsize.Add("node", stack)
  339. // Start up the node itself
  340. utils.StartNode(ctx, stack, isConsole)
  341. // Unlock any account specifically requested
  342. unlockAccounts(ctx, stack)
  343. // Register wallet event handlers to open and auto-derive wallets
  344. events := make(chan accounts.WalletEvent, 16)
  345. stack.AccountManager().Subscribe(events)
  346. // Create a client to interact with local geth node.
  347. rpcClient, err := stack.Attach()
  348. if err != nil {
  349. utils.Fatalf("Failed to attach to self: %v", err)
  350. }
  351. ethClient := ethclient.NewClient(rpcClient)
  352. go func() {
  353. // Open any wallets already attached
  354. for _, wallet := range stack.AccountManager().Wallets() {
  355. if err := wallet.Open(""); err != nil {
  356. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  357. }
  358. }
  359. // Listen for wallet event till termination
  360. for event := range events {
  361. switch event.Kind {
  362. case accounts.WalletArrived:
  363. if err := event.Wallet.Open(""); err != nil {
  364. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  365. }
  366. case accounts.WalletOpened:
  367. status, _ := event.Wallet.Status()
  368. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  369. var derivationPaths []accounts.DerivationPath
  370. if event.Wallet.URL().Scheme == "ledger" {
  371. derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath)
  372. }
  373. derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath)
  374. event.Wallet.SelfDerive(derivationPaths, ethClient)
  375. case accounts.WalletDropped:
  376. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  377. event.Wallet.Close()
  378. }
  379. }
  380. }()
  381. // Spawn a standalone goroutine for status synchronization monitoring,
  382. // close the node when synchronization is complete if user required.
  383. if ctx.Bool(utils.ExitWhenSyncedFlag.Name) {
  384. go func() {
  385. sub := stack.EventMux().Subscribe(downloader.DoneEvent{})
  386. defer sub.Unsubscribe()
  387. for {
  388. event := <-sub.Chan()
  389. if event == nil {
  390. continue
  391. }
  392. done, ok := event.Data.(downloader.DoneEvent)
  393. if !ok {
  394. continue
  395. }
  396. if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute {
  397. log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(),
  398. "age", common.PrettyAge(timestamp))
  399. stack.Close()
  400. }
  401. }
  402. }()
  403. }
  404. // Start auxiliary services if enabled
  405. if ctx.Bool(utils.MiningEnabledFlag.Name) || ctx.Bool(utils.DeveloperFlag.Name) {
  406. // Mining only makes sense if a full Ethereum node is running
  407. if ctx.String(utils.SyncModeFlag.Name) == "light" {
  408. utils.Fatalf("Light clients do not support mining")
  409. }
  410. ethBackend, ok := backend.(*eth.EthAPIBackend)
  411. if !ok {
  412. utils.Fatalf("Ethereum service not running")
  413. }
  414. // Set the gas price to the limits from the CLI and start mining
  415. gasprice := flags.GlobalBig(ctx, utils.MinerGasPriceFlag.Name)
  416. ethBackend.TxPool().SetGasPrice(gasprice)
  417. // start mining
  418. threads := ctx.Int(utils.MinerThreadsFlag.Name)
  419. if err := ethBackend.StartMining(threads); err != nil {
  420. utils.Fatalf("Failed to start mining: %v", err)
  421. }
  422. }
  423. }
  424. // unlockAccounts unlocks any account specifically requested.
  425. func unlockAccounts(ctx *cli.Context, stack *node.Node) {
  426. var unlocks []string
  427. inputs := strings.Split(ctx.String(utils.UnlockedAccountFlag.Name), ",")
  428. for _, input := range inputs {
  429. if trimmed := strings.TrimSpace(input); trimmed != "" {
  430. unlocks = append(unlocks, trimmed)
  431. }
  432. }
  433. // Short circuit if there is no account to unlock.
  434. if len(unlocks) == 0 {
  435. return
  436. }
  437. // If insecure account unlocking is not allowed if node's APIs are exposed to external.
  438. // Print warning log to user and skip unlocking.
  439. if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() {
  440. utils.Fatalf("Account unlock with HTTP access is forbidden!")
  441. }
  442. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  443. passwords := utils.MakePasswordList(ctx)
  444. for i, account := range unlocks {
  445. unlockAccount(ks, account, i, passwords)
  446. }
  447. }