Skip to content

Commit

Permalink
fix(kad): close progress whenever closer in range
Browse files Browse the repository at this point in the history
  • Loading branch information
maqi committed Nov 27, 2023
1 parent d1d90c4 commit 2b333db
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
4 changes: 4 additions & 0 deletions protocols/kad/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.45.3 - unreleased
- Close progress whenever closer in range, instead of having to be the closest.
See [PR 4596](https://github.com/libp2p/rust-libp2p/pull/4934).

## 0.45.2

- Ensure `Multiaddr` handled and returned by `Behaviour` are `/p2p` terminated.
Expand Down
25 changes: 18 additions & 7 deletions protocols/kad/src/query/peers/closest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,17 @@ impl ClosestPeersIter {
},
}

let mut cur_range = distance;
let mut index = 0;
for (dist, _state) in self.closest_peers.iter() {
if index < self.config.num_results.get() {
index += 1;
cur_range = *dist;
} else {
break;
}
}

let num_closest = self.closest_peers.len();
let mut progress = false;

Expand All @@ -187,11 +198,10 @@ impl ClosestPeersIter {
state: PeerState::NotContacted,
};
self.closest_peers.entry(distance).or_insert(peer);
// The iterator makes progress if the new peer is either closer to the target
// than any peer seen so far (i.e. is the first entry), or the iterator did
// not yet accumulate enough closest peers.
progress = self.closest_peers.keys().next() == Some(&distance)
|| num_closest < self.config.num_results.get();
// The iterator makes progress if either any of the new peer is among the `num_results`
// closest peers to the target seen so far,
// or the iterator did not yet accumulate enough closest peers.
progress = distance < cur_range || num_closest < self.config.num_results.get();
}

// Update the iterator state.
Expand Down Expand Up @@ -316,8 +326,9 @@ impl ClosestPeersIter {
if let Some(ref mut cnt) = result_counter {
*cnt += 1;
// If `num_results` successful results have been delivered for the
// closest peers, the iterator is done.
if *cnt >= self.config.num_results.get() {
// closest peers, AND there is no `waiting on result` peer so far,
// the iterator is done.
if *cnt >= self.config.num_results.get() && result_counter.is_some() {
self.state = State::Finished;
return PeersIterState::Finished;
}
Expand Down

0 comments on commit 2b333db

Please sign in to comment.