sequencer/request_response/
network.rs

1use anyhow::{Context, Result};
2use async_trait::async_trait;
3use espresso_types::{PubKey, SeqTypes};
4use hotshot_types::message::MessageKind;
5use request_response::network::{Bytes, Sender as SenderTrait};
6use tokio::sync::mpsc;
7
8use crate::external_event_handler::{ExternalMessage, OutboundMessage};
9
10/// A wrapper type that we will implement the `Sender` trait for
11#[derive(Clone)]
12pub struct Sender(mpsc::Sender<OutboundMessage>);
13
14impl Sender {
15    pub fn new(sender: mpsc::Sender<OutboundMessage>) -> Self {
16        Self(sender)
17    }
18}
19
20/// Implement the `Sender` trait for the `RequestResponseSender` type. This tells
21/// the request response protocol how to send messages to other nodes.
22#[async_trait]
23impl SenderTrait<PubKey> for Sender {
24    async fn send_direct_message(&self, message: &Bytes, recipient: PubKey) -> Result<()> {
25        // Serialize the inner message
26        let message_bytes = bincode::serialize(&ExternalMessage::RequestResponse(message.to_vec()))
27            .with_context(|| "failed to serialize message")?;
28
29        // Send the message
30        self.0
31            .send(OutboundMessage::Direct(
32                MessageKind::External::<SeqTypes>(message_bytes),
33                recipient,
34            ))
35            .await
36            .with_context(|| "failed to send message over channel")?;
37        Ok(())
38    }
39
40    async fn send_broadcast_message(&self, message: &Bytes) -> Result<()> {
41        // Serialize the inner message
42        let message_bytes = bincode::serialize(&ExternalMessage::RequestResponse(message.to_vec()))
43            .with_context(|| "failed to serialize message")?;
44
45        // Send the message
46        self.0
47            .send(OutboundMessage::Broadcast(
48                MessageKind::External::<SeqTypes>(message_bytes),
49            ))
50            .await
51            .with_context(|| "failed to send message over channel")?;
52        Ok(())
53    }
54}