lookup.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 discover
  17. import (
  18. "context"
  19. "github.com/ethereum/go-ethereum/p2p/enode"
  20. )
  21. // lookup performs a network search for nodes close to the given target. It approaches the
  22. // target by querying nodes that are closer to it on each iteration. The given target does
  23. // not need to be an actual node identifier.
  24. type lookup struct {
  25. tab *Table
  26. queryfunc func(*node) ([]*node, error)
  27. replyCh chan []*node
  28. cancelCh <-chan struct{}
  29. asked, seen map[enode.ID]bool
  30. result nodesByDistance
  31. replyBuffer []*node
  32. queries int
  33. }
  34. type queryFunc func(*node) ([]*node, error)
  35. func newLookup(ctx context.Context, tab *Table, target enode.ID, q queryFunc) *lookup {
  36. it := &lookup{
  37. tab: tab,
  38. queryfunc: q,
  39. asked: make(map[enode.ID]bool),
  40. seen: make(map[enode.ID]bool),
  41. result: nodesByDistance{target: target},
  42. replyCh: make(chan []*node, alpha),
  43. cancelCh: ctx.Done(),
  44. queries: -1,
  45. }
  46. // Don't query further if we hit ourself.
  47. // Unlikely to happen often in practice.
  48. it.asked[tab.self().ID()] = true
  49. return it
  50. }
  51. // run runs the lookup to completion and returns the closest nodes found.
  52. func (it *lookup) run() []*enode.Node {
  53. for it.advance() {
  54. }
  55. return unwrapNodes(it.result.entries)
  56. }
  57. // advance advances the lookup until any new nodes have been found.
  58. // It returns false when the lookup has ended.
  59. func (it *lookup) advance() bool {
  60. for it.startQueries() {
  61. select {
  62. case nodes := <-it.replyCh:
  63. it.replyBuffer = it.replyBuffer[:0]
  64. for _, n := range nodes {
  65. if n != nil && !it.seen[n.ID()] {
  66. it.seen[n.ID()] = true
  67. it.result.push(n, bucketSize)
  68. it.replyBuffer = append(it.replyBuffer, n)
  69. }
  70. }
  71. it.queries--
  72. if len(it.replyBuffer) > 0 {
  73. return true
  74. }
  75. case <-it.cancelCh:
  76. it.shutdown()
  77. }
  78. }
  79. return false
  80. }
  81. func (it *lookup) shutdown() {
  82. for it.queries > 0 {
  83. <-it.replyCh
  84. it.queries--
  85. }
  86. it.queryfunc = nil
  87. it.replyBuffer = nil
  88. }
  89. func (it *lookup) startQueries() bool {
  90. if it.queryfunc == nil {
  91. return false
  92. }
  93. // The first query returns nodes from the local table.
  94. if it.queries == -1 {
  95. it.tab.mutex.Lock()
  96. closest := it.tab.closest(it.result.target, bucketSize, false)
  97. it.tab.mutex.Unlock()
  98. it.queries = 1
  99. it.replyCh <- closest.entries
  100. return true
  101. }
  102. // Ask the closest nodes that we haven't asked yet.
  103. for i := 0; i < len(it.result.entries) && it.queries < alpha; i++ {
  104. n := it.result.entries[i]
  105. if !it.asked[n.ID()] {
  106. it.asked[n.ID()] = true
  107. it.queries++
  108. go it.query(n, it.replyCh)
  109. }
  110. }
  111. // The lookup ends when no more nodes can be asked.
  112. return it.queries > 0
  113. }
  114. func (it *lookup) query(n *node, reply chan<- []*node) {
  115. fails := it.tab.db.FindFails(n.ID(), n.IP())
  116. r, err := it.queryfunc(n)
  117. if err == errClosed {
  118. // Avoid recording failures on shutdown.
  119. reply <- nil
  120. return
  121. } else if len(r) == 0 {
  122. fails++
  123. it.tab.db.UpdateFindFails(n.ID(), n.IP(), fails)
  124. it.tab.log.Trace("Findnode failed", "id", n.ID(), "failcount", fails, "err", err)
  125. if fails >= maxFindnodeFailures {
  126. it.tab.log.Trace("Too many findnode failures, dropping", "id", n.ID(), "failcount", fails)
  127. it.tab.delete(n)
  128. }
  129. } else if fails > 0 {
  130. // Reset failure counter because it counts _consecutive_ failures.
  131. it.tab.db.UpdateFindFails(n.ID(), n.IP(), 0)
  132. }
  133. // Grab as many nodes as possible. Some of them might not be alive anymore, but we'll
  134. // just remove those again during revalidation.
  135. for _, n := range r {
  136. it.tab.addSeenNode(n)
  137. }
  138. reply <- r
  139. }
  140. // lookupIterator performs lookup operations and iterates over all seen nodes.
  141. // When a lookup finishes, a new one is created through nextLookup.
  142. type lookupIterator struct {
  143. buffer []*node
  144. nextLookup lookupFunc
  145. ctx context.Context
  146. cancel func()
  147. lookup *lookup
  148. }
  149. type lookupFunc func(ctx context.Context) *lookup
  150. func newLookupIterator(ctx context.Context, next lookupFunc) *lookupIterator {
  151. ctx, cancel := context.WithCancel(ctx)
  152. return &lookupIterator{ctx: ctx, cancel: cancel, nextLookup: next}
  153. }
  154. // Node returns the current node.
  155. func (it *lookupIterator) Node() *enode.Node {
  156. if len(it.buffer) == 0 {
  157. return nil
  158. }
  159. return unwrapNode(it.buffer[0])
  160. }
  161. // Next moves to the next node.
  162. func (it *lookupIterator) Next() bool {
  163. // Consume next node in buffer.
  164. if len(it.buffer) > 0 {
  165. it.buffer = it.buffer[1:]
  166. }
  167. // Advance the lookup to refill the buffer.
  168. for len(it.buffer) == 0 {
  169. if it.ctx.Err() != nil {
  170. it.lookup = nil
  171. it.buffer = nil
  172. return false
  173. }
  174. if it.lookup == nil {
  175. it.lookup = it.nextLookup(it.ctx)
  176. continue
  177. }
  178. if !it.lookup.advance() {
  179. it.lookup = nil
  180. continue
  181. }
  182. it.buffer = it.lookup.replyBuffer
  183. }
  184. return true
  185. }
  186. // Close ends the iterator.
  187. func (it *lookupIterator) Close() {
  188. it.cancel()
  189. }