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;
}
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 smol::Executor;
use karyon_p2p::{
protocol::{Protocol, ProtocolID, ProtocolEvent},
Backend, PeerID, Config, Version, Error, Peer,
keypair::{KeyPair, KeyPairType},
};
pub struct NewProtocol {
peer: Arc<Peer>,
}
impl NewProtocol {
fn new(peer: Arc<Peer>) -> Arc<dyn Protocol> {
Arc::new(Self {
peer,
})
}
}
#[async_trait]
impl Protocol for NewProtocol {
async fn start(self: Arc<Self>) -> Result<(), Error> {
loop {
match self.peer.recv::<Self>().await.expect("Receive msg") {
ProtocolEvent::Message(msg) => {
println!("{:?}", msg);
}
ProtocolEvent::Shutdown => {
break;
}
}
}
Ok(())
}
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 config = Config::default();
// Create a new Executor
let ex = Arc::new(Executor::new());
// Create a new Backend
let backend = Backend::new(&key_pair, config, ex.into());
// Attach the NewProtocol
let c = move |peer| NewProtocol::new(peer);
backend.attach_protocol::<NewProtocol>(c).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,
Start the protocol
Sourcefn id() -> ProtocolIDwhere
Self: Sized,
fn id() -> ProtocolIDwhere
Self: Sized,
Returns the unique ProtocolID associated with the protocol.