topic_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2016 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 discv5
  17. import (
  18. "encoding/binary"
  19. "testing"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/mclock"
  23. )
  24. func TestTopicRadius(t *testing.T) {
  25. now := mclock.Now()
  26. topic := Topic("qwerty")
  27. rad := newTopicRadius(topic)
  28. targetRad := (^uint64(0)) / 100
  29. waitFn := func(addr common.Hash) time.Duration {
  30. prefix := binary.BigEndian.Uint64(addr[0:8])
  31. dist := prefix ^ rad.topicHashPrefix
  32. relDist := float64(dist) / float64(targetRad)
  33. relTime := (1 - relDist/2) * 2
  34. if relTime < 0 {
  35. relTime = 0
  36. }
  37. return time.Duration(float64(targetWaitTime) * relTime)
  38. }
  39. bcnt := 0
  40. cnt := 0
  41. var sum float64
  42. for cnt < 100 {
  43. addr := rad.nextTarget(false).target
  44. wait := waitFn(addr)
  45. ticket := &ticket{
  46. topics: []Topic{topic},
  47. regTime: []mclock.AbsTime{mclock.AbsTime(wait)},
  48. node: &Node{nodeNetGuts: nodeNetGuts{sha: addr}},
  49. }
  50. rad.adjustWithTicket(now, addr, ticketRef{ticket, 0})
  51. if rad.radius != maxRadius {
  52. cnt++
  53. sum += float64(rad.radius)
  54. } else {
  55. bcnt++
  56. if bcnt > 500 {
  57. t.Errorf("Radius did not converge in 500 iterations")
  58. }
  59. }
  60. }
  61. avgRel := sum / float64(cnt) / float64(targetRad)
  62. if avgRel > 1.05 || avgRel < 0.95 {
  63. t.Errorf("Average/target ratio is too far from 1 (%v)", avgRel)
  64. }
  65. }