Skip to main content

Protocol

Trait Protocol 

Source
pub trait Protocol: Send + Sync {
    // Required methods
    fn start<'async_trait>(
        self: Arc<Self>,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
       where Self: 'async_trait;
    fn version() -> Result<Version>
       where Self: Sized;
    fn id() -> ProtocolID
       where Self: Sized;

    // Provided method
    fn kind() -> ProtocolKind
       where Self: Sized { ... }
}
Expand description

The Protocol trait defines the interface for core protocols and custom protocols.

§Example

use std::sync::Arc;

use async_trait::async_trait;

use karyon_core::async_runtime::global_executor;
use karyon_p2p::{
    protocol::{PeerConn, Protocol, ProtocolID},
    Node, Config, Version, Error,
    keypair::{KeyPair, KeyPairType},
};

pub struct NewProtocol {
    peer: PeerConn,
}

impl NewProtocol {
    fn new(peer: PeerConn) -> Arc<dyn Protocol> {
        Arc::new(Self { peer })
    }
}

#[async_trait]
impl Protocol for NewProtocol {
    async fn start(self: Arc<Self>) -> Result<(), Error> {
        loop {
            let bytes = self.peer.recv().await?;
            println!("{:?}", bytes);
        }
    }

    fn version() -> Result<Version, Error> {
        "0.2.0, >0.1.0".parse()
    }

    fn id() -> ProtocolID {
        "NEWPROTOCOLID".into()
    }
}

async {
    let key_pair = KeyPair::generate(&KeyPairType::Ed25519);
    let node = Node::new(&key_pair, Config::default(), global_executor());
    node.attach_protocol::<NewProtocol>(|peer| Ok(NewProtocol::new(peer))).await.unwrap();
};

Required Methods§

Source

fn start<'async_trait>( self: Arc<Self>, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait,

Drive the protocol to completion. Use self.peer.recv() etc.

Source

fn version() -> Result<Version>
where Self: Sized,

Returns the version of the protocol.

Source

fn id() -> ProtocolID
where Self: Sized,

Returns the unique ProtocolID associated with the protocol.

Provided Methods§

Source

fn kind() -> ProtocolKind
where Self: Sized,

Whether peers must speak this protocol or it’s optional. Defaults to Optional – override for protocols required for any meaningful interaction (e.g. PING).

Implementors§