server.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser 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. // The go-ethereum library 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 Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package les
  17. import (
  18. "crypto/ecdsa"
  19. "time"
  20. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  21. "github.com/ethereum/go-ethereum/common/mclock"
  22. "github.com/ethereum/go-ethereum/core"
  23. "github.com/ethereum/go-ethereum/eth"
  24. "github.com/ethereum/go-ethereum/les/checkpointoracle"
  25. "github.com/ethereum/go-ethereum/les/flowcontrol"
  26. "github.com/ethereum/go-ethereum/light"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/p2p"
  29. "github.com/ethereum/go-ethereum/p2p/discv5"
  30. "github.com/ethereum/go-ethereum/p2p/enode"
  31. "github.com/ethereum/go-ethereum/p2p/enr"
  32. "github.com/ethereum/go-ethereum/params"
  33. "github.com/ethereum/go-ethereum/rpc"
  34. )
  35. type LesServer struct {
  36. lesCommons
  37. archiveMode bool // Flag whether the ethereum node runs in archive mode.
  38. peers *clientPeerSet
  39. handler *serverHandler
  40. lesTopics []discv5.Topic
  41. privateKey *ecdsa.PrivateKey
  42. // Flow control and capacity management
  43. fcManager *flowcontrol.ClientManager
  44. costTracker *costTracker
  45. defParams flowcontrol.ServerParams
  46. servingQueue *servingQueue
  47. clientPool *clientPool
  48. minCapacity, maxCapacity, freeCapacity uint64
  49. threadsIdle int // Request serving threads count when system is idle.
  50. threadsBusy int // Request serving threads count when system is busy(block insertion).
  51. }
  52. func NewLesServer(e *eth.Ethereum, config *eth.Config) (*LesServer, error) {
  53. // Collect les protocol version information supported by local node.
  54. lesTopics := make([]discv5.Topic, len(AdvertiseProtocolVersions))
  55. for i, pv := range AdvertiseProtocolVersions {
  56. lesTopics[i] = lesTopic(e.BlockChain().Genesis().Hash(), pv)
  57. }
  58. // Calculate the number of threads used to service the light client
  59. // requests based on the user-specified value.
  60. threads := config.LightServ * 4 / 100
  61. if threads < 4 {
  62. threads = 4
  63. }
  64. srv := &LesServer{
  65. lesCommons: lesCommons{
  66. genesis: e.BlockChain().Genesis().Hash(),
  67. config: config,
  68. chainConfig: e.BlockChain().Config(),
  69. iConfig: light.DefaultServerIndexerConfig,
  70. chainDb: e.ChainDb(),
  71. chainReader: e.BlockChain(),
  72. chtIndexer: light.NewChtIndexer(e.ChainDb(), nil, params.CHTFrequency, params.HelperTrieProcessConfirmations),
  73. bloomTrieIndexer: light.NewBloomTrieIndexer(e.ChainDb(), nil, params.BloomBitsBlocks, params.BloomTrieFrequency),
  74. closeCh: make(chan struct{}),
  75. },
  76. archiveMode: e.ArchiveMode(),
  77. peers: newClientPeerSet(),
  78. lesTopics: lesTopics,
  79. fcManager: flowcontrol.NewClientManager(nil, &mclock.System{}),
  80. servingQueue: newServingQueue(int64(time.Millisecond*10), float64(config.LightServ)/100),
  81. threadsBusy: config.LightServ/100 + 1,
  82. threadsIdle: threads,
  83. }
  84. srv.handler = newServerHandler(srv, e.BlockChain(), e.ChainDb(), e.TxPool(), e.Synced)
  85. srv.costTracker, srv.minCapacity = newCostTracker(e.ChainDb(), config)
  86. srv.freeCapacity = srv.minCapacity
  87. // Set up checkpoint oracle.
  88. oracle := config.CheckpointOracle
  89. if oracle == nil {
  90. oracle = params.CheckpointOracles[e.BlockChain().Genesis().Hash()]
  91. }
  92. srv.oracle = checkpointoracle.New(oracle, srv.localCheckpoint)
  93. // Initialize server capacity management fields.
  94. srv.defParams = flowcontrol.ServerParams{
  95. BufLimit: srv.freeCapacity * bufLimitRatio,
  96. MinRecharge: srv.freeCapacity,
  97. }
  98. // LES flow control tries to more or less guarantee the possibility for the
  99. // clients to send a certain amount of requests at any time and get a quick
  100. // response. Most of the clients want this guarantee but don't actually need
  101. // to send requests most of the time. Our goal is to serve as many clients as
  102. // possible while the actually used server capacity does not exceed the limits
  103. totalRecharge := srv.costTracker.totalRecharge()
  104. srv.maxCapacity = srv.freeCapacity * uint64(srv.config.LightPeers)
  105. if totalRecharge > srv.maxCapacity {
  106. srv.maxCapacity = totalRecharge
  107. }
  108. srv.fcManager.SetCapacityLimits(srv.freeCapacity, srv.maxCapacity, srv.freeCapacity*2)
  109. srv.clientPool = newClientPool(srv.chainDb, srv.freeCapacity, mclock.System{}, func(id enode.ID) { go srv.peers.unregister(peerIdToString(id)) })
  110. srv.clientPool.setDefaultFactors(priceFactors{0, 1, 1}, priceFactors{0, 1, 1})
  111. checkpoint := srv.latestLocalCheckpoint()
  112. if !checkpoint.Empty() {
  113. log.Info("Loaded latest checkpoint", "section", checkpoint.SectionIndex, "head", checkpoint.SectionHead,
  114. "chtroot", checkpoint.CHTRoot, "bloomroot", checkpoint.BloomRoot)
  115. }
  116. srv.chtIndexer.Start(e.BlockChain())
  117. return srv, nil
  118. }
  119. func (s *LesServer) APIs() []rpc.API {
  120. return []rpc.API{
  121. {
  122. Namespace: "les",
  123. Version: "1.0",
  124. Service: NewPrivateLightAPI(&s.lesCommons),
  125. Public: false,
  126. },
  127. {
  128. Namespace: "les",
  129. Version: "1.0",
  130. Service: NewPrivateLightServerAPI(s),
  131. Public: false,
  132. },
  133. {
  134. Namespace: "debug",
  135. Version: "1.0",
  136. Service: NewPrivateDebugAPI(s),
  137. Public: false,
  138. },
  139. }
  140. }
  141. func (s *LesServer) Protocols() []p2p.Protocol {
  142. ps := s.makeProtocols(ServerProtocolVersions, s.handler.runPeer, func(id enode.ID) interface{} {
  143. if p := s.peers.peer(peerIdToString(id)); p != nil {
  144. return p.Info()
  145. }
  146. return nil
  147. }, nil)
  148. // Add "les" ENR entries.
  149. for i := range ps {
  150. ps[i].Attributes = []enr.Entry{&lesEntry{}}
  151. }
  152. return ps
  153. }
  154. // Start starts the LES server
  155. func (s *LesServer) Start(srvr *p2p.Server) {
  156. s.privateKey = srvr.PrivateKey
  157. s.handler.start()
  158. s.wg.Add(1)
  159. go s.capacityManagement()
  160. if srvr.DiscV5 != nil {
  161. for _, topic := range s.lesTopics {
  162. topic := topic
  163. go func() {
  164. logger := log.New("topic", topic)
  165. logger.Info("Starting topic registration")
  166. defer logger.Info("Terminated topic registration")
  167. srvr.DiscV5.RegisterTopic(topic, s.closeCh)
  168. }()
  169. }
  170. }
  171. }
  172. // Stop stops the LES service
  173. func (s *LesServer) Stop() {
  174. close(s.closeCh)
  175. // Disconnect existing sessions.
  176. // This also closes the gate for any new registrations on the peer set.
  177. // sessions which are already established but not added to pm.peers yet
  178. // will exit when they try to register.
  179. s.peers.close()
  180. s.fcManager.Stop()
  181. s.costTracker.stop()
  182. s.handler.stop()
  183. s.clientPool.stop() // client pool should be closed after handler.
  184. s.servingQueue.stop()
  185. // Note, bloom trie indexer is closed by parent bloombits indexer.
  186. s.chtIndexer.Close()
  187. s.wg.Wait()
  188. log.Info("Les server stopped")
  189. }
  190. func (s *LesServer) SetBloomBitsIndexer(bloomIndexer *core.ChainIndexer) {
  191. bloomIndexer.AddChildIndexer(s.bloomTrieIndexer)
  192. }
  193. // SetClient sets the rpc client and starts running checkpoint contract if it is not yet watched.
  194. func (s *LesServer) SetContractBackend(backend bind.ContractBackend) {
  195. if s.oracle == nil {
  196. return
  197. }
  198. s.oracle.Start(backend)
  199. }
  200. // capacityManagement starts an event handler loop that updates the recharge curve of
  201. // the client manager and adjusts the client pool's size according to the total
  202. // capacity updates coming from the client manager
  203. func (s *LesServer) capacityManagement() {
  204. defer s.wg.Done()
  205. processCh := make(chan bool, 100)
  206. sub := s.handler.blockchain.SubscribeBlockProcessingEvent(processCh)
  207. defer sub.Unsubscribe()
  208. totalRechargeCh := make(chan uint64, 100)
  209. totalRecharge := s.costTracker.subscribeTotalRecharge(totalRechargeCh)
  210. totalCapacityCh := make(chan uint64, 100)
  211. totalCapacity := s.fcManager.SubscribeTotalCapacity(totalCapacityCh)
  212. s.clientPool.setLimits(s.config.LightPeers, totalCapacity)
  213. var (
  214. busy bool
  215. freePeers uint64
  216. blockProcess mclock.AbsTime
  217. )
  218. updateRecharge := func() {
  219. if busy {
  220. s.servingQueue.setThreads(s.threadsBusy)
  221. s.fcManager.SetRechargeCurve(flowcontrol.PieceWiseLinear{{0, 0}, {totalRecharge, totalRecharge}})
  222. } else {
  223. s.servingQueue.setThreads(s.threadsIdle)
  224. s.fcManager.SetRechargeCurve(flowcontrol.PieceWiseLinear{{0, 0}, {totalRecharge / 10, totalRecharge}, {totalRecharge, totalRecharge}})
  225. }
  226. }
  227. updateRecharge()
  228. for {
  229. select {
  230. case busy = <-processCh:
  231. if busy {
  232. blockProcess = mclock.Now()
  233. } else {
  234. blockProcessingTimer.Update(time.Duration(mclock.Now() - blockProcess))
  235. }
  236. updateRecharge()
  237. case totalRecharge = <-totalRechargeCh:
  238. totalRechargeGauge.Update(int64(totalRecharge))
  239. updateRecharge()
  240. case totalCapacity = <-totalCapacityCh:
  241. totalCapacityGauge.Update(int64(totalCapacity))
  242. newFreePeers := totalCapacity / s.freeCapacity
  243. if newFreePeers < freePeers && newFreePeers < uint64(s.config.LightPeers) {
  244. log.Warn("Reduced free peer connections", "from", freePeers, "to", newFreePeers)
  245. }
  246. freePeers = newFreePeers
  247. s.clientPool.setLimits(s.config.LightPeers, totalCapacity)
  248. case <-s.closeCh:
  249. return
  250. }
  251. }
  252. }