github.com/phillinzzz/newBsc@v1.1.6/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 "github.com/phillinzzz/newBsc/accounts" 29 "github.com/phillinzzz/newBsc/accounts/keystore" 30 "github.com/phillinzzz/newBsc/cmd/utils" 31 "github.com/phillinzzz/newBsc/common" 32 "github.com/phillinzzz/newBsc/console/prompt" 33 "github.com/phillinzzz/newBsc/eth" 34 "github.com/phillinzzz/newBsc/eth/downloader" 35 "github.com/phillinzzz/newBsc/ethclient" 36 "github.com/phillinzzz/newBsc/internal/debug" 37 "github.com/phillinzzz/newBsc/internal/ethapi" 38 "github.com/phillinzzz/newBsc/internal/flags" 39 "github.com/phillinzzz/newBsc/log" 40 "github.com/phillinzzz/newBsc/metrics" 41 "github.com/phillinzzz/newBsc/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.DirectBroadcastFlag, 68 utils.DisableSnapProtocolFlag, 69 utils.DiffSyncFlag, 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.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 } 163 164 rpcFlags = []cli.Flag{ 165 utils.HTTPEnabledFlag, 166 utils.HTTPListenAddrFlag, 167 utils.HTTPPortFlag, 168 utils.HTTPCORSDomainFlag, 169 utils.HTTPVirtualHostsFlag, 170 utils.LegacyRPCEnabledFlag, 171 utils.LegacyRPCListenAddrFlag, 172 utils.LegacyRPCPortFlag, 173 utils.LegacyRPCCORSDomainFlag, 174 utils.LegacyRPCVirtualHostsFlag, 175 utils.LegacyRPCApiFlag, 176 utils.GraphQLEnabledFlag, 177 utils.GraphQLCORSDomainFlag, 178 utils.GraphQLVirtualHostsFlag, 179 utils.HTTPApiFlag, 180 utils.HTTPPathPrefixFlag, 181 utils.WSEnabledFlag, 182 utils.WSListenAddrFlag, 183 utils.WSPortFlag, 184 utils.WSApiFlag, 185 utils.WSAllowedOriginsFlag, 186 utils.WSPathPrefixFlag, 187 utils.IPCDisabledFlag, 188 utils.IPCPathFlag, 189 utils.InsecureUnlockAllowedFlag, 190 utils.RPCGlobalGasCapFlag, 191 utils.RPCGlobalTxFeeCapFlag, 192 utils.AllowUnprotectedTxs, 193 } 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 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-2020 The go-ethereum Authors and BSC 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 249 app.Flags = append(app.Flags, nodeFlags...) 250 app.Flags = append(app.Flags, rpcFlags...) 251 app.Flags = append(app.Flags, consoleFlags...) 252 app.Flags = append(app.Flags, debug.Flags...) 253 app.Flags = append(app.Flags, metricsFlags...) 254 255 app.Before = func(ctx *cli.Context) error { 256 return debug.Setup(ctx) 257 } 258 app.After = func(ctx *cli.Context) error { 259 debug.Exit() 260 prompt.Stdin.Close() // Resets terminal mode. 261 return nil 262 } 263 } 264 265 func main() { 266 if err := app.Run(os.Args); err != nil { 267 fmt.Fprintln(os.Stderr, err) 268 os.Exit(1) 269 } 270 } 271 272 // prepare manipulates memory cache allowance and setups metric system. 273 // This function should be called before launching devp2p stack. 274 func prepare(ctx *cli.Context) { 275 // If we're running a known preset, log it for convenience. 276 switch { 277 case ctx.GlobalIsSet(utils.RopstenFlag.Name): 278 log.Info("Starting Geth on Ropsten testnet...") 279 280 case ctx.GlobalIsSet(utils.RinkebyFlag.Name): 281 log.Info("Starting Geth on Rinkeby testnet...") 282 283 case ctx.GlobalIsSet(utils.GoerliFlag.Name): 284 log.Info("Starting Geth on Görli testnet...") 285 286 case ctx.GlobalIsSet(utils.YoloV3Flag.Name): 287 log.Info("Starting Geth on YOLOv3 testnet...") 288 289 case ctx.GlobalIsSet(utils.DeveloperFlag.Name): 290 log.Info("Starting Geth in ephemeral dev mode...") 291 292 case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name): 293 log.Info("Starting Geth on Ethereum mainnet...") 294 } 295 // If we're a full node on mainnet without --cache specified, bump default cache allowance 296 if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) { 297 // Make sure we're not on any supported preconfigured testnet either 298 if !ctx.GlobalIsSet(utils.RopstenFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) { 299 // Nope, we're really on mainnet. Bump that cache up! 300 log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096) 301 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096)) 302 } 303 } 304 // If we're running a light client on any network, drop the cache to some meaningfully low amount 305 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) { 306 log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128) 307 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128)) 308 } 309 310 // Start metrics export if enabled 311 utils.SetupMetrics(ctx) 312 313 // Start system runtime metrics collection 314 go metrics.CollectProcessMetrics(3 * time.Second) 315 } 316 317 // geth is the main entry point into the system if no special subcommand is ran. 318 // It creates a default node based on the command line arguments and runs it in 319 // blocking mode, waiting for it to be shut down. 320 func geth(ctx *cli.Context) error { 321 if args := ctx.Args(); len(args) > 0 { 322 return fmt.Errorf("invalid command: %q", args[0]) 323 } 324 325 prepare(ctx) 326 stack, backend := makeFullNode(ctx) 327 defer stack.Close() 328 329 startNode(ctx, stack, backend) 330 stack.Wait() 331 return nil 332 } 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) { 338 debug.Memsize.Add("node", stack) 339 340 // Start up the node itself 341 utils.StartNode(ctx, stack) 342 343 // Unlock any account specifically requested 344 unlockAccounts(ctx, stack) 345 346 // Register wallet event handlers to open and auto-derive wallets 347 events := make(chan accounts.WalletEvent, 16) 348 stack.AccountManager().Subscribe(events) 349 350 // Create a client to interact with local geth node. 351 rpcClient, err := stack.Attach() 352 if err != nil { 353 utils.Fatalf("Failed to attach to self: %v", err) 354 } 355 ethClient := ethclient.NewClient(rpcClient) 356 357 go func() { 358 // Open any wallets already attached 359 for _, wallet := range stack.AccountManager().Wallets() { 360 if err := wallet.Open(""); err != nil { 361 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 362 } 363 } 364 // Listen for wallet event till termination 365 for event := range events { 366 switch event.Kind { 367 case accounts.WalletArrived: 368 if err := event.Wallet.Open(""); err != nil { 369 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 370 } 371 case accounts.WalletOpened: 372 status, _ := event.Wallet.Status() 373 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 374 375 var derivationPaths []accounts.DerivationPath 376 if event.Wallet.URL().Scheme == "ledger" { 377 derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath) 378 } 379 derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath) 380 381 event.Wallet.SelfDerive(derivationPaths, ethClient) 382 383 case accounts.WalletDropped: 384 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 385 event.Wallet.Close() 386 } 387 } 388 }() 389 390 // Spawn a standalone goroutine for status synchronization monitoring, 391 // close the node when synchronization is complete if user required. 392 if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) { 393 go func() { 394 sub := stack.EventMux().Subscribe(downloader.DoneEvent{}) 395 defer sub.Unsubscribe() 396 for { 397 event := <-sub.Chan() 398 if event == nil { 399 continue 400 } 401 done, ok := event.Data.(downloader.DoneEvent) 402 if !ok { 403 continue 404 } 405 if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute { 406 log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(), 407 "age", common.PrettyAge(timestamp)) 408 stack.Close() 409 } 410 } 411 }() 412 } 413 414 // Start auxiliary services if enabled 415 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 416 // Mining only makes sense if a full Ethereum node is running 417 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 418 utils.Fatalf("Light clients do not support mining") 419 } 420 ethBackend, ok := backend.(*eth.EthAPIBackend) 421 if !ok { 422 utils.Fatalf("Ethereum service not running: %v", err) 423 } 424 // Set the gas price to the limits from the CLI and start mining 425 gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 426 ethBackend.TxPool().SetGasPrice(gasprice) 427 // start mining 428 threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name) 429 if err := ethBackend.StartMining(threads); err != nil { 430 utils.Fatalf("Failed to start mining: %v", err) 431 } 432 } 433 } 434 435 // unlockAccounts unlocks any account specifically requested. 436 func unlockAccounts(ctx *cli.Context, stack *node.Node) { 437 var unlocks []string 438 inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 439 for _, input := range inputs { 440 if trimmed := strings.TrimSpace(input); trimmed != "" { 441 unlocks = append(unlocks, trimmed) 442 } 443 } 444 // Short circuit if there is no account to unlock. 445 if len(unlocks) == 0 { 446 return 447 } 448 // If insecure account unlocking is not allowed if node's APIs are exposed to external. 449 // Print warning log to user and skip unlocking. 450 if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() { 451 utils.Fatalf("Account unlock with HTTP access is forbidden!") 452 } 453 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 454 passwords := utils.MakePasswordList(ctx) 455 for i, account := range unlocks { 456 unlockAccount(ks, account, i, passwords) 457 } 458 }