request_response/network.rs
1//! This file contains the [`Sender`] and [`Receiver`] traits. These traits are **used** by the
2//! [`RequestResponseProtocol`] to send and receive messages from a network or other source.
3//!
4//! There is no blanket implementation of [`Receiver`] for a network, because both HS and the
5//! confirmation layer will receive messages from a single point and _then_ decide what to do
6//! with them (as opposed to having some sort of filtering mechanism). So for [`Receiver`] I've
7//! done a blanket implementation for channels that send [`Vec<u8>`]s.
8
9use std::sync::Arc;
10
11use anyhow::Result;
12use async_trait::async_trait;
13use hotshot_types::traits::signature_key::SignatureKey;
14use tokio::sync::mpsc;
15
16/// A type alias for a shareable byte array
17pub type Bytes = Arc<Vec<u8>>;
18
19/// The [`Sender`] trait is used to allow the [`RequestResponseProtocol`] to send messages to a specific recipient
20#[async_trait]
21pub trait Sender<K: SignatureKey + 'static>: Send + Sync + 'static + Clone {
22 /// Send a message to a specific recipient
23 async fn send_direct_message(&self, message: &Bytes, recipient: K) -> Result<()>;
24}
25
26/// The [`Receiver`] trait is used to allow the [`RequestResponseProtocol`] to receive messages from a network
27/// or other source.
28#[async_trait]
29pub trait Receiver: Send + Sync + 'static {
30 /// Receive a message. Returning an error here means the receiver will _NEVER_ receive any more messages
31 async fn receive_message(&mut self) -> Result<Bytes>;
32}
33
34/// An implementation of the [`Receiver`] trait for the [`mpsc::Receiver`] type. Allows us to send messages
35/// to a channel and have the protocol receive them.
36#[async_trait]
37impl Receiver for mpsc::Receiver<Bytes> {
38 async fn receive_message(&mut self) -> Result<Bytes> {
39 // Just receive a message from the channel
40 self.recv().await.ok_or(anyhow::anyhow!("channel closed"))
41 }
42}