Skip to main content

karyon_p2p/discovery/
mod.rs

1pub mod kademlia;
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6
7use crate::{message::PeerAddr, PeerID, Result};
8
9/// Represents a discovered peer that the discovery protocol wants the
10/// Node to connect to.
11pub struct DiscoveredPeer {
12    pub peer_id: Option<PeerID>,
13    pub addrs: Vec<PeerAddr>,
14    pub discovery_addrs: Vec<PeerAddr>,
15}
16
17/// Connection lifecycle events the Node forwards to discovery.
18#[derive(Debug, Clone)]
19pub enum PeerConnectionEvent {
20    /// Outbound connection completed handshake successfully.
21    Connected(PeerID),
22    /// Previously-connected peer has disconnected.
23    Disconnected(PeerID),
24    /// Connection attempt failed. Peer id may be unknown for
25    /// manual peer endpoints whose id wasn't pre-shared.
26    ConnectFailed(Option<PeerID>),
27}
28
29/// Trait that any discovery protocol must implement.
30///
31/// Discovery implementations find peers and yield them via
32/// `recv()`. The Node awaits `recv()` in a loop and handles
33/// connecting - discovery never connects directly.
34#[async_trait]
35pub trait Discovery: Send + Sync {
36    /// Start the discovery service. Listen endpoints, if needed by
37    /// the implementation, must be provided at construction time.
38    async fn start(self: Arc<Self>) -> Result<()>;
39
40    /// Shutdown the discovery service.
41    async fn shutdown(&self);
42
43    /// Await the next discovered peer. The Node calls this in a
44    /// loop; on shutdown the surrounding task is cancelled.
45    async fn recv(&self) -> DiscoveredPeer;
46
47    /// Receive a peer connection event from the Node.
48    fn on_event(&self, event: PeerConnectionEvent);
49
50    /// Return peers in the routing table whose advertised bloom may
51    /// contain `item`. Used by application layers (e.g. Swarm) to find
52    /// candidates for protocol- or swarm-targeted dials. Implementations
53    /// without a routing table may return an empty vector.
54    fn find_peers_with(&self, item: &[u8]) -> Vec<DiscoveredPeer>;
55}