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