reth_ecies/
stream.rs

1//! The ECIES Stream implementation which wraps over [`AsyncRead`] and [`AsyncWrite`].
2
3use crate::{
4    codec::ECIESCodec, error::ECIESErrorImpl, ECIESError, EgressECIESValue, IngressECIESValue,
5};
6use alloy_primitives::{
7    bytes::{Bytes, BytesMut},
8    B512 as PeerId,
9};
10use futures::{ready, Sink, SinkExt};
11use secp256k1::SecretKey;
12use std::{
13    fmt::Debug,
14    io,
15    pin::Pin,
16    task::{Context, Poll},
17    time::Duration,
18};
19use tokio::{
20    io::{AsyncRead, AsyncWrite},
21    time::timeout,
22};
23use tokio_stream::{Stream, StreamExt};
24use tokio_util::codec::{Decoder, Framed};
25use tracing::{instrument, trace};
26
27const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
28
29/// `ECIES` stream over TCP exchanging raw bytes
30#[derive(Debug)]
31#[pin_project::pin_project]
32pub struct ECIESStream<Io> {
33    #[pin]
34    stream: Framed<Io, ECIESCodec>,
35    remote_id: PeerId,
36}
37
38impl<Io> ECIESStream<Io>
39where
40    Io: AsyncRead + AsyncWrite + Unpin,
41{
42    /// Connect to an `ECIES` server
43    #[instrument(level = "trace", target = "net::ecies", skip(transport, secret_key))]
44    pub async fn connect(
45        transport: Io,
46        secret_key: SecretKey,
47        remote_id: PeerId,
48    ) -> Result<Self, ECIESError> {
49        Self::connect_with_timeout(transport, secret_key, remote_id, HANDSHAKE_TIMEOUT).await
50    }
51
52    /// Wrapper around `connect_no_timeout` which enforces a timeout.
53    pub async fn connect_with_timeout(
54        transport: Io,
55        secret_key: SecretKey,
56        remote_id: PeerId,
57        timeout_limit: Duration,
58    ) -> Result<Self, ECIESError> {
59        timeout(timeout_limit, Self::connect_without_timeout(transport, secret_key, remote_id))
60            .await
61            .map_err(|_| ECIESError::from(ECIESErrorImpl::StreamTimeout))?
62    }
63
64    /// Connect to an `ECIES` server with no timeout.
65    pub async fn connect_without_timeout(
66        transport: Io,
67        secret_key: SecretKey,
68        remote_id: PeerId,
69    ) -> Result<Self, ECIESError> {
70        let ecies = ECIESCodec::new_client(secret_key, remote_id)?;
71
72        let mut transport = ecies.framed(transport);
73
74        trace!("sending ecies auth ...");
75        transport.send(EgressECIESValue::Auth).await?;
76
77        trace!("waiting for ecies ack ...");
78
79        let msg = transport.try_next().await?;
80
81        // `Framed` returns `None` if the underlying stream is no longer readable, and the codec is
82        // unable to decode another message from the (partially filled) buffer. This usually happens
83        // if the remote drops the TcpStream.
84        let msg = msg.ok_or(ECIESErrorImpl::UnreadableStream)?;
85
86        trace!("parsing ecies ack ...");
87        if matches!(msg, IngressECIESValue::Ack) {
88            Ok(Self { stream: transport, remote_id })
89        } else {
90            Err(ECIESErrorImpl::InvalidHandshake {
91                expected: IngressECIESValue::Ack,
92                msg: Some(msg),
93            }
94            .into())
95        }
96    }
97
98    /// Listen on a just connected ECIES client
99    pub async fn incoming(transport: Io, secret_key: SecretKey) -> Result<Self, ECIESError> {
100        let ecies = ECIESCodec::new_server(secret_key)?;
101
102        trace!("incoming ecies stream");
103        let mut transport = ecies.framed(transport);
104        let msg = transport.try_next().await?;
105
106        trace!("receiving ecies auth");
107        let remote_id = match &msg {
108            Some(IngressECIESValue::AuthReceive(remote_id)) => *remote_id,
109            _ => {
110                return Err(ECIESErrorImpl::InvalidHandshake {
111                    expected: IngressECIESValue::AuthReceive(Default::default()),
112                    msg,
113                }
114                .into())
115            }
116        };
117
118        trace!("sending ecies ack");
119        transport.send(EgressECIESValue::Ack).await?;
120
121        Ok(Self { stream: transport, remote_id })
122    }
123
124    /// Get the remote id
125    pub const fn remote_id(&self) -> PeerId {
126        self.remote_id
127    }
128}
129
130impl<Io> Stream for ECIESStream<Io>
131where
132    Io: AsyncRead + Unpin,
133{
134    type Item = Result<BytesMut, io::Error>;
135
136    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
137        match ready!(self.project().stream.poll_next(cx)) {
138            Some(Ok(IngressECIESValue::Message(body))) => Poll::Ready(Some(Ok(body))),
139            Some(other) => Poll::Ready(Some(Err(io::Error::other(format!(
140                "ECIES stream protocol error: expected message, received {other:?}"
141            ))))),
142            None => Poll::Ready(None),
143        }
144    }
145}
146
147impl<Io> Sink<Bytes> for ECIESStream<Io>
148where
149    Io: AsyncWrite + Unpin,
150{
151    type Error = io::Error;
152
153    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
154        self.project().stream.poll_ready(cx)
155    }
156
157    fn start_send(self: Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> {
158        self.project().stream.start_send(EgressECIESValue::Message(item))?;
159        Ok(())
160    }
161
162    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
163        self.project().stream.poll_flush(cx)
164    }
165
166    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
167        self.project().stream.poll_close(cx)
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use reth_network_peers::pk2id;
175    use secp256k1::SECP256K1;
176    use tokio::net::{TcpListener, TcpStream};
177
178    #[tokio::test]
179    async fn can_write_and_read() {
180        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
181        let addr = listener.local_addr().unwrap();
182        let server_key = SecretKey::new(&mut rand_08::thread_rng());
183
184        let handle = tokio::spawn(async move {
185            // roughly based off of the design of tokio::net::TcpListener
186            let (incoming, _) = listener.accept().await.unwrap();
187            let mut stream = ECIESStream::incoming(incoming, server_key).await.unwrap();
188
189            // use the stream to get the next message
190            let message = stream.next().await.unwrap().unwrap();
191            assert_eq!(message, Bytes::from("hello"));
192        });
193
194        // create the server pubkey
195        let server_id = pk2id(&server_key.public_key(SECP256K1));
196
197        let client_key = SecretKey::new(&mut rand_08::thread_rng());
198        let outgoing = TcpStream::connect(addr).await.unwrap();
199        let mut client_stream =
200            ECIESStream::connect(outgoing, client_key, server_id).await.unwrap();
201        client_stream.send(Bytes::from("hello")).await.unwrap();
202
203        // make sure the server receives the message and asserts before ending the test
204        handle.await.unwrap();
205    }
206
207    #[tokio::test]
208    async fn connection_should_timeout() {
209        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
210        let addr = listener.local_addr().unwrap();
211        let server_key = SecretKey::new(&mut rand_08::thread_rng());
212
213        let _handle = tokio::spawn(async move {
214            // Delay accepting the connection for longer than the client's timeout period
215            tokio::time::sleep(Duration::from_secs(11)).await;
216            let (incoming, _) = listener.accept().await.unwrap();
217            let mut stream = ECIESStream::incoming(incoming, server_key).await.unwrap();
218
219            // use the stream to get the next message
220            let message = stream.next().await.unwrap().unwrap();
221            assert_eq!(message, Bytes::from("hello"));
222        });
223
224        // create the server pubkey
225        let server_id = pk2id(&server_key.public_key(SECP256K1));
226
227        let client_key = SecretKey::new(&mut rand_08::thread_rng());
228        let outgoing = TcpStream::connect(addr).await.unwrap();
229
230        // Attempt to connect, expecting a timeout due to the server's delayed response
231        let connect_result = ECIESStream::connect_with_timeout(
232            outgoing,
233            client_key,
234            server_id,
235            Duration::from_secs(1),
236        )
237        .await;
238
239        // Assert that a timeout error occurred
240        assert!(
241            matches!(connect_result, Err(e) if e.to_string() == ECIESErrorImpl::StreamTimeout.to_string())
242        );
243    }
244}