main.go 8.7 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. "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/console"
  29. "github.com/ethereum/go-ethereum/eth"
  30. "github.com/ethereum/go-ethereum/ethclient"
  31. "github.com/ethereum/go-ethereum/internal/debug"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/metrics"
  34. "github.com/ethereum/go-ethereum/node"
  35. "gopkg.in/urfave/cli.v1"
  36. )
  37. const (
  38. clientIdentifier = "geth" // Client identifier to advertise over the network
  39. )
  40. var (
  41. // Git SHA1 commit hash of the release (set via linker flags)
  42. gitCommit = ""
  43. // The app that holds all commands and flags.
  44. app = utils.NewApp(gitCommit, "the go-ethereum command line interface")
  45. // flags that configure the node
  46. nodeFlags = []cli.Flag{
  47. utils.IdentityFlag,
  48. utils.UnlockedAccountFlag,
  49. utils.PasswordFileFlag,
  50. utils.BootnodesFlag,
  51. utils.BootnodesV4Flag,
  52. utils.BootnodesV5Flag,
  53. utils.DataDirFlag,
  54. utils.KeyStoreDirFlag,
  55. utils.NoUSBFlag,
  56. utils.DashboardEnabledFlag,
  57. utils.DashboardAddrFlag,
  58. utils.DashboardPortFlag,
  59. utils.DashboardRefreshFlag,
  60. utils.EthashCacheDirFlag,
  61. utils.EthashCachesInMemoryFlag,
  62. utils.EthashCachesOnDiskFlag,
  63. utils.EthashDatasetDirFlag,
  64. utils.EthashDatasetsInMemoryFlag,
  65. utils.EthashDatasetsOnDiskFlag,
  66. utils.TxPoolNoLocalsFlag,
  67. utils.TxPoolJournalFlag,
  68. utils.TxPoolRejournalFlag,
  69. utils.TxPoolPriceLimitFlag,
  70. utils.TxPoolPriceBumpFlag,
  71. utils.TxPoolAccountSlotsFlag,
  72. utils.TxPoolGlobalSlotsFlag,
  73. utils.TxPoolAccountQueueFlag,
  74. utils.TxPoolGlobalQueueFlag,
  75. utils.TxPoolLifetimeFlag,
  76. utils.FastSyncFlag,
  77. utils.LightModeFlag,
  78. utils.SyncModeFlag,
  79. utils.GCModeFlag,
  80. utils.LightServFlag,
  81. utils.LightPeersFlag,
  82. utils.LightKDFFlag,
  83. utils.CacheFlag,
  84. utils.CacheDatabaseFlag,
  85. utils.CacheGCFlag,
  86. utils.TrieCacheGenFlag,
  87. utils.ListenPortFlag,
  88. utils.MaxPeersFlag,
  89. utils.MaxPendingPeersFlag,
  90. utils.EtherbaseFlag,
  91. utils.GasPriceFlag,
  92. utils.MinerThreadsFlag,
  93. utils.MiningEnabledFlag,
  94. utils.TargetGasLimitFlag,
  95. utils.NATFlag,
  96. utils.NoDiscoverFlag,
  97. utils.DiscoveryV5Flag,
  98. utils.NetrestrictFlag,
  99. utils.NodeKeyFileFlag,
  100. utils.NodeKeyHexFlag,
  101. utils.DeveloperFlag,
  102. utils.DeveloperPeriodFlag,
  103. utils.TestnetFlag,
  104. utils.RinkebyFlag,
  105. utils.VMEnableDebugFlag,
  106. utils.NetworkIdFlag,
  107. utils.RPCCORSDomainFlag,
  108. utils.RPCVirtualHostsFlag,
  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-2018 The go-ethereum Authors"
  142. app.Commands = []cli.Command{
  143. // See chaincmd.go:
  144. initCommand,
  145. importCommand,
  146. exportCommand,
  147. importPreimagesCommand,
  148. exportPreimagesCommand,
  149. copydbCommand,
  150. removedbCommand,
  151. dumpCommand,
  152. // See monitorcmd.go:
  153. monitorCommand,
  154. // See accountcmd.go:
  155. accountCommand,
  156. walletCommand,
  157. // See consolecmd.go:
  158. consoleCommand,
  159. attachCommand,
  160. javascriptCommand,
  161. // See misccmd.go:
  162. makecacheCommand,
  163. makedagCommand,
  164. versionCommand,
  165. bugCommand,
  166. licenseCommand,
  167. // See config.go
  168. dumpConfigCommand,
  169. }
  170. sort.Sort(cli.CommandsByName(app.Commands))
  171. app.Flags = append(app.Flags, nodeFlags...)
  172. app.Flags = append(app.Flags, rpcFlags...)
  173. app.Flags = append(app.Flags, consoleFlags...)
  174. app.Flags = append(app.Flags, debug.Flags...)
  175. app.Flags = append(app.Flags, whisperFlags...)
  176. app.Before = func(ctx *cli.Context) error {
  177. runtime.GOMAXPROCS(runtime.NumCPU())
  178. if err := debug.Setup(ctx); err != nil {
  179. return err
  180. }
  181. // Start system runtime metrics collection
  182. go metrics.CollectProcessMetrics(3 * time.Second)
  183. utils.SetupNetwork(ctx)
  184. return nil
  185. }
  186. app.After = func(ctx *cli.Context) error {
  187. debug.Exit()
  188. console.Stdin.Close() // Resets terminal mode.
  189. return nil
  190. }
  191. }
  192. func main() {
  193. if err := app.Run(os.Args); err != nil {
  194. fmt.Fprintln(os.Stderr, err)
  195. os.Exit(1)
  196. }
  197. }
  198. // geth is the main entry point into the system if no special subcommand is ran.
  199. // It creates a default node based on the command line arguments and runs it in
  200. // blocking mode, waiting for it to be shut down.
  201. func geth(ctx *cli.Context) error {
  202. node := makeFullNode(ctx)
  203. startNode(ctx, node)
  204. node.Wait()
  205. return nil
  206. }
  207. // startNode boots up the system node and all registered protocols, after which
  208. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  209. // miner.
  210. func startNode(ctx *cli.Context, stack *node.Node) {
  211. debug.Memsize.Add("node", stack)
  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 a 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. }