Skip to main content

snarkos_node/client/
router.rs

1// Copyright (c) 2019-2026 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
16use super::*;
17use snarkos_node_network::{PeerPoolHandling, harden_socket};
18use snarkos_node_router::{
19    Routing,
20    messages::{
21        BlockRequest,
22        BlockResponse,
23        DataBlocks,
24        DisconnectReason,
25        MessageCodec,
26        PeerRequest,
27        Ping,
28        Pong,
29        PuzzleResponse,
30        UnconfirmedTransaction,
31    },
32};
33use snarkos_node_tcp::{ConnectError, Connection, ConnectionSide, Tcp, connections::DisconnectOrigin};
34use snarkvm::{
35    console::network::{ConsensusVersion, Network},
36    ledger::{block::Transaction, narwhal::Data},
37    utilities::flatten_error,
38};
39
40use std::{io, net::SocketAddr};
41
42impl<N: Network, C: ConsensusStorage<N>> P2P for Client<N, C> {
43    /// Returns a reference to the TCP instance.
44    fn tcp(&self) -> &Tcp {
45        self.router.tcp()
46    }
47}
48
49#[async_trait]
50impl<N: Network, C: ConsensusStorage<N>> Handshake for Client<N, C> {
51    /// Performs the handshake protocol.
52    async fn perform_handshake(&self, mut connection: Connection) -> Result<Connection, ConnectError> {
53        // Perform the handshake.
54        let peer_addr = connection.addr();
55        let conn_side = connection.side();
56        let stream = self.borrow_stream(&mut connection);
57        // Make the socket more robust.
58        harden_socket(stream)?;
59        let genesis_header = *self.genesis.header();
60        let restrictions_id = self.ledger.vm().restrictions().restrictions_id();
61
62        self.router.handshake(peer_addr, stream, conn_side, genesis_header, restrictions_id).await?;
63
64        Ok(connection)
65    }
66}
67
68#[async_trait]
69impl<N: Network, C: ConsensusStorage<N>> OnConnect for Client<N, C> {
70    async fn on_connect(&self, peer_addr: SocketAddr) {
71        // Resolve the peer address to the listener address.
72        if let Some(listener_addr) = self.router().resolve_to_listener(peer_addr)
73            && let Some(peer) = self.router().get_connected_peer(listener_addr)
74        {
75            // If it's a bootstrap client, only request its peers.
76            if peer.node_type == NodeType::BootstrapClient {
77                self.router().send(listener_addr, Message::PeerRequest(PeerRequest));
78            } else {
79                // Send the first `Ping` message to the peer.
80                self.ping.on_peer_connected(listener_addr);
81            }
82        }
83    }
84}
85
86#[async_trait]
87impl<N: Network, C: ConsensusStorage<N>> Disconnect for Client<N, C> {
88    /// Any extra operations to be performed during a disconnect.
89    async fn handle_disconnect(&self, peer_addr: SocketAddr, origin: DisconnectOrigin) {
90        debug!("Physically disconnecting from {peer_addr}; origin: {origin:?}");
91
92        if let Some(peer_ip) = self.router.resolve_to_listener(peer_addr) {
93            let was_fully_connected = self.router.downgrade_peer_to_candidate(peer_ip);
94
95            // Only remove the peer from sync if the handshake was successful.
96            // This handles the cases where a client unsuccessfully tries to connect to another client using the router.
97            if was_fully_connected {
98                self.sync.remove_peer(&peer_ip);
99            }
100
101            // Clear cached entries applicable to the peer.
102            self.router.cache().clear_peer_entries(peer_ip);
103            #[cfg(feature = "metrics")]
104            self.router.update_metrics();
105        } else {
106            warn!("Got disconnect for a peer '{peer_addr}' that is not in the peer pool");
107        }
108    }
109}
110
111#[async_trait]
112impl<N: Network, C: ConsensusStorage<N>> Reading for Client<N, C> {
113    type Codec = MessageCodec<N>;
114    type Message = Message<N>;
115
116    /// Creates a [`Decoder`] used to interpret messages from the network.
117    /// The `side` param indicates the connection side **from the node's perspective**.
118    fn codec(&self, _peer_addr: SocketAddr, _side: ConnectionSide) -> Self::Codec {
119        Default::default()
120    }
121
122    /// Processes a message received from the network.
123    async fn process_message(&self, peer_addr: SocketAddr, message: Self::Message) -> io::Result<()> {
124        let clone = self.clone();
125        if matches!(message, Message::BlockRequest(_) | Message::BlockResponse(_)) {
126            // Handle BlockRequest and BlockResponse messages in a separate task to not block the
127            // inbound queue.
128            tokio::spawn(async move {
129                clone.process_message_inner(peer_addr, message).await;
130            });
131        } else {
132            self.process_message_inner(peer_addr, message).await;
133        }
134        Ok(())
135    }
136}
137
138impl<N: Network, C: ConsensusStorage<N>> Client<N, C> {
139    async fn process_message_inner(
140        &self,
141        peer_addr: SocketAddr,
142        message: <Client<N, C> as snarkos_node_tcp::protocols::Reading>::Message,
143    ) {
144        // Process the message. Disconnect if the peer violated the protocol.
145        if let Err(error) = self.inbound(peer_addr, message).await {
146            warn!("Failed to process inbound message from '{peer_addr}' - {error}");
147
148            //TODO(kaimast): set disconnect reason based on error
149            if let Some(peer_ip) = self.router().resolve_to_listener(peer_addr) {
150                warn!("Disconnecting from '{peer_ip}' for protocol violation");
151                self.router().send(peer_ip, Message::Disconnect(DisconnectReason::ProtocolViolation.into()));
152                // Disconnect from this peer.
153                self.router().disconnect(peer_ip);
154            }
155        }
156    }
157}
158
159#[async_trait]
160impl<N: Network, C: ConsensusStorage<N>> Routing<N> for Client<N, C> {}
161
162impl<N: Network, C: ConsensusStorage<N>> Heartbeat<N> for Client<N, C> {}
163
164impl<N: Network, C: ConsensusStorage<N>> Outbound<N> for Client<N, C> {
165    /// Returns a reference to the router.
166    fn router(&self) -> &Router<N> {
167        &self.router
168    }
169
170    /// Returns `true` if the node is synced up to the latest block (within the given tolerance).
171    fn is_block_synced(&self) -> bool {
172        self.sync.is_block_synced()
173    }
174
175    /// Returns the number of blocks this node is behind the greatest peer height,
176    /// or `None` if not connected to peers yet.
177    fn num_blocks_behind(&self) -> Option<u32> {
178        self.sync.num_blocks_behind()
179    }
180
181    /// Returns the current sync speed in blocks per second.
182    fn get_sync_speed(&self) -> f64 {
183        self.sync.get_sync_speed()
184    }
185}
186
187#[async_trait]
188impl<N: Network, C: ConsensusStorage<N>> Inbound<N> for Client<N, C> {
189    /// Returns `true` if the message version is valid.
190    fn is_valid_message_version(&self, message_version: u32) -> bool {
191        self.router().is_valid_message_version(message_version)
192    }
193
194    /// Handles a `BlockRequest` message.
195    fn block_request(&self, peer_ip: SocketAddr, message: BlockRequest) -> bool {
196        let BlockRequest { start_height, end_height } = &message;
197
198        // Get the latest consensus version, i.e., the one for the last block's height.
199        let latest_consensus_version = match N::CONSENSUS_VERSION(end_height.saturating_sub(1)) {
200            Ok(version) => version,
201            Err(err) => {
202                let err = err.context("Failed to retrieve consensus version");
203                error!("{}", flatten_error(&err));
204                return false;
205            }
206        };
207
208        // Retrieve the blocks within the requested range.
209        let blocks = match self.ledger.get_blocks(*start_height..*end_height) {
210            Ok(blocks) => DataBlocks(blocks),
211            Err(error) => {
212                let err =
213                    error.context(format!("Failed to retrieve blocks {start_height} to {end_height} from the ledger"));
214                error!("{}", flatten_error(&err));
215                return false;
216            }
217        };
218
219        // Send the `BlockResponse` message to the peer.
220        self.router()
221            .send(peer_ip, Message::BlockResponse(BlockResponse::new(message, blocks, latest_consensus_version)));
222        true
223    }
224
225    /// Handles a `BlockResponse` message.
226    fn block_response(
227        &self,
228        peer_ip: SocketAddr,
229        blocks: Vec<Block<N>>,
230        latest_consensus_version: Option<ConsensusVersion>,
231    ) -> bool {
232        // We do not need to explicitly sync here because insert_block_response, will wake up the sync task.
233        match self.sync.insert_block_responses(peer_ip, blocks, latest_consensus_version) {
234            Ok(_) => true,
235            Err(err) if err.is_benign() => {
236                let err: anyhow::Error = err.into();
237                debug!("{}", flatten_error(err.context(format!("Ignoring block response from peer '{peer_ip}'"))));
238                true
239            }
240            Err(err) if err.is_consensus_version_ahead() => {
241                let err: anyhow::Error = err.into();
242                let err = err.context(format!("Peer sent a block response with a newer consensus version '{peer_ip}'"));
243                warn!("{}", flatten_error(&err));
244                true
245            }
246            Err(err) if err.is_consensus_version_behind() => {
247                // If the error indicates the peer missed an upgrade and forked, ban it.
248                let err: anyhow::Error = err.into();
249                let err = err.context(format!("Peer sent an invalid block response '{peer_ip}'"));
250
251                let msg = flatten_error(&err);
252                error!("{msg}");
253                self.router().ip_ban_peer(peer_ip, Some(&err.to_string()));
254
255                false
256            }
257            Err(err) => {
258                let err: anyhow::Error = err.into();
259                let err = err.context(format!("Failed to insert block response from '{peer_ip}'"));
260                warn!("{}", flatten_error(err));
261
262                // TODO(kaimast): This needs more testing to ensure disconnect is the correct action.
263                true
264            }
265        }
266    }
267
268    /// Processes the block locators and sends back a `Pong` message.
269    fn ping(&self, peer_ip: SocketAddr, message: Ping<N>) -> bool {
270        // If block locators were provided, then update the peer in the sync pool.
271        if let Some(block_locators) = message.block_locators {
272            // Check the block locators are valid, and update the peer in the sync pool.
273            if let Err(err) = self.sync.update_peer_locators(peer_ip, &block_locators) {
274                warn!("{}", flatten_error(err.context(format!("Peer '{peer_ip}' sent invalid block locators"))));
275                return false;
276            }
277
278            let last_peer_height = Some(block_locators.latest_locator_height());
279            self.router().update_connected_peer(&peer_ip, |peer| peer.last_height_seen = last_peer_height);
280        }
281
282        // Send a `Pong` message to the peer.
283        self.router().send(peer_ip, Message::Pong(Pong { is_fork: Some(false) }));
284        true
285    }
286
287    /// Sleeps for a period and then sends a `Ping` message to the peer.
288    fn pong(&self, peer_ip: SocketAddr, _message: Pong) -> bool {
289        self.ping.on_pong_received(peer_ip);
290        true
291    }
292
293    /// Retrieves the latest epoch hash and latest block header, and returns the puzzle response to the peer.
294    fn puzzle_request(&self, peer_ip: SocketAddr) -> bool {
295        // Retrieve the latest epoch hash.
296        let epoch_hash = match self.ledger.latest_epoch_hash() {
297            Ok(epoch_hash) => epoch_hash,
298            Err(err) => {
299                let err = err.context(format!("Failed to prepare a puzzle request for '{peer_ip}'"));
300                error!("{}", flatten_error(err));
301                return false;
302            }
303        };
304        // Retrieve the latest block header.
305        let block_header = Data::Object(self.ledger.latest_header());
306        // Send the `PuzzleResponse` message to the peer.
307        self.router().send(peer_ip, Message::PuzzleResponse(PuzzleResponse { epoch_hash, block_header }));
308        true
309    }
310
311    /// Saves the latest epoch hash and latest block header in the node.
312    fn puzzle_response(&self, peer_ip: SocketAddr, _epoch_hash: N::BlockHash, _header: Header<N>) -> bool {
313        debug!("Disconnecting '{peer_ip}' for the following reason - {}", DisconnectReason::ProtocolViolation);
314        false
315    }
316
317    /// Propagates the unconfirmed solution to all connected validators.
318    async fn unconfirmed_solution(
319        &self,
320        peer_ip: SocketAddr,
321        serialized: UnconfirmedSolution<N>,
322        solution: Solution<N>,
323    ) -> bool {
324        // Try to add the solution to the verification queue, without changing LRU status of known solutions.
325        let mut solution_queue = self.solution_queue.lock();
326        if !solution_queue.contains(&solution.id()) {
327            solution_queue.put(solution.id(), (peer_ip, serialized, solution));
328        }
329
330        true // Maintain the connection
331    }
332
333    /// Handles an `UnconfirmedTransaction` message.
334    async fn unconfirmed_transaction(
335        &self,
336        peer_ip: SocketAddr,
337        serialized: UnconfirmedTransaction<N>,
338        transaction: Transaction<N>,
339    ) -> bool {
340        // Try to add the transaction to a verification queue, without changing LRU status of known transactions.
341        match &transaction {
342            Transaction::<N>::Fee(..) => (), // Fee Transactions are not valid.
343            Transaction::<N>::Deploy(..) => {
344                let mut deploy_queue = self.deploy_queue.lock();
345                if !deploy_queue.contains(&transaction.id()) {
346                    deploy_queue.put(transaction.id(), (peer_ip, serialized, transaction));
347                }
348            }
349            Transaction::<N>::Execute(..) => {
350                let mut execute_queue = self.execute_queue.lock();
351                if !execute_queue.contains(&transaction.id()) {
352                    execute_queue.put(transaction.id(), (peer_ip, serialized, transaction));
353                }
354            }
355        }
356
357        true // Maintain the connection
358    }
359}