main.go 8.8 KB

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