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

feat(peer-store): introduce libp2p-peer-store #5724

Draft
wants to merge 29 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
1affefe
template implementation
drHuangMHT Dec 6, 2024
8d4930a
implement in-memory store
drHuangMHT Dec 7, 2024
9cb59c3
manifest update
drHuangMHT Dec 7, 2024
fbc1344
formatting
drHuangMHT Dec 7, 2024
2bcfa7f
docs
drHuangMHT Dec 7, 2024
6df6ee5
return iterator of references instead of heap allocation
drHuangMHT Dec 8, 2024
99a6bfd
move conencted_peers out of Store
drHuangMHT Dec 8, 2024
5c7ba32
use capped LruCache instead of uncapped HashMap for address records
drHuangMHT Dec 8, 2024
b6dcd59
update address book when a connection is established regardless of fu…
drHuangMHT Dec 8, 2024
cbb1906
provide address for dial
drHuangMHT Dec 9, 2024
6270259
apply suggestions
drHuangMHT Dec 13, 2024
cc91ab5
garbage collect records, test
drHuangMHT Dec 17, 2024
f9b040e
documentation and formatting
drHuangMHT Dec 18, 2024
a9597da
clippy lint
drHuangMHT Dec 18, 2024
0e6b280
simplify Store trait
drHuangMHT Dec 20, 2024
fe14c42
Merge branch 'master' into peer-store
drHuangMHT Dec 20, 2024
92ac2fb
manifest and changelog
drHuangMHT Dec 20, 2024
913ed1f
Merge branch 'peer-store' of https://github.com/drHuangMHT/rust-libp2…
drHuangMHT Dec 20, 2024
b8a7114
export at libp2p crate root
drHuangMHT Dec 20, 2024
5f628fb
changelog for libp2p
drHuangMHT Dec 20, 2024
121e91b
introduce PeerRecord
drHuangMHT Dec 31, 2024
47048ec
remove borrowed type and unused associated type
drHuangMHT Dec 31, 2024
9da96ff
move garbage collection to Store level
drHuangMHT Jan 2, 2025
9945fd0
delay cloning of PeerRecord
drHuangMHT Jan 2, 2025
cb294c6
MemoryStore strict mode
drHuangMHT Jan 3, 2025
a9dc9aa
allow Store to report to Swarm
drHuangMHT Jan 8, 2025
c94f636
don't store connected peers
drHuangMHT Jan 23, 2025
a02f088
allow attaching custom data
drHuangMHT Jan 31, 2025
a909499
make Behaviour composable
drHuangMHT Feb 1, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ members = [
"misc/memory-connection-limits",
"misc/metrics",
"misc/multistream-select",
"misc/peer-store",
"misc/quick-protobuf-codec",
"misc/quickcheck-ext",
"misc/rw-stream-sink",
Expand Down Expand Up @@ -89,6 +90,7 @@ libp2p-memory-connection-limits = { version = "0.3.1", path = "misc/memory-conne
libp2p-metrics = { version = "0.15.0", path = "misc/metrics" }
libp2p-mplex = { version = "0.42.0", path = "muxers/mplex" }
libp2p-noise = { version = "0.45.1", path = "transports/noise" }
libp2p-peer-store = { version = "0.1.0", path = "misc/peer-store" }
libp2p-perf = { version = "0.4.0", path = "protocols/perf" }
libp2p-ping = { version = "0.45.1", path = "protocols/ping" }
libp2p-plaintext = { version = "0.42.0", path = "transports/plaintext" }
Expand All @@ -100,7 +102,7 @@ libp2p-request-response = { version = "0.28.0", path = "protocols/request-respon
libp2p-server = { version = "0.12.8", path = "misc/server" }
libp2p-stream = { version = "0.2.0-alpha.1", path = "protocols/stream" }
libp2p-swarm = { version = "0.45.2", path = "swarm" }
libp2p-swarm-derive = { version = "=0.35.0", path = "swarm-derive" } # `libp2p-swarm-derive` may not be compatible with different `libp2p-swarm` non-breaking releases. E.g. `libp2p-swarm` might introduce a new enum variant `FromSwarm` (which is `#[non-exhaustive]`) in a non-breaking release. Older versions of `libp2p-swarm-derive` would not forward this enum variant within the `NetworkBehaviour` hierarchy. Thus the version pinning is required.
libp2p-swarm-derive = { version = "=0.35.0", path = "swarm-derive" } # `libp2p-swarm-derive` may not be compatible with different `libp2p-swarm` non-breaking releases. E.g. `libp2p-swarm` might introduce a new enum variant `FromSwarm` (which is `#[non-exhaustive]`) in a non-breaking release. Older versions of `libp2p-swarm-derive` would not forward this enum variant within the `NetworkBehaviour` hierarchy. Thus the version pinning is required.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't need this white space right?

libp2p-swarm-test = { version = "0.5.0", path = "swarm-test" }
libp2p-tcp = { version = "0.42.0", path = "transports/tcp" }
libp2p-tls = { version = "0.5.0", path = "transports/tls" }
Expand Down
5 changes: 5 additions & 0 deletions libp2p/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 0.55.0(unreleased)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably will be addressed when solving the conflicts, but this doesn't need to be a minor, we can add the peer store as a patch release to the main libp2p


- Introduce `libp2p-peer-store`.
See [PR 5724](https://github.com/libp2p/rust-libp2p/pull/5724).

## 0.54.2

- Add `with_connection_timeout` on `SwarmBuilder` to allow configuration of the connection_timeout parameter.
Expand Down
2 changes: 2 additions & 0 deletions libp2p/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ mdns = ["dep:libp2p-mdns"]
memory-connection-limits = ["dep:libp2p-memory-connection-limits"]
metrics = ["dep:libp2p-metrics"]
noise = ["dep:libp2p-noise"]
# peer-store = ["dep:libp2p-peer-store"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to be uncommented right?

ping = ["dep:libp2p-ping", "libp2p-metrics?/ping"]
plaintext = ["dep:libp2p-plaintext"]
pnet = ["dep:libp2p-pnet"]
Expand Down Expand Up @@ -110,6 +111,7 @@ libp2p-identity = { workspace = true, features = ["rand"] }
libp2p-kad = { workspace = true, optional = true }
libp2p-metrics = { workspace = true, optional = true }
libp2p-noise = { workspace = true, optional = true }
libp2p-peer-store = { workspace = true }
libp2p-ping = { workspace = true, optional = true }
libp2p-plaintext = { workspace = true, optional = true }
libp2p-pnet = { workspace = true, optional = true }
Expand Down
2 changes: 2 additions & 0 deletions libp2p/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ pub use libp2p_metrics as metrics;
#[cfg(feature = "noise")]
#[doc(inline)]
pub use libp2p_noise as noise;
#[doc(inline)]
pub use libp2p_peer_store as peer_store;
#[cfg(feature = "ping")]
#[doc(inline)]
pub use libp2p_ping as ping;
Expand Down
4 changes: 4 additions & 0 deletions misc/peer-store/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## 0.1.0

- Introduce `libp2p-peer-store`.
See [PR 5724](https://github.com/libp2p/rust-libp2p/pull/5724).
21 changes: 21 additions & 0 deletions misc/peer-store/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[package]
name = "libp2p-peer-store"
edition = "2021"
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
version = "0.1.0"
authors = ["drHuangMHT <[email protected]>"]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
rust-version.workspace = true

[dependencies]
libp2p-core = { workspace = true }
libp2p-swarm = { workspace = true }
lru = "*"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to define proper versions of these dependencies

futures-timer = "*"
futures-util = "*"

[dev-dependencies]
libp2p-identity = { workspace = true, features = ["rand"] }

[lints]
workspace = true
179 changes: 179 additions & 0 deletions misc/peer-store/src/behaviour.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
use std::{collections::VecDeque, task::Poll};

use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::{dummy, NetworkBehaviour};

use crate::store::{AddressSource, Store};

/// Events generated by [`Behaviour`] and emitted back to the [`libp2p_swarm::Swarm`].
pub enum Event<S: Store> {
/// The peer's record has been updated.
/// Manually updating a record will always emit this event
/// even if it provides no new information.
RecordUpdated {
peer: PeerId,
},
Store(S::ToSwarm),
}

drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
pub struct Behaviour<S: Store> {
store: S,
/// Pending Events to be emitted back to the [`libp2p_swarm::Swarm`].
pending_events: VecDeque<Event<S>>,
}

drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
impl<'a, S> Behaviour<S>
where
S: Store + 'static,
{
pub fn new(store: S) -> Self {
Self {
store,
pending_events: VecDeque::new(),
}
}

/// Try to get all observed address of the given peer.
/// Returns `None` when the peer is not in the store.
pub fn address_of_peer<'b>(
&'a self,
peer: &'b PeerId,
) -> Option<impl Iterator<Item = &'a Multiaddr> + use<'a, 'b, S>> {
self.store.addresses_of_peer(peer)
}

/// Manually update a record.
/// This will always emit an `Event::RecordUpdated`.
pub fn update_address(&mut self, peer: &PeerId, address: &Multiaddr) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

having this duplication where the Behaviour and the Store share the same method is prone to confusion to the end user. I suggest we have a thin Behaviour delegating the on_swarm_event to the Store

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is for users who might want to update the cache from outside of the behavior. However if we only expect updates through swarm event, it can be removed.

self.store
.update_address(peer, address, AddressSource::Manual, false);
self.pending_events
.push_back(Event::RecordUpdated { peer: *peer });
}

/// Should be called when other protocol emits a [`PeerRecord`](libp2p_core::PeerRecord).
/// This will always emit an `Event::RecordUpdated`.
pub fn on_signed_peer_record(
&mut self,
signed_record: &libp2p_core::PeerRecord,
source: AddressSource,
) {
self.store
.update_certified_address(signed_record, source, false);
self.pending_events.push_back(Event::RecordUpdated {
peer: signed_record.peer_id(),
});
}

/// Get a immutable reference to the internal store.
pub fn store(&self) -> &S {
&self.store
}

/// Get a mutable reference to the internal store.
pub fn store_mut(&mut self) -> &mut S {
&mut self.store
}

fn on_address_update(
&mut self,
peer: &PeerId,
address: &Multiaddr,
source: AddressSource,
should_expire: bool,
) {
if self
.store
.update_address(peer, address, source, should_expire)
{
self.pending_events
.push_back(Event::RecordUpdated { peer: *peer });
}
}
fn handle_store_event(&mut self, event: super::store::Event) {
use super::store::Event::*;
match event {
RecordUpdated(peer) => self.pending_events.push_back(Event::RecordUpdated { peer }),
}
}
}

impl<S> NetworkBehaviour for Behaviour<S>
where
S: Store + 'static,
<S as Store>::ToSwarm: Send + Sync,
{
type ConnectionHandler = dummy::ConnectionHandler;

type ToSwarm = Event<S>;

fn handle_established_inbound_connection(
&mut self,
_connection_id: libp2p_swarm::ConnectionId,
peer: libp2p_core::PeerId,
_local_addr: &libp2p_core::Multiaddr,
remote_addr: &libp2p_core::Multiaddr,
) -> Result<libp2p_swarm::THandler<Self>, libp2p_swarm::ConnectionDenied> {
self.on_address_update(&peer, remote_addr, AddressSource::DirectConnection, false);
Ok(dummy::ConnectionHandler)
}

fn handle_pending_outbound_connection(
&mut self,
_connection_id: libp2p_swarm::ConnectionId,
maybe_peer: Option<PeerId>,
_addresses: &[Multiaddr],
_effective_role: libp2p_core::Endpoint,
) -> Result<Vec<Multiaddr>, libp2p_swarm::ConnectionDenied> {
if maybe_peer.is_none() {
return Ok(Vec::new());
}
let peer = maybe_peer.expect("already handled");
Ok(self
.store
.addresses_of_peer(&peer)
.map(|i| i.cloned().collect())
.unwrap_or_default())
}

fn handle_established_outbound_connection(
&mut self,
_connection_id: libp2p_swarm::ConnectionId,
peer: libp2p_core::PeerId,
addr: &libp2p_core::Multiaddr,
_role_override: libp2p_core::Endpoint,
_port_use: libp2p_core::transport::PortUse,
) -> Result<libp2p_swarm::THandler<Self>, libp2p_swarm::ConnectionDenied> {
self.on_address_update(&peer, addr, AddressSource::DirectConnection, false);
Ok(dummy::ConnectionHandler)
}

fn on_swarm_event(&mut self, event: libp2p_swarm::FromSwarm) {
if let Some(ev) = self.store.on_swarm_event(&event) {
self.handle_store_event(ev);
};
}

fn on_connection_handler_event(
&mut self,
_peer_id: libp2p_core::PeerId,
_connection_id: libp2p_swarm::ConnectionId,
_event: libp2p_swarm::THandlerOutEvent<Self>,
) {
unreachable!("No event will be produced by a dummy handler.")
}

fn poll(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<libp2p_swarm::ToSwarm<Self::ToSwarm, libp2p_swarm::THandlerInEvent<Self>>>
{
if let Some(ev) = self.pending_events.pop_front() {
return Poll::Ready(libp2p_swarm::ToSwarm::GenerateEvent(ev));
}
if let Some(ev) = self.store.poll(cx) {
self.pending_events.push_back(Event::Store(ev));
};
Poll::Pending
}
}
6 changes: 6 additions & 0 deletions misc/peer-store/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
mod behaviour;
pub mod memory_store;
mod store;

pub use behaviour::{Behaviour, Event};
pub use store::Store;
Loading
Loading