Skip to main content

Node

Struct Node 

Source
pub struct Node {
    config: Arc<Config>,
    key_pair: KeyPair,
    peer_id: PeerID,
    monitor: Arc<Monitor>,
    discovery: Arc<dyn Discovery>,
    peer_pool: Arc<PeerPool>,
    connector: Arc<Connector<PeerNetMsgCodec>>,
    listener: Arc<Listener<PeerNetMsgCodec>>,
    task_group: TaskGroup,
    bloom: BloomRef,
}
Expand description

Central entry point for the p2p network.

Manages peer connections, discovery, and protocol registration.

§Example

use karyon_core::async_runtime::global_executor;
use karyon_p2p::{Node, Config, keypair::{KeyPair, KeyPairType}};

let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
let config = Config {
    listen_endpoints: vec![
        "tcp://0.0.0.0:8000".parse().unwrap(),
    ],
    ..Config::default()
};

let node = Node::new(&key_pair, config, global_executor());

// node.run().await.unwrap();
// node.attach_protocol::<MyProto>(|peer| MyProto::new(peer)).await;
// node.shutdown().await;

Fields§

§config: Arc<Config>

The Configuration for the P2P network.

§key_pair: KeyPair

Identity Key pair

§peer_id: PeerID

Peer ID

§monitor: Arc<Monitor>

Responsible for network and system monitoring.

§discovery: Arc<dyn Discovery>

Discovery instance.

§peer_pool: Arc<PeerPool>

PeerPool instance.

§connector: Arc<Connector<PeerNetMsgCodec>>

Connector for outbound connections.

§listener: Arc<Listener<PeerNetMsgCodec>>

Listener for inbound connections.

§task_group: TaskGroup

Managing spawned tasks.

§bloom: BloomRef

Local bloom advertising what items (protocols, swarm keys, …) this node supports. The mandatory side is filtered with covers, the optional side with intersects. Updated by attach_protocol (via Protocol::kind()) and by application layers like Swarm.

Implementations§

Source§

impl Node

Source

pub fn new(key_pair: &KeyPair, config: Config, ex: Executor) -> Arc<Node>

Creates a new Node with the default Kademlia discovery.

Source

pub fn with_discovery( key_pair: &KeyPair, config: Config, discovery: Arc<dyn Discovery>, ex: Executor, ) -> Arc<Node>

Creates a new Node with a custom discovery implementation. The caller is responsible for wiring its own bloom_provider into the discovery; Node’s bloom_add_* methods will not affect it unless the discovery reads from the same source.

Source

pub async fn run(self: &Arc<Self>) -> Result<()>

Run the Node, starting listeners, PeerPool, and Discovery.

Source

async fn forward_peer_events(self: Arc<Self>)

Forward peer-pool lifecycle events to discovery so it can update its routing state. Each registered listener (Node’s here, plus any external Swarm subscriber) gets every event independently - no MPMC stealing.

Source

async fn connect_discovered_peers(self: Arc<Self>)

Consume discovered peers from the discovery service and connect to them. Runs forever; the task_group cancels it on Node::shutdown.

Source

pub async fn attach_protocol<P: ProtocolTrait>( &self, c: impl Fn(PeerConn) -> Result<Arc<dyn ProtocolTrait>> + Send + Sync + 'static, ) -> Result<()>

Attach a custom protocol. karyon runs the constructor closure once per connected peer with a typed PeerConn scoped to this protocol. Bloom advertises the protocol id according to P::kind().

Source

async fn attach_core_protocols(self: &Arc<Self>) -> Result<()>

Attach the core protocols (PING). Called once during run.

Source

pub fn bloom_add_mandatory(&self, item: impl AsRef<[u8]>)

Add an item the local node REQUIRES peers to also support. Reflected in the next bloom snapshot advertised in PeerMsg.

Source

pub fn bloom_add_optional(&self, item: impl AsRef<[u8]>)

Add an item the local node would LIKE peers to also support but doesn’t require. Used by Swarm and other layers for fuzzy protocol-aware discovery without rejecting non-matches.

Source

pub fn bloom_snapshot(&self) -> Bloom

Snapshot of the local bloom (mandatory + optional sides).

Source

pub fn find_peers_with(&self, item: impl AsRef<[u8]>) -> Vec<DiscoveredPeer>

Find peers in the routing table whose advertised bloom may contain item. Useful for swarm-targeted lookups (e.g. “peers in this room”) without changing handshake semantics.

Source

pub async fn peers(&self) -> usize

Returns the number of currently connected peers.

Source

pub fn config(&self) -> Arc<Config>

Returns the Config.

Source

pub fn peer_id(&self) -> &PeerID

Returns the PeerID.

Source

pub fn key_pair(&self) -> &KeyPair

Returns the KeyPair.

Source

pub async fn inbound_peers(&self) -> HashMap<PeerID, Endpoint>

Returns a map of inbound connected peers with their endpoints.

Source

pub async fn outbound_peers(&self) -> HashMap<PeerID, Endpoint>

Returns a map of outbound connected peers with their endpoints.

Source

pub fn monitor(&self) -> Arc<Monitor>

Returns the monitor to receive system events.

Source

pub fn register_peer_events(&self) -> EventListener<PeerEventTopic, PeerEvent>

Register a listener for peer lifecycle events. Each call returns a fresh listener that receives every event (true broadcast).

Source

pub async fn broadcast_to( &self, proto_id: &ProtocolID, msg: Vec<u8>, targets: &HashSet<PeerID>, )

Broadcast a message to a specific set of peers on a given protocol. Used by Swarm and other layers to scope broadcasts.

Source

pub async fn send_to( &self, peer_id: &PeerID, proto_id: &ProtocolID, msg: Vec<u8>, ) -> Result<()>

Send a message to a specific peer on the given protocol. Returns PeerNotFound if the peer is not currently connected.

Source

pub async fn peer_protocol_set( &self, pid: &PeerID, ) -> Option<HashSet<ProtocolID>>

Returns the negotiated protocol set for a connected peer, or None if no peer with that id is currently in the pool.

Source

pub async fn shutdown(&self)

Shuts down the Node.

Auto Trait Implementations§

§

impl !Freeze for Node

§

impl !RefUnwindSafe for Node

§

impl Send for Node

§

impl Sync for Node

§

impl Unpin for Node

§

impl UnsafeUnpin for Node

§

impl !UnwindSafe for Node

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more