github.com/avence12/go-ethereum@v1.5.10-0.20170320123548-1dfd65f6d047/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 "encoding/hex" 22 "fmt" 23 "os" 24 "runtime" 25 "strings" 26 "time" 27 28 "github.com/ethereum/go-ethereum/accounts" 29 "github.com/ethereum/go-ethereum/accounts/keystore" 30 "github.com/ethereum/go-ethereum/cmd/utils" 31 "github.com/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/common/hexutil" 33 "github.com/ethereum/go-ethereum/console" 34 "github.com/ethereum/go-ethereum/contracts/release" 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 "github.com/ethereum/go-ethereum/params" 42 "github.com/ethereum/go-ethereum/rlp" 43 "gopkg.in/urfave/cli.v1" 44 ) 45 46 const ( 47 clientIdentifier = "geth" // Client identifier to advertise over the network 48 ) 49 50 var ( 51 // Git SHA1 commit hash of the release (set via linker flags) 52 gitCommit = "" 53 // Ethereum address of the Geth release oracle. 54 relOracle = common.HexToAddress("0xfa7b9770ca4cb04296cac84f37736d4041251cdf") 55 // The app that holds all commands and flags. 56 app = utils.NewApp(gitCommit, "the go-ethereum command line interface") 57 ) 58 59 func init() { 60 // Initialize the CLI app and start Geth 61 app.Action = geth 62 app.HideVersion = true // we have a command to print the version 63 app.Copyright = "Copyright 2013-2016 The go-ethereum Authors" 64 app.Commands = []cli.Command{ 65 // See chaincmd.go: 66 initCommand, 67 importCommand, 68 exportCommand, 69 removedbCommand, 70 dumpCommand, 71 // See monitorcmd.go: 72 monitorCommand, 73 // See accountcmd.go: 74 accountCommand, 75 walletCommand, 76 // See consolecmd.go: 77 consoleCommand, 78 attachCommand, 79 javascriptCommand, 80 // See misccmd.go: 81 makedagCommand, 82 versionCommand, 83 bugCommand, 84 licenseCommand, 85 } 86 87 app.Flags = []cli.Flag{ 88 utils.IdentityFlag, 89 utils.UnlockedAccountFlag, 90 utils.PasswordFileFlag, 91 utils.BootnodesFlag, 92 utils.DataDirFlag, 93 utils.KeyStoreDirFlag, 94 utils.EthashCacheDirFlag, 95 utils.EthashCachesInMemoryFlag, 96 utils.EthashCachesOnDiskFlag, 97 utils.EthashDatasetDirFlag, 98 utils.EthashDatasetsInMemoryFlag, 99 utils.EthashDatasetsOnDiskFlag, 100 utils.FastSyncFlag, 101 utils.LightModeFlag, 102 utils.LightServFlag, 103 utils.LightPeersFlag, 104 utils.LightKDFFlag, 105 utils.CacheFlag, 106 utils.TrieCacheGenFlag, 107 utils.JSpathFlag, 108 utils.ListenPortFlag, 109 utils.MaxPeersFlag, 110 utils.MaxPendingPeersFlag, 111 utils.EtherbaseFlag, 112 utils.GasPriceFlag, 113 utils.MinerThreadsFlag, 114 utils.MiningEnabledFlag, 115 utils.TargetGasLimitFlag, 116 utils.NATFlag, 117 utils.NoDiscoverFlag, 118 utils.DiscoveryV5Flag, 119 utils.NetrestrictFlag, 120 utils.NodeKeyFileFlag, 121 utils.NodeKeyHexFlag, 122 utils.RPCEnabledFlag, 123 utils.RPCListenAddrFlag, 124 utils.RPCPortFlag, 125 utils.RPCApiFlag, 126 utils.WSEnabledFlag, 127 utils.WSListenAddrFlag, 128 utils.WSPortFlag, 129 utils.WSApiFlag, 130 utils.WSAllowedOriginsFlag, 131 utils.IPCDisabledFlag, 132 utils.IPCApiFlag, 133 utils.IPCPathFlag, 134 utils.ExecFlag, 135 utils.PreloadJSFlag, 136 utils.WhisperEnabledFlag, 137 utils.DevModeFlag, 138 utils.TestNetFlag, 139 utils.VMForceJitFlag, 140 utils.VMJitCacheFlag, 141 utils.VMEnableJitFlag, 142 utils.VMEnableDebugFlag, 143 utils.NetworkIdFlag, 144 utils.RPCCORSDomainFlag, 145 utils.EthStatsURLFlag, 146 utils.MetricsEnabledFlag, 147 utils.FakePoWFlag, 148 utils.NoCompactionFlag, 149 utils.SolcPathFlag, 150 utils.GpoMinGasPriceFlag, 151 utils.GpoMaxGasPriceFlag, 152 utils.GpoFullBlockRatioFlag, 153 utils.GpobaseStepDownFlag, 154 utils.GpobaseStepUpFlag, 155 utils.GpobaseCorrectionFactorFlag, 156 utils.ExtraDataFlag, 157 } 158 app.Flags = append(app.Flags, debug.Flags...) 159 160 app.Before = func(ctx *cli.Context) error { 161 runtime.GOMAXPROCS(runtime.NumCPU()) 162 if err := debug.Setup(ctx); err != nil { 163 return err 164 } 165 // Start system runtime metrics collection 166 go metrics.CollectProcessMetrics(3 * time.Second) 167 168 // This should be the only place where reporting is enabled 169 // because it is not intended to run while testing. 170 // In addition to this check, bad block reports are sent only 171 // for chains with the main network genesis block and network id 1. 172 eth.EnableBadBlockReporting = true 173 174 utils.SetupNetwork(ctx) 175 return nil 176 } 177 178 app.After = func(ctx *cli.Context) error { 179 debug.Exit() 180 console.Stdin.Close() // Resets terminal mode. 181 return nil 182 } 183 } 184 185 func main() { 186 if err := app.Run(os.Args); err != nil { 187 fmt.Fprintln(os.Stderr, err) 188 os.Exit(1) 189 } 190 } 191 192 // geth is the main entry point into the system if no special subcommand is ran. 193 // It creates a default node based on the command line arguments and runs it in 194 // blocking mode, waiting for it to be shut down. 195 func geth(ctx *cli.Context) error { 196 node := makeFullNode(ctx) 197 startNode(ctx, node) 198 node.Wait() 199 return nil 200 } 201 202 func makeFullNode(ctx *cli.Context) *node.Node { 203 // Create the default extradata and construct the base node 204 var clientInfo = struct { 205 Version uint 206 Name string 207 GoVersion string 208 Os string 209 }{uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch), clientIdentifier, runtime.Version(), runtime.GOOS} 210 extra, err := rlp.EncodeToBytes(clientInfo) 211 if err != nil { 212 log.Warn("Failed to set canonical miner information", "err", err) 213 } 214 if uint64(len(extra)) > params.MaximumExtraDataSize { 215 log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize) 216 extra = nil 217 } 218 stack := utils.MakeNode(ctx, clientIdentifier, gitCommit) 219 utils.RegisterEthService(ctx, stack, extra) 220 221 // Whisper must be explicitly enabled, but is auto-enabled in --dev mode. 222 shhEnabled := ctx.GlobalBool(utils.WhisperEnabledFlag.Name) 223 shhAutoEnabled := !ctx.GlobalIsSet(utils.WhisperEnabledFlag.Name) && ctx.GlobalIsSet(utils.DevModeFlag.Name) 224 if shhEnabled || shhAutoEnabled { 225 utils.RegisterShhService(stack) 226 } 227 // Add the Ethereum Stats daemon if requested 228 if url := ctx.GlobalString(utils.EthStatsURLFlag.Name); url != "" { 229 utils.RegisterEthStatsService(stack, url) 230 } 231 // Add the release oracle service so it boots along with node. 232 if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 233 config := release.Config{ 234 Oracle: relOracle, 235 Major: uint32(params.VersionMajor), 236 Minor: uint32(params.VersionMinor), 237 Patch: uint32(params.VersionPatch), 238 } 239 commit, _ := hex.DecodeString(gitCommit) 240 copy(config.Commit[:], commit) 241 return release.NewReleaseService(ctx, config) 242 }); err != nil { 243 utils.Fatalf("Failed to register the Geth release oracle service: %v", err) 244 } 245 return stack 246 } 247 248 // startNode boots up the system node and all registered protocols, after which 249 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 250 // miner. 251 func startNode(ctx *cli.Context, stack *node.Node) { 252 // Start up the node itself 253 utils.StartNode(stack) 254 255 // Unlock any account specifically requested 256 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 257 258 passwords := utils.MakePasswordList(ctx) 259 unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 260 for i, account := range unlocks { 261 if trimmed := strings.TrimSpace(account); trimmed != "" { 262 unlockAccount(ctx, ks, trimmed, i, passwords) 263 } 264 } 265 // Register wallet event handlers to open and auto-derive wallets 266 events := make(chan accounts.WalletEvent, 16) 267 stack.AccountManager().Subscribe(events) 268 269 go func() { 270 // Create an chain state reader for self-derivation 271 rpcClient, err := stack.Attach() 272 if err != nil { 273 utils.Fatalf("Failed to attach to self: %v", err) 274 } 275 stateReader := ethclient.NewClient(rpcClient) 276 277 // Open and self derive any wallets already attached 278 for _, wallet := range stack.AccountManager().Wallets() { 279 if err := wallet.Open(""); err != nil { 280 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 281 } else { 282 wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader) 283 } 284 } 285 // Listen for wallet event till termination 286 for event := range events { 287 if event.Arrive { 288 if err := event.Wallet.Open(""); err != nil { 289 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 290 } else { 291 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", event.Wallet.Status()) 292 event.Wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader) 293 } 294 } else { 295 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 296 event.Wallet.Close() 297 } 298 } 299 }() 300 // Start auxiliary services if enabled 301 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) { 302 var ethereum *eth.Ethereum 303 if err := stack.Service(ðereum); err != nil { 304 utils.Fatalf("ethereum service not running: %v", err) 305 } 306 if err := ethereum.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name)); err != nil { 307 utils.Fatalf("Failed to start mining: %v", err) 308 } 309 } 310 }