github.com/daeglee/go-ethereum@v0.0.0-20190504220456-cad3e8d18e9b/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/elastic/gosigar" 31 "github.com/ethereum/go-ethereum/accounts" 32 "github.com/ethereum/go-ethereum/accounts/keystore" 33 "github.com/ethereum/go-ethereum/cmd/utils" 34 "github.com/ethereum/go-ethereum/common" 35 "github.com/ethereum/go-ethereum/console" 36 "github.com/ethereum/go-ethereum/eth" 37 "github.com/ethereum/go-ethereum/eth/downloader" 38 "github.com/ethereum/go-ethereum/ethclient" 39 "github.com/ethereum/go-ethereum/internal/debug" 40 "github.com/ethereum/go-ethereum/log" 41 "github.com/ethereum/go-ethereum/metrics" 42 "github.com/ethereum/go-ethereum/node" 43 cli "gopkg.in/urfave/cli.v1" 44 ) 45 46 const ( 47 clientIdentifier = "geth" // Client identifier to advertise over the network 48 ) 49 50 var ( 51 // Git SHA1 commit hash of the release (set via linker flags) 52 gitCommit = "" 53 // The app that holds all commands and flags. 54 app = utils.NewApp(gitCommit, "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.BootnodesV4Flag, 62 utils.BootnodesV5Flag, 63 utils.DataDirFlag, 64 utils.KeyStoreDirFlag, 65 utils.ExternalSignerFlag, 66 utils.NoUSBFlag, 67 utils.DashboardEnabledFlag, 68 utils.DashboardAddrFlag, 69 utils.DashboardPortFlag, 70 utils.DashboardRefreshFlag, 71 utils.EthashCacheDirFlag, 72 utils.EthashCachesInMemoryFlag, 73 utils.EthashCachesOnDiskFlag, 74 utils.EthashDatasetDirFlag, 75 utils.EthashDatasetsInMemoryFlag, 76 utils.EthashDatasetsOnDiskFlag, 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.ULCModeConfigFlag, 89 utils.OnlyAnnounceModeFlag, 90 utils.ULCTrustedNodesFlag, 91 utils.ULCMinTrustedFractionFlag, 92 utils.SyncModeFlag, 93 utils.ExitWhenSyncedFlag, 94 utils.GCModeFlag, 95 utils.LightServFlag, 96 utils.LightBandwidthInFlag, 97 utils.LightBandwidthOutFlag, 98 utils.LightPeersFlag, 99 utils.LightKDFFlag, 100 utils.WhitelistFlag, 101 utils.CacheFlag, 102 utils.CacheDatabaseFlag, 103 utils.CacheTrieFlag, 104 utils.CacheGCFlag, 105 utils.ListenPortFlag, 106 utils.MaxPeersFlag, 107 utils.MaxPendingPeersFlag, 108 utils.MiningEnabledFlag, 109 utils.MinerThreadsFlag, 110 utils.MinerLegacyThreadsFlag, 111 utils.MinerNotifyFlag, 112 utils.MinerGasTargetFlag, 113 utils.MinerLegacyGasTargetFlag, 114 utils.MinerGasLimitFlag, 115 utils.MinerGasPriceFlag, 116 utils.MinerLegacyGasPriceFlag, 117 utils.MinerEtherbaseFlag, 118 utils.MinerLegacyEtherbaseFlag, 119 utils.MinerExtraDataFlag, 120 utils.MinerLegacyExtraDataFlag, 121 utils.MinerRecommitIntervalFlag, 122 utils.MinerNoVerfiyFlag, 123 utils.NATFlag, 124 utils.NoDiscoverFlag, 125 utils.DiscoveryV5Flag, 126 utils.NetrestrictFlag, 127 utils.NodeKeyFileFlag, 128 utils.NodeKeyHexFlag, 129 utils.DeveloperFlag, 130 utils.DeveloperPeriodFlag, 131 utils.TestnetFlag, 132 utils.RinkebyFlag, 133 utils.GoerliFlag, 134 utils.VMEnableDebugFlag, 135 utils.NetworkIdFlag, 136 utils.ConstantinopleOverrideFlag, 137 utils.RPCCORSDomainFlag, 138 utils.RPCVirtualHostsFlag, 139 utils.EthStatsURLFlag, 140 utils.FakePoWFlag, 141 utils.NoCompactionFlag, 142 utils.GpoBlocksFlag, 143 utils.GpoPercentileFlag, 144 utils.EWASMInterpreterFlag, 145 utils.EVMInterpreterFlag, 146 configFileFlag, 147 } 148 149 rpcFlags = []cli.Flag{ 150 utils.RPCEnabledFlag, 151 utils.RPCListenAddrFlag, 152 utils.RPCPortFlag, 153 utils.GraphQLEnabledFlag, 154 utils.GraphQLListenAddrFlag, 155 utils.GraphQLPortFlag, 156 utils.GraphQLCORSDomainFlag, 157 utils.GraphQLVirtualHostsFlag, 158 utils.RPCApiFlag, 159 utils.WSEnabledFlag, 160 utils.WSListenAddrFlag, 161 utils.WSPortFlag, 162 utils.WSApiFlag, 163 utils.WSAllowedOriginsFlag, 164 utils.IPCDisabledFlag, 165 utils.IPCPathFlag, 166 } 167 168 whisperFlags = []cli.Flag{ 169 utils.WhisperEnabledFlag, 170 utils.WhisperMaxMessageSizeFlag, 171 utils.WhisperMinPOWFlag, 172 utils.WhisperRestrictConnectionBetweenLightClientsFlag, 173 } 174 175 metricsFlags = []cli.Flag{ 176 utils.MetricsEnabledFlag, 177 utils.MetricsEnabledExpensiveFlag, 178 utils.MetricsEnableInfluxDBFlag, 179 utils.MetricsInfluxDBEndpointFlag, 180 utils.MetricsInfluxDBDatabaseFlag, 181 utils.MetricsInfluxDBUsernameFlag, 182 utils.MetricsInfluxDBPasswordFlag, 183 utils.MetricsInfluxDBTagsFlag, 184 } 185 ) 186 187 func init() { 188 // Initialize the CLI app and start Geth 189 app.Action = geth 190 app.HideVersion = true // we have a command to print the version 191 app.Copyright = "Copyright 2013-2019 The go-ethereum Authors" 192 app.Commands = []cli.Command{ 193 // See chaincmd.go: 194 initCommand, 195 importCommand, 196 exportCommand, 197 importPreimagesCommand, 198 exportPreimagesCommand, 199 copydbCommand, 200 removedbCommand, 201 dumpCommand, 202 // See monitorcmd.go: 203 monitorCommand, 204 // See accountcmd.go: 205 accountCommand, 206 walletCommand, 207 // See consolecmd.go: 208 consoleCommand, 209 attachCommand, 210 javascriptCommand, 211 // See misccmd.go: 212 makecacheCommand, 213 makedagCommand, 214 versionCommand, 215 bugCommand, 216 licenseCommand, 217 // See config.go 218 dumpConfigCommand, 219 } 220 sort.Sort(cli.CommandsByName(app.Commands)) 221 222 app.Flags = append(app.Flags, nodeFlags...) 223 app.Flags = append(app.Flags, rpcFlags...) 224 app.Flags = append(app.Flags, consoleFlags...) 225 app.Flags = append(app.Flags, debug.Flags...) 226 app.Flags = append(app.Flags, whisperFlags...) 227 app.Flags = append(app.Flags, metricsFlags...) 228 229 app.Before = func(ctx *cli.Context) error { 230 logdir := "" 231 if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) { 232 logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs") 233 } 234 if err := debug.Setup(ctx, logdir); err != nil { 235 return err 236 } 237 // Cap the cache allowance and tune the garbage collector 238 var mem gosigar.Mem 239 if err := mem.Get(); err == nil { 240 allowance := int(mem.Total / 1024 / 1024 / 3) 241 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 242 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 243 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 244 } 245 } 246 // Ensure Go's GC ignores the database cache for trigger percentage 247 cache := ctx.GlobalInt(utils.CacheFlag.Name) 248 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 249 250 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 251 godebug.SetGCPercent(int(gogc)) 252 253 // Start metrics export if enabled 254 utils.SetupMetrics(ctx) 255 256 // Start system runtime metrics collection 257 go metrics.CollectProcessMetrics(3 * time.Second) 258 259 return nil 260 } 261 262 app.After = func(ctx *cli.Context) error { 263 debug.Exit() 264 console.Stdin.Close() // Resets terminal mode. 265 return nil 266 } 267 } 268 269 func main() { 270 if err := app.Run(os.Args); err != nil { 271 fmt.Fprintln(os.Stderr, err) 272 os.Exit(1) 273 } 274 } 275 276 // geth is the main entry point into the system if no special subcommand is ran. 277 // It creates a default node based on the command line arguments and runs it in 278 // blocking mode, waiting for it to be shut down. 279 func geth(ctx *cli.Context) error { 280 if args := ctx.Args(); len(args) > 0 { 281 return fmt.Errorf("invalid command: %q", args[0]) 282 } 283 node := makeFullNode(ctx) 284 defer node.Close() 285 startNode(ctx, node) 286 node.Wait() 287 return nil 288 } 289 290 // startNode boots up the system node and all registered protocols, after which 291 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 292 // miner. 293 func startNode(ctx *cli.Context, stack *node.Node) { 294 debug.Memsize.Add("node", stack) 295 296 // Start up the node itself 297 utils.StartNode(stack) 298 299 // Unlock any account specifically requested 300 if keystores := stack.AccountManager().Backends(keystore.KeyStoreType); len(keystores) > 0 { 301 ks := keystores[0].(*keystore.KeyStore) 302 passwords := utils.MakePasswordList(ctx) 303 unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 304 for i, account := range unlocks { 305 if trimmed := strings.TrimSpace(account); trimmed != "" { 306 unlockAccount(ctx, ks, trimmed, i, passwords) 307 } 308 } 309 } 310 // Register wallet event handlers to open and auto-derive wallets 311 events := make(chan accounts.WalletEvent, 16) 312 stack.AccountManager().Subscribe(events) 313 314 go func() { 315 // Create a chain state reader for self-derivation 316 rpcClient, err := stack.Attach() 317 if err != nil { 318 utils.Fatalf("Failed to attach to self: %v", err) 319 } 320 stateReader := ethclient.NewClient(rpcClient) 321 322 // Open any wallets already attached 323 for _, wallet := range stack.AccountManager().Wallets() { 324 if err := wallet.Open(""); err != nil { 325 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 326 } 327 } 328 // Listen for wallet event till termination 329 for event := range events { 330 switch event.Kind { 331 case accounts.WalletArrived: 332 if err := event.Wallet.Open(""); err != nil { 333 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 334 } 335 case accounts.WalletOpened: 336 status, _ := event.Wallet.Status() 337 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 338 339 derivationPath := accounts.DefaultBaseDerivationPath 340 if event.Wallet.URL().Scheme == "ledger" { 341 derivationPath = accounts.DefaultLedgerBaseDerivationPath 342 } 343 event.Wallet.SelfDerive(derivationPath, stateReader) 344 345 case accounts.WalletDropped: 346 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 347 event.Wallet.Close() 348 } 349 } 350 }() 351 352 // Spawn a standalone goroutine for status synchronization monitoring, 353 // close the node when synchronization is complete if user required. 354 if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) { 355 go func() { 356 sub := stack.EventMux().Subscribe(downloader.DoneEvent{}) 357 defer sub.Unsubscribe() 358 for { 359 event := <-sub.Chan() 360 if event == nil { 361 continue 362 } 363 done, ok := event.Data.(downloader.DoneEvent) 364 if !ok { 365 continue 366 } 367 if timestamp := time.Unix(done.Latest.Time.Int64(), 0); time.Since(timestamp) < 10*time.Minute { 368 log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(), 369 "age", common.PrettyAge(timestamp)) 370 stack.Stop() 371 } 372 373 } 374 }() 375 } 376 377 // Start auxiliary services if enabled 378 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 379 // Mining only makes sense if a full Ethereum node is running 380 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 381 utils.Fatalf("Light clients do not support mining") 382 } 383 var ethereum *eth.Ethereum 384 if err := stack.Service(ðereum); err != nil { 385 utils.Fatalf("Ethereum service not running: %v", err) 386 } 387 // Set the gas price to the limits from the CLI and start mining 388 gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name) 389 if ctx.IsSet(utils.MinerGasPriceFlag.Name) { 390 gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 391 } 392 ethereum.TxPool().SetGasPrice(gasprice) 393 394 threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name) 395 if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) { 396 threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name) 397 } 398 if err := ethereum.StartMining(threads); err != nil { 399 utils.Fatalf("Failed to start mining: %v", err) 400 } 401 } 402 }