clientpool.go 16 KB

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