main.go 9.0 KB

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