clientpool.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2019 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. "fmt"
  19. "sync"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common/mclock"
  22. "github.com/ethereum/go-ethereum/ethdb"
  23. "github.com/ethereum/go-ethereum/les/utils"
  24. "github.com/ethereum/go-ethereum/les/vflux"
  25. vfs "github.com/ethereum/go-ethereum/les/vflux/server"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/p2p/enode"
  28. "github.com/ethereum/go-ethereum/p2p/enr"
  29. "github.com/ethereum/go-ethereum/p2p/nodestate"
  30. "github.com/ethereum/go-ethereum/rlp"
  31. )
  32. const (
  33. defaultNegExpTC = 3600 // default time constant (in seconds) for exponentially reducing negative balance
  34. // defaultConnectedBias is applied to already connected clients So that
  35. // already connected client won't be kicked out very soon and we
  36. // can ensure all connected clients can have enough time to request
  37. // or sync some data.
  38. //
  39. // todo(rjl493456442) make it configurable. It can be the option of
  40. // free trial time!
  41. defaultConnectedBias = time.Minute * 3
  42. inactiveTimeout = time.Second * 10
  43. )
  44. // clientPool implements a client database that assigns a priority to each client
  45. // based on a positive and negative balance. Positive balance is externally assigned
  46. // to prioritized clients and is decreased with connection time and processed
  47. // requests (unless the price factors are zero). If the positive balance is zero
  48. // then negative balance is accumulated.
  49. //
  50. // Balance tracking and priority calculation for connected clients is done by
  51. // balanceTracker. activeQueue ensures that clients with the lowest positive or
  52. // highest negative balance get evicted when the total capacity allowance is full
  53. // and new clients with a better balance want to connect.
  54. //
  55. // Already connected nodes receive a small bias in their favor in order to avoid
  56. // accepting and instantly kicking out clients. In theory, we try to ensure that
  57. // each client can have several minutes of connection time.
  58. //
  59. // Balances of disconnected clients are stored in nodeDB including positive balance
  60. // and negative banalce. Boeth positive balance and negative balance will decrease
  61. // exponentially. If the balance is low enough, then the record will be dropped.
  62. type clientPool struct {
  63. vfs.BalanceTrackerSetup
  64. vfs.PriorityPoolSetup
  65. lock sync.Mutex
  66. clock mclock.Clock
  67. closed bool
  68. removePeer func(enode.ID)
  69. ns *nodestate.NodeStateMachine
  70. pp *vfs.PriorityPool
  71. bt *vfs.BalanceTracker
  72. defaultPosFactors, defaultNegFactors vfs.PriceFactors
  73. posExpTC, negExpTC uint64
  74. minCap uint64 // The minimal capacity value allowed for any client
  75. connectedBias time.Duration
  76. capLimit uint64
  77. }
  78. // clientPoolPeer represents a client peer in the pool.
  79. // Positive balances are assigned to node key while negative balances are assigned
  80. // to freeClientId. Currently network IP address without port is used because
  81. // clients have a limited access to IP addresses while new node keys can be easily
  82. // generated so it would be useless to assign a negative value to them.
  83. type clientPoolPeer interface {
  84. Node() *enode.Node
  85. freeClientId() string
  86. updateCapacity(uint64)
  87. freeze()
  88. allowInactive() bool
  89. }
  90. // clientInfo defines all information required by clientpool.
  91. type clientInfo struct {
  92. node *enode.Node
  93. address string
  94. peer clientPoolPeer
  95. connected, priority bool
  96. connectedAt mclock.AbsTime
  97. balance *vfs.NodeBalance
  98. }
  99. // newClientPool creates a new client pool
  100. func newClientPool(ns *nodestate.NodeStateMachine, lesDb ethdb.Database, minCap uint64, connectedBias time.Duration, clock mclock.Clock, removePeer func(enode.ID)) *clientPool {
  101. pool := &clientPool{
  102. ns: ns,
  103. BalanceTrackerSetup: balanceTrackerSetup,
  104. PriorityPoolSetup: priorityPoolSetup,
  105. clock: clock,
  106. minCap: minCap,
  107. connectedBias: connectedBias,
  108. removePeer: removePeer,
  109. }
  110. pool.bt = vfs.NewBalanceTracker(ns, balanceTrackerSetup, lesDb, clock, &utils.Expirer{}, &utils.Expirer{})
  111. pool.pp = vfs.NewPriorityPool(ns, priorityPoolSetup, clock, minCap, connectedBias, 4)
  112. // set default expiration constants used by tests
  113. // Note: server overwrites this if token sale is active
  114. pool.bt.SetExpirationTCs(0, defaultNegExpTC)
  115. ns.SubscribeState(pool.InactiveFlag.Or(pool.PriorityFlag), func(node *enode.Node, oldState, newState nodestate.Flags) {
  116. if newState.Equals(pool.InactiveFlag) {
  117. ns.AddTimeout(node, pool.InactiveFlag, inactiveTimeout)
  118. }
  119. if oldState.Equals(pool.InactiveFlag) && newState.Equals(pool.InactiveFlag.Or(pool.PriorityFlag)) {
  120. ns.SetStateSub(node, pool.InactiveFlag, nodestate.Flags{}, 0) // remove timeout
  121. }
  122. })
  123. ns.SubscribeState(pool.ActiveFlag.Or(pool.PriorityFlag), func(node *enode.Node, oldState, newState nodestate.Flags) {
  124. c, _ := ns.GetField(node, clientInfoField).(*clientInfo)
  125. if c == nil {
  126. return
  127. }
  128. c.priority = newState.HasAll(pool.PriorityFlag)
  129. if newState.Equals(pool.ActiveFlag) {
  130. cap, _ := ns.GetField(node, pool.CapacityField).(uint64)
  131. if cap > minCap {
  132. pool.pp.RequestCapacity(node, minCap, 0, true)
  133. }
  134. }
  135. })
  136. ns.SubscribeState(pool.InactiveFlag.Or(pool.ActiveFlag), func(node *enode.Node, oldState, newState nodestate.Flags) {
  137. if oldState.IsEmpty() {
  138. clientConnectedMeter.Mark(1)
  139. log.Debug("Client connected", "id", node.ID())
  140. }
  141. if oldState.Equals(pool.InactiveFlag) && newState.Equals(pool.ActiveFlag) {
  142. clientActivatedMeter.Mark(1)
  143. log.Debug("Client activated", "id", node.ID())
  144. }
  145. if oldState.Equals(pool.ActiveFlag) && newState.Equals(pool.InactiveFlag) {
  146. clientDeactivatedMeter.Mark(1)
  147. log.Debug("Client deactivated", "id", node.ID())
  148. c, _ := ns.GetField(node, clientInfoField).(*clientInfo)
  149. if c == nil || !c.peer.allowInactive() {
  150. pool.removePeer(node.ID())
  151. }
  152. }
  153. if newState.IsEmpty() {
  154. clientDisconnectedMeter.Mark(1)
  155. log.Debug("Client disconnected", "id", node.ID())
  156. pool.removePeer(node.ID())
  157. }
  158. })
  159. var totalConnected uint64
  160. ns.SubscribeField(pool.CapacityField, func(node *enode.Node, state nodestate.Flags, oldValue, newValue interface{}) {
  161. oldCap, _ := oldValue.(uint64)
  162. newCap, _ := newValue.(uint64)
  163. totalConnected += newCap - oldCap
  164. totalConnectedGauge.Update(int64(totalConnected))
  165. c, _ := ns.GetField(node, clientInfoField).(*clientInfo)
  166. if c != nil {
  167. c.peer.updateCapacity(newCap)
  168. }
  169. })
  170. return pool
  171. }
  172. // stop shuts the client pool down
  173. func (f *clientPool) stop() {
  174. f.lock.Lock()
  175. f.closed = true
  176. f.lock.Unlock()
  177. f.ns.ForEach(nodestate.Flags{}, nodestate.Flags{}, func(node *enode.Node, state nodestate.Flags) {
  178. // enforces saving all balances in BalanceTracker
  179. f.disconnectNode(node)
  180. })
  181. f.bt.Stop()
  182. }
  183. // connect should be called after a successful handshake. If the connection was
  184. // rejected, there is no need to call disconnect.
  185. func (f *clientPool) connect(peer clientPoolPeer) (uint64, error) {
  186. f.lock.Lock()
  187. defer f.lock.Unlock()
  188. // Short circuit if clientPool is already closed.
  189. if f.closed {
  190. return 0, fmt.Errorf("Client pool is already closed")
  191. }
  192. // Dedup connected peers.
  193. node, freeID := peer.Node(), peer.freeClientId()
  194. if f.ns.GetField(node, clientInfoField) != nil {
  195. log.Debug("Client already connected", "address", freeID, "id", node.ID().String())
  196. return 0, fmt.Errorf("Client already connected address=%s id=%s", freeID, node.ID().String())
  197. }
  198. now := f.clock.Now()
  199. c := &clientInfo{
  200. node: node,
  201. address: freeID,
  202. peer: peer,
  203. connected: true,
  204. connectedAt: now,
  205. }
  206. f.ns.SetField(node, clientInfoField, c)
  207. f.ns.SetField(node, connAddressField, freeID)
  208. if c.balance, _ = f.ns.GetField(node, f.BalanceField).(*vfs.NodeBalance); c.balance == nil {
  209. f.disconnect(peer)
  210. return 0, nil
  211. }
  212. c.balance.SetPriceFactors(f.defaultPosFactors, f.defaultNegFactors)
  213. f.ns.SetState(node, f.InactiveFlag, nodestate.Flags{}, 0)
  214. var allowed bool
  215. f.ns.Operation(func() {
  216. _, allowed = f.pp.RequestCapacity(node, f.minCap, f.connectedBias, true)
  217. })
  218. if allowed {
  219. return f.minCap, nil
  220. }
  221. if !peer.allowInactive() {
  222. f.disconnect(peer)
  223. }
  224. return 0, nil
  225. }
  226. // setConnectedBias sets the connection bias, which is applied to already connected clients
  227. // So that already connected client won't be kicked out very soon and we can ensure all
  228. // connected clients can have enough time to request or sync some data.
  229. func (f *clientPool) setConnectedBias(bias time.Duration) {
  230. f.lock.Lock()
  231. defer f.lock.Unlock()
  232. f.connectedBias = bias
  233. f.pp.SetActiveBias(bias)
  234. }
  235. // disconnect should be called when a connection is terminated. If the disconnection
  236. // was initiated by the pool itself using disconnectFn then calling disconnect is
  237. // not necessary but permitted.
  238. func (f *clientPool) disconnect(p clientPoolPeer) {
  239. f.disconnectNode(p.Node())
  240. }
  241. // disconnectNode removes node fields and flags related to connected status
  242. func (f *clientPool) disconnectNode(node *enode.Node) {
  243. f.ns.SetField(node, connAddressField, nil)
  244. f.ns.SetField(node, clientInfoField, nil)
  245. }
  246. // setDefaultFactors sets the default price factors applied to subsequently connected clients
  247. func (f *clientPool) setDefaultFactors(posFactors, negFactors vfs.PriceFactors) {
  248. f.lock.Lock()
  249. defer f.lock.Unlock()
  250. f.defaultPosFactors = posFactors
  251. f.defaultNegFactors = negFactors
  252. }
  253. // capacityInfo returns the total capacity allowance, the total capacity of connected
  254. // clients and the total capacity of connected and prioritized clients
  255. func (f *clientPool) capacityInfo() (uint64, uint64, uint64) {
  256. f.lock.Lock()
  257. defer f.lock.Unlock()
  258. // total priority active cap will be supported when the token issuer module is added
  259. _, activeCap := f.pp.Active()
  260. return f.capLimit, activeCap, 0
  261. }
  262. // setLimits sets the maximum number and total capacity of connected clients,
  263. // dropping some of them if necessary.
  264. func (f *clientPool) setLimits(totalConn int, totalCap uint64) {
  265. f.lock.Lock()
  266. defer f.lock.Unlock()
  267. f.capLimit = totalCap
  268. f.pp.SetLimits(uint64(totalConn), totalCap)
  269. }
  270. // setCapacity sets the assigned capacity of a connected client
  271. func (f *clientPool) setCapacity(node *enode.Node, freeID string, capacity uint64, bias time.Duration, setCap bool) (uint64, error) {
  272. c, _ := f.ns.GetField(node, clientInfoField).(*clientInfo)
  273. if c == nil {
  274. if setCap {
  275. return 0, fmt.Errorf("client %064x is not connected", node.ID())
  276. }
  277. c = &clientInfo{node: node}
  278. f.ns.SetField(node, clientInfoField, c)
  279. f.ns.SetField(node, connAddressField, freeID)
  280. if c.balance, _ = f.ns.GetField(node, f.BalanceField).(*vfs.NodeBalance); c.balance == nil {
  281. log.Error("BalanceField is missing", "node", node.ID())
  282. return 0, fmt.Errorf("BalanceField of %064x is missing", node.ID())
  283. }
  284. defer func() {
  285. f.ns.SetField(node, connAddressField, nil)
  286. f.ns.SetField(node, clientInfoField, nil)
  287. }()
  288. }
  289. var (
  290. minPriority int64
  291. allowed bool
  292. )
  293. f.ns.Operation(func() {
  294. if !setCap || c.priority {
  295. // check clientInfo.priority inside Operation to ensure thread safety
  296. minPriority, allowed = f.pp.RequestCapacity(node, capacity, bias, setCap)
  297. }
  298. })
  299. if allowed {
  300. return 0, nil
  301. }
  302. missing := c.balance.PosBalanceMissing(minPriority, capacity, bias)
  303. if missing < 1 {
  304. // ensure that we never return 0 missing and insufficient priority error
  305. missing = 1
  306. }
  307. return missing, errNoPriority
  308. }
  309. // setCapacityLocked is the equivalent of setCapacity used when f.lock is already locked
  310. func (f *clientPool) setCapacityLocked(node *enode.Node, freeID string, capacity uint64, minConnTime time.Duration, setCap bool) (uint64, error) {
  311. f.lock.Lock()
  312. defer f.lock.Unlock()
  313. return f.setCapacity(node, freeID, capacity, minConnTime, setCap)
  314. }
  315. // forClients calls the supplied callback for either the listed node IDs or all connected
  316. // nodes. It passes a valid clientInfo to the callback and ensures that the necessary
  317. // fields and flags are set in order for BalanceTracker and PriorityPool to work even if
  318. // the node is not connected.
  319. func (f *clientPool) forClients(ids []enode.ID, cb func(client *clientInfo)) {
  320. f.lock.Lock()
  321. defer f.lock.Unlock()
  322. if len(ids) == 0 {
  323. f.ns.ForEach(nodestate.Flags{}, nodestate.Flags{}, func(node *enode.Node, state nodestate.Flags) {
  324. c, _ := f.ns.GetField(node, clientInfoField).(*clientInfo)
  325. if c != nil {
  326. cb(c)
  327. }
  328. })
  329. } else {
  330. for _, id := range ids {
  331. node := f.ns.GetNode(id)
  332. if node == nil {
  333. node = enode.SignNull(&enr.Record{}, id)
  334. }
  335. c, _ := f.ns.GetField(node, clientInfoField).(*clientInfo)
  336. if c != nil {
  337. cb(c)
  338. } else {
  339. c = &clientInfo{node: node}
  340. f.ns.SetField(node, clientInfoField, c)
  341. f.ns.SetField(node, connAddressField, "")
  342. if c.balance, _ = f.ns.GetField(node, f.BalanceField).(*vfs.NodeBalance); c.balance != nil {
  343. cb(c)
  344. } else {
  345. log.Error("BalanceField is missing")
  346. }
  347. f.ns.SetField(node, connAddressField, nil)
  348. f.ns.SetField(node, clientInfoField, nil)
  349. }
  350. }
  351. }
  352. }
  353. // serveCapQuery serves a vflux capacity query. It receives multiple token amount values
  354. // and a bias time value. For each given token amount it calculates the maximum achievable
  355. // capacity in case the amount is added to the balance.
  356. func (f *clientPool) serveCapQuery(id enode.ID, freeID string, data []byte) []byte {
  357. var req vflux.CapacityQueryReq
  358. if rlp.DecodeBytes(data, &req) != nil {
  359. return nil
  360. }
  361. if l := len(req.AddTokens); l == 0 || l > vflux.CapacityQueryMaxLen {
  362. return nil
  363. }
  364. node := f.ns.GetNode(id)
  365. if node == nil {
  366. node = enode.SignNull(&enr.Record{}, id)
  367. }
  368. c, _ := f.ns.GetField(node, clientInfoField).(*clientInfo)
  369. if c == nil {
  370. c = &clientInfo{node: node}
  371. f.ns.SetField(node, clientInfoField, c)
  372. f.ns.SetField(node, connAddressField, freeID)
  373. defer func() {
  374. f.ns.SetField(node, connAddressField, nil)
  375. f.ns.SetField(node, clientInfoField, nil)
  376. }()
  377. if c.balance, _ = f.ns.GetField(node, f.BalanceField).(*vfs.NodeBalance); c.balance == nil {
  378. log.Error("BalanceField is missing", "node", node.ID())
  379. return nil
  380. }
  381. }
  382. // use vfs.CapacityCurve to answer request for multiple newly bought token amounts
  383. curve := f.pp.GetCapacityCurve().Exclude(id)
  384. result := make(vflux.CapacityQueryReply, len(req.AddTokens))
  385. bias := time.Second * time.Duration(req.Bias)
  386. if f.connectedBias > bias {
  387. bias = f.connectedBias
  388. }
  389. pb, _ := c.balance.GetBalance()
  390. for i, addTokens := range req.AddTokens {
  391. add := addTokens.Int64()
  392. result[i] = curve.MaxCapacity(func(capacity uint64) int64 {
  393. return c.balance.EstimatePriority(capacity, add, 0, bias, false) / int64(capacity)
  394. })
  395. if add <= 0 && uint64(-add) >= pb && result[i] > f.minCap {
  396. result[i] = f.minCap
  397. }
  398. if result[i] < f.minCap {
  399. result[i] = 0
  400. }
  401. }
  402. reply, _ := rlp.EncodeToBytes(&result)
  403. return reply
  404. }