gitee.com/liu-zhao234568/cntest@v1.0.0/cmd/geth/main.go (about) 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 17 // geth is the official command-line client for Ethereum. 18 package main 19 20 import ( 21 "fmt" 22 "os" 23 "sort" 24 "strconv" 25 "strings" 26 "time" 27 28 "gitee.com/liu-zhao234568/cntest/accounts" 29 "gitee.com/liu-zhao234568/cntest/accounts/keystore" 30 "gitee.com/liu-zhao234568/cntest/cmd/utils" 31 "gitee.com/liu-zhao234568/cntest/common" 32 "gitee.com/liu-zhao234568/cntest/console/prompt" 33 "gitee.com/liu-zhao234568/cntest/eth" 34 "gitee.com/liu-zhao234568/cntest/eth/downloader" 35 "gitee.com/liu-zhao234568/cntest/ethclient" 36 "gitee.com/liu-zhao234568/cntest/internal/debug" 37 "gitee.com/liu-zhao234568/cntest/internal/ethapi" 38 "gitee.com/liu-zhao234568/cntest/internal/flags" 39 "gitee.com/liu-zhao234568/cntest/log" 40 "gitee.com/liu-zhao234568/cntest/metrics" 41 "gitee.com/liu-zhao234568/cntest/node" 42 "gopkg.in/urfave/cli.v1" 43 ) 44 45 const ( 46 clientIdentifier = "geth" // Client identifier to advertise over the network 47 ) 48 49 var ( 50 // Git SHA1 commit hash of the release (set via linker flags) 51 gitCommit = "" 52 gitDate = "" 53 // The app that holds all commands and flags. 54 app = flags.NewApp(gitCommit, gitDate, "the go-ethereum command line interface") 55 // flags that configure the node 56 nodeFlags = []cli.Flag{ 57 utils.IdentityFlag, 58 utils.UnlockedAccountFlag, 59 utils.PasswordFileFlag, 60 utils.BootnodesFlag, 61 utils.DataDirFlag, 62 utils.AncientFlag, 63 utils.MinFreeDiskSpaceFlag, 64 utils.KeyStoreDirFlag, 65 utils.ExternalSignerFlag, 66 utils.NoUSBFlag, 67 utils.USBFlag, 68 utils.SmartCardDaemonPathFlag, 69 utils.OverrideLondonFlag, 70 utils.EthashCacheDirFlag, 71 utils.EthashCachesInMemoryFlag, 72 utils.EthashCachesOnDiskFlag, 73 utils.EthashCachesLockMmapFlag, 74 utils.EthashDatasetDirFlag, 75 utils.EthashDatasetsInMemoryFlag, 76 utils.EthashDatasetsOnDiskFlag, 77 utils.EthashDatasetsLockMmapFlag, 78 utils.TxPoolLocalsFlag, 79 utils.TxPoolNoLocalsFlag, 80 utils.TxPoolJournalFlag, 81 utils.TxPoolRejournalFlag, 82 utils.TxPoolPriceLimitFlag, 83 utils.TxPoolPriceBumpFlag, 84 utils.TxPoolAccountSlotsFlag, 85 utils.TxPoolGlobalSlotsFlag, 86 utils.TxPoolAccountQueueFlag, 87 utils.TxPoolGlobalQueueFlag, 88 utils.TxPoolLifetimeFlag, 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.CacheFlag, 107 utils.CacheDatabaseFlag, 108 utils.CacheTrieFlag, 109 utils.CacheTrieJournalFlag, 110 utils.CacheTrieRejournalFlag, 111 utils.CacheGCFlag, 112 utils.CacheSnapshotFlag, 113 utils.CacheNoPrefetchFlag, 114 utils.CachePreimagesFlag, 115 utils.ListenPortFlag, 116 utils.MaxPeersFlag, 117 utils.MaxPendingPeersFlag, 118 utils.MiningEnabledFlag, 119 utils.MinerThreadsFlag, 120 utils.MinerNotifyFlag, 121 utils.MinerGasTargetFlag, 122 utils.MinerGasLimitFlag, 123 utils.MinerGasPriceFlag, 124 utils.MinerEtherbaseFlag, 125 utils.MinerExtraDataFlag, 126 utils.MinerRecommitIntervalFlag, 127 utils.MinerNoVerfiyFlag, 128 utils.NATFlag, 129 utils.NoDiscoverFlag, 130 utils.DiscoveryV5Flag, 131 utils.NetrestrictFlag, 132 utils.NodeKeyFileFlag, 133 utils.NodeKeyHexFlag, 134 utils.DNSDiscoveryFlag, 135 utils.MainnetFlag, 136 utils.DeveloperFlag, 137 utils.DeveloperPeriodFlag, 138 utils.RopstenFlag, 139 utils.RinkebyFlag, 140 utils.GoerliFlag, 141 utils.CalaverasFlag, 142 utils.VMEnableDebugFlag, 143 utils.NetworkIdFlag, 144 utils.EthStatsURLFlag, 145 utils.FakePoWFlag, 146 utils.NoCompactionFlag, 147 utils.GpoBlocksFlag, 148 utils.GpoPercentileFlag, 149 utils.GpoMaxGasPriceFlag, 150 utils.GpoIgnoreGasPriceFlag, 151 utils.MinerNotifyFullFlag, 152 configFileFlag, 153 utils.CatalystFlag, 154 } 155 156 rpcFlags = []cli.Flag{ 157 utils.HTTPEnabledFlag, 158 utils.HTTPListenAddrFlag, 159 utils.HTTPPortFlag, 160 utils.HTTPCORSDomainFlag, 161 utils.HTTPVirtualHostsFlag, 162 utils.LegacyRPCEnabledFlag, 163 utils.LegacyRPCListenAddrFlag, 164 utils.LegacyRPCPortFlag, 165 utils.LegacyRPCCORSDomainFlag, 166 utils.LegacyRPCVirtualHostsFlag, 167 utils.LegacyRPCApiFlag, 168 utils.GraphQLEnabledFlag, 169 utils.GraphQLCORSDomainFlag, 170 utils.GraphQLVirtualHostsFlag, 171 utils.HTTPApiFlag, 172 utils.HTTPPathPrefixFlag, 173 utils.WSEnabledFlag, 174 utils.WSListenAddrFlag, 175 utils.WSPortFlag, 176 utils.WSApiFlag, 177 utils.WSAllowedOriginsFlag, 178 utils.WSPathPrefixFlag, 179 utils.IPCDisabledFlag, 180 utils.IPCPathFlag, 181 utils.InsecureUnlockAllowedFlag, 182 utils.RPCGlobalGasCapFlag, 183 utils.RPCGlobalTxFeeCapFlag, 184 utils.AllowUnprotectedTxs, 185 } 186 187 metricsFlags = []cli.Flag{ 188 utils.MetricsEnabledFlag, 189 utils.MetricsEnabledExpensiveFlag, 190 utils.MetricsHTTPFlag, 191 utils.MetricsPortFlag, 192 utils.MetricsEnableInfluxDBFlag, 193 utils.MetricsInfluxDBEndpointFlag, 194 utils.MetricsInfluxDBDatabaseFlag, 195 utils.MetricsInfluxDBUsernameFlag, 196 utils.MetricsInfluxDBPasswordFlag, 197 utils.MetricsInfluxDBTagsFlag, 198 } 199 ) 200 201 func init() { 202 // Initialize the CLI app and start Geth 203 app.Action = geth 204 app.HideVersion = true // we have a command to print the version 205 app.Copyright = "Copyright 2013-2021 The go-ethereum Authors" 206 app.Commands = []cli.Command{ 207 // See chaincmd.go: 208 initCommand, 209 importCommand, 210 exportCommand, 211 importPreimagesCommand, 212 exportPreimagesCommand, 213 removedbCommand, 214 dumpCommand, 215 dumpGenesisCommand, 216 // See accountcmd.go: 217 accountCommand, 218 walletCommand, 219 // See consolecmd.go: 220 consoleCommand, 221 attachCommand, 222 javascriptCommand, 223 // See misccmd.go: 224 makecacheCommand, 225 makedagCommand, 226 versionCommand, 227 versionCheckCommand, 228 licenseCommand, 229 // See config.go 230 dumpConfigCommand, 231 // see dbcmd.go 232 dbCommand, 233 // See cmd/utils/flags_legacy.go 234 utils.ShowDeprecated, 235 // See snapshot.go 236 snapshotCommand, 237 } 238 sort.Sort(cli.CommandsByName(app.Commands)) 239 240 app.Flags = append(app.Flags, nodeFlags...) 241 app.Flags = append(app.Flags, rpcFlags...) 242 app.Flags = append(app.Flags, consoleFlags...) 243 app.Flags = append(app.Flags, debug.Flags...) 244 app.Flags = append(app.Flags, metricsFlags...) 245 246 app.Before = func(ctx *cli.Context) error { 247 return debug.Setup(ctx) 248 } 249 app.After = func(ctx *cli.Context) error { 250 debug.Exit() 251 prompt.Stdin.Close() // Resets terminal mode. 252 return nil 253 } 254 } 255 256 func main() { 257 if err := app.Run(os.Args); err != nil { 258 fmt.Fprintln(os.Stderr, err) 259 os.Exit(1) 260 } 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 271 case ctx.GlobalIsSet(utils.RinkebyFlag.Name): 272 log.Info("Starting Geth on Rinkeby testnet...") 273 274 case ctx.GlobalIsSet(utils.GoerliFlag.Name): 275 log.Info("Starting Geth on Görli testnet...") 276 277 case ctx.GlobalIsSet(utils.CalaverasFlag.Name): 278 log.Info("Starting Geth on Calaveras testnet...") 279 280 case ctx.GlobalIsSet(utils.DeveloperFlag.Name): 281 log.Info("Starting Geth in ephemeral dev mode...") 282 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 301 // Start metrics export if enabled 302 utils.SetupMetrics(ctx) 303 304 // Start system runtime metrics collection 305 go metrics.CollectProcessMetrics(3 * time.Second) 306 } 307 308 // geth is the main entry point into the system if no special subcommand is ran. 309 // It creates a default node based on the command line arguments and runs it in 310 // blocking mode, waiting for it to be shut down. 311 func geth(ctx *cli.Context) error { 312 if args := ctx.Args(); len(args) > 0 { 313 return fmt.Errorf("invalid command: %q", args[0]) 314 } 315 316 prepare(ctx) 317 stack, backend := makeFullNode(ctx) 318 defer stack.Close() 319 320 startNode(ctx, stack, backend) 321 stack.Wait() 322 return nil 323 } 324 325 // startNode boots up the system node and all registered protocols, after which 326 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 327 // miner. 328 func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend) { 329 debug.Memsize.Add("node", stack) 330 331 // Start up the node itself 332 utils.StartNode(ctx, stack) 333 334 // Unlock any account specifically requested 335 unlockAccounts(ctx, stack) 336 337 // Register wallet event handlers to open and auto-derive wallets 338 events := make(chan accounts.WalletEvent, 16) 339 stack.AccountManager().Subscribe(events) 340 341 // Create a client to interact with local geth node. 342 rpcClient, err := stack.Attach() 343 if err != nil { 344 utils.Fatalf("Failed to attach to self: %v", err) 345 } 346 ethClient := ethclient.NewClient(rpcClient) 347 348 go func() { 349 // Open any wallets already attached 350 for _, wallet := range stack.AccountManager().Wallets() { 351 if err := wallet.Open(""); err != nil { 352 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 353 } 354 } 355 // Listen for wallet event till termination 356 for event := range events { 357 switch event.Kind { 358 case accounts.WalletArrived: 359 if err := event.Wallet.Open(""); err != nil { 360 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 361 } 362 case accounts.WalletOpened: 363 status, _ := event.Wallet.Status() 364 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 365 366 var derivationPaths []accounts.DerivationPath 367 if event.Wallet.URL().Scheme == "ledger" { 368 derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath) 369 } 370 derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath) 371 372 event.Wallet.SelfDerive(derivationPaths, ethClient) 373 374 case accounts.WalletDropped: 375 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 376 event.Wallet.Close() 377 } 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.GlobalBool(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 405 // Start auxiliary services if enabled 406 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 407 // Mining only makes sense if a full Ethereum node is running 408 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 409 utils.Fatalf("Light clients do not support mining") 410 } 411 ethBackend, ok := backend.(*eth.EthAPIBackend) 412 if !ok { 413 utils.Fatalf("Ethereum service not running: %v", err) 414 } 415 // Set the gas price to the limits from the CLI and start mining 416 gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 417 ethBackend.TxPool().SetGasPrice(gasprice) 418 // start mining 419 threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name) 420 if err := ethBackend.StartMining(threads); err != nil { 421 utils.Fatalf("Failed to start mining: %v", err) 422 } 423 } 424 } 425 426 // unlockAccounts unlocks any account specifically requested. 427 func unlockAccounts(ctx *cli.Context, stack *node.Node) { 428 var unlocks []string 429 inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 430 for _, input := range inputs { 431 if trimmed := strings.TrimSpace(input); trimmed != "" { 432 unlocks = append(unlocks, trimmed) 433 } 434 } 435 // Short circuit if there is no account to unlock. 436 if len(unlocks) == 0 { 437 return 438 } 439 // If insecure account unlocking is not allowed if node's APIs are exposed to external. 440 // Print warning log to user and skip unlocking. 441 if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() { 442 utils.Fatalf("Account unlock with HTTP access is forbidden!") 443 } 444 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 445 passwords := utils.MakePasswordList(ctx) 446 for i, account := range unlocks { 447 unlockAccount(ks, account, i, passwords) 448 } 449 }