server.go 10 KB

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