lookup.go 6.0 KB

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