github.com/gilgames000/kcc-geth@v1.0.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 "math" 23 "os" 24 godebug "runtime/debug" 25 "sort" 26 "strconv" 27 "strings" 28 "time" 29 30 "github.com/ethereum/go-ethereum/accounts" 31 "github.com/ethereum/go-ethereum/accounts/keystore" 32 "github.com/ethereum/go-ethereum/cmd/utils" 33 "github.com/ethereum/go-ethereum/common" 34 "github.com/ethereum/go-ethereum/console/prompt" 35 "github.com/ethereum/go-ethereum/eth" 36 "github.com/ethereum/go-ethereum/eth/downloader" 37 "github.com/ethereum/go-ethereum/ethclient" 38 "github.com/ethereum/go-ethereum/internal/debug" 39 "github.com/ethereum/go-ethereum/internal/ethapi" 40 "github.com/ethereum/go-ethereum/internal/flags" 41 "github.com/ethereum/go-ethereum/log" 42 "github.com/ethereum/go-ethereum/metrics" 43 "github.com/ethereum/go-ethereum/node" 44 gopsutil "github.com/shirou/gopsutil/mem" 45 "gopkg.in/urfave/cli.v1" 46 ) 47 48 const ( 49 clientIdentifier = "geth" // Client identifier to advertise over the network 50 ) 51 52 var ( 53 // Git SHA1 commit hash of the release (set via linker flags) 54 gitCommit = "" 55 gitDate = "" 56 // The app that holds all commands and flags. 57 app = flags.NewApp(gitCommit, gitDate, "the go-ethereum command line interface") 58 // flags that configure the node 59 nodeFlags = []cli.Flag{ 60 utils.IdentityFlag, 61 utils.UnlockedAccountFlag, 62 utils.PasswordFileFlag, 63 utils.BootnodesFlag, 64 utils.DataDirFlag, 65 utils.AncientFlag, 66 utils.MinFreeDiskSpaceFlag, 67 utils.KeyStoreDirFlag, 68 utils.ExternalSignerFlag, 69 utils.NoUSBFlag, 70 utils.USBFlag, 71 utils.SmartCardDaemonPathFlag, 72 utils.OverrideBerlinFlag, 73 utils.EthashCacheDirFlag, 74 utils.EthashCachesInMemoryFlag, 75 utils.EthashCachesOnDiskFlag, 76 utils.EthashCachesLockMmapFlag, 77 utils.EthashDatasetDirFlag, 78 utils.EthashDatasetsInMemoryFlag, 79 utils.EthashDatasetsOnDiskFlag, 80 utils.EthashDatasetsLockMmapFlag, 81 utils.TxPoolLocalsFlag, 82 utils.TxPoolNoLocalsFlag, 83 utils.TxPoolJournalFlag, 84 utils.TxPoolRejournalFlag, 85 utils.TxPoolPriceLimitFlag, 86 utils.TxPoolPriceBumpFlag, 87 utils.TxPoolAccountSlotsFlag, 88 utils.TxPoolGlobalSlotsFlag, 89 utils.TxPoolAccountQueueFlag, 90 utils.TxPoolGlobalQueueFlag, 91 utils.TxPoolLifetimeFlag, 92 utils.SyncModeFlag, 93 utils.ExitWhenSyncedFlag, 94 utils.GCModeFlag, 95 utils.SnapshotFlag, 96 utils.TxLookupLimitFlag, 97 utils.LightServeFlag, 98 utils.LightIngressFlag, 99 utils.LightEgressFlag, 100 utils.LightMaxPeersFlag, 101 utils.LightNoPruneFlag, 102 utils.LightKDFFlag, 103 utils.UltraLightServersFlag, 104 utils.UltraLightFractionFlag, 105 utils.UltraLightOnlyAnnounceFlag, 106 utils.LightNoSyncServeFlag, 107 utils.WhitelistFlag, 108 utils.BloomFilterSizeFlag, 109 utils.CacheFlag, 110 utils.CacheDatabaseFlag, 111 utils.CacheTrieFlag, 112 utils.CacheTrieJournalFlag, 113 utils.CacheTrieRejournalFlag, 114 utils.CacheGCFlag, 115 utils.CacheSnapshotFlag, 116 utils.CacheNoPrefetchFlag, 117 utils.CachePreimagesFlag, 118 utils.ListenPortFlag, 119 utils.MaxPeersFlag, 120 utils.MaxPendingPeersFlag, 121 utils.MiningEnabledFlag, 122 utils.MinerThreadsFlag, 123 utils.MinerNotifyFlag, 124 utils.MinerGasTargetFlag, 125 utils.MinerGasLimitFlag, 126 utils.MinerGasPriceFlag, 127 utils.MinerEtherbaseFlag, 128 utils.MinerExtraDataFlag, 129 utils.MinerRecommitIntervalFlag, 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.TestnetFlag, 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.EWASMInterpreterFlag, 151 utils.EVMInterpreterFlag, 152 configFileFlag, 153 } 154 155 rpcFlags = []cli.Flag{ 156 utils.HTTPEnabledFlag, 157 utils.HTTPListenAddrFlag, 158 utils.HTTPPortFlag, 159 utils.HTTPCORSDomainFlag, 160 utils.HTTPVirtualHostsFlag, 161 utils.LegacyRPCEnabledFlag, 162 utils.LegacyRPCListenAddrFlag, 163 utils.LegacyRPCPortFlag, 164 utils.LegacyRPCCORSDomainFlag, 165 utils.LegacyRPCVirtualHostsFlag, 166 utils.LegacyRPCApiFlag, 167 utils.GraphQLEnabledFlag, 168 utils.GraphQLCORSDomainFlag, 169 utils.GraphQLVirtualHostsFlag, 170 utils.HTTPApiFlag, 171 utils.HTTPPathPrefixFlag, 172 utils.WSEnabledFlag, 173 utils.WSListenAddrFlag, 174 utils.WSPortFlag, 175 utils.WSApiFlag, 176 utils.WSAllowedOriginsFlag, 177 utils.WSPathPrefixFlag, 178 utils.IPCDisabledFlag, 179 utils.IPCPathFlag, 180 utils.InsecureUnlockAllowedFlag, 181 utils.RPCGlobalGasCapFlag, 182 utils.RPCGlobalTxFeeCapFlag, 183 utils.AllowUnprotectedTxs, 184 } 185 186 metricsFlags = []cli.Flag{ 187 utils.MetricsEnabledFlag, 188 utils.MetricsEnabledExpensiveFlag, 189 utils.MetricsHTTPFlag, 190 utils.MetricsPortFlag, 191 utils.MetricsEnableInfluxDBFlag, 192 utils.MetricsInfluxDBEndpointFlag, 193 utils.MetricsInfluxDBDatabaseFlag, 194 utils.MetricsInfluxDBUsernameFlag, 195 utils.MetricsInfluxDBPasswordFlag, 196 utils.MetricsInfluxDBTagsFlag, 197 } 198 ) 199 200 func init() { 201 // Initialize the CLI app and start Geth 202 app.Action = geth 203 app.HideVersion = true // we have a command to print the version 204 app.Copyright = "Copyright 2013-2021 The go-ethereum Authors" 205 app.Commands = []cli.Command{ 206 // See chaincmd.go: 207 initCommand, 208 importCommand, 209 exportCommand, 210 importPreimagesCommand, 211 exportPreimagesCommand, 212 copydbCommand, 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.TestnetFlag.Name): 269 log.Info("Starting Geth on testnet...") 270 271 case ctx.GlobalIsSet(utils.DeveloperFlag.Name): 272 log.Info("Starting Geth in ephemeral dev mode...") 273 274 case !ctx.GlobalIsSet(utils.NetworkIdFlag.Name): 275 log.Info("Starting Geth on Ethereum mainnet...") 276 } 277 // If we're a full node on mainnet without --cache specified, bump default cache allowance 278 if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) { 279 // Make sure we're not on any supported preconfigured testnet either 280 if !ctx.GlobalIsSet(utils.TestnetFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) { 281 // Nope, we're really on mainnet. Bump that cache up! 282 log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096) 283 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096)) 284 } 285 } 286 // If we're running a light client on any network, drop the cache to some meaningfully low amount 287 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) { 288 log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128) 289 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128)) 290 } 291 // Cap the cache allowance and tune the garbage collector 292 mem, err := gopsutil.VirtualMemory() 293 if err == nil { 294 if 32<<(^uintptr(0)>>63) == 32 && mem.Total > 2*1024*1024*1024 { 295 log.Warn("Lowering memory allowance on 32bit arch", "available", mem.Total/1024/1024, "addressable", 2*1024) 296 mem.Total = 2 * 1024 * 1024 * 1024 297 } 298 allowance := int(mem.Total / 1024 / 1024 / 3) 299 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 300 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 301 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 302 } 303 } 304 // Ensure Go's GC ignores the database cache for trigger percentage 305 cache := ctx.GlobalInt(utils.CacheFlag.Name) 306 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 307 308 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 309 godebug.SetGCPercent(int(gogc)) 310 311 // Start metrics export if enabled 312 utils.SetupMetrics(ctx) 313 314 // Start system runtime metrics collection 315 go metrics.CollectProcessMetrics(3 * time.Second) 316 } 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(); len(args) > 0 { 323 return fmt.Errorf("invalid command: %q", args[0]) 324 } 325 326 prepare(ctx) 327 stack, backend := makeFullNode(ctx) 328 defer stack.Close() 329 330 startNode(ctx, stack, backend) 331 stack.Wait() 332 return nil 333 } 334 335 // startNode boots up the system node and all registered protocols, after which 336 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 337 // miner. 338 func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend) { 339 debug.Memsize.Add("node", stack) 340 341 // Start up the node itself 342 utils.StartNode(ctx, stack) 343 344 // Unlock any account specifically requested 345 unlockAccounts(ctx, stack) 346 347 // Register wallet event handlers to open and auto-derive wallets 348 events := make(chan accounts.WalletEvent, 16) 349 stack.AccountManager().Subscribe(events) 350 351 // Create a client to interact with local geth node. 352 rpcClient, err := stack.Attach() 353 if err != nil { 354 utils.Fatalf("Failed to attach to self: %v", err) 355 } 356 ethClient := ethclient.NewClient(rpcClient) 357 358 go func() { 359 // Open any wallets already attached 360 for _, wallet := range stack.AccountManager().Wallets() { 361 if err := wallet.Open(""); err != nil { 362 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 363 } 364 } 365 // Listen for wallet event till termination 366 for event := range events { 367 switch event.Kind { 368 case accounts.WalletArrived: 369 if err := event.Wallet.Open(""); err != nil { 370 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 371 } 372 case accounts.WalletOpened: 373 status, _ := event.Wallet.Status() 374 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 375 376 var derivationPaths []accounts.DerivationPath 377 if event.Wallet.URL().Scheme == "ledger" { 378 derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath) 379 } 380 derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath) 381 382 event.Wallet.SelfDerive(derivationPaths, ethClient) 383 384 case accounts.WalletDropped: 385 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 386 event.Wallet.Close() 387 } 388 } 389 }() 390 391 // Spawn a standalone goroutine for status synchronization monitoring, 392 // close the node when synchronization is complete if user required. 393 if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) { 394 go func() { 395 sub := stack.EventMux().Subscribe(downloader.DoneEvent{}) 396 defer sub.Unsubscribe() 397 for { 398 event := <-sub.Chan() 399 if event == nil { 400 continue 401 } 402 done, ok := event.Data.(downloader.DoneEvent) 403 if !ok { 404 continue 405 } 406 if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute { 407 log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(), 408 "age", common.PrettyAge(timestamp)) 409 stack.Close() 410 } 411 } 412 }() 413 } 414 415 // Start auxiliary services if enabled 416 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 417 // Mining only makes sense if a full Ethereum node is running 418 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 419 utils.Fatalf("Light clients do not support mining") 420 } 421 ethBackend, ok := backend.(*eth.EthAPIBackend) 422 if !ok { 423 utils.Fatalf("Ethereum service not running: %v", err) 424 } 425 // Set the gas price to the limits from the CLI and start mining 426 gasprice := utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 427 ethBackend.TxPool().SetGasPrice(gasprice) 428 // start mining 429 threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name) 430 if err := ethBackend.StartMining(threads); err != nil { 431 utils.Fatalf("Failed to start mining: %v", err) 432 } 433 } 434 } 435 436 // unlockAccounts unlocks any account specifically requested. 437 func unlockAccounts(ctx *cli.Context, stack *node.Node) { 438 var unlocks []string 439 inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 440 for _, input := range inputs { 441 if trimmed := strings.TrimSpace(input); trimmed != "" { 442 unlocks = append(unlocks, trimmed) 443 } 444 } 445 // Short circuit if there is no account to unlock. 446 if len(unlocks) == 0 { 447 return 448 } 449 // If insecure account unlocking is not allowed if node's APIs are exposed to external. 450 // Print warning log to user and skip unlocking. 451 if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() { 452 utils.Fatalf("Account unlock with HTTP access is forbidden!") 453 } 454 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 455 passwords := utils.MakePasswordList(ctx) 456 for i, account := range unlocks { 457 unlockAccount(ks, account, i, passwords) 458 } 459 }