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 flags() -> ProtocolFlags
       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) -> Self {
        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::new).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 flags() -> ProtocolFlags
where Self: Sized,

How this protocol takes part in handshake and discovery. Defaults to PREFERRED – override with REQUIRED for protocols needed for any meaningful interaction (e.g. PING).

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§