main.go 9.4 KB

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