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