clientpool_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. "bytes"
  19. "fmt"
  20. "math"
  21. "math/rand"
  22. "reflect"
  23. "testing"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common/mclock"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/p2p/enode"
  28. )
  29. func TestClientPoolL10C100Free(t *testing.T) {
  30. testClientPool(t, 10, 100, 0, true)
  31. }
  32. func TestClientPoolL40C200Free(t *testing.T) {
  33. testClientPool(t, 40, 200, 0, true)
  34. }
  35. func TestClientPoolL100C300Free(t *testing.T) {
  36. testClientPool(t, 100, 300, 0, true)
  37. }
  38. func TestClientPoolL10C100P4(t *testing.T) {
  39. testClientPool(t, 10, 100, 4, false)
  40. }
  41. func TestClientPoolL40C200P30(t *testing.T) {
  42. testClientPool(t, 40, 200, 30, false)
  43. }
  44. func TestClientPoolL100C300P20(t *testing.T) {
  45. testClientPool(t, 100, 300, 20, false)
  46. }
  47. const testClientPoolTicks = 100000
  48. type poolTestPeer int
  49. func (i poolTestPeer) ID() enode.ID {
  50. return enode.ID{byte(i % 256), byte(i >> 8)}
  51. }
  52. func (i poolTestPeer) freeClientId() string {
  53. return fmt.Sprintf("addr #%d", i)
  54. }
  55. func (i poolTestPeer) updateCapacity(uint64) {}
  56. type poolTestPeerWithCap struct {
  57. poolTestPeer
  58. cap uint64
  59. }
  60. func (i *poolTestPeerWithCap) updateCapacity(cap uint64) { i.cap = cap }
  61. func (i poolTestPeer) freezeClient() {}
  62. func testClientPool(t *testing.T, connLimit, clientCount, paidCount int, randomDisconnect bool) {
  63. rand.Seed(time.Now().UnixNano())
  64. var (
  65. clock mclock.Simulated
  66. db = rawdb.NewMemoryDatabase()
  67. connected = make([]bool, clientCount)
  68. connTicks = make([]int, clientCount)
  69. disconnCh = make(chan int, clientCount)
  70. disconnFn = func(id enode.ID) {
  71. disconnCh <- int(id[0]) + int(id[1])<<8
  72. }
  73. pool = newClientPool(db, 1, &clock, disconnFn)
  74. )
  75. pool.disableBias = true
  76. pool.setLimits(connLimit, uint64(connLimit))
  77. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  78. // pool should accept new peers up to its connected limit
  79. for i := 0; i < connLimit; i++ {
  80. if pool.connect(poolTestPeer(i), 0) {
  81. connected[i] = true
  82. } else {
  83. t.Fatalf("Test peer #%d rejected", i)
  84. }
  85. }
  86. // randomly connect and disconnect peers, expect to have a similar total connection time at the end
  87. for tickCounter := 0; tickCounter < testClientPoolTicks; tickCounter++ {
  88. clock.Run(1 * time.Second)
  89. if tickCounter == testClientPoolTicks/4 {
  90. // give a positive balance to some of the peers
  91. amount := testClientPoolTicks / 2 * int64(time.Second) // enough for half of the simulation period
  92. for i := 0; i < paidCount; i++ {
  93. pool.addBalance(poolTestPeer(i).ID(), amount, "")
  94. }
  95. }
  96. i := rand.Intn(clientCount)
  97. if connected[i] {
  98. if randomDisconnect {
  99. pool.disconnect(poolTestPeer(i))
  100. connected[i] = false
  101. connTicks[i] += tickCounter
  102. }
  103. } else {
  104. if pool.connect(poolTestPeer(i), 0) {
  105. connected[i] = true
  106. connTicks[i] -= tickCounter
  107. }
  108. }
  109. pollDisconnects:
  110. for {
  111. select {
  112. case i := <-disconnCh:
  113. pool.disconnect(poolTestPeer(i))
  114. if connected[i] {
  115. connTicks[i] += tickCounter
  116. connected[i] = false
  117. }
  118. default:
  119. break pollDisconnects
  120. }
  121. }
  122. }
  123. expTicks := testClientPoolTicks/2*connLimit/clientCount + testClientPoolTicks/2*(connLimit-paidCount)/(clientCount-paidCount)
  124. expMin := expTicks - expTicks/5
  125. expMax := expTicks + expTicks/5
  126. paidTicks := testClientPoolTicks/2*connLimit/clientCount + testClientPoolTicks/2
  127. paidMin := paidTicks - paidTicks/5
  128. paidMax := paidTicks + paidTicks/5
  129. // check if the total connected time of peers are all in the expected range
  130. for i, c := range connected {
  131. if c {
  132. connTicks[i] += testClientPoolTicks
  133. }
  134. min, max := expMin, expMax
  135. if i < paidCount {
  136. // expect a higher amount for clients with a positive balance
  137. min, max = paidMin, paidMax
  138. }
  139. if connTicks[i] < min || connTicks[i] > max {
  140. t.Errorf("Total connected time of test node #%d (%d) outside expected range (%d to %d)", i, connTicks[i], min, max)
  141. }
  142. }
  143. pool.stop()
  144. }
  145. func TestConnectPaidClient(t *testing.T) {
  146. var (
  147. clock mclock.Simulated
  148. db = rawdb.NewMemoryDatabase()
  149. )
  150. pool := newClientPool(db, 1, &clock, nil)
  151. defer pool.stop()
  152. pool.setLimits(10, uint64(10))
  153. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  154. // Add balance for an external client and mark it as paid client
  155. pool.addBalance(poolTestPeer(0).ID(), 1000, "")
  156. if !pool.connect(poolTestPeer(0), 10) {
  157. t.Fatalf("Failed to connect paid client")
  158. }
  159. }
  160. func TestConnectPaidClientToSmallPool(t *testing.T) {
  161. var (
  162. clock mclock.Simulated
  163. db = rawdb.NewMemoryDatabase()
  164. )
  165. pool := newClientPool(db, 1, &clock, nil)
  166. defer pool.stop()
  167. pool.setLimits(10, uint64(10)) // Total capacity limit is 10
  168. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  169. // Add balance for an external client and mark it as paid client
  170. pool.addBalance(poolTestPeer(0).ID(), 1000, "")
  171. // Connect a fat paid client to pool, should reject it.
  172. if pool.connect(poolTestPeer(0), 100) {
  173. t.Fatalf("Connected fat paid client, should reject it")
  174. }
  175. }
  176. func TestConnectPaidClientToFullPool(t *testing.T) {
  177. var (
  178. clock mclock.Simulated
  179. db = rawdb.NewMemoryDatabase()
  180. )
  181. removeFn := func(enode.ID) {} // Noop
  182. pool := newClientPool(db, 1, &clock, removeFn)
  183. defer pool.stop()
  184. pool.setLimits(10, uint64(10)) // Total capacity limit is 10
  185. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  186. for i := 0; i < 10; i++ {
  187. pool.addBalance(poolTestPeer(i).ID(), 1000000000, "")
  188. pool.connect(poolTestPeer(i), 1)
  189. }
  190. pool.addBalance(poolTestPeer(11).ID(), 1000, "") // Add low balance to new paid client
  191. if pool.connect(poolTestPeer(11), 1) {
  192. t.Fatalf("Low balance paid client should be rejected")
  193. }
  194. clock.Run(time.Second)
  195. pool.addBalance(poolTestPeer(12).ID(), 1000000000*60*3, "") // Add high balance to new paid client
  196. if !pool.connect(poolTestPeer(12), 1) {
  197. t.Fatalf("High balance paid client should be accpected")
  198. }
  199. }
  200. func TestPaidClientKickedOut(t *testing.T) {
  201. var (
  202. clock mclock.Simulated
  203. db = rawdb.NewMemoryDatabase()
  204. kickedCh = make(chan int, 1)
  205. )
  206. removeFn := func(id enode.ID) { kickedCh <- int(id[0]) }
  207. pool := newClientPool(db, 1, &clock, removeFn)
  208. defer pool.stop()
  209. pool.setLimits(10, uint64(10)) // Total capacity limit is 10
  210. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  211. for i := 0; i < 10; i++ {
  212. pool.addBalance(poolTestPeer(i).ID(), 1000000000, "") // 1 second allowance
  213. pool.connect(poolTestPeer(i), 1)
  214. clock.Run(time.Millisecond)
  215. }
  216. clock.Run(time.Second)
  217. clock.Run(connectedBias)
  218. if !pool.connect(poolTestPeer(11), 0) {
  219. t.Fatalf("Free client should be accectped")
  220. }
  221. select {
  222. case id := <-kickedCh:
  223. if id != 0 {
  224. t.Fatalf("Kicked client mismatch, want %v, got %v", 0, id)
  225. }
  226. case <-time.NewTimer(time.Second).C:
  227. t.Fatalf("timeout")
  228. }
  229. }
  230. func TestConnectFreeClient(t *testing.T) {
  231. var (
  232. clock mclock.Simulated
  233. db = rawdb.NewMemoryDatabase()
  234. )
  235. pool := newClientPool(db, 1, &clock, nil)
  236. defer pool.stop()
  237. pool.setLimits(10, uint64(10))
  238. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  239. if !pool.connect(poolTestPeer(0), 10) {
  240. t.Fatalf("Failed to connect free client")
  241. }
  242. }
  243. func TestConnectFreeClientToFullPool(t *testing.T) {
  244. var (
  245. clock mclock.Simulated
  246. db = rawdb.NewMemoryDatabase()
  247. )
  248. removeFn := func(enode.ID) {} // Noop
  249. pool := newClientPool(db, 1, &clock, removeFn)
  250. defer pool.stop()
  251. pool.setLimits(10, uint64(10)) // Total capacity limit is 10
  252. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  253. for i := 0; i < 10; i++ {
  254. pool.connect(poolTestPeer(i), 1)
  255. }
  256. if pool.connect(poolTestPeer(11), 1) {
  257. t.Fatalf("New free client should be rejected")
  258. }
  259. clock.Run(time.Minute)
  260. if pool.connect(poolTestPeer(12), 1) {
  261. t.Fatalf("New free client should be rejected")
  262. }
  263. clock.Run(time.Millisecond)
  264. clock.Run(4 * time.Minute)
  265. if !pool.connect(poolTestPeer(13), 1) {
  266. t.Fatalf("Old client connects more than 5min should be kicked")
  267. }
  268. }
  269. func TestFreeClientKickedOut(t *testing.T) {
  270. var (
  271. clock mclock.Simulated
  272. db = rawdb.NewMemoryDatabase()
  273. kicked = make(chan int, 10)
  274. )
  275. removeFn := func(id enode.ID) { kicked <- int(id[0]) }
  276. pool := newClientPool(db, 1, &clock, removeFn)
  277. defer pool.stop()
  278. pool.setLimits(10, uint64(10)) // Total capacity limit is 10
  279. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  280. for i := 0; i < 10; i++ {
  281. pool.connect(poolTestPeer(i), 1)
  282. clock.Run(time.Millisecond)
  283. }
  284. if pool.connect(poolTestPeer(10), 1) {
  285. t.Fatalf("New free client should be rejected")
  286. }
  287. clock.Run(5 * time.Minute)
  288. for i := 0; i < 10; i++ {
  289. pool.connect(poolTestPeer(i+10), 1)
  290. }
  291. for i := 0; i < 10; i++ {
  292. select {
  293. case id := <-kicked:
  294. if id >= 10 {
  295. t.Fatalf("Old client should be kicked, now got: %d", id)
  296. }
  297. case <-time.NewTimer(time.Second).C:
  298. t.Fatalf("timeout")
  299. }
  300. }
  301. }
  302. func TestPositiveBalanceCalculation(t *testing.T) {
  303. var (
  304. clock mclock.Simulated
  305. db = rawdb.NewMemoryDatabase()
  306. kicked = make(chan int, 10)
  307. )
  308. removeFn := func(id enode.ID) { kicked <- int(id[0]) } // Noop
  309. pool := newClientPool(db, 1, &clock, removeFn)
  310. defer pool.stop()
  311. pool.setLimits(10, uint64(10)) // Total capacity limit is 10
  312. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  313. pool.addBalance(poolTestPeer(0).ID(), int64(time.Minute*3), "")
  314. pool.connect(poolTestPeer(0), 10)
  315. clock.Run(time.Minute)
  316. pool.disconnect(poolTestPeer(0))
  317. pb := pool.ndb.getOrNewPB(poolTestPeer(0).ID())
  318. if pb.value != uint64(time.Minute*2) {
  319. t.Fatalf("Positive balance mismatch, want %v, got %v", uint64(time.Minute*2), pb.value)
  320. }
  321. }
  322. func TestDowngradePriorityClient(t *testing.T) {
  323. var (
  324. clock mclock.Simulated
  325. db = rawdb.NewMemoryDatabase()
  326. kicked = make(chan int, 10)
  327. )
  328. removeFn := func(id enode.ID) { kicked <- int(id[0]) } // Noop
  329. pool := newClientPool(db, 1, &clock, removeFn)
  330. defer pool.stop()
  331. pool.setLimits(10, uint64(10)) // Total capacity limit is 10
  332. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  333. p := &poolTestPeerWithCap{
  334. poolTestPeer: poolTestPeer(0),
  335. }
  336. pool.addBalance(p.ID(), int64(time.Minute), "")
  337. pool.connect(p, 10)
  338. if p.cap != 10 {
  339. t.Fatalf("The capcacity of priority peer hasn't been updated, got: %d", p.cap)
  340. }
  341. clock.Run(time.Minute) // All positive balance should be used up.
  342. time.Sleep(300 * time.Millisecond) // Ensure the callback is called
  343. if p.cap != 1 {
  344. t.Fatalf("The capcacity of peer should be downgraded, got: %d", p.cap)
  345. }
  346. pb := pool.ndb.getOrNewPB(poolTestPeer(0).ID())
  347. if pb.value != 0 {
  348. t.Fatalf("Positive balance mismatch, want %v, got %v", 0, pb.value)
  349. }
  350. pool.addBalance(poolTestPeer(0).ID(), int64(time.Minute), "")
  351. pb = pool.ndb.getOrNewPB(poolTestPeer(0).ID())
  352. if pb.value != uint64(time.Minute) {
  353. t.Fatalf("Positive balance mismatch, want %v, got %v", uint64(time.Minute), pb.value)
  354. }
  355. }
  356. func TestNegativeBalanceCalculation(t *testing.T) {
  357. var (
  358. clock mclock.Simulated
  359. db = rawdb.NewMemoryDatabase()
  360. kicked = make(chan int, 10)
  361. )
  362. removeFn := func(id enode.ID) { kicked <- int(id[0]) } // Noop
  363. pool := newClientPool(db, 1, &clock, removeFn)
  364. defer pool.stop()
  365. pool.setLimits(10, uint64(10)) // Total capacity limit is 10
  366. pool.setDefaultFactors(priceFactors{1, 0, 1}, priceFactors{1, 0, 1})
  367. for i := 0; i < 10; i++ {
  368. pool.connect(poolTestPeer(i), 1)
  369. }
  370. clock.Run(time.Second)
  371. for i := 0; i < 10; i++ {
  372. pool.disconnect(poolTestPeer(i))
  373. nb := pool.ndb.getOrNewNB(poolTestPeer(i).freeClientId())
  374. if nb.logValue != 0 {
  375. t.Fatalf("Short connection shouldn't be recorded")
  376. }
  377. }
  378. for i := 0; i < 10; i++ {
  379. pool.connect(poolTestPeer(i), 1)
  380. }
  381. clock.Run(time.Minute)
  382. for i := 0; i < 10; i++ {
  383. pool.disconnect(poolTestPeer(i))
  384. nb := pool.ndb.getOrNewNB(poolTestPeer(i).freeClientId())
  385. nb.logValue -= pool.logOffset(clock.Now())
  386. nb.logValue /= fixedPointMultiplier
  387. if nb.logValue != int64(math.Log(float64(time.Minute/time.Second))) {
  388. t.Fatalf("Negative balance mismatch, want %v, got %v", int64(math.Log(float64(time.Minute/time.Second))), nb.logValue)
  389. }
  390. }
  391. }
  392. func TestNodeDB(t *testing.T) {
  393. ndb := newNodeDB(rawdb.NewMemoryDatabase(), mclock.System{})
  394. defer ndb.close()
  395. if !bytes.Equal(ndb.verbuf[:], []byte{0x00, nodeDBVersion}) {
  396. t.Fatalf("version buffer mismatch, want %v, got %v", []byte{0x00, nodeDBVersion}, ndb.verbuf)
  397. }
  398. var cases = []struct {
  399. id enode.ID
  400. ip string
  401. balance interface{}
  402. positive bool
  403. }{
  404. {enode.ID{0x00, 0x01, 0x02}, "", posBalance{value: 100}, true},
  405. {enode.ID{0x00, 0x01, 0x02}, "", posBalance{value: 200}, true},
  406. {enode.ID{}, "127.0.0.1", negBalance{logValue: 10}, false},
  407. {enode.ID{}, "127.0.0.1", negBalance{logValue: 20}, false},
  408. }
  409. for _, c := range cases {
  410. if c.positive {
  411. ndb.setPB(c.id, c.balance.(posBalance))
  412. if pb := ndb.getOrNewPB(c.id); !reflect.DeepEqual(pb, c.balance.(posBalance)) {
  413. t.Fatalf("Positive balance mismatch, want %v, got %v", c.balance.(posBalance), pb)
  414. }
  415. } else {
  416. ndb.setNB(c.ip, c.balance.(negBalance))
  417. if nb := ndb.getOrNewNB(c.ip); !reflect.DeepEqual(nb, c.balance.(negBalance)) {
  418. t.Fatalf("Negative balance mismatch, want %v, got %v", c.balance.(negBalance), nb)
  419. }
  420. }
  421. }
  422. for _, c := range cases {
  423. if c.positive {
  424. ndb.delPB(c.id)
  425. if pb := ndb.getOrNewPB(c.id); !reflect.DeepEqual(pb, posBalance{}) {
  426. t.Fatalf("Positive balance mismatch, want %v, got %v", posBalance{}, pb)
  427. }
  428. } else {
  429. ndb.delNB(c.ip)
  430. if nb := ndb.getOrNewNB(c.ip); !reflect.DeepEqual(nb, negBalance{}) {
  431. t.Fatalf("Negative balance mismatch, want %v, got %v", negBalance{}, nb)
  432. }
  433. }
  434. }
  435. ndb.setCumulativeTime(100)
  436. if ndb.getCumulativeTime() != 100 {
  437. t.Fatalf("Cumulative time mismatch, want %v, got %v", 100, ndb.getCumulativeTime())
  438. }
  439. }
  440. func TestNodeDBExpiration(t *testing.T) {
  441. var (
  442. iterated int
  443. done = make(chan struct{}, 1)
  444. )
  445. callback := func(now mclock.AbsTime, b negBalance) bool {
  446. iterated += 1
  447. return true
  448. }
  449. clock := &mclock.Simulated{}
  450. ndb := newNodeDB(rawdb.NewMemoryDatabase(), clock)
  451. defer ndb.close()
  452. ndb.nbEvictCallBack = callback
  453. ndb.cleanupHook = func() { done <- struct{}{} }
  454. var cases = []struct {
  455. ip string
  456. balance negBalance
  457. }{
  458. {"127.0.0.1", negBalance{logValue: 1}},
  459. {"127.0.0.2", negBalance{logValue: 1}},
  460. {"127.0.0.3", negBalance{logValue: 1}},
  461. {"127.0.0.4", negBalance{logValue: 1}},
  462. }
  463. for _, c := range cases {
  464. ndb.setNB(c.ip, c.balance)
  465. }
  466. clock.WaitForTimers(1)
  467. clock.Run(time.Hour + time.Minute)
  468. select {
  469. case <-done:
  470. case <-time.NewTimer(time.Second).C:
  471. t.Fatalf("timeout")
  472. }
  473. if iterated != 4 {
  474. t.Fatalf("Failed to evict useless negative balances, want %v, got %d", 4, iterated)
  475. }
  476. clock.WaitForTimers(1)
  477. for _, c := range cases {
  478. ndb.setNB(c.ip, c.balance)
  479. }
  480. clock.Run(time.Hour + time.Minute)
  481. select {
  482. case <-done:
  483. case <-time.NewTimer(time.Second).C:
  484. t.Fatalf("timeout")
  485. }
  486. if iterated != 8 {
  487. t.Fatalf("Failed to evict useless negative balances, want %v, got %d", 4, iterated)
  488. }
  489. }