table_test.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. type nullTransport struct{}
  30. func (nullTransport) sendPing(remote *Node, remoteAddr *net.UDPAddr) []byte { return []byte{1} }
  31. func (nullTransport) sendPong(remote *Node, pingHash []byte) {}
  32. func (nullTransport) sendFindnode(remote *Node, target NodeID) {}
  33. func (nullTransport) sendNeighbours(remote *Node, nodes []*Node) {}
  34. func (nullTransport) localAddr() *net.UDPAddr { return new(net.UDPAddr) }
  35. func (nullTransport) Close() {}
  36. // func TestTable_pingReplace(t *testing.T) {
  37. // doit := func(newNodeIsResponding, lastInBucketIsResponding bool) {
  38. // transport := newPingRecorder()
  39. // tab, _ := newTable(transport, NodeID{}, &net.UDPAddr{})
  40. // defer tab.Close()
  41. // pingSender := NewNode(MustHexID("a502af0f59b2aab7746995408c79e9ca312d2793cc997e44fc55eda62f0150bbb8c59a6f9269ba3a081518b62699ee807c7c19c20125ddfccca872608af9e370"), net.IP{}, 99, 99)
  42. //
  43. // // fill up the sender's bucket.
  44. // last := fillBucket(tab, 253)
  45. //
  46. // // this call to bond should replace the last node
  47. // // in its bucket if the node is not responding.
  48. // transport.responding[last.ID] = lastInBucketIsResponding
  49. // transport.responding[pingSender.ID] = newNodeIsResponding
  50. // tab.bond(true, pingSender.ID, &net.UDPAddr{}, 0)
  51. //
  52. // // first ping goes to sender (bonding pingback)
  53. // if !transport.pinged[pingSender.ID] {
  54. // t.Error("table did not ping back sender")
  55. // }
  56. // if newNodeIsResponding {
  57. // // second ping goes to oldest node in bucket
  58. // // to see whether it is still alive.
  59. // if !transport.pinged[last.ID] {
  60. // t.Error("table did not ping last node in bucket")
  61. // }
  62. // }
  63. //
  64. // tab.mutex.Lock()
  65. // defer tab.mutex.Unlock()
  66. // if l := len(tab.buckets[253].entries); l != bucketSize {
  67. // t.Errorf("wrong bucket size after bond: got %d, want %d", l, bucketSize)
  68. // }
  69. //
  70. // if lastInBucketIsResponding || !newNodeIsResponding {
  71. // if !contains(tab.buckets[253].entries, last.ID) {
  72. // t.Error("last entry was removed")
  73. // }
  74. // if contains(tab.buckets[253].entries, pingSender.ID) {
  75. // t.Error("new entry was added")
  76. // }
  77. // } else {
  78. // if contains(tab.buckets[253].entries, last.ID) {
  79. // t.Error("last entry was not removed")
  80. // }
  81. // if !contains(tab.buckets[253].entries, pingSender.ID) {
  82. // t.Error("new entry was not added")
  83. // }
  84. // }
  85. // }
  86. //
  87. // doit(true, true)
  88. // doit(false, true)
  89. // doit(true, false)
  90. // doit(false, false)
  91. // }
  92. func TestBucket_bumpNoDuplicates(t *testing.T) {
  93. t.Parallel()
  94. cfg := &quick.Config{
  95. MaxCount: 1000,
  96. Rand: rand.New(rand.NewSource(time.Now().Unix())),
  97. Values: func(args []reflect.Value, rand *rand.Rand) {
  98. // generate a random list of nodes. this will be the content of the bucket.
  99. n := rand.Intn(bucketSize-1) + 1
  100. nodes := make([]*Node, n)
  101. for i := range nodes {
  102. nodes[i] = nodeAtDistance(common.Hash{}, 200)
  103. }
  104. args[0] = reflect.ValueOf(nodes)
  105. // generate random bump positions.
  106. bumps := make([]int, rand.Intn(100))
  107. for i := range bumps {
  108. bumps[i] = rand.Intn(len(nodes))
  109. }
  110. args[1] = reflect.ValueOf(bumps)
  111. },
  112. }
  113. prop := func(nodes []*Node, bumps []int) (ok bool) {
  114. b := &bucket{entries: make([]*Node, len(nodes))}
  115. copy(b.entries, nodes)
  116. for i, pos := range bumps {
  117. b.bump(b.entries[pos])
  118. if hasDuplicates(b.entries) {
  119. t.Logf("bucket has duplicates after %d/%d bumps:", i+1, len(bumps))
  120. for _, n := range b.entries {
  121. t.Logf(" %p", n)
  122. }
  123. return false
  124. }
  125. }
  126. return true
  127. }
  128. if err := quick.Check(prop, cfg); err != nil {
  129. t.Error(err)
  130. }
  131. }
  132. // fillBucket inserts nodes into the given bucket until
  133. // it is full. The node's IDs dont correspond to their
  134. // hashes.
  135. func fillBucket(tab *Table, ld int) (last *Node) {
  136. b := tab.buckets[ld]
  137. for len(b.entries) < bucketSize {
  138. b.entries = append(b.entries, nodeAtDistance(tab.self.sha, ld))
  139. }
  140. return b.entries[bucketSize-1]
  141. }
  142. // nodeAtDistance creates a node for which logdist(base, n.sha) == ld.
  143. // The node's ID does not correspond to n.sha.
  144. func nodeAtDistance(base common.Hash, ld int) (n *Node) {
  145. n = new(Node)
  146. n.sha = hashAtDistance(base, ld)
  147. copy(n.ID[:], n.sha[:]) // ensure the node still has a unique ID
  148. return n
  149. }
  150. type pingRecorder struct{ responding, pinged map[NodeID]bool }
  151. func newPingRecorder() *pingRecorder {
  152. return &pingRecorder{make(map[NodeID]bool), make(map[NodeID]bool)}
  153. }
  154. func (t *pingRecorder) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node, error) {
  155. panic("findnode called on pingRecorder")
  156. }
  157. func (t *pingRecorder) close() {}
  158. func (t *pingRecorder) waitping(from NodeID) error {
  159. return nil // remote always pings
  160. }
  161. func (t *pingRecorder) ping(toid NodeID, toaddr *net.UDPAddr) error {
  162. t.pinged[toid] = true
  163. if t.responding[toid] {
  164. return nil
  165. } else {
  166. return errTimeout
  167. }
  168. }
  169. func TestTable_closest(t *testing.T) {
  170. t.Parallel()
  171. test := func(test *closeTest) bool {
  172. // for any node table, Target and N
  173. tab := newTable(test.Self, &net.UDPAddr{})
  174. tab.stuff(test.All)
  175. // check that doClosest(Target, N) returns nodes
  176. result := tab.closest(test.Target, test.N).entries
  177. if hasDuplicates(result) {
  178. t.Errorf("result contains duplicates")
  179. return false
  180. }
  181. if !sortedByDistanceTo(test.Target, result) {
  182. t.Errorf("result is not sorted by distance to target")
  183. return false
  184. }
  185. // check that the number of results is min(N, tablen)
  186. wantN := test.N
  187. if tab.count < test.N {
  188. wantN = tab.count
  189. }
  190. if len(result) != wantN {
  191. t.Errorf("wrong number of nodes: got %d, want %d", len(result), wantN)
  192. return false
  193. } else if len(result) == 0 {
  194. return true // no need to check distance
  195. }
  196. // check that the result nodes have minimum distance to target.
  197. for _, b := range tab.buckets {
  198. for _, n := range b.entries {
  199. if contains(result, n.ID) {
  200. continue // don't run the check below for nodes in result
  201. }
  202. farthestResult := result[len(result)-1].sha
  203. if distcmp(test.Target, n.sha, farthestResult) < 0 {
  204. t.Errorf("table contains node that is closer to target but it's not in result")
  205. t.Logf(" Target: %v", test.Target)
  206. t.Logf(" Farthest Result: %v", farthestResult)
  207. t.Logf(" ID: %v", n.ID)
  208. return false
  209. }
  210. }
  211. }
  212. return true
  213. }
  214. if err := quick.Check(test, quickcfg()); err != nil {
  215. t.Error(err)
  216. }
  217. }
  218. func TestTable_ReadRandomNodesGetAll(t *testing.T) {
  219. cfg := &quick.Config{
  220. MaxCount: 200,
  221. Rand: rand.New(rand.NewSource(time.Now().Unix())),
  222. Values: func(args []reflect.Value, rand *rand.Rand) {
  223. args[0] = reflect.ValueOf(make([]*Node, rand.Intn(1000)))
  224. },
  225. }
  226. test := func(buf []*Node) bool {
  227. tab := newTable(NodeID{}, &net.UDPAddr{})
  228. for i := 0; i < len(buf); i++ {
  229. ld := cfg.Rand.Intn(len(tab.buckets))
  230. tab.stuff([]*Node{nodeAtDistance(tab.self.sha, ld)})
  231. }
  232. gotN := tab.readRandomNodes(buf)
  233. if gotN != tab.count {
  234. t.Errorf("wrong number of nodes, got %d, want %d", gotN, tab.count)
  235. return false
  236. }
  237. if hasDuplicates(buf[:gotN]) {
  238. t.Errorf("result contains duplicates")
  239. return false
  240. }
  241. return true
  242. }
  243. if err := quick.Check(test, cfg); err != nil {
  244. t.Error(err)
  245. }
  246. }
  247. type closeTest struct {
  248. Self NodeID
  249. Target common.Hash
  250. All []*Node
  251. N int
  252. }
  253. func (*closeTest) Generate(rand *rand.Rand, size int) reflect.Value {
  254. t := &closeTest{
  255. Self: gen(NodeID{}, rand).(NodeID),
  256. Target: gen(common.Hash{}, rand).(common.Hash),
  257. N: rand.Intn(bucketSize),
  258. }
  259. for _, id := range gen([]NodeID{}, rand).([]NodeID) {
  260. t.All = append(t.All, &Node{ID: id})
  261. }
  262. return reflect.ValueOf(t)
  263. }
  264. func hasDuplicates(slice []*Node) bool {
  265. seen := make(map[NodeID]bool)
  266. for i, e := range slice {
  267. if e == nil {
  268. panic(fmt.Sprintf("nil *Node at %d", i))
  269. }
  270. if seen[e.ID] {
  271. return true
  272. }
  273. seen[e.ID] = true
  274. }
  275. return false
  276. }
  277. func sortedByDistanceTo(distbase common.Hash, slice []*Node) bool {
  278. var last common.Hash
  279. for i, e := range slice {
  280. if i > 0 && distcmp(distbase, e.sha, last) < 0 {
  281. return false
  282. }
  283. last = e.sha
  284. }
  285. return true
  286. }
  287. func contains(ns []*Node, id NodeID) bool {
  288. for _, n := range ns {
  289. if n.ID == id {
  290. return true
  291. }
  292. }
  293. return false
  294. }
  295. // gen wraps quick.Value so it's easier to use.
  296. // it generates a random value of the given value's type.
  297. func gen(typ interface{}, rand *rand.Rand) interface{} {
  298. v, ok := quick.Value(reflect.TypeOf(typ), rand)
  299. if !ok {
  300. panic(fmt.Sprintf("couldn't generate random value of type %T", typ))
  301. }
  302. return v.Interface()
  303. }
  304. func newkey() *ecdsa.PrivateKey {
  305. key, err := crypto.GenerateKey()
  306. if err != nil {
  307. panic("couldn't generate key: " + err.Error())
  308. }
  309. return key
  310. }