lookup.go 6.0 KB

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