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