server.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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/common/mclock"
  21. "github.com/ethereum/go-ethereum/eth"
  22. "github.com/ethereum/go-ethereum/les/flowcontrol"
  23. "github.com/ethereum/go-ethereum/light"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/node"
  26. "github.com/ethereum/go-ethereum/p2p"
  27. "github.com/ethereum/go-ethereum/p2p/discv5"
  28. "github.com/ethereum/go-ethereum/p2p/enode"
  29. "github.com/ethereum/go-ethereum/p2p/enr"
  30. "github.com/ethereum/go-ethereum/params"
  31. "github.com/ethereum/go-ethereum/rpc"
  32. )
  33. type LesServer struct {
  34. lesCommons
  35. archiveMode bool // Flag whether the ethereum node runs in archive mode.
  36. peers *clientPeerSet
  37. handler *serverHandler
  38. lesTopics []discv5.Topic
  39. privateKey *ecdsa.PrivateKey
  40. // Flow control and capacity management
  41. fcManager *flowcontrol.ClientManager
  42. costTracker *costTracker
  43. defParams flowcontrol.ServerParams
  44. servingQueue *servingQueue
  45. clientPool *clientPool
  46. minCapacity, maxCapacity, freeCapacity uint64
  47. threadsIdle int // Request serving threads count when system is idle.
  48. threadsBusy int // Request serving threads count when system is busy(block insertion).
  49. p2pSrv *p2p.Server
  50. }
  51. func NewLesServer(node *node.Node, e *eth.Ethereum, config *eth.Config) (*LesServer, error) {
  52. // Collect les protocol version information supported by local node.
  53. lesTopics := make([]discv5.Topic, len(AdvertiseProtocolVersions))
  54. for i, pv := range AdvertiseProtocolVersions {
  55. lesTopics[i] = lesTopic(e.BlockChain().Genesis().Hash(), pv)
  56. }
  57. // Calculate the number of threads used to service the light client
  58. // requests based on the user-specified value.
  59. threads := config.LightServ * 4 / 100
  60. if threads < 4 {
  61. threads = 4
  62. }
  63. srv := &LesServer{
  64. lesCommons: lesCommons{
  65. genesis: e.BlockChain().Genesis().Hash(),
  66. config: config,
  67. chainConfig: e.BlockChain().Config(),
  68. iConfig: light.DefaultServerIndexerConfig,
  69. chainDb: e.ChainDb(),
  70. chainReader: e.BlockChain(),
  71. chtIndexer: light.NewChtIndexer(e.ChainDb(), nil, params.CHTFrequency, params.HelperTrieProcessConfirmations, true),
  72. bloomTrieIndexer: light.NewBloomTrieIndexer(e.ChainDb(), nil, params.BloomBitsBlocks, params.BloomTrieFrequency, true),
  73. closeCh: make(chan struct{}),
  74. },
  75. archiveMode: e.ArchiveMode(),
  76. peers: newClientPeerSet(),
  77. lesTopics: lesTopics,
  78. fcManager: flowcontrol.NewClientManager(nil, &mclock.System{}),
  79. servingQueue: newServingQueue(int64(time.Millisecond*10), float64(config.LightServ)/100),
  80. threadsBusy: config.LightServ/100 + 1,
  81. threadsIdle: threads,
  82. p2pSrv: node.Server(),
  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. srv.oracle = srv.setupOracle(node, e.BlockChain().Genesis().Hash(), config)
  88. // Initialize the bloom trie indexer.
  89. e.BloomIndexer().AddChildIndexer(srv.bloomTrieIndexer)
  90. // Initialize server capacity management fields.
  91. srv.defParams = flowcontrol.ServerParams{
  92. BufLimit: srv.freeCapacity * bufLimitRatio,
  93. MinRecharge: srv.freeCapacity,
  94. }
  95. // LES flow control tries to more or less guarantee the possibility for the
  96. // clients to send a certain amount of requests at any time and get a quick
  97. // response. Most of the clients want this guarantee but don't actually need
  98. // to send requests most of the time. Our goal is to serve as many clients as
  99. // possible while the actually used server capacity does not exceed the limits
  100. totalRecharge := srv.costTracker.totalRecharge()
  101. srv.maxCapacity = srv.freeCapacity * uint64(srv.config.LightPeers)
  102. if totalRecharge > srv.maxCapacity {
  103. srv.maxCapacity = totalRecharge
  104. }
  105. srv.fcManager.SetCapacityLimits(srv.freeCapacity, srv.maxCapacity, srv.freeCapacity*2)
  106. srv.clientPool = newClientPool(srv.chainDb, srv.freeCapacity, mclock.System{}, func(id enode.ID) { go srv.peers.unregister(id.String()) })
  107. srv.clientPool.setDefaultFactors(priceFactors{0, 1, 1}, priceFactors{0, 1, 1})
  108. checkpoint := srv.latestLocalCheckpoint()
  109. if !checkpoint.Empty() {
  110. log.Info("Loaded latest checkpoint", "section", checkpoint.SectionIndex, "head", checkpoint.SectionHead,
  111. "chtroot", checkpoint.CHTRoot, "bloomroot", checkpoint.BloomRoot)
  112. }
  113. srv.chtIndexer.Start(e.BlockChain())
  114. node.RegisterProtocols(srv.Protocols())
  115. node.RegisterAPIs(srv.APIs())
  116. node.RegisterLifecycle(srv)
  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(id.String()); 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() error {
  156. s.privateKey = s.p2pSrv.PrivateKey
  157. s.handler.start()
  158. s.wg.Add(1)
  159. go s.capacityManagement()
  160. if s.p2pSrv.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. s.p2pSrv.DiscV5.RegisterTopic(topic, s.closeCh)
  168. }()
  169. }
  170. }
  171. return nil
  172. }
  173. // Stop stops the LES service
  174. func (s *LesServer) Stop() error {
  175. close(s.closeCh)
  176. // Disconnect existing sessions.
  177. // This also closes the gate for any new registrations on the peer set.
  178. // sessions which are already established but not added to pm.peers yet
  179. // will exit when they try to register.
  180. s.peers.close()
  181. s.fcManager.Stop()
  182. s.costTracker.stop()
  183. s.handler.stop()
  184. s.clientPool.stop() // client pool should be closed after handler.
  185. s.servingQueue.stop()
  186. // Note, bloom trie indexer is closed by parent bloombits indexer.
  187. s.chtIndexer.Close()
  188. s.wg.Wait()
  189. log.Info("Les server stopped")
  190. return nil
  191. }
  192. // capacityManagement starts an event handler loop that updates the recharge curve of
  193. // the client manager and adjusts the client pool's size according to the total
  194. // capacity updates coming from the client manager
  195. func (s *LesServer) capacityManagement() {
  196. defer s.wg.Done()
  197. processCh := make(chan bool, 100)
  198. sub := s.handler.blockchain.SubscribeBlockProcessingEvent(processCh)
  199. defer sub.Unsubscribe()
  200. totalRechargeCh := make(chan uint64, 100)
  201. totalRecharge := s.costTracker.subscribeTotalRecharge(totalRechargeCh)
  202. totalCapacityCh := make(chan uint64, 100)
  203. totalCapacity := s.fcManager.SubscribeTotalCapacity(totalCapacityCh)
  204. s.clientPool.setLimits(s.config.LightPeers, totalCapacity)
  205. var (
  206. busy bool
  207. freePeers uint64
  208. blockProcess mclock.AbsTime
  209. )
  210. updateRecharge := func() {
  211. if busy {
  212. s.servingQueue.setThreads(s.threadsBusy)
  213. s.fcManager.SetRechargeCurve(flowcontrol.PieceWiseLinear{{0, 0}, {totalRecharge, totalRecharge}})
  214. } else {
  215. s.servingQueue.setThreads(s.threadsIdle)
  216. s.fcManager.SetRechargeCurve(flowcontrol.PieceWiseLinear{{0, 0}, {totalRecharge / 10, totalRecharge}, {totalRecharge, totalRecharge}})
  217. }
  218. }
  219. updateRecharge()
  220. for {
  221. select {
  222. case busy = <-processCh:
  223. if busy {
  224. blockProcess = mclock.Now()
  225. } else {
  226. blockProcessingTimer.Update(time.Duration(mclock.Now() - blockProcess))
  227. }
  228. updateRecharge()
  229. case totalRecharge = <-totalRechargeCh:
  230. totalRechargeGauge.Update(int64(totalRecharge))
  231. updateRecharge()
  232. case totalCapacity = <-totalCapacityCh:
  233. totalCapacityGauge.Update(int64(totalCapacity))
  234. newFreePeers := totalCapacity / s.freeCapacity
  235. if newFreePeers < freePeers && newFreePeers < uint64(s.config.LightPeers) {
  236. log.Warn("Reduced free peer connections", "from", freePeers, "to", newFreePeers)
  237. }
  238. freePeers = newFreePeers
  239. s.clientPool.setLimits(s.config.LightPeers, totalCapacity)
  240. case <-s.closeCh:
  241. return
  242. }
  243. }
  244. }