server.go 10 KB

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