balance_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 server
  17. import (
  18. "math"
  19. "math/rand"
  20. "reflect"
  21. "testing"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common/mclock"
  24. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  25. "github.com/ethereum/go-ethereum/les/utils"
  26. "github.com/ethereum/go-ethereum/p2p/enode"
  27. "github.com/ethereum/go-ethereum/p2p/enr"
  28. "github.com/ethereum/go-ethereum/p2p/nodestate"
  29. )
  30. var (
  31. testFlag = testSetup.NewFlag("testFlag")
  32. connAddrFlag = testSetup.NewField("connAddr", reflect.TypeOf(""))
  33. btTestSetup = NewBalanceTrackerSetup(testSetup)
  34. )
  35. func init() {
  36. btTestSetup.Connect(connAddrFlag, ppTestSetup.CapacityField)
  37. }
  38. type zeroExpirer struct{}
  39. func (z zeroExpirer) SetRate(now mclock.AbsTime, rate float64) {}
  40. func (z zeroExpirer) SetLogOffset(now mclock.AbsTime, logOffset utils.Fixed64) {}
  41. func (z zeroExpirer) LogOffset(now mclock.AbsTime) utils.Fixed64 { return 0 }
  42. type balanceTestSetup struct {
  43. clock *mclock.Simulated
  44. ns *nodestate.NodeStateMachine
  45. bt *BalanceTracker
  46. }
  47. func newBalanceTestSetup() *balanceTestSetup {
  48. clock := &mclock.Simulated{}
  49. ns := nodestate.NewNodeStateMachine(nil, nil, clock, testSetup)
  50. db := memorydb.New()
  51. bt := NewBalanceTracker(ns, btTestSetup, db, clock, zeroExpirer{}, zeroExpirer{})
  52. ns.Start()
  53. return &balanceTestSetup{
  54. clock: clock,
  55. ns: ns,
  56. bt: bt,
  57. }
  58. }
  59. func (b *balanceTestSetup) newNode(capacity uint64) *NodeBalance {
  60. node := enode.SignNull(&enr.Record{}, enode.ID{})
  61. b.ns.SetState(node, testFlag, nodestate.Flags{}, 0)
  62. b.ns.SetField(node, btTestSetup.connAddressField, "")
  63. if capacity != 0 {
  64. b.ns.SetField(node, ppTestSetup.CapacityField, capacity)
  65. }
  66. n, _ := b.ns.GetField(node, btTestSetup.BalanceField).(*NodeBalance)
  67. return n
  68. }
  69. func (b *balanceTestSetup) stop() {
  70. b.bt.Stop()
  71. b.ns.Stop()
  72. }
  73. func TestAddBalance(t *testing.T) {
  74. b := newBalanceTestSetup()
  75. defer b.stop()
  76. node := b.newNode(1000)
  77. var inputs = []struct {
  78. delta int64
  79. expect [2]uint64
  80. total uint64
  81. expectErr bool
  82. }{
  83. {100, [2]uint64{0, 100}, 100, false},
  84. {-100, [2]uint64{100, 0}, 0, false},
  85. {-100, [2]uint64{0, 0}, 0, false},
  86. {1, [2]uint64{0, 1}, 1, false},
  87. {maxBalance, [2]uint64{0, 0}, 0, true},
  88. }
  89. for _, i := range inputs {
  90. old, new, err := node.AddBalance(i.delta)
  91. if i.expectErr {
  92. if err == nil {
  93. t.Fatalf("Expect get error but nil")
  94. }
  95. continue
  96. } else if err != nil {
  97. t.Fatalf("Expect get no error but %v", err)
  98. }
  99. if old != i.expect[0] || new != i.expect[1] {
  100. t.Fatalf("Positive balance mismatch, got %v -> %v", old, new)
  101. }
  102. if b.bt.TotalTokenAmount() != i.total {
  103. t.Fatalf("Total positive balance mismatch, want %v, got %v", i.total, b.bt.TotalTokenAmount())
  104. }
  105. }
  106. }
  107. func TestSetBalance(t *testing.T) {
  108. b := newBalanceTestSetup()
  109. defer b.stop()
  110. node := b.newNode(1000)
  111. var inputs = []struct {
  112. pos, neg uint64
  113. }{
  114. {1000, 0},
  115. {0, 1000},
  116. {1000, 1000},
  117. }
  118. for _, i := range inputs {
  119. node.SetBalance(i.pos, i.neg)
  120. pos, neg := node.GetBalance()
  121. if pos != i.pos {
  122. t.Fatalf("Positive balance mismatch, want %v, got %v", i.pos, pos)
  123. }
  124. if neg != i.neg {
  125. t.Fatalf("Negative balance mismatch, want %v, got %v", i.neg, neg)
  126. }
  127. }
  128. }
  129. func TestBalanceTimeCost(t *testing.T) {
  130. b := newBalanceTestSetup()
  131. defer b.stop()
  132. node := b.newNode(1000)
  133. b.ns.SetField(node.node, ppTestSetup.CapacityField, uint64(1))
  134. node.SetPriceFactors(PriceFactors{1, 0, 1}, PriceFactors{1, 0, 1})
  135. node.SetBalance(uint64(time.Minute), 0) // 1 minute time allowance
  136. var inputs = []struct {
  137. runTime time.Duration
  138. expPos uint64
  139. expNeg uint64
  140. }{
  141. {time.Second, uint64(time.Second * 59), 0},
  142. {0, uint64(time.Second * 59), 0},
  143. {time.Second * 59, 0, 0},
  144. {time.Second, 0, uint64(time.Second)},
  145. }
  146. for _, i := range inputs {
  147. b.clock.Run(i.runTime)
  148. if pos, _ := node.GetBalance(); pos != i.expPos {
  149. t.Fatalf("Positive balance mismatch, want %v, got %v", i.expPos, pos)
  150. }
  151. if _, neg := node.GetBalance(); neg != i.expNeg {
  152. t.Fatalf("Negative balance mismatch, want %v, got %v", i.expNeg, neg)
  153. }
  154. }
  155. node.SetBalance(uint64(time.Minute), 0) // Refill 1 minute time allowance
  156. for _, i := range inputs {
  157. b.clock.Run(i.runTime)
  158. if pos, _ := node.GetBalance(); pos != i.expPos {
  159. t.Fatalf("Positive balance mismatch, want %v, got %v", i.expPos, pos)
  160. }
  161. if _, neg := node.GetBalance(); neg != i.expNeg {
  162. t.Fatalf("Negative balance mismatch, want %v, got %v", i.expNeg, neg)
  163. }
  164. }
  165. }
  166. func TestBalanceReqCost(t *testing.T) {
  167. b := newBalanceTestSetup()
  168. defer b.stop()
  169. node := b.newNode(1000)
  170. node.SetPriceFactors(PriceFactors{1, 0, 1}, PriceFactors{1, 0, 1})
  171. b.ns.SetField(node.node, ppTestSetup.CapacityField, uint64(1))
  172. node.SetBalance(uint64(time.Minute), 0) // 1 minute time serving time allowance
  173. var inputs = []struct {
  174. reqCost uint64
  175. expPos uint64
  176. expNeg uint64
  177. }{
  178. {uint64(time.Second), uint64(time.Second * 59), 0},
  179. {0, uint64(time.Second * 59), 0},
  180. {uint64(time.Second * 59), 0, 0},
  181. {uint64(time.Second), 0, uint64(time.Second)},
  182. }
  183. for _, i := range inputs {
  184. node.RequestServed(i.reqCost)
  185. if pos, _ := node.GetBalance(); pos != i.expPos {
  186. t.Fatalf("Positive balance mismatch, want %v, got %v", i.expPos, pos)
  187. }
  188. if _, neg := node.GetBalance(); neg != i.expNeg {
  189. t.Fatalf("Negative balance mismatch, want %v, got %v", i.expNeg, neg)
  190. }
  191. }
  192. }
  193. func TestBalanceToPriority(t *testing.T) {
  194. b := newBalanceTestSetup()
  195. defer b.stop()
  196. node := b.newNode(1000)
  197. node.SetPriceFactors(PriceFactors{1, 0, 1}, PriceFactors{1, 0, 1})
  198. var inputs = []struct {
  199. pos uint64
  200. neg uint64
  201. priority int64
  202. }{
  203. {1000, 0, 1},
  204. {2000, 0, 2}, // Higher balance, higher priority value
  205. {0, 0, 0},
  206. {0, 1000, -1000},
  207. }
  208. for _, i := range inputs {
  209. node.SetBalance(i.pos, i.neg)
  210. priority := node.Priority(b.clock.Now(), 1000)
  211. if priority != i.priority {
  212. t.Fatalf("Priority mismatch, want %v, got %v", i.priority, priority)
  213. }
  214. }
  215. }
  216. func TestEstimatedPriority(t *testing.T) {
  217. b := newBalanceTestSetup()
  218. defer b.stop()
  219. node := b.newNode(1000000000)
  220. node.SetPriceFactors(PriceFactors{1, 0, 1}, PriceFactors{1, 0, 1})
  221. b.ns.SetField(node.node, ppTestSetup.CapacityField, uint64(1))
  222. node.SetBalance(uint64(time.Minute), 0)
  223. var inputs = []struct {
  224. runTime time.Duration // time cost
  225. futureTime time.Duration // diff of future time
  226. reqCost uint64 // single request cost
  227. priority int64 // expected estimated priority
  228. }{
  229. {time.Second, time.Second, 0, 58},
  230. {0, time.Second, 0, 58},
  231. // 2 seconds time cost, 1 second estimated time cost, 10^9 request cost,
  232. // 10^9 estimated request cost per second.
  233. {time.Second, time.Second, 1000000000, 55},
  234. // 3 seconds time cost, 3 second estimated time cost, 10^9*2 request cost,
  235. // 4*10^9 estimated request cost.
  236. {time.Second, 3 * time.Second, 1000000000, 48},
  237. // All positive balance is used up
  238. {time.Second * 55, 0, 0, 0},
  239. // 1 minute estimated time cost, 4/58 * 10^9 estimated request cost per sec.
  240. {0, time.Minute, 0, -int64(time.Minute) - int64(time.Second)*120/29},
  241. }
  242. for _, i := range inputs {
  243. b.clock.Run(i.runTime)
  244. node.RequestServed(i.reqCost)
  245. priority := node.EstMinPriority(b.clock.Now()+mclock.AbsTime(i.futureTime), 1000000000, false)
  246. if priority != i.priority {
  247. t.Fatalf("Estimated priority mismatch, want %v, got %v", i.priority, priority)
  248. }
  249. }
  250. }
  251. func TestPosBalanceMissing(t *testing.T) {
  252. b := newBalanceTestSetup()
  253. defer b.stop()
  254. node := b.newNode(1000)
  255. node.SetPriceFactors(PriceFactors{1, 0, 1}, PriceFactors{1, 0, 1})
  256. b.ns.SetField(node.node, ppTestSetup.CapacityField, uint64(1))
  257. var inputs = []struct {
  258. pos, neg uint64
  259. priority int64
  260. cap uint64
  261. after time.Duration
  262. expect uint64
  263. }{
  264. {uint64(time.Second * 2), 0, 0, 1, time.Second, 0},
  265. {uint64(time.Second * 2), 0, 0, 1, 2 * time.Second, 1},
  266. {uint64(time.Second * 2), 0, int64(time.Second), 1, 2 * time.Second, uint64(time.Second) + 1},
  267. {0, 0, int64(time.Second), 1, time.Second, uint64(2*time.Second) + 1},
  268. {0, 0, -int64(time.Second), 1, time.Second, 1},
  269. }
  270. for _, i := range inputs {
  271. node.SetBalance(i.pos, i.neg)
  272. got := node.PosBalanceMissing(i.priority, i.cap, i.after)
  273. if got != i.expect {
  274. t.Fatalf("Missing budget mismatch, want %v, got %v", i.expect, got)
  275. }
  276. }
  277. }
  278. func TestPostiveBalanceCounting(t *testing.T) {
  279. b := newBalanceTestSetup()
  280. defer b.stop()
  281. var nodes []*NodeBalance
  282. for i := 0; i < 100; i += 1 {
  283. node := b.newNode(1000000)
  284. node.SetPriceFactors(PriceFactors{1, 0, 1}, PriceFactors{1, 0, 1})
  285. nodes = append(nodes, node)
  286. }
  287. // Allocate service token
  288. var sum uint64
  289. for i := 0; i < 100; i += 1 {
  290. amount := int64(rand.Intn(100) + 100)
  291. nodes[i].AddBalance(amount)
  292. sum += uint64(amount)
  293. }
  294. if b.bt.TotalTokenAmount() != sum {
  295. t.Fatalf("Invalid token amount")
  296. }
  297. // Change client status
  298. for i := 0; i < 100; i += 1 {
  299. if rand.Intn(2) == 0 {
  300. b.ns.SetField(nodes[i].node, ppTestSetup.CapacityField, uint64(1))
  301. }
  302. }
  303. if b.bt.TotalTokenAmount() != sum {
  304. t.Fatalf("Invalid token amount")
  305. }
  306. for i := 0; i < 100; i += 1 {
  307. if rand.Intn(2) == 0 {
  308. b.ns.SetField(nodes[i].node, ppTestSetup.CapacityField, uint64(1))
  309. }
  310. }
  311. if b.bt.TotalTokenAmount() != sum {
  312. t.Fatalf("Invalid token amount")
  313. }
  314. }
  315. func TestCallbackChecking(t *testing.T) {
  316. b := newBalanceTestSetup()
  317. defer b.stop()
  318. node := b.newNode(1000000)
  319. node.SetPriceFactors(PriceFactors{1, 0, 1}, PriceFactors{1, 0, 1})
  320. var inputs = []struct {
  321. priority int64
  322. expDiff time.Duration
  323. }{
  324. {500, time.Millisecond * 500},
  325. {0, time.Second},
  326. {-int64(time.Second), 2 * time.Second},
  327. }
  328. node.SetBalance(uint64(time.Second), 0)
  329. for _, i := range inputs {
  330. diff, _ := node.timeUntil(i.priority)
  331. if diff != i.expDiff {
  332. t.Fatalf("Time difference mismatch, want %v, got %v", i.expDiff, diff)
  333. }
  334. }
  335. }
  336. func TestCallback(t *testing.T) {
  337. b := newBalanceTestSetup()
  338. defer b.stop()
  339. node := b.newNode(1000)
  340. node.SetPriceFactors(PriceFactors{1, 0, 1}, PriceFactors{1, 0, 1})
  341. b.ns.SetField(node.node, ppTestSetup.CapacityField, uint64(1))
  342. callCh := make(chan struct{}, 1)
  343. node.SetBalance(uint64(time.Minute), 0)
  344. node.addCallback(balanceCallbackZero, 0, func() { callCh <- struct{}{} })
  345. b.clock.Run(time.Minute)
  346. select {
  347. case <-callCh:
  348. case <-time.NewTimer(time.Second).C:
  349. t.Fatalf("Callback hasn't been called yet")
  350. }
  351. node.SetBalance(uint64(time.Minute), 0)
  352. node.addCallback(balanceCallbackZero, 0, func() { callCh <- struct{}{} })
  353. node.removeCallback(balanceCallbackZero)
  354. b.clock.Run(time.Minute)
  355. select {
  356. case <-callCh:
  357. t.Fatalf("Callback shouldn't be called")
  358. case <-time.NewTimer(time.Millisecond * 100).C:
  359. }
  360. }
  361. func TestBalancePersistence(t *testing.T) {
  362. clock := &mclock.Simulated{}
  363. ns := nodestate.NewNodeStateMachine(nil, nil, clock, testSetup)
  364. db := memorydb.New()
  365. posExp := &utils.Expirer{}
  366. negExp := &utils.Expirer{}
  367. posExp.SetRate(clock.Now(), math.Log(2)/float64(time.Hour*2)) // halves every two hours
  368. negExp.SetRate(clock.Now(), math.Log(2)/float64(time.Hour)) // halves every hour
  369. bt := NewBalanceTracker(ns, btTestSetup, db, clock, posExp, negExp)
  370. ns.Start()
  371. bts := &balanceTestSetup{
  372. clock: clock,
  373. ns: ns,
  374. bt: bt,
  375. }
  376. var nb *NodeBalance
  377. exp := func(expPos, expNeg uint64) {
  378. pos, neg := nb.GetBalance()
  379. if pos != expPos {
  380. t.Fatalf("Positive balance incorrect, want %v, got %v", expPos, pos)
  381. }
  382. if neg != expNeg {
  383. t.Fatalf("Positive balance incorrect, want %v, got %v", expPos, pos)
  384. }
  385. }
  386. expTotal := func(expTotal uint64) {
  387. total := bt.TotalTokenAmount()
  388. if total != expTotal {
  389. t.Fatalf("Total token amount incorrect, want %v, got %v", expTotal, total)
  390. }
  391. }
  392. expTotal(0)
  393. nb = bts.newNode(0)
  394. expTotal(0)
  395. nb.SetBalance(16000000000, 16000000000)
  396. exp(16000000000, 16000000000)
  397. expTotal(16000000000)
  398. clock.Run(time.Hour * 2)
  399. exp(8000000000, 4000000000)
  400. expTotal(8000000000)
  401. bt.Stop()
  402. ns.Stop()
  403. clock = &mclock.Simulated{}
  404. ns = nodestate.NewNodeStateMachine(nil, nil, clock, testSetup)
  405. posExp = &utils.Expirer{}
  406. negExp = &utils.Expirer{}
  407. posExp.SetRate(clock.Now(), math.Log(2)/float64(time.Hour*2)) // halves every two hours
  408. negExp.SetRate(clock.Now(), math.Log(2)/float64(time.Hour)) // halves every hour
  409. bt = NewBalanceTracker(ns, btTestSetup, db, clock, posExp, negExp)
  410. ns.Start()
  411. bts = &balanceTestSetup{
  412. clock: clock,
  413. ns: ns,
  414. bt: bt,
  415. }
  416. expTotal(8000000000)
  417. nb = bts.newNode(0)
  418. exp(8000000000, 4000000000)
  419. expTotal(8000000000)
  420. clock.Run(time.Hour * 2)
  421. exp(4000000000, 1000000000)
  422. expTotal(4000000000)
  423. bt.Stop()
  424. ns.Stop()
  425. }