server.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. "reflect"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common/mclock"
  22. "github.com/ethereum/go-ethereum/eth"
  23. "github.com/ethereum/go-ethereum/les/flowcontrol"
  24. lps "github.com/ethereum/go-ethereum/les/lespay/server"
  25. "github.com/ethereum/go-ethereum/light"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/node"
  28. "github.com/ethereum/go-ethereum/p2p"
  29. "github.com/ethereum/go-ethereum/p2p/enode"
  30. "github.com/ethereum/go-ethereum/p2p/enr"
  31. "github.com/ethereum/go-ethereum/p2p/nodestate"
  32. "github.com/ethereum/go-ethereum/params"
  33. "github.com/ethereum/go-ethereum/rpc"
  34. )
  35. var (
  36. serverSetup = &nodestate.Setup{}
  37. clientPeerField = serverSetup.NewField("clientPeer", reflect.TypeOf(&clientPeer{}))
  38. clientInfoField = serverSetup.NewField("clientInfo", reflect.TypeOf(&clientInfo{}))
  39. connAddressField = serverSetup.NewField("connAddr", reflect.TypeOf(""))
  40. balanceTrackerSetup = lps.NewBalanceTrackerSetup(serverSetup)
  41. priorityPoolSetup = lps.NewPriorityPoolSetup(serverSetup)
  42. )
  43. func init() {
  44. balanceTrackerSetup.Connect(connAddressField, priorityPoolSetup.CapacityField)
  45. priorityPoolSetup.Connect(balanceTrackerSetup.BalanceField, balanceTrackerSetup.UpdateFlag) // NodeBalance implements nodePriority
  46. }
  47. type LesServer struct {
  48. lesCommons
  49. ns *nodestate.NodeStateMachine
  50. archiveMode bool // Flag whether the ethereum node runs in archive mode.
  51. handler *serverHandler
  52. broadcaster *broadcaster
  53. privateKey *ecdsa.PrivateKey
  54. // Flow control and capacity management
  55. fcManager *flowcontrol.ClientManager
  56. costTracker *costTracker
  57. defParams flowcontrol.ServerParams
  58. servingQueue *servingQueue
  59. clientPool *clientPool
  60. minCapacity, maxCapacity uint64
  61. threadsIdle int // Request serving threads count when system is idle.
  62. threadsBusy int // Request serving threads count when system is busy(block insertion).
  63. p2pSrv *p2p.Server
  64. }
  65. func NewLesServer(node *node.Node, e *eth.Ethereum, config *eth.Config) (*LesServer, error) {
  66. ns := nodestate.NewNodeStateMachine(nil, nil, mclock.System{}, serverSetup)
  67. // Calculate the number of threads used to service the light client
  68. // requests based on the user-specified value.
  69. threads := config.LightServ * 4 / 100
  70. if threads < 4 {
  71. threads = 4
  72. }
  73. srv := &LesServer{
  74. lesCommons: lesCommons{
  75. genesis: e.BlockChain().Genesis().Hash(),
  76. config: config,
  77. chainConfig: e.BlockChain().Config(),
  78. iConfig: light.DefaultServerIndexerConfig,
  79. chainDb: e.ChainDb(),
  80. chainReader: e.BlockChain(),
  81. chtIndexer: light.NewChtIndexer(e.ChainDb(), nil, params.CHTFrequency, params.HelperTrieProcessConfirmations, true),
  82. bloomTrieIndexer: light.NewBloomTrieIndexer(e.ChainDb(), nil, params.BloomBitsBlocks, params.BloomTrieFrequency, true),
  83. closeCh: make(chan struct{}),
  84. },
  85. ns: ns,
  86. archiveMode: e.ArchiveMode(),
  87. broadcaster: newBroadcaster(ns),
  88. fcManager: flowcontrol.NewClientManager(nil, &mclock.System{}),
  89. servingQueue: newServingQueue(int64(time.Millisecond*10), float64(config.LightServ)/100),
  90. threadsBusy: config.LightServ/100 + 1,
  91. threadsIdle: threads,
  92. p2pSrv: node.Server(),
  93. }
  94. srv.handler = newServerHandler(srv, e.BlockChain(), e.ChainDb(), e.TxPool(), e.Synced)
  95. srv.costTracker, srv.minCapacity = newCostTracker(e.ChainDb(), config)
  96. srv.oracle = srv.setupOracle(node, e.BlockChain().Genesis().Hash(), config)
  97. // Initialize the bloom trie indexer.
  98. e.BloomIndexer().AddChildIndexer(srv.bloomTrieIndexer)
  99. // Initialize server capacity management fields.
  100. srv.defParams = flowcontrol.ServerParams{
  101. BufLimit: srv.minCapacity * bufLimitRatio,
  102. MinRecharge: srv.minCapacity,
  103. }
  104. // LES flow control tries to more or less guarantee the possibility for the
  105. // clients to send a certain amount of requests at any time and get a quick
  106. // response. Most of the clients want this guarantee but don't actually need
  107. // to send requests most of the time. Our goal is to serve as many clients as
  108. // possible while the actually used server capacity does not exceed the limits
  109. totalRecharge := srv.costTracker.totalRecharge()
  110. srv.maxCapacity = srv.minCapacity * uint64(srv.config.LightPeers)
  111. if totalRecharge > srv.maxCapacity {
  112. srv.maxCapacity = totalRecharge
  113. }
  114. srv.fcManager.SetCapacityLimits(srv.minCapacity, srv.maxCapacity, srv.minCapacity*2)
  115. srv.clientPool = newClientPool(ns, srv.chainDb, srv.minCapacity, defaultConnectedBias, mclock.System{}, srv.dropClient)
  116. srv.clientPool.setDefaultFactors(lps.PriceFactors{TimeFactor: 0, CapacityFactor: 1, RequestFactor: 1}, lps.PriceFactors{TimeFactor: 0, CapacityFactor: 1, RequestFactor: 1})
  117. checkpoint := srv.latestLocalCheckpoint()
  118. if !checkpoint.Empty() {
  119. log.Info("Loaded latest checkpoint", "section", checkpoint.SectionIndex, "head", checkpoint.SectionHead,
  120. "chtroot", checkpoint.CHTRoot, "bloomroot", checkpoint.BloomRoot)
  121. }
  122. srv.chtIndexer.Start(e.BlockChain())
  123. node.RegisterProtocols(srv.Protocols())
  124. node.RegisterAPIs(srv.APIs())
  125. node.RegisterLifecycle(srv)
  126. // disconnect all peers at nsm shutdown
  127. ns.SubscribeField(clientPeerField, func(node *enode.Node, state nodestate.Flags, oldValue, newValue interface{}) {
  128. if state.Equals(serverSetup.OfflineFlag()) && oldValue != nil {
  129. oldValue.(*clientPeer).Peer.Disconnect(p2p.DiscRequested)
  130. }
  131. })
  132. ns.Start()
  133. return srv, nil
  134. }
  135. func (s *LesServer) APIs() []rpc.API {
  136. return []rpc.API{
  137. {
  138. Namespace: "les",
  139. Version: "1.0",
  140. Service: NewPrivateLightAPI(&s.lesCommons),
  141. Public: false,
  142. },
  143. {
  144. Namespace: "les",
  145. Version: "1.0",
  146. Service: NewPrivateLightServerAPI(s),
  147. Public: false,
  148. },
  149. {
  150. Namespace: "debug",
  151. Version: "1.0",
  152. Service: NewPrivateDebugAPI(s),
  153. Public: false,
  154. },
  155. }
  156. }
  157. func (s *LesServer) Protocols() []p2p.Protocol {
  158. ps := s.makeProtocols(ServerProtocolVersions, s.handler.runPeer, func(id enode.ID) interface{} {
  159. if p := s.getClient(id); p != nil {
  160. return p.Info()
  161. }
  162. return nil
  163. }, nil)
  164. // Add "les" ENR entries.
  165. for i := range ps {
  166. ps[i].Attributes = []enr.Entry{&lesEntry{}}
  167. }
  168. return ps
  169. }
  170. // Start starts the LES server
  171. func (s *LesServer) Start() error {
  172. s.privateKey = s.p2pSrv.PrivateKey
  173. s.broadcaster.setSignerKey(s.privateKey)
  174. s.handler.start()
  175. s.wg.Add(1)
  176. go s.capacityManagement()
  177. return nil
  178. }
  179. // Stop stops the LES service
  180. func (s *LesServer) Stop() error {
  181. close(s.closeCh)
  182. s.clientPool.stop()
  183. s.ns.Stop()
  184. s.fcManager.Stop()
  185. s.costTracker.stop()
  186. s.handler.stop()
  187. s.servingQueue.stop()
  188. // Note, bloom trie indexer is closed by parent bloombits indexer.
  189. s.chtIndexer.Close()
  190. s.wg.Wait()
  191. log.Info("Les server stopped")
  192. return nil
  193. }
  194. // capacityManagement starts an event handler loop that updates the recharge curve of
  195. // the client manager and adjusts the client pool's size according to the total
  196. // capacity updates coming from the client manager
  197. func (s *LesServer) capacityManagement() {
  198. defer s.wg.Done()
  199. processCh := make(chan bool, 100)
  200. sub := s.handler.blockchain.SubscribeBlockProcessingEvent(processCh)
  201. defer sub.Unsubscribe()
  202. totalRechargeCh := make(chan uint64, 100)
  203. totalRecharge := s.costTracker.subscribeTotalRecharge(totalRechargeCh)
  204. totalCapacityCh := make(chan uint64, 100)
  205. totalCapacity := s.fcManager.SubscribeTotalCapacity(totalCapacityCh)
  206. s.clientPool.setLimits(s.config.LightPeers, totalCapacity)
  207. var (
  208. busy bool
  209. freePeers uint64
  210. blockProcess mclock.AbsTime
  211. )
  212. updateRecharge := func() {
  213. if busy {
  214. s.servingQueue.setThreads(s.threadsBusy)
  215. s.fcManager.SetRechargeCurve(flowcontrol.PieceWiseLinear{{0, 0}, {totalRecharge, totalRecharge}})
  216. } else {
  217. s.servingQueue.setThreads(s.threadsIdle)
  218. s.fcManager.SetRechargeCurve(flowcontrol.PieceWiseLinear{{0, 0}, {totalRecharge / 10, totalRecharge}, {totalRecharge, totalRecharge}})
  219. }
  220. }
  221. updateRecharge()
  222. for {
  223. select {
  224. case busy = <-processCh:
  225. if busy {
  226. blockProcess = mclock.Now()
  227. } else {
  228. blockProcessingTimer.Update(time.Duration(mclock.Now() - blockProcess))
  229. }
  230. updateRecharge()
  231. case totalRecharge = <-totalRechargeCh:
  232. totalRechargeGauge.Update(int64(totalRecharge))
  233. updateRecharge()
  234. case totalCapacity = <-totalCapacityCh:
  235. totalCapacityGauge.Update(int64(totalCapacity))
  236. newFreePeers := totalCapacity / s.minCapacity
  237. if newFreePeers < freePeers && newFreePeers < uint64(s.config.LightPeers) {
  238. log.Warn("Reduced free peer connections", "from", freePeers, "to", newFreePeers)
  239. }
  240. freePeers = newFreePeers
  241. s.clientPool.setLimits(s.config.LightPeers, totalCapacity)
  242. case <-s.closeCh:
  243. return
  244. }
  245. }
  246. }
  247. func (s *LesServer) getClient(id enode.ID) *clientPeer {
  248. if node := s.ns.GetNode(id); node != nil {
  249. if p, ok := s.ns.GetField(node, clientPeerField).(*clientPeer); ok {
  250. return p
  251. }
  252. }
  253. return nil
  254. }
  255. func (s *LesServer) dropClient(id enode.ID) {
  256. if p := s.getClient(id); p != nil {
  257. p.Peer.Disconnect(p2p.DiscRequested)
  258. }
  259. }