github.com/quinndk/ethereum_read@v0.0.0-20181211143958-29c55eec3237/go-ethereum-master_read/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 metricsFlags = []cli.Flag{ 149 utils.MetricsEnableInfluxDBFlag, 150 utils.MetricsInfluxDBEndpointFlag, 151 utils.MetricsInfluxDBDatabaseFlag, 152 utils.MetricsInfluxDBUsernameFlag, 153 utils.MetricsInfluxDBPasswordFlag, 154 utils.MetricsInfluxDBHostTagFlag, 155 } 156 ) 157 158 func init() { 159 // Initialize the CLI app and start Geth 160 // 初始化命令行工具CLI并启动Geth 161 app.Action = geth 162 app.HideVersion = true // we have a command to print the version 163 app.Copyright = "Copyright 2013-2018 The go-ethereum Authors" 164 app.Commands = []cli.Command{ 165 // See chaincmd.go: 166 initCommand, 167 importCommand, 168 exportCommand, 169 importPreimagesCommand, 170 exportPreimagesCommand, 171 copydbCommand, 172 removedbCommand, 173 dumpCommand, 174 // See monitorcmd.go: 175 monitorCommand, 176 // See accountcmd.go: 177 accountCommand, 178 walletCommand, 179 // See consolecmd.go: 180 consoleCommand, 181 attachCommand, 182 javascriptCommand, 183 // See misccmd.go: 184 makecacheCommand, 185 makedagCommand, 186 versionCommand, 187 bugCommand, 188 licenseCommand, 189 // See config.go 190 dumpConfigCommand, 191 } 192 sort.Sort(cli.CommandsByName(app.Commands)) 193 194 app.Flags = append(app.Flags, nodeFlags...) 195 app.Flags = append(app.Flags, rpcFlags...) 196 app.Flags = append(app.Flags, consoleFlags...) 197 app.Flags = append(app.Flags, debug.Flags...) 198 app.Flags = append(app.Flags, whisperFlags...) 199 app.Flags = append(app.Flags, metricsFlags...) 200 201 app.Before = func(ctx *cli.Context) error { 202 runtime.GOMAXPROCS(runtime.NumCPU()) 203 if err := debug.Setup(ctx); err != nil { 204 return err 205 } 206 // Cap the cache allowance and tune the garbage colelctor 207 var mem gosigar.Mem 208 if err := mem.Get(); err == nil { 209 allowance := int(mem.Total / 1024 / 1024 / 3) 210 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 211 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 212 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 213 } 214 } 215 // Ensure Go's GC ignores the database cache for trigger percentage 216 cache := ctx.GlobalInt(utils.CacheFlag.Name) 217 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 218 219 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 220 godebug.SetGCPercent(int(gogc)) 221 222 // Start metrics export if enabled 223 utils.SetupMetrics(ctx) 224 225 // Start system runtime metrics collection 226 go metrics.CollectProcessMetrics(3 * time.Second) 227 228 // 网络配置 是主网或者测试网 229 utils.SetupNetwork(ctx) 230 return nil 231 } 232 233 app.After = func(ctx *cli.Context) error { 234 debug.Exit() 235 console.Stdin.Close() // Resets terminal mode. 236 return nil 237 } 238 } 239 240 func main() { 241 if err := app.Run(os.Args); err != nil { 242 fmt.Fprintln(os.Stderr, err) 243 os.Exit(1) 244 } 245 } 246 247 // geth is the main entry point into the system if no special subcommand is ran. 248 // It creates a default node based on the command line arguments and runs it in 249 // blocking mode, waiting for it to be shut down. 250 func geth(ctx *cli.Context) error { 251 node := makeFullNode(ctx) 252 startNode(ctx, node) 253 node.Wait() 254 return nil 255 } 256 257 // startNode boots up the system node and all registered protocols, after which 258 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 259 // miner. 260 func startNode(ctx *cli.Context, stack *node.Node) { 261 debug.Memsize.Add("node", stack) 262 263 // Start up the node itself 264 utils.StartNode(stack) 265 266 // Unlock any account specifically requested 267 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 268 269 passwords := utils.MakePasswordList(ctx) 270 unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 271 for i, account := range unlocks { 272 if trimmed := strings.TrimSpace(account); trimmed != "" { 273 unlockAccount(ctx, ks, trimmed, i, passwords) 274 } 275 } 276 // Register wallet event handlers to open and auto-derive wallets 277 events := make(chan accounts.WalletEvent, 16) 278 stack.AccountManager().Subscribe(events) 279 280 go func() { 281 // Create a chain state reader for self-derivation 282 rpcClient, err := stack.Attach() 283 if err != nil { 284 utils.Fatalf("Failed to attach to self: %v", err) 285 } 286 stateReader := ethclient.NewClient(rpcClient) 287 288 // Open any wallets already attached 289 for _, wallet := range stack.AccountManager().Wallets() { 290 if err := wallet.Open(""); err != nil { 291 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 292 } 293 } 294 // Listen for wallet event till termination 295 for event := range events { 296 switch event.Kind { 297 case accounts.WalletArrived: 298 if err := event.Wallet.Open(""); err != nil { 299 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 300 } 301 case accounts.WalletOpened: 302 status, _ := event.Wallet.Status() 303 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 304 305 if event.Wallet.URL().Scheme == "ledger" { 306 event.Wallet.SelfDerive(accounts.DefaultLedgerBaseDerivationPath, stateReader) 307 } else { 308 event.Wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader) 309 } 310 311 case accounts.WalletDropped: 312 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 313 event.Wallet.Close() 314 } 315 } 316 }() 317 // Start auxiliary services if enabled 318 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 319 // Mining only makes sense if a full Ethereum node is running 320 if ctx.GlobalBool(utils.LightModeFlag.Name) || ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 321 utils.Fatalf("Light clients do not support mining") 322 } 323 var ethereum *eth.Ethereum 324 if err := stack.Service(ðereum); err != nil { 325 utils.Fatalf("Ethereum service not running: %v", err) 326 } 327 // Use a reduced number of threads if requested 328 if threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name); threads > 0 { 329 type threaded interface { 330 SetThreads(threads int) 331 } 332 if th, ok := ethereum.Engine().(threaded); ok { 333 th.SetThreads(threads) 334 } 335 } 336 // Set the gas price to the limits from the CLI and start mining 337 ethereum.TxPool().SetGasPrice(utils.GlobalBig(ctx, utils.GasPriceFlag.Name)) 338 if err := ethereum.StartMining(true); err != nil { 339 utils.Fatalf("Failed to start mining: %v", err) 340 } 341 } 342 }