github.com/divan/go-ethereum@v1.8.14-0.20180820134928-1de9ada4016d/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 "runtime" 25 godebug "runtime/debug" 26 "sort" 27 "strconv" 28 "strings" 29 "time" 30 31 "github.com/elastic/gosigar" 32 "github.com/ethereum/go-ethereum/accounts" 33 "github.com/ethereum/go-ethereum/accounts/keystore" 34 "github.com/ethereum/go-ethereum/cmd/utils" 35 "github.com/ethereum/go-ethereum/console" 36 "github.com/ethereum/go-ethereum/eth" 37 "github.com/ethereum/go-ethereum/ethclient" 38 "github.com/ethereum/go-ethereum/internal/debug" 39 "github.com/ethereum/go-ethereum/log" 40 "github.com/ethereum/go-ethereum/metrics" 41 "github.com/ethereum/go-ethereum/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 // The app that holds all commands and flags. 53 app = utils.NewApp(gitCommit, "the go-ethereum command line interface") 54 // flags that configure the node 55 nodeFlags = []cli.Flag{ 56 utils.IdentityFlag, 57 utils.UnlockedAccountFlag, 58 utils.PasswordFileFlag, 59 utils.BootnodesFlag, 60 utils.BootnodesV4Flag, 61 utils.BootnodesV5Flag, 62 utils.DataDirFlag, 63 utils.KeyStoreDirFlag, 64 utils.NoUSBFlag, 65 utils.DashboardEnabledFlag, 66 utils.DashboardAddrFlag, 67 utils.DashboardPortFlag, 68 utils.DashboardRefreshFlag, 69 utils.EthashCacheDirFlag, 70 utils.EthashCachesInMemoryFlag, 71 utils.EthashCachesOnDiskFlag, 72 utils.EthashDatasetDirFlag, 73 utils.EthashDatasetsInMemoryFlag, 74 utils.EthashDatasetsOnDiskFlag, 75 utils.TxPoolNoLocalsFlag, 76 utils.TxPoolJournalFlag, 77 utils.TxPoolRejournalFlag, 78 utils.TxPoolPriceLimitFlag, 79 utils.TxPoolPriceBumpFlag, 80 utils.TxPoolAccountSlotsFlag, 81 utils.TxPoolGlobalSlotsFlag, 82 utils.TxPoolAccountQueueFlag, 83 utils.TxPoolGlobalQueueFlag, 84 utils.TxPoolLifetimeFlag, 85 utils.SyncModeFlag, 86 utils.GCModeFlag, 87 utils.LightServFlag, 88 utils.LightPeersFlag, 89 utils.LightKDFFlag, 90 utils.CacheFlag, 91 utils.CacheDatabaseFlag, 92 utils.CacheGCFlag, 93 utils.TrieCacheGenFlag, 94 utils.ListenPortFlag, 95 utils.MaxPeersFlag, 96 utils.MaxPendingPeersFlag, 97 utils.MiningEnabledFlag, 98 utils.MinerThreadsFlag, 99 utils.MinerLegacyThreadsFlag, 100 utils.MinerNotifyFlag, 101 utils.MinerGasTargetFlag, 102 utils.MinerLegacyGasTargetFlag, 103 utils.MinerGasPriceFlag, 104 utils.MinerLegacyGasPriceFlag, 105 utils.MinerEtherbaseFlag, 106 utils.MinerLegacyEtherbaseFlag, 107 utils.MinerExtraDataFlag, 108 utils.MinerLegacyExtraDataFlag, 109 utils.NATFlag, 110 utils.NoDiscoverFlag, 111 utils.DiscoveryV5Flag, 112 utils.NetrestrictFlag, 113 utils.NodeKeyFileFlag, 114 utils.NodeKeyHexFlag, 115 utils.DeveloperFlag, 116 utils.DeveloperPeriodFlag, 117 utils.TestnetFlag, 118 utils.RinkebyFlag, 119 utils.VMEnableDebugFlag, 120 utils.NetworkIdFlag, 121 utils.RPCCORSDomainFlag, 122 utils.RPCVirtualHostsFlag, 123 utils.EthStatsURLFlag, 124 utils.MetricsEnabledFlag, 125 utils.FakePoWFlag, 126 utils.NoCompactionFlag, 127 utils.GpoBlocksFlag, 128 utils.GpoPercentileFlag, 129 configFileFlag, 130 } 131 132 rpcFlags = []cli.Flag{ 133 utils.RPCEnabledFlag, 134 utils.RPCListenAddrFlag, 135 utils.RPCPortFlag, 136 utils.RPCApiFlag, 137 utils.WSEnabledFlag, 138 utils.WSListenAddrFlag, 139 utils.WSPortFlag, 140 utils.WSApiFlag, 141 utils.WSAllowedOriginsFlag, 142 utils.IPCDisabledFlag, 143 utils.IPCPathFlag, 144 } 145 146 whisperFlags = []cli.Flag{ 147 utils.WhisperEnabledFlag, 148 utils.WhisperMaxMessageSizeFlag, 149 utils.WhisperMinPOWFlag, 150 } 151 152 metricsFlags = []cli.Flag{ 153 utils.MetricsEnableInfluxDBFlag, 154 utils.MetricsInfluxDBEndpointFlag, 155 utils.MetricsInfluxDBDatabaseFlag, 156 utils.MetricsInfluxDBUsernameFlag, 157 utils.MetricsInfluxDBPasswordFlag, 158 utils.MetricsInfluxDBHostTagFlag, 159 } 160 ) 161 162 func init() { 163 // Initialize the CLI app and start Geth 164 app.Action = geth 165 app.HideVersion = true // we have a command to print the version 166 app.Copyright = "Copyright 2013-2018 The go-ethereum Authors" 167 app.Commands = []cli.Command{ 168 // See chaincmd.go: 169 initCommand, 170 importCommand, 171 exportCommand, 172 importPreimagesCommand, 173 exportPreimagesCommand, 174 copydbCommand, 175 removedbCommand, 176 dumpCommand, 177 // See monitorcmd.go: 178 monitorCommand, 179 // See accountcmd.go: 180 accountCommand, 181 walletCommand, 182 // See consolecmd.go: 183 consoleCommand, 184 attachCommand, 185 javascriptCommand, 186 // See misccmd.go: 187 makecacheCommand, 188 makedagCommand, 189 versionCommand, 190 bugCommand, 191 licenseCommand, 192 // See config.go 193 dumpConfigCommand, 194 } 195 sort.Sort(cli.CommandsByName(app.Commands)) 196 197 app.Flags = append(app.Flags, nodeFlags...) 198 app.Flags = append(app.Flags, rpcFlags...) 199 app.Flags = append(app.Flags, consoleFlags...) 200 app.Flags = append(app.Flags, debug.Flags...) 201 app.Flags = append(app.Flags, whisperFlags...) 202 app.Flags = append(app.Flags, metricsFlags...) 203 204 app.Before = func(ctx *cli.Context) error { 205 runtime.GOMAXPROCS(runtime.NumCPU()) 206 207 logdir := "" 208 if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) { 209 logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs") 210 } 211 if err := debug.Setup(ctx, logdir); err != nil { 212 return err 213 } 214 // Cap the cache allowance and tune the garbage collector 215 var mem gosigar.Mem 216 if err := mem.Get(); err == nil { 217 allowance := int(mem.Total / 1024 / 1024 / 3) 218 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 219 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 220 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 221 } 222 } 223 // Ensure Go's GC ignores the database cache for trigger percentage 224 cache := ctx.GlobalInt(utils.CacheFlag.Name) 225 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 226 227 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 228 godebug.SetGCPercent(int(gogc)) 229 230 // Start metrics export if enabled 231 utils.SetupMetrics(ctx) 232 233 // Start system runtime metrics collection 234 go metrics.CollectProcessMetrics(3 * time.Second) 235 236 utils.SetupNetwork(ctx) 237 return nil 238 } 239 240 app.After = func(ctx *cli.Context) error { 241 debug.Exit() 242 console.Stdin.Close() // Resets terminal mode. 243 return nil 244 } 245 } 246 247 func main() { 248 if err := app.Run(os.Args); err != nil { 249 fmt.Fprintln(os.Stderr, err) 250 os.Exit(1) 251 } 252 } 253 254 // geth is the main entry point into the system if no special subcommand is ran. 255 // It creates a default node based on the command line arguments and runs it in 256 // blocking mode, waiting for it to be shut down. 257 func geth(ctx *cli.Context) error { 258 if args := ctx.Args(); len(args) > 0 { 259 return fmt.Errorf("invalid command: %q", args[0]) 260 } 261 node := makeFullNode(ctx) 262 startNode(ctx, node) 263 node.Wait() 264 return nil 265 } 266 267 // startNode boots up the system node and all registered protocols, after which 268 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 269 // miner. 270 func startNode(ctx *cli.Context, stack *node.Node) { 271 debug.Memsize.Add("node", stack) 272 273 // Start up the node itself 274 utils.StartNode(stack) 275 276 // Unlock any account specifically requested 277 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 278 279 passwords := utils.MakePasswordList(ctx) 280 unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 281 for i, account := range unlocks { 282 if trimmed := strings.TrimSpace(account); trimmed != "" { 283 unlockAccount(ctx, ks, trimmed, i, passwords) 284 } 285 } 286 // Register wallet event handlers to open and auto-derive wallets 287 events := make(chan accounts.WalletEvent, 16) 288 stack.AccountManager().Subscribe(events) 289 290 go func() { 291 // Create a chain state reader for self-derivation 292 rpcClient, err := stack.Attach() 293 if err != nil { 294 utils.Fatalf("Failed to attach to self: %v", err) 295 } 296 stateReader := ethclient.NewClient(rpcClient) 297 298 // Open any wallets already attached 299 for _, wallet := range stack.AccountManager().Wallets() { 300 if err := wallet.Open(""); err != nil { 301 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 302 } 303 } 304 // Listen for wallet event till termination 305 for event := range events { 306 switch event.Kind { 307 case accounts.WalletArrived: 308 if err := event.Wallet.Open(""); err != nil { 309 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 310 } 311 case accounts.WalletOpened: 312 status, _ := event.Wallet.Status() 313 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 314 315 derivationPath := accounts.DefaultBaseDerivationPath 316 if event.Wallet.URL().Scheme == "ledger" { 317 derivationPath = accounts.DefaultLedgerBaseDerivationPath 318 } 319 event.Wallet.SelfDerive(derivationPath, stateReader) 320 321 case accounts.WalletDropped: 322 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 323 event.Wallet.Close() 324 } 325 } 326 }() 327 // Start auxiliary services if enabled 328 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 329 // Mining only makes sense if a full Ethereum node is running 330 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 331 utils.Fatalf("Light clients do not support mining") 332 } 333 var ethereum *eth.Ethereum 334 if err := stack.Service(ðereum); err != nil { 335 utils.Fatalf("Ethereum service not running: %v", err) 336 } 337 // Use a reduced number of threads if requested 338 threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name) 339 if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) { 340 threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name) 341 } 342 if threads > 0 { 343 type threaded interface { 344 SetThreads(threads int) 345 } 346 if th, ok := ethereum.Engine().(threaded); ok { 347 th.SetThreads(threads) 348 } 349 } 350 // Set the gas price to the limits from the CLI and start mining 351 gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name) 352 if ctx.IsSet(utils.MinerGasPriceFlag.Name) { 353 gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 354 } 355 ethereum.TxPool().SetGasPrice(gasprice) 356 if err := ethereum.StartMining(true); err != nil { 357 utils.Fatalf("Failed to start mining: %v", err) 358 } 359 } 360 }