main.go 12 KB

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