server.go 9.9 KB

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