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