main.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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.GpoBlocksFlag,
  144. utils.GpoPercentileFlag,
  145. utils.ExtraDataFlag,
  146. }
  147. app.Flags = append(app.Flags, debug.Flags...)
  148. app.Before = func(ctx *cli.Context) error {
  149. runtime.GOMAXPROCS(runtime.NumCPU())
  150. if err := debug.Setup(ctx); err != nil {
  151. return err
  152. }
  153. // Start system runtime metrics collection
  154. go metrics.CollectProcessMetrics(3 * time.Second)
  155. // This should be the only place where reporting is enabled
  156. // because it is not intended to run while testing.
  157. // In addition to this check, bad block reports are sent only
  158. // for chains with the main network genesis block and network id 1.
  159. eth.EnableBadBlockReporting = true
  160. utils.SetupNetwork(ctx)
  161. return nil
  162. }
  163. app.After = func(ctx *cli.Context) error {
  164. debug.Exit()
  165. console.Stdin.Close() // Resets terminal mode.
  166. return nil
  167. }
  168. }
  169. func main() {
  170. if err := app.Run(os.Args); err != nil {
  171. fmt.Fprintln(os.Stderr, err)
  172. os.Exit(1)
  173. }
  174. }
  175. // geth is the main entry point into the system if no special subcommand is ran.
  176. // It creates a default node based on the command line arguments and runs it in
  177. // blocking mode, waiting for it to be shut down.
  178. func geth(ctx *cli.Context) error {
  179. node := makeFullNode(ctx)
  180. startNode(ctx, node)
  181. node.Wait()
  182. return nil
  183. }
  184. func makeFullNode(ctx *cli.Context) *node.Node {
  185. // Create the default extradata and construct the base node
  186. var clientInfo = struct {
  187. Version uint
  188. Name string
  189. GoVersion string
  190. Os string
  191. }{uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch), clientIdentifier, runtime.Version(), runtime.GOOS}
  192. extra, err := rlp.EncodeToBytes(clientInfo)
  193. if err != nil {
  194. log.Warn("Failed to set canonical miner information", "err", err)
  195. }
  196. if uint64(len(extra)) > params.MaximumExtraDataSize {
  197. log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize)
  198. extra = nil
  199. }
  200. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  201. utils.RegisterEthService(ctx, stack, extra)
  202. // Whisper must be explicitly enabled, but is auto-enabled in --dev mode.
  203. shhEnabled := ctx.GlobalBool(utils.WhisperEnabledFlag.Name)
  204. shhAutoEnabled := !ctx.GlobalIsSet(utils.WhisperEnabledFlag.Name) && ctx.GlobalIsSet(utils.DevModeFlag.Name)
  205. if shhEnabled || shhAutoEnabled {
  206. utils.RegisterShhService(stack)
  207. }
  208. // Add the Ethereum Stats daemon if requested
  209. if url := ctx.GlobalString(utils.EthStatsURLFlag.Name); url != "" {
  210. utils.RegisterEthStatsService(stack, url)
  211. }
  212. // Add the release oracle service so it boots along with node.
  213. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  214. config := release.Config{
  215. Oracle: relOracle,
  216. Major: uint32(params.VersionMajor),
  217. Minor: uint32(params.VersionMinor),
  218. Patch: uint32(params.VersionPatch),
  219. }
  220. commit, _ := hex.DecodeString(gitCommit)
  221. copy(config.Commit[:], commit)
  222. return release.NewReleaseService(ctx, config)
  223. }); err != nil {
  224. utils.Fatalf("Failed to register the Geth release oracle service: %v", err)
  225. }
  226. return stack
  227. }
  228. // startNode boots up the system node and all registered protocols, after which
  229. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  230. // miner.
  231. func startNode(ctx *cli.Context, stack *node.Node) {
  232. // Start up the node itself
  233. utils.StartNode(stack)
  234. // Unlock any account specifically requested
  235. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  236. passwords := utils.MakePasswordList(ctx)
  237. unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  238. for i, account := range unlocks {
  239. if trimmed := strings.TrimSpace(account); trimmed != "" {
  240. unlockAccount(ctx, ks, trimmed, i, passwords)
  241. }
  242. }
  243. // Register wallet event handlers to open and auto-derive wallets
  244. events := make(chan accounts.WalletEvent, 16)
  245. stack.AccountManager().Subscribe(events)
  246. go func() {
  247. // Create an chain state reader for self-derivation
  248. rpcClient, err := stack.Attach()
  249. if err != nil {
  250. utils.Fatalf("Failed to attach to self: %v", err)
  251. }
  252. stateReader := ethclient.NewClient(rpcClient)
  253. // Open and self derive any wallets already attached
  254. for _, wallet := range stack.AccountManager().Wallets() {
  255. if err := wallet.Open(""); err != nil {
  256. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  257. } else {
  258. wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader)
  259. }
  260. }
  261. // Listen for wallet event till termination
  262. for event := range events {
  263. if event.Arrive {
  264. if err := event.Wallet.Open(""); err != nil {
  265. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  266. } else {
  267. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", event.Wallet.Status())
  268. event.Wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader)
  269. }
  270. } else {
  271. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  272. event.Wallet.Close()
  273. }
  274. }
  275. }()
  276. // Start auxiliary services if enabled
  277. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
  278. var ethereum *eth.Ethereum
  279. if err := stack.Service(&ethereum); err != nil {
  280. utils.Fatalf("ethereum service not running: %v", err)
  281. }
  282. if threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name); threads > 0 {
  283. type threaded interface {
  284. SetThreads(threads int)
  285. }
  286. if th, ok := ethereum.Engine().(threaded); ok {
  287. th.SetThreads(threads)
  288. }
  289. }
  290. if err := ethereum.StartMining(); err != nil {
  291. utils.Fatalf("Failed to start mining: %v", err)
  292. }
  293. }
  294. }