github.com/chapsuk/go-ethereum@v1.8.12-0.20180615081455-574378edb50c/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.FastSyncFlag, 86 utils.LightModeFlag, 87 utils.SyncModeFlag, 88 utils.GCModeFlag, 89 utils.LightServFlag, 90 utils.LightPeersFlag, 91 utils.LightKDFFlag, 92 utils.CacheFlag, 93 utils.CacheDatabaseFlag, 94 utils.CacheGCFlag, 95 utils.TrieCacheGenFlag, 96 utils.ListenPortFlag, 97 utils.MaxPeersFlag, 98 utils.MaxPendingPeersFlag, 99 utils.EtherbaseFlag, 100 utils.GasPriceFlag, 101 utils.MinerThreadsFlag, 102 utils.MiningEnabledFlag, 103 utils.TargetGasLimitFlag, 104 utils.NATFlag, 105 utils.NoDiscoverFlag, 106 utils.DiscoveryV5Flag, 107 utils.NetrestrictFlag, 108 utils.NodeKeyFileFlag, 109 utils.NodeKeyHexFlag, 110 utils.DeveloperFlag, 111 utils.DeveloperPeriodFlag, 112 utils.TestnetFlag, 113 utils.RinkebyFlag, 114 utils.VMEnableDebugFlag, 115 utils.NetworkIdFlag, 116 utils.RPCCORSDomainFlag, 117 utils.RPCVirtualHostsFlag, 118 utils.EthStatsURLFlag, 119 utils.MetricsEnabledFlag, 120 utils.FakePoWFlag, 121 utils.NoCompactionFlag, 122 utils.GpoBlocksFlag, 123 utils.GpoPercentileFlag, 124 utils.ExtraDataFlag, 125 configFileFlag, 126 } 127 128 rpcFlags = []cli.Flag{ 129 utils.RPCEnabledFlag, 130 utils.RPCListenAddrFlag, 131 utils.RPCPortFlag, 132 utils.RPCApiFlag, 133 utils.WSEnabledFlag, 134 utils.WSListenAddrFlag, 135 utils.WSPortFlag, 136 utils.WSApiFlag, 137 utils.WSAllowedOriginsFlag, 138 utils.IPCDisabledFlag, 139 utils.IPCPathFlag, 140 } 141 142 whisperFlags = []cli.Flag{ 143 utils.WhisperEnabledFlag, 144 utils.WhisperMaxMessageSizeFlag, 145 utils.WhisperMinPOWFlag, 146 } 147 ) 148 149 func init() { 150 // Initialize the CLI app and start Geth 151 app.Action = geth 152 app.HideVersion = true // we have a command to print the version 153 app.Copyright = "Copyright 2013-2018 The go-ethereum Authors" 154 app.Commands = []cli.Command{ 155 // See chaincmd.go: 156 initCommand, 157 importCommand, 158 exportCommand, 159 importPreimagesCommand, 160 exportPreimagesCommand, 161 copydbCommand, 162 removedbCommand, 163 dumpCommand, 164 // See monitorcmd.go: 165 monitorCommand, 166 // See accountcmd.go: 167 accountCommand, 168 walletCommand, 169 // See consolecmd.go: 170 consoleCommand, 171 attachCommand, 172 javascriptCommand, 173 // See misccmd.go: 174 makecacheCommand, 175 makedagCommand, 176 versionCommand, 177 bugCommand, 178 licenseCommand, 179 // See config.go 180 dumpConfigCommand, 181 } 182 sort.Sort(cli.CommandsByName(app.Commands)) 183 184 app.Flags = append(app.Flags, nodeFlags...) 185 app.Flags = append(app.Flags, rpcFlags...) 186 app.Flags = append(app.Flags, consoleFlags...) 187 app.Flags = append(app.Flags, debug.Flags...) 188 app.Flags = append(app.Flags, whisperFlags...) 189 190 app.Before = func(ctx *cli.Context) error { 191 runtime.GOMAXPROCS(runtime.NumCPU()) 192 if err := debug.Setup(ctx); err != nil { 193 return err 194 } 195 // Cap the cache allowance and tune the garbage colelctor 196 var mem gosigar.Mem 197 if err := mem.Get(); err == nil { 198 allowance := int(mem.Total / 1024 / 1024 / 3) 199 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 200 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 201 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 202 } 203 } 204 // Ensure Go's GC ignores the database cache for trigger percentage 205 cache := ctx.GlobalInt(utils.CacheFlag.Name) 206 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 207 208 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 209 godebug.SetGCPercent(int(gogc)) 210 211 // Start system runtime metrics collection 212 go metrics.CollectProcessMetrics(3 * time.Second) 213 214 utils.SetupNetwork(ctx) 215 return nil 216 } 217 218 app.After = func(ctx *cli.Context) error { 219 debug.Exit() 220 console.Stdin.Close() // Resets terminal mode. 221 return nil 222 } 223 } 224 225 func main() { 226 if err := app.Run(os.Args); err != nil { 227 fmt.Fprintln(os.Stderr, err) 228 os.Exit(1) 229 } 230 } 231 232 // geth is the main entry point into the system if no special subcommand is ran. 233 // It creates a default node based on the command line arguments and runs it in 234 // blocking mode, waiting for it to be shut down. 235 func geth(ctx *cli.Context) error { 236 node := makeFullNode(ctx) 237 startNode(ctx, node) 238 node.Wait() 239 return nil 240 } 241 242 // startNode boots up the system node and all registered protocols, after which 243 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 244 // miner. 245 func startNode(ctx *cli.Context, stack *node.Node) { 246 debug.Memsize.Add("node", stack) 247 248 // Start up the node itself 249 utils.StartNode(stack) 250 251 // Unlock any account specifically requested 252 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 253 254 passwords := utils.MakePasswordList(ctx) 255 unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 256 for i, account := range unlocks { 257 if trimmed := strings.TrimSpace(account); trimmed != "" { 258 unlockAccount(ctx, ks, trimmed, i, passwords) 259 } 260 } 261 // Register wallet event handlers to open and auto-derive wallets 262 events := make(chan accounts.WalletEvent, 16) 263 stack.AccountManager().Subscribe(events) 264 265 go func() { 266 // Create a chain state reader for self-derivation 267 rpcClient, err := stack.Attach() 268 if err != nil { 269 utils.Fatalf("Failed to attach to self: %v", err) 270 } 271 stateReader := ethclient.NewClient(rpcClient) 272 273 // Open any wallets already attached 274 for _, wallet := range stack.AccountManager().Wallets() { 275 if err := wallet.Open(""); err != nil { 276 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 277 } 278 } 279 // Listen for wallet event till termination 280 for event := range events { 281 switch event.Kind { 282 case accounts.WalletArrived: 283 if err := event.Wallet.Open(""); err != nil { 284 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 285 } 286 case accounts.WalletOpened: 287 status, _ := event.Wallet.Status() 288 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 289 290 if event.Wallet.URL().Scheme == "ledger" { 291 event.Wallet.SelfDerive(accounts.DefaultLedgerBaseDerivationPath, stateReader) 292 } else { 293 event.Wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader) 294 } 295 296 case accounts.WalletDropped: 297 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 298 event.Wallet.Close() 299 } 300 } 301 }() 302 // Start auxiliary services if enabled 303 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 304 // Mining only makes sense if a full Ethereum node is running 305 if ctx.GlobalBool(utils.LightModeFlag.Name) || ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 306 utils.Fatalf("Light clients do not support mining") 307 } 308 var ethereum *eth.Ethereum 309 if err := stack.Service(ðereum); err != nil { 310 utils.Fatalf("Ethereum service not running: %v", err) 311 } 312 // Use a reduced number of threads if requested 313 if threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name); threads > 0 { 314 type threaded interface { 315 SetThreads(threads int) 316 } 317 if th, ok := ethereum.Engine().(threaded); ok { 318 th.SetThreads(threads) 319 } 320 } 321 // Set the gas price to the limits from the CLI and start mining 322 ethereum.TxPool().SetGasPrice(utils.GlobalBig(ctx, utils.GasPriceFlag.Name)) 323 if err := ethereum.StartMining(true); err != nil { 324 utils.Fatalf("Failed to start mining: %v", err) 325 } 326 } 327 }