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§
Sourcefn start<'async_trait>(
self: Arc<Self>,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>where
Self: 'async_trait,
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.
Sourcefn id() -> ProtocolIDwhere
Self: Sized,
fn id() -> ProtocolIDwhere
Self: Sized,
Returns the unique ProtocolID associated with the protocol.
Provided Methods§
Sourcefn kind() -> ProtocolKindwhere
Self: Sized,
fn kind() -> ProtocolKindwhere
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).