main.go 9.2 KB

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