snarkos_node_tcp/protocols/
reading.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#[cfg(doc)]
17use crate::{Config, protocols::Handshake};
18use crate::{
19    ConnectionSide,
20    P2P,
21    Tcp,
22    protocols::{ProtocolHandler, ReturnableConnection},
23};
24
25use async_trait::async_trait;
26use bytes::BytesMut;
27use futures_util::StreamExt;
28use std::{io, net::SocketAddr};
29use tokio::{
30    io::AsyncRead,
31    sync::{mpsc, oneshot},
32};
33use tokio_util::codec::{Decoder, FramedRead};
34use tracing::*;
35
36/// Can be used to specify and enable reading, i.e. receiving inbound messages. If the [`Handshake`]
37/// protocol is enabled too, it goes into force only after the handshake has been concluded.
38///
39/// Each inbound message is isolated by the user-supplied [`Reading::Codec`], creating a [`Reading::Message`],
40/// which is immediately queued (with a [`Reading::MESSAGE_QUEUE_DEPTH`] limit) to be processed by
41/// [`Reading::process_message`]. The configured fatal IO errors result in an immediate disconnect
42/// (in order to e.g. avoid accidentally reading "borked" messages).
43#[async_trait]
44pub trait Reading: P2P
45where
46    Self: Clone + Send + Sync + 'static,
47{
48    /// The depth of per-connection queues used to process inbound messages; the greater it is, the more inbound
49    /// messages the node can enqueue, but setting it to a large value can make the node more susceptible to DoS
50    /// attacks.
51    ///
52    /// The default value is 1024.
53    const MESSAGE_QUEUE_DEPTH: usize = 1024;
54
55    /// The initial size of a per-connection buffer for reading inbound messages. Can be set to the maximum expected size
56    /// of the inbound message in order to only allocate it once.
57    ///
58    /// The default value is 1024KiB.
59    const INITIAL_BUFFER_SIZE: usize = 1024 * 1024;
60
61    /// The final (deserialized) type of inbound messages.
62    type Message: Send;
63
64    /// The user-supplied [`Decoder`] used to interpret inbound messages.
65    type Codec: Decoder<Item = Self::Message, Error = io::Error> + Send;
66
67    /// Prepares the node to receive messages.
68    async fn enable_reading(&self) {
69        let (conn_sender, mut conn_receiver) = mpsc::unbounded_channel();
70
71        // use a channel to know when the reading task is ready
72        let (tx_reading, rx_reading) = oneshot::channel();
73
74        // the main task spawning per-connection tasks reading messages from their streams
75        let self_clone = self.clone();
76        let reading_task = tokio::spawn(async move {
77            trace!(parent: self_clone.tcp().span(), "spawned the Reading handler task");
78            tx_reading.send(()).unwrap(); // safe; the channel was just opened
79
80            // these objects are sent from `Tcp::adapt_stream`
81            while let Some(returnable_conn) = conn_receiver.recv().await {
82                self_clone.handle_new_connection(returnable_conn).await;
83            }
84        });
85        let _ = rx_reading.await;
86        self.tcp().tasks.lock().push(reading_task);
87
88        // register the Reading handler with the Tcp
89        let hdl = Box::new(ProtocolHandler(conn_sender));
90        assert!(self.tcp().protocols.reading.set(hdl).is_ok(), "the Reading protocol was enabled more than once!");
91    }
92
93    /// Creates a [`Decoder`] used to interpret messages from the network.
94    /// The `side` param indicates the connection side **from the node's perspective**.
95    fn codec(&self, addr: SocketAddr, side: ConnectionSide) -> Self::Codec;
96
97    /// Processes an inbound message. Can be used to update state, send replies etc.
98    async fn process_message(&self, source: SocketAddr, message: Self::Message) -> io::Result<()>;
99}
100
101/// This trait is used to restrict access to methods that would otherwise be public in [`Reading`].
102#[async_trait]
103trait ReadingInternal: Reading {
104    /// Applies the [`Reading`] protocol to a single connection.
105    async fn handle_new_connection(&self, (conn, conn_returner): ReturnableConnection);
106
107    /// Wraps the user-supplied [`Decoder`] ([`Reading::Codec`]) in another one used for message accounting.
108    fn map_codec<T: AsyncRead>(
109        &self,
110        framed: FramedRead<T, Self::Codec>,
111        addr: SocketAddr,
112    ) -> FramedRead<T, CountingCodec<Self::Codec>>;
113}
114
115#[async_trait]
116impl<R: Reading> ReadingInternal for R {
117    async fn handle_new_connection(&self, (mut conn, conn_returner): ReturnableConnection) {
118        let addr = conn.addr();
119        let codec = self.codec(addr, !conn.side());
120        let reader = conn.reader.take().expect("missing connection reader!");
121        let framed = FramedRead::new(reader, codec);
122        let mut framed = self.map_codec(framed, addr);
123
124        // the connection will notify the reading task once it's fully ready
125        let (tx_conn_ready, rx_conn_ready) = oneshot::channel();
126        conn.readiness_notifier = Some(tx_conn_ready);
127
128        if Self::INITIAL_BUFFER_SIZE != 0 {
129            framed.read_buffer_mut().reserve(Self::INITIAL_BUFFER_SIZE);
130        }
131
132        let (inbound_message_sender, mut inbound_message_receiver) = mpsc::channel(Self::MESSAGE_QUEUE_DEPTH);
133
134        // use a channel to know when the processing task is ready
135        let (tx_processing, rx_processing) = oneshot::channel::<()>();
136
137        // the task for processing parsed messages
138        let self_clone = self.clone();
139        let inbound_processing_task = tokio::spawn(async move {
140            let node = self_clone.tcp();
141            trace!(parent: node.span(), "spawned a task for processing messages from {addr}");
142            tx_processing.send(()).unwrap(); // safe; the channel was just opened
143
144            while let Some(msg) = inbound_message_receiver.recv().await {
145                if let Err(e) = self_clone.process_message(addr, msg).await {
146                    error!(parent: node.span(), "can't process a message from {addr}: {e}");
147                    node.known_peers().register_failure(addr.ip());
148                }
149                #[cfg(feature = "metrics")]
150                metrics::decrement_gauge(metrics::tcp::TCP_TASKS, 1f64);
151            }
152        });
153        let _ = rx_processing.await;
154        conn.tasks.push(inbound_processing_task);
155
156        // use a channel to know when the reader task is ready
157        let (tx_reader, rx_reader) = oneshot::channel::<()>();
158
159        // the task for reading messages from a stream
160        let node = self.tcp().clone();
161        let reader_task = tokio::spawn(async move {
162            trace!(parent: node.span(), "spawned a task for reading messages from {addr}");
163            tx_reader.send(()).unwrap(); // safe; the channel was just opened
164
165            // postpone reads until the connection is fully established; if the process fails,
166            // this task gets aborted, so there is no need for a dedicated timeout
167            let _ = rx_conn_ready.await;
168
169            while let Some(bytes) = framed.next().await {
170                match bytes {
171                    Ok(msg) => {
172                        // send the message for further processing
173                        if let Err(e) = inbound_message_sender.try_send(msg) {
174                            error!(parent: node.span(), "can't process a message from {addr}: {e}");
175                            node.stats().register_failure();
176                        }
177                        #[cfg(feature = "metrics")]
178                        metrics::increment_gauge(metrics::tcp::TCP_TASKS, 1f64);
179                    }
180                    Err(e) => {
181                        error!(parent: node.span(), "can't read from {addr}: {e}");
182                        node.known_peers().register_failure(addr.ip());
183                        if node.config().fatal_io_errors.contains(&e.kind()) {
184                            break;
185                        }
186                    }
187                }
188            }
189
190            let _ = node.disconnect(addr).await;
191        });
192        let _ = rx_reader.await;
193        conn.tasks.push(reader_task);
194
195        // return the Connection to the Tcp, resuming Tcp::adapt_stream
196        if conn_returner.send(Ok(conn)).is_err() {
197            unreachable!("couldn't return a Connection to the Tcp");
198        }
199    }
200
201    fn map_codec<T: AsyncRead>(
202        &self,
203        framed: FramedRead<T, Self::Codec>,
204        addr: SocketAddr,
205    ) -> FramedRead<T, CountingCodec<Self::Codec>> {
206        framed.map_decoder(|codec| CountingCodec { codec, node: self.tcp().clone(), addr, acc: 0 })
207    }
208}
209
210/// A wrapper [`Decoder`] that also counts the inbound messages.
211struct CountingCodec<D: Decoder> {
212    codec: D,
213    node: Tcp,
214    addr: SocketAddr,
215    acc: usize,
216}
217
218impl<D: Decoder> Decoder for CountingCodec<D> {
219    type Error = D::Error;
220    type Item = D::Item;
221
222    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
223        let initial_buf_len = src.len();
224        let ret = self.codec.decode(src)?;
225        let final_buf_len = src.len();
226        let read_len = initial_buf_len - final_buf_len + self.acc;
227
228        if read_len != 0 {
229            trace!(parent: self.node.span(), "read {}B from {}", read_len, self.addr);
230
231            if ret.is_some() {
232                self.acc = 0;
233                self.node.known_peers().register_received_message(self.addr.ip(), read_len);
234                self.node.stats().register_received_message(read_len);
235            } else {
236                self.acc = read_len;
237            }
238        }
239
240        Ok(ret)
241    }
242}