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