Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(kad): close progress whenever closer in range #4934

Merged
merged 1 commit into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions protocols/kad/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
See [PR 5270](https://github.com/libp2p/rust-libp2p/pull/5270)
- Update to DHT republish interval and expiration time defaults to 22h and 48h respectively, rationale in [libp2p/specs#451](https://github.com/libp2p/specs/pull/451)
See [PR 3230](https://github.com/libp2p/rust-libp2p/pull/3230)
- QueryClose progress whenever closer in range, instead of having to be the closest.
See [PR 4934](https://github.com/libp2p/rust-libp2p/pull/4934).

## 0.45.4

Expand Down
25 changes: 23 additions & 2 deletions protocols/kad/src/query/peers/closest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,20 @@ impl ClosestPeersIter {
},
}

let mut cur_range = distance;
let num_results = self.config.num_results.get();
// furthest_peer is the furthest peer in range among the closest_peers
let furthest_peer = self
.closest_peers
.iter()
.enumerate()
.nth(num_results - 1)
.map(|(_, peer)| peer)
.or_else(|| self.closest_peers.iter().last());
if let Some((dist, _)) = furthest_peer {
cur_range = *dist;
}

// Incorporate the reported closer peers into the iterator.
//
// The iterator makes progress if:
Expand All @@ -189,9 +203,16 @@ impl ClosestPeersIter {
key,
state: PeerState::NotContacted,
};
self.closest_peers.entry(distance).or_insert(peer);

progress = self.closest_peers.keys().next() == Some(&distance) || progress;
let is_first_insert = match self.closest_peers.entry(distance) {
Entry::Occupied(_) => false,
Entry::Vacant(entry) => {
entry.insert(peer);
true
}
};

progress = (is_first_insert && distance < cur_range) || progress;
}

// Update the iterator state.
Expand Down