Skip to main content

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/// Write buffer size at which the underlying `Framed` transport starts flushing frames to the
30/// socket from `poll_ready`, replacing the tokio-util default of 8KiB.
31///
32/// `RLPx` callers queue batches of messages (e.g. transaction broadcasts) and drive one flush per
33/// batch; the 8KiB default splits such a batch into one write syscall per few messages. A larger
34/// boundary batches them into fewer, larger writes. Once grown, the write buffer's capacity is
35/// retained for the connection's lifetime, so this also bounds the resident write buffer per
36/// connection.
37pub const DEFAULT_BACKPRESSURE_BOUNDARY: usize = 64 * 1024;
38
39/// `ECIES` stream over TCP exchanging raw bytes
40#[derive(Debug)]
41#[pin_project::pin_project]
42pub struct ECIESStream<Io> {
43    #[pin]
44    stream: Framed<Io, ECIESCodec>,
45    remote_id: PeerId,
46}
47
48impl<Io> ECIESStream<Io>
49where
50    Io: AsyncRead + AsyncWrite + Unpin,
51{
52    /// Connect to an `ECIES` server
53    #[instrument(level = "trace", target = "net::ecies", skip(transport, secret_key))]
54    pub async fn connect(
55        transport: Io,
56        secret_key: SecretKey,
57        remote_id: PeerId,
58    ) -> Result<Self, ECIESError> {
59        Self::connect_with_timeout(transport, secret_key, remote_id, HANDSHAKE_TIMEOUT).await
60    }
61
62    /// Wrapper around `connect_no_timeout` which enforces a timeout.
63    pub async fn connect_with_timeout(
64        transport: Io,
65        secret_key: SecretKey,
66        remote_id: PeerId,
67        timeout_limit: Duration,
68    ) -> Result<Self, ECIESError> {
69        timeout(timeout_limit, Self::connect_without_timeout(transport, secret_key, remote_id))
70            .await
71            .map_err(|_| ECIESError::from(ECIESErrorImpl::StreamTimeout))?
72    }
73
74    /// Connect to an `ECIES` server with no timeout.
75    pub async fn connect_without_timeout(
76        transport: Io,
77        secret_key: SecretKey,
78        remote_id: PeerId,
79    ) -> Result<Self, ECIESError> {
80        let ecies = ECIESCodec::new_client(secret_key, remote_id)?;
81
82        let mut transport = ecies.framed(transport);
83        transport.set_backpressure_boundary(DEFAULT_BACKPRESSURE_BOUNDARY);
84
85        trace!("sending ecies auth ...");
86        transport.send(EgressECIESValue::Auth).await?;
87
88        trace!("waiting for ecies ack ...");
89
90        let msg = transport.try_next().await?;
91
92        // `Framed` returns `None` if the underlying stream is no longer readable, and the codec is
93        // unable to decode another message from the (partially filled) buffer. This usually happens
94        // if the remote drops the TcpStream.
95        let msg = msg.ok_or(ECIESErrorImpl::UnreadableStream)?;
96
97        trace!("parsing ecies ack ...");
98        if matches!(msg, IngressECIESValue::Ack) {
99            Ok(Self { stream: transport, remote_id })
100        } else {
101            Err(ECIESErrorImpl::InvalidHandshake {
102                expected: IngressECIESValue::Ack,
103                msg: Some(msg),
104            }
105            .into())
106        }
107    }
108
109    /// Listen on a just connected ECIES client
110    pub async fn incoming(transport: Io, secret_key: SecretKey) -> Result<Self, ECIESError> {
111        let ecies = ECIESCodec::new_server(secret_key)?;
112
113        trace!("incoming ecies stream");
114        let mut transport = ecies.framed(transport);
115        transport.set_backpressure_boundary(DEFAULT_BACKPRESSURE_BOUNDARY);
116        let msg = transport.try_next().await?;
117
118        // `Framed` returns `None` if the underlying stream is no longer readable, and the codec is
119        // unable to decode another message from the (partially filled) buffer. This usually happens
120        // if the remote drops the TcpStream.
121        let msg = msg.ok_or(ECIESErrorImpl::UnreadableStream)?;
122
123        trace!("receiving ecies auth");
124        let remote_id = match &msg {
125            IngressECIESValue::AuthReceive(remote_id) => *remote_id,
126            _ => {
127                return Err(ECIESErrorImpl::InvalidHandshake {
128                    expected: IngressECIESValue::AuthReceive(Default::default()),
129                    msg: Some(msg),
130                }
131                .into())
132            }
133        };
134
135        trace!("sending ecies ack");
136        transport.send(EgressECIESValue::Ack).await?;
137
138        Ok(Self { stream: transport, remote_id })
139    }
140
141    /// Get the remote id
142    pub const fn remote_id(&self) -> PeerId {
143        self.remote_id
144    }
145}
146
147impl<Io> ECIESStream<Io> {
148    /// Sets the write buffer size at which the underlying transport starts flushing to the socket
149    /// from `poll_ready`, overriding [`DEFAULT_BACKPRESSURE_BOUNDARY`].
150    ///
151    /// A larger boundary batches more frames into a single write syscall when many messages are
152    /// sent back to back, at the cost of buffering more encrypted data in memory per connection.
153    pub fn set_backpressure_boundary(&mut self, boundary: usize) {
154        self.stream.set_backpressure_boundary(boundary);
155    }
156}
157
158impl<Io> Stream for ECIESStream<Io>
159where
160    Io: AsyncRead + Unpin,
161{
162    type Item = Result<BytesMut, io::Error>;
163
164    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
165        match ready!(self.project().stream.poll_next(cx)) {
166            Some(Ok(IngressECIESValue::Message(body))) => Poll::Ready(Some(Ok(body))),
167            Some(Err(err)) => Poll::Ready(Some(Err(io::Error::other(err)))),
168            Some(Ok(other)) => Poll::Ready(Some(Err(io::Error::other(format!(
169                "ECIES stream protocol error: expected message, received {other:?}"
170            ))))),
171            None => Poll::Ready(None),
172        }
173    }
174}
175
176impl<Io> Sink<Bytes> for ECIESStream<Io>
177where
178    Io: AsyncWrite + Unpin,
179{
180    type Error = io::Error;
181
182    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
183        self.project().stream.poll_ready(cx)
184    }
185
186    fn start_send(self: Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> {
187        self.project().stream.start_send(EgressECIESValue::Message(item))?;
188        Ok(())
189    }
190
191    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
192        self.project().stream.poll_flush(cx)
193    }
194
195    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
196        self.project().stream.poll_close(cx)
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::codec::MAX_FRAME_SIZE;
204    use reth_network_peers::pk2id;
205    use tokio::net::{TcpListener, TcpStream};
206
207    #[tokio::test]
208    async fn can_write_and_read() {
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::rng());
212
213        let handle = tokio::spawn(async move {
214            // roughly based off of the design of tokio::net::TcpListener
215            let (incoming, _) = listener.accept().await.unwrap();
216            let mut stream = ECIESStream::incoming(incoming, server_key).await.unwrap();
217
218            // use the stream to get the next message
219            let message = stream.next().await.unwrap().unwrap();
220            assert_eq!(message, Bytes::from("hello"));
221        });
222
223        // create the server pubkey
224        let server_id = pk2id(&server_key.public_key());
225
226        let client_key = SecretKey::new(&mut rand::rng());
227        let outgoing = TcpStream::connect(addr).await.unwrap();
228        let mut client_stream =
229            ECIESStream::connect(outgoing, client_key, server_id).await.unwrap();
230        client_stream.send(Bytes::from("hello")).await.unwrap();
231
232        // make sure the server receives the message and asserts before ending the test
233        handle.await.unwrap();
234    }
235
236    #[tokio::test]
237    async fn connection_should_timeout() {
238        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
239        let addr = listener.local_addr().unwrap();
240        let server_key = SecretKey::new(&mut rand::rng());
241
242        let _handle = tokio::spawn(async move {
243            // Delay accepting the connection for longer than the client's timeout period
244            tokio::time::sleep(Duration::from_secs(11)).await;
245            let (incoming, _) = listener.accept().await.unwrap();
246            let mut stream = ECIESStream::incoming(incoming, server_key).await.unwrap();
247
248            // use the stream to get the next message
249            let message = stream.next().await.unwrap().unwrap();
250            assert_eq!(message, Bytes::from("hello"));
251        });
252
253        // create the server pubkey
254        let server_id = pk2id(&server_key.public_key());
255
256        let client_key = SecretKey::new(&mut rand::rng());
257        let outgoing = TcpStream::connect(addr).await.unwrap();
258
259        // Attempt to connect, expecting a timeout due to the server's delayed response
260        let connect_result = ECIESStream::connect_with_timeout(
261            outgoing,
262            client_key,
263            server_id,
264            Duration::from_secs(1),
265        )
266        .await;
267
268        // Assert that a timeout error occurred
269        assert!(
270            matches!(connect_result, Err(e) if e.to_string() == ECIESErrorImpl::StreamTimeout.to_string())
271        );
272    }
273
274    #[tokio::test]
275    async fn rejects_frame_larger_than_header_can_describe() {
276        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
277        let addr = listener.local_addr().unwrap();
278        let server_key = SecretKey::new(&mut rand::rng());
279
280        let handle = tokio::spawn(async move {
281            let (incoming, _) = listener.accept().await.unwrap();
282            ECIESStream::incoming(incoming, server_key).await.unwrap()
283        });
284
285        let server_id = pk2id(&server_key.public_key());
286        let client_key = SecretKey::new(&mut rand::rng());
287        let outgoing = TcpStream::connect(addr).await.unwrap();
288        let mut client_stream =
289            ECIESStream::connect(outgoing, client_key, server_id).await.unwrap();
290        let mut server_stream = handle.await.unwrap();
291
292        let err = client_stream.send(Bytes::from(vec![0; MAX_FRAME_SIZE + 1])).await.unwrap_err();
293        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
294        assert_eq!(
295            err.to_string(),
296            ECIESErrorImpl::FrameTooLarge { size: MAX_FRAME_SIZE + 1, max_size: MAX_FRAME_SIZE }
297                .to_string()
298        );
299
300        // A frame header whose MAC does not match keeps the codec error as the read error source.
301        client_stream.stream.write_buffer_mut().extend_from_slice(&[0; 32]);
302        client_stream.flush().await.unwrap();
303        let err = server_stream.try_next().await.unwrap_err();
304        let source = err.get_ref().and_then(|source| source.downcast_ref::<ECIESError>());
305        assert!(
306            matches!(source.map(ECIESError::inner), Some(ECIESErrorImpl::TagCheckHeaderFailed)),
307            "{err:?}"
308        );
309    }
310
311    #[tokio::test]
312    async fn incoming_eof_before_auth_is_unreadable_stream() {
313        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
314        let addr = listener.local_addr().unwrap();
315        let server_key = SecretKey::new(&mut rand::rng());
316
317        // Close the connection without sending any auth data.
318        drop(TcpStream::connect(addr).await.unwrap());
319        let (incoming, _) = listener.accept().await.unwrap();
320
321        let err = ECIESStream::incoming(incoming, server_key).await.unwrap_err();
322        assert!(matches!(err.inner(), ECIESErrorImpl::UnreadableStream), "{err:?}");
323    }
324}