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