main.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. "fmt"
  20. "os"
  21. "runtime"
  22. "sort"
  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/eth"
  31. "github.com/ethereum/go-ethereum/ethclient"
  32. "github.com/ethereum/go-ethereum/internal/debug"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/metrics"
  35. "github.com/ethereum/go-ethereum/node"
  36. "gopkg.in/urfave/cli.v1"
  37. )
  38. const (
  39. clientIdentifier = "geth" // Client identifier to advertise over the network
  40. )
  41. var (
  42. // Git SHA1 commit hash of the release (set via linker flags)
  43. gitCommit = ""
  44. // Ethereum address of the Geth release oracle.
  45. relOracle = common.HexToAddress("0xfa7b9770ca4cb04296cac84f37736d4041251cdf")
  46. // The app that holds all commands and flags.
  47. app = utils.NewApp(gitCommit, "the go-ethereum command line interface")
  48. // flags that configure the node
  49. nodeFlags = []cli.Flag{
  50. utils.IdentityFlag,
  51. utils.UnlockedAccountFlag,
  52. utils.PasswordFileFlag,
  53. utils.BootnodesFlag,
  54. utils.BootnodesV4Flag,
  55. utils.BootnodesV5Flag,
  56. utils.DataDirFlag,
  57. utils.KeyStoreDirFlag,
  58. utils.NoUSBFlag,
  59. utils.DashboardEnabledFlag,
  60. utils.DashboardAddrFlag,
  61. utils.DashboardPortFlag,
  62. utils.DashboardRefreshFlag,
  63. utils.DashboardAssetsFlag,
  64. utils.EthashCacheDirFlag,
  65. utils.EthashCachesInMemoryFlag,
  66. utils.EthashCachesOnDiskFlag,
  67. utils.EthashDatasetDirFlag,
  68. utils.EthashDatasetsInMemoryFlag,
  69. utils.EthashDatasetsOnDiskFlag,
  70. utils.TxPoolNoLocalsFlag,
  71. utils.TxPoolJournalFlag,
  72. utils.TxPoolRejournalFlag,
  73. utils.TxPoolPriceLimitFlag,
  74. utils.TxPoolPriceBumpFlag,
  75. utils.TxPoolAccountSlotsFlag,
  76. utils.TxPoolGlobalSlotsFlag,
  77. utils.TxPoolAccountQueueFlag,
  78. utils.TxPoolGlobalQueueFlag,
  79. utils.TxPoolLifetimeFlag,
  80. utils.FastSyncFlag,
  81. utils.LightModeFlag,
  82. utils.SyncModeFlag,
  83. utils.LightServFlag,
  84. utils.LightPeersFlag,
  85. utils.LightKDFFlag,
  86. utils.CacheFlag,
  87. utils.TrieCacheGenFlag,
  88. utils.ListenPortFlag,
  89. utils.MaxPeersFlag,
  90. utils.MaxPendingPeersFlag,
  91. utils.EtherbaseFlag,
  92. utils.GasPriceFlag,
  93. utils.MinerThreadsFlag,
  94. utils.MiningEnabledFlag,
  95. utils.TargetGasLimitFlag,
  96. utils.NATFlag,
  97. utils.NoDiscoverFlag,
  98. utils.DiscoveryV5Flag,
  99. utils.NetrestrictFlag,
  100. utils.NodeKeyFileFlag,
  101. utils.NodeKeyHexFlag,
  102. utils.DeveloperFlag,
  103. utils.DeveloperPeriodFlag,
  104. utils.TestnetFlag,
  105. utils.RinkebyFlag,
  106. utils.VMEnableDebugFlag,
  107. utils.NetworkIdFlag,
  108. utils.RPCCORSDomainFlag,
  109. utils.EthStatsURLFlag,
  110. utils.MetricsEnabledFlag,
  111. utils.FakePoWFlag,
  112. utils.NoCompactionFlag,
  113. utils.GpoBlocksFlag,
  114. utils.GpoPercentileFlag,
  115. utils.ExtraDataFlag,
  116. configFileFlag,
  117. }
  118. rpcFlags = []cli.Flag{
  119. utils.RPCEnabledFlag,
  120. utils.RPCListenAddrFlag,
  121. utils.RPCPortFlag,
  122. utils.RPCApiFlag,
  123. utils.WSEnabledFlag,
  124. utils.WSListenAddrFlag,
  125. utils.WSPortFlag,
  126. utils.WSApiFlag,
  127. utils.WSAllowedOriginsFlag,
  128. utils.IPCDisabledFlag,
  129. utils.IPCPathFlag,
  130. }
  131. whisperFlags = []cli.Flag{
  132. utils.WhisperEnabledFlag,
  133. utils.WhisperMaxMessageSizeFlag,
  134. utils.WhisperMinPOWFlag,
  135. }
  136. )
  137. func init() {
  138. // Initialize the CLI app and start Geth
  139. app.Action = geth
  140. app.HideVersion = true // we have a command to print the version
  141. app.Copyright = "Copyright 2013-2017 The go-ethereum Authors"
  142. app.Commands = []cli.Command{
  143. // See chaincmd.go:
  144. initCommand,
  145. importCommand,
  146. exportCommand,
  147. copydbCommand,
  148. removedbCommand,
  149. dumpCommand,
  150. // See monitorcmd.go:
  151. monitorCommand,
  152. // See accountcmd.go:
  153. accountCommand,
  154. walletCommand,
  155. // See consolecmd.go:
  156. consoleCommand,
  157. attachCommand,
  158. javascriptCommand,
  159. // See misccmd.go:
  160. makecacheCommand,
  161. makedagCommand,
  162. versionCommand,
  163. bugCommand,
  164. licenseCommand,
  165. // See config.go
  166. dumpConfigCommand,
  167. }
  168. sort.Sort(cli.CommandsByName(app.Commands))
  169. app.Flags = append(app.Flags, nodeFlags...)
  170. app.Flags = append(app.Flags, rpcFlags...)
  171. app.Flags = append(app.Flags, consoleFlags...)
  172. app.Flags = append(app.Flags, debug.Flags...)
  173. app.Flags = append(app.Flags, whisperFlags...)
  174. app.Before = func(ctx *cli.Context) error {
  175. runtime.GOMAXPROCS(runtime.NumCPU())
  176. if err := debug.Setup(ctx); err != nil {
  177. return err
  178. }
  179. // Start system runtime metrics collection
  180. go metrics.CollectProcessMetrics(3 * time.Second)
  181. utils.SetupNetwork(ctx)
  182. return nil
  183. }
  184. app.After = func(ctx *cli.Context) error {
  185. debug.Exit()
  186. console.Stdin.Close() // Resets terminal mode.
  187. return nil
  188. }
  189. }
  190. func main() {
  191. if err := app.Run(os.Args); err != nil {
  192. fmt.Fprintln(os.Stderr, err)
  193. os.Exit(1)
  194. }
  195. }
  196. // geth is the main entry point into the system if no special subcommand is ran.
  197. // It creates a default node based on the command line arguments and runs it in
  198. // blocking mode, waiting for it to be shut down.
  199. func geth(ctx *cli.Context) error {
  200. node := makeFullNode(ctx)
  201. startNode(ctx, node)
  202. node.Wait()
  203. return nil
  204. }
  205. // startNode boots up the system node and all registered protocols, after which
  206. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  207. // miner.
  208. func startNode(ctx *cli.Context, stack *node.Node) {
  209. // Start up the node itself
  210. utils.StartNode(stack)
  211. // Unlock any account specifically requested
  212. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  213. passwords := utils.MakePasswordList(ctx)
  214. unlocks := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  215. for i, account := range unlocks {
  216. if trimmed := strings.TrimSpace(account); trimmed != "" {
  217. unlockAccount(ctx, ks, trimmed, i, passwords)
  218. }
  219. }
  220. // Register wallet event handlers to open and auto-derive wallets
  221. events := make(chan accounts.WalletEvent, 16)
  222. stack.AccountManager().Subscribe(events)
  223. go func() {
  224. // Create an chain state reader for self-derivation
  225. rpcClient, err := stack.Attach()
  226. if err != nil {
  227. utils.Fatalf("Failed to attach to self: %v", err)
  228. }
  229. stateReader := ethclient.NewClient(rpcClient)
  230. // Open any wallets already attached
  231. for _, wallet := range stack.AccountManager().Wallets() {
  232. if err := wallet.Open(""); err != nil {
  233. log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
  234. }
  235. }
  236. // Listen for wallet event till termination
  237. for event := range events {
  238. switch event.Kind {
  239. case accounts.WalletArrived:
  240. if err := event.Wallet.Open(""); err != nil {
  241. log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err)
  242. }
  243. case accounts.WalletOpened:
  244. status, _ := event.Wallet.Status()
  245. log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status)
  246. if event.Wallet.URL().Scheme == "ledger" {
  247. event.Wallet.SelfDerive(accounts.DefaultLedgerBaseDerivationPath, stateReader)
  248. } else {
  249. event.Wallet.SelfDerive(accounts.DefaultBaseDerivationPath, stateReader)
  250. }
  251. case accounts.WalletDropped:
  252. log.Info("Old wallet dropped", "url", event.Wallet.URL())
  253. event.Wallet.Close()
  254. }
  255. }
  256. }()
  257. // Start auxiliary services if enabled
  258. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) {
  259. // Mining only makes sense if a full Ethereum node is running
  260. var ethereum *eth.Ethereum
  261. if err := stack.Service(&ethereum); err != nil {
  262. utils.Fatalf("ethereum service not running: %v", err)
  263. }
  264. // Use a reduced number of threads if requested
  265. if threads := ctx.GlobalInt(utils.MinerThreadsFlag.Name); threads > 0 {
  266. type threaded interface {
  267. SetThreads(threads int)
  268. }
  269. if th, ok := ethereum.Engine().(threaded); ok {
  270. th.SetThreads(threads)
  271. }
  272. }
  273. // Set the gas price to the limits from the CLI and start mining
  274. ethereum.TxPool().SetGasPrice(utils.GlobalBig(ctx, utils.GasPriceFlag.Name))
  275. if err := ethereum.StartMining(true); err != nil {
  276. utils.Fatalf("Failed to start mining: %v", err)
  277. }
  278. }
  279. }