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