table_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. "crypto/ecdsa"
  19. "fmt"
  20. "math/rand"
  21. "net"
  22. "reflect"
  23. "testing"
  24. "testing/quick"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. )
  29. func TestBucket_bumpNoDuplicates(t *testing.T) {
  30. t.Parallel()
  31. cfg := &quick.Config{
  32. MaxCount: 1000,
  33. Rand: rand.New(rand.NewSource(time.Now().Unix())),
  34. Values: func(args []reflect.Value, rand *rand.Rand) {
  35. // generate a random list of nodes. this will be the content of the bucket.
  36. n := rand.Intn(bucketSize-1) + 1
  37. nodes := make([]*Node, n)
  38. for i := range nodes {
  39. nodes[i] = nodeAtDistance(common.Hash{}, 200)
  40. }
  41. args[0] = reflect.ValueOf(nodes)
  42. // generate random bump positions.
  43. bumps := make([]int, rand.Intn(100))
  44. for i := range bumps {
  45. bumps[i] = rand.Intn(len(nodes))
  46. }
  47. args[1] = reflect.ValueOf(bumps)
  48. },
  49. }
  50. prop := func(nodes []*Node, bumps []int) (ok bool) {
  51. b := &bucket{entries: make([]*Node, len(nodes))}
  52. copy(b.entries, nodes)
  53. for i, pos := range bumps {
  54. b.bump(b.entries[pos])
  55. if hasDuplicates(b.entries) {
  56. t.Logf("bucket has duplicates after %d/%d bumps:", i+1, len(bumps))
  57. for _, n := range b.entries {
  58. t.Logf(" %p", n)
  59. }
  60. return false
  61. }
  62. }
  63. return true
  64. }
  65. if err := quick.Check(prop, cfg); err != nil {
  66. t.Error(err)
  67. }
  68. }
  69. // nodeAtDistance creates a node for which logdist(base, n.sha) == ld.
  70. // The node's ID does not correspond to n.sha.
  71. func nodeAtDistance(base common.Hash, ld int) (n *Node) {
  72. n = new(Node)
  73. n.sha = hashAtDistance(base, ld)
  74. copy(n.ID[:], n.sha[:]) // ensure the node still has a unique ID
  75. return n
  76. }
  77. func TestTable_closest(t *testing.T) {
  78. t.Parallel()
  79. test := func(test *closeTest) bool {
  80. // for any node table, Target and N
  81. tab := newTable(test.Self, &net.UDPAddr{})
  82. tab.stuff(test.All)
  83. // check that doClosest(Target, N) returns nodes
  84. result := tab.closest(test.Target, test.N).entries
  85. if hasDuplicates(result) {
  86. t.Errorf("result contains duplicates")
  87. return false
  88. }
  89. if !sortedByDistanceTo(test.Target, result) {
  90. t.Errorf("result is not sorted by distance to target")
  91. return false
  92. }
  93. // check that the number of results is min(N, tablen)
  94. wantN := test.N
  95. if tab.count < test.N {
  96. wantN = tab.count
  97. }
  98. if len(result) != wantN {
  99. t.Errorf("wrong number of nodes: got %d, want %d", len(result), wantN)
  100. return false
  101. } else if len(result) == 0 {
  102. return true // no need to check distance
  103. }
  104. // check that the result nodes have minimum distance to target.
  105. for _, b := range tab.buckets {
  106. for _, n := range b.entries {
  107. if contains(result, n.ID) {
  108. continue // don't run the check below for nodes in result
  109. }
  110. farthestResult := result[len(result)-1].sha
  111. if distcmp(test.Target, n.sha, farthestResult) < 0 {
  112. t.Errorf("table contains node that is closer to target but it's not in result")
  113. t.Logf(" Target: %v", test.Target)
  114. t.Logf(" Farthest Result: %v", farthestResult)
  115. t.Logf(" ID: %v", n.ID)
  116. return false
  117. }
  118. }
  119. }
  120. return true
  121. }
  122. if err := quick.Check(test, quickcfg()); err != nil {
  123. t.Error(err)
  124. }
  125. }
  126. func TestTable_ReadRandomNodesGetAll(t *testing.T) {
  127. cfg := &quick.Config{
  128. MaxCount: 200,
  129. Rand: rand.New(rand.NewSource(time.Now().Unix())),
  130. Values: func(args []reflect.Value, rand *rand.Rand) {
  131. args[0] = reflect.ValueOf(make([]*Node, rand.Intn(1000)))
  132. },
  133. }
  134. test := func(buf []*Node) bool {
  135. tab := newTable(NodeID{}, &net.UDPAddr{})
  136. for i := 0; i < len(buf); i++ {
  137. ld := cfg.Rand.Intn(len(tab.buckets))
  138. tab.stuff([]*Node{nodeAtDistance(tab.self.sha, ld)})
  139. }
  140. gotN := tab.readRandomNodes(buf)
  141. if gotN != tab.count {
  142. t.Errorf("wrong number of nodes, got %d, want %d", gotN, tab.count)
  143. return false
  144. }
  145. if hasDuplicates(buf[:gotN]) {
  146. t.Errorf("result contains duplicates")
  147. return false
  148. }
  149. return true
  150. }
  151. if err := quick.Check(test, cfg); err != nil {
  152. t.Error(err)
  153. }
  154. }
  155. type closeTest struct {
  156. Self NodeID
  157. Target common.Hash
  158. All []*Node
  159. N int
  160. }
  161. func (*closeTest) Generate(rand *rand.Rand, size int) reflect.Value {
  162. t := &closeTest{
  163. Self: gen(NodeID{}, rand).(NodeID),
  164. Target: gen(common.Hash{}, rand).(common.Hash),
  165. N: rand.Intn(bucketSize),
  166. }
  167. for _, id := range gen([]NodeID{}, rand).([]NodeID) {
  168. t.All = append(t.All, &Node{ID: id})
  169. }
  170. return reflect.ValueOf(t)
  171. }
  172. func hasDuplicates(slice []*Node) bool {
  173. seen := make(map[NodeID]bool)
  174. for i, e := range slice {
  175. if e == nil {
  176. panic(fmt.Sprintf("nil *Node at %d", i))
  177. }
  178. if seen[e.ID] {
  179. return true
  180. }
  181. seen[e.ID] = true
  182. }
  183. return false
  184. }
  185. func sortedByDistanceTo(distbase common.Hash, slice []*Node) bool {
  186. var last common.Hash
  187. for i, e := range slice {
  188. if i > 0 && distcmp(distbase, e.sha, last) < 0 {
  189. return false
  190. }
  191. last = e.sha
  192. }
  193. return true
  194. }
  195. func contains(ns []*Node, id NodeID) bool {
  196. for _, n := range ns {
  197. if n.ID == id {
  198. return true
  199. }
  200. }
  201. return false
  202. }
  203. // gen wraps quick.Value so it's easier to use.
  204. // it generates a random value of the given value's type.
  205. func gen(typ interface{}, rand *rand.Rand) interface{} {
  206. v, ok := quick.Value(reflect.TypeOf(typ), rand)
  207. if !ok {
  208. panic(fmt.Sprintf("couldn't generate random value of type %T", typ))
  209. }
  210. return v.Interface()
  211. }
  212. func newkey() *ecdsa.PrivateKey {
  213. key, err := crypto.GenerateKey()
  214. if err != nil {
  215. panic("couldn't generate key: " + err.Error())
  216. }
  217. return key
  218. }