table_util_test.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Copyright 2018 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 discover
  17. import (
  18. "crypto/ecdsa"
  19. "encoding/hex"
  20. "fmt"
  21. "math/rand"
  22. "net"
  23. "sort"
  24. "sync"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/p2p/enode"
  28. "github.com/ethereum/go-ethereum/p2p/enr"
  29. )
  30. var nullNode *enode.Node
  31. func init() {
  32. var r enr.Record
  33. r.Set(enr.IP{0, 0, 0, 0})
  34. nullNode = enode.SignNull(&r, enode.ID{})
  35. }
  36. func newTestTable(t transport) (*Table, *enode.DB) {
  37. db, _ := enode.OpenDB("")
  38. tab, _ := newTable(t, db, nil, log.Root())
  39. go tab.loop()
  40. return tab, db
  41. }
  42. // nodeAtDistance creates a node for which enode.LogDist(base, n.id) == ld.
  43. func nodeAtDistance(base enode.ID, ld int, ip net.IP) *node {
  44. var r enr.Record
  45. r.Set(enr.IP(ip))
  46. return wrapNode(enode.SignNull(&r, idAtDistance(base, ld)))
  47. }
  48. // idAtDistance returns a random hash such that enode.LogDist(a, b) == n
  49. func idAtDistance(a enode.ID, n int) (b enode.ID) {
  50. if n == 0 {
  51. return a
  52. }
  53. // flip bit at position n, fill the rest with random bits
  54. b = a
  55. pos := len(a) - n/8 - 1
  56. bit := byte(0x01) << (byte(n%8) - 1)
  57. if bit == 0 {
  58. pos++
  59. bit = 0x80
  60. }
  61. b[pos] = a[pos]&^bit | ^a[pos]&bit // TODO: randomize end bits
  62. for i := pos + 1; i < len(a); i++ {
  63. b[i] = byte(rand.Intn(255))
  64. }
  65. return b
  66. }
  67. func intIP(i int) net.IP {
  68. return net.IP{byte(i), 0, 2, byte(i)}
  69. }
  70. // fillBucket inserts nodes into the given bucket until it is full.
  71. func fillBucket(tab *Table, n *node) (last *node) {
  72. ld := enode.LogDist(tab.self().ID(), n.ID())
  73. b := tab.bucket(n.ID())
  74. for len(b.entries) < bucketSize {
  75. b.entries = append(b.entries, nodeAtDistance(tab.self().ID(), ld, intIP(ld)))
  76. }
  77. return b.entries[bucketSize-1]
  78. }
  79. // fillTable adds nodes the table to the end of their corresponding bucket
  80. // if the bucket is not full. The caller must not hold tab.mutex.
  81. func fillTable(tab *Table, nodes []*node) {
  82. for _, n := range nodes {
  83. tab.addSeenNode(n)
  84. }
  85. }
  86. type pingRecorder struct {
  87. mu sync.Mutex
  88. dead, pinged map[enode.ID]bool
  89. records map[enode.ID]*enode.Node
  90. n *enode.Node
  91. }
  92. func newPingRecorder() *pingRecorder {
  93. var r enr.Record
  94. r.Set(enr.IP{0, 0, 0, 0})
  95. n := enode.SignNull(&r, enode.ID{})
  96. return &pingRecorder{
  97. dead: make(map[enode.ID]bool),
  98. pinged: make(map[enode.ID]bool),
  99. records: make(map[enode.ID]*enode.Node),
  100. n: n,
  101. }
  102. }
  103. // setRecord updates a node record. Future calls to ping and
  104. // requestENR will return this record.
  105. func (t *pingRecorder) updateRecord(n *enode.Node) {
  106. t.mu.Lock()
  107. defer t.mu.Unlock()
  108. t.records[n.ID()] = n
  109. }
  110. // Stubs to satisfy the transport interface.
  111. func (t *pingRecorder) Self() *enode.Node { return nullNode }
  112. func (t *pingRecorder) lookupSelf() []*enode.Node { return nil }
  113. func (t *pingRecorder) lookupRandom() []*enode.Node { return nil }
  114. func (t *pingRecorder) close() {}
  115. // ping simulates a ping request.
  116. func (t *pingRecorder) ping(n *enode.Node) (seq uint64, err error) {
  117. t.mu.Lock()
  118. defer t.mu.Unlock()
  119. t.pinged[n.ID()] = true
  120. if t.dead[n.ID()] {
  121. return 0, errTimeout
  122. }
  123. if t.records[n.ID()] != nil {
  124. seq = t.records[n.ID()].Seq()
  125. }
  126. return seq, nil
  127. }
  128. // requestENR simulates an ENR request.
  129. func (t *pingRecorder) RequestENR(n *enode.Node) (*enode.Node, error) {
  130. t.mu.Lock()
  131. defer t.mu.Unlock()
  132. if t.dead[n.ID()] || t.records[n.ID()] == nil {
  133. return nil, errTimeout
  134. }
  135. return t.records[n.ID()], nil
  136. }
  137. func hasDuplicates(slice []*node) bool {
  138. seen := make(map[enode.ID]bool)
  139. for i, e := range slice {
  140. if e == nil {
  141. panic(fmt.Sprintf("nil *Node at %d", i))
  142. }
  143. if seen[e.ID()] {
  144. return true
  145. }
  146. seen[e.ID()] = true
  147. }
  148. return false
  149. }
  150. func sortedByDistanceTo(distbase enode.ID, slice []*node) bool {
  151. return sort.SliceIsSorted(slice, func(i, j int) bool {
  152. return enode.DistCmp(distbase, slice[i].ID(), slice[j].ID()) < 0
  153. })
  154. }
  155. func hexEncPrivkey(h string) *ecdsa.PrivateKey {
  156. b, err := hex.DecodeString(h)
  157. if err != nil {
  158. panic(err)
  159. }
  160. key, err := crypto.ToECDSA(b)
  161. if err != nil {
  162. panic(err)
  163. }
  164. return key
  165. }
  166. func hexEncPubkey(h string) (ret encPubkey) {
  167. b, err := hex.DecodeString(h)
  168. if err != nil {
  169. panic(err)
  170. }
  171. if len(b) != len(ret) {
  172. panic("invalid length")
  173. }
  174. copy(ret[:], b)
  175. return ret
  176. }