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 26 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
26 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
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
8 changes: 8 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ members = [
"transports/websocket-websys",
"transports/websocket",
"transports/webtransport-websys",
"wasm-tests/webtransport-tests",
"wasm-tests/webtransport-tests", "misc/peer-store",
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
]
resolver = "2"

Expand Down
12 changes: 12 additions & 0 deletions misc/peer-store/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "libp2p-peer-store"
version = "0.1.0"
edition = "2021"
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
rust-version.workspace = true

[dependencies]
libp2p-core = { workspace = true }
libp2p-swarm = { workspace = true }

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

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

use crate::store::Store;

/// Events of this behaviour that will be emmitted to the swarm.
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
pub enum Event {
RecordUpdated { peer: PeerId },
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
}

pub struct Behaviour<S> {
store: S,
/// Events that will be emitted.
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
pending_events: VecDeque<Event>,
}

impl<S> Behaviour<S>
where
S: Store + 'static,
{
pub fn new(store: S) -> Self {
Self {
store,
pending_events: VecDeque::new(),
}
}
/// List peers that are currently connected to this peer.
pub fn list_connected(&self) -> Box<[&PeerId]> {
self.store.list_connected()
}
/// 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(&self, peer: &PeerId) -> Option<Box<[super::AddressRecord]>> {
self.store.addresses_of_peer(peer)
}
/// Manually update a record.
/// This will always cause an `Event::RecordUpdated` to be emitted.
pub fn update_record(&mut self, peer: &PeerId, address: &Multiaddr) {
self.store.on_address_update(peer, address);
self.pending_events
.push_back(Event::RecordUpdated { peer: *peer });
}
}

impl<S> NetworkBehaviour for Behaviour<S>
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
where
S: Store + 'static,
{
type ConnectionHandler = dummy::ConnectionHandler;

type ToSwarm = Event;

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.store.on_peer_connect(&peer);
if self.store.on_address_update(&peer, remote_addr) {
self.pending_events.push_back(Event::RecordUpdated { peer });
}
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
Ok(dummy::ConnectionHandler)
}

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.store.on_peer_connect(&peer);
Copy link
Member

Choose a reason for hiding this comment

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

It might make more sense to remove this for FromSwarm events since a connection could be denied later on (ie connection limits, banned peer, etc.), so that way the store isnt exactly cluttered.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That makes sense. Will favor the swarm event.

Copy link
Member

Choose a reason for hiding this comment

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

can we instead define Store::handle_* methods that are called here and in the other NetworkBehaviour::handle_*
so that it allows us to further manage our peers?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

can we instead define Store::handle_* methods that are called here and in the other NetworkBehaviour::handle_* so that it allows us to further manage our peers?

What are those specifically? The store no longer record connected peers.

Ok(dummy::ConnectionHandler)
}

fn on_swarm_event(&mut self, event: libp2p_swarm::FromSwarm) {
match event {
FromSwarm::ConnectionClosed(info) => {
if info.remaining_established < 1 {
self.store.on_peer_disconnect(&info.peer_id);
}
}
FromSwarm::ConnectionEstablished(info) => {
if info.other_established == 0 {
self.store.on_peer_connect(&info.peer_id);
}
}
FromSwarm::NewExternalAddrOfPeer(info) => {
if self.store.on_address_update(&info.peer_id, info.addr) {
self.pending_events
.push_back(Event::RecordUpdated { peer: info.peer_id });
}
}
_ => {}
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
}
}

fn on_connection_handler_event(
&mut self,
_peer_id: libp2p_core::PeerId,
_connection_id: libp2p_swarm::ConnectionId,
_event: libp2p_swarm::THandlerOutEvent<Self>,
) {
todo!()
}

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));
}
Poll::Pending
}
}
24 changes: 24 additions & 0 deletions misc/peer-store/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
mod behaviour;
mod store;

use std::time::SystemTime;

pub use behaviour::{Behaviour, Event};
use libp2p_core::Multiaddr;
pub use store::{MemoryStore, Store};

pub struct AddressRecord<'a> {
address: &'a Multiaddr,
last_seen: &'a SystemTime,
}
impl<'a> AddressRecord<'a> {

Check failure on line 14 in misc/peer-store/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy (beta)

the following explicit lifetimes could be elided: 'a
/// The address of this record.
pub fn address(&self) -> &Multiaddr {
self.address
}
/// How much time has passed since the address is last reported wrt. current time.
/// This may fail because of system time change.
pub fn last_seen(&self) -> Result<std::time::Duration, std::time::SystemTimeError> {
self.last_seen.elapsed()
}
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
}
99 changes: 99 additions & 0 deletions misc/peer-store/src/store.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
use std::{
collections::{HashMap, HashSet},
time::SystemTime,
};

use libp2p_core::{Multiaddr, PeerId};

/// A store that
/// - keep track of currently connected peers;
/// - contains all observed addresses of peers;
pub trait Store {
/// Called when a peer connects.
fn on_peer_connect(&mut self, peer: &PeerId);
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

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

If we are tracking peer connections too, should we also keep tabs on the ConnectionId?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We can, but how to store it? I think there can be multiple connections from a single peer, no?

/// Called when a peer disconnects.
fn on_peer_disconnect(&mut self, peer: &PeerId);
/// Update an address record.
/// Return `true` when the address is new.
fn on_address_update(&mut self, peer: &PeerId, address: &Multiaddr) -> bool;
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: update gives the impression that a peer just has one address, and that this address gets updated here.
Wdyt of instead of calling it instead on_new_address or something like that?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Because for now I only see one address pop up at a time. I was planning to use a boxed slice but you know there would be a heap allocation, which isn't necessary for only one element.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Also we can't do a batch update so there will be a iterator anyway.

Copy link
Contributor

Choose a reason for hiding this comment

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

Sorry, maybe I wasn't clear. I was just nitpicking on the name of the function, not the address: &Multiaddr parameter :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Um, I'm not so sure about the naming, because the address isn't necessarily a new address. If the address is not new, it is updated due to LRU rules, like touch, so I can't quite make the decision.

Copy link
Contributor

Choose a reason for hiding this comment

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

Wdyt of on_address_discovered then?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Wdyt of on_address_discovered then?

discovered also kind of suggests the address is new? I'm not really convinced.

fn list_connected(&self) -> Box<[&PeerId]>;
fn addresses_of_peer(&self, peer: &PeerId) -> Option<Box<[super::AddressRecord]>>;
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
}

pub(crate) struct PeerAddressRecord {
addresses: HashMap<Multiaddr, AddressRecord>,
}
drHuangMHT marked this conversation as resolved.
Show resolved Hide resolved
impl PeerAddressRecord {
pub(crate) fn records(&self) -> Box<[super::AddressRecord]> {
self.addresses
.iter()
.map(|(address, record)| super::AddressRecord {
address,
last_seen: &record.last_seen,
})
.collect()
}
pub(crate) fn new(address: &Multiaddr) -> Self {
let mut address_book = HashMap::new();
address_book.insert(address.clone(), AddressRecord::new());
Self {
addresses: address_book,
}
}
pub(crate) fn on_address_update(&mut self, address: &Multiaddr) -> bool {
if let Some(record) = self.addresses.get_mut(address) {
record.update_last_seen();
false
} else {
self.addresses.insert(address.clone(), AddressRecord::new());
true
}
}
}

pub(crate) struct AddressRecord {
/// The time when the address is last seen.
last_seen: SystemTime,
}
impl AddressRecord {
pub(crate) fn new() -> Self {
Self {
last_seen: SystemTime::now(),
}
}
pub(crate) fn update_last_seen(&mut self) {
self.last_seen = SystemTime::now();
}
}

/// A in-memory store.
pub struct MemoryStore {
/// Peers that are currently connected.
connected_peers: HashSet<PeerId>,
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a case where using a HashSet<PeerId> to track connected peers is unsuitable for a specific use case? If now, how about moving this into the Behavior, so that the Store only concerns the "address-book" part of this behavior?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The idea of Store trait is to allow on-disk storage, now I think about it, this info will be changing in real time so it should be kept in memory anyway. Will move it into the behaviour itself.

Copy link
Member

Choose a reason for hiding this comment

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

can we have MemoryStore<T=()> so that we are able to store data for peers (like scoring etc):

Copy link
Contributor Author

Choose a reason for hiding this comment

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

can we have MemoryStore<T=()> so that we are able to store data for peers (like scoring etc):

MemoryStore is more of a reference implementation, I don't think it is necessary to include a generic parameter for customization since we are maintaining its internals.

/// An address book of peers regardless of their status(connected or not).
address_book: HashMap<PeerId, PeerAddressRecord>,
}

impl Store for MemoryStore {
fn on_peer_connect(&mut self, peer: &PeerId) {
self.connected_peers.insert(*peer);
}
fn on_peer_disconnect(&mut self, peer: &PeerId) {
self.connected_peers.remove(peer);
}
fn on_address_update(&mut self, peer: &PeerId, address: &Multiaddr) -> bool {
if let Some(record) = self.address_book.get_mut(peer) {
record.on_address_update(address)
} else {
self.address_book
.insert(*peer, PeerAddressRecord::new(address));
true
}
}
fn list_connected(&self) -> Box<[&PeerId]> {
self.connected_peers.iter().collect()
}
fn addresses_of_peer(&self, peer: &PeerId) -> Option<Box<[crate::AddressRecord]>> {
self.address_book.get(peer).map(|record| record.records())
}
}
Loading