snarkos_node/validator/
router.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
16use super::*;
17use snarkos_node_router::messages::{
18    BlockRequest,
19    BlockResponse,
20    DataBlocks,
21    DisconnectReason,
22    Message,
23    MessageCodec,
24    Ping,
25    Pong,
26    UnconfirmedTransaction,
27};
28use snarkos_node_tcp::{Connection, ConnectionSide, Tcp};
29use snarkvm::{
30    ledger::narwhal::Data,
31    prelude::{Network, block::Transaction, error},
32};
33
34use std::{io, net::SocketAddr, time::Duration};
35
36impl<N: Network, C: ConsensusStorage<N>> P2P for Validator<N, C> {
37    /// Returns a reference to the TCP instance.
38    fn tcp(&self) -> &Tcp {
39        self.router.tcp()
40    }
41}
42
43#[async_trait]
44impl<N: Network, C: ConsensusStorage<N>> Handshake for Validator<N, C> {
45    /// Performs the handshake protocol.
46    async fn perform_handshake(&self, mut connection: Connection) -> io::Result<Connection> {
47        // Perform the handshake.
48        let peer_addr = connection.addr();
49        let conn_side = connection.side();
50        let stream = self.borrow_stream(&mut connection);
51        let genesis_header = self.ledger.get_header(0).map_err(|e| error(format!("{e}")))?;
52        let restrictions_id = self.ledger.vm().restrictions().restrictions_id();
53        self.router.handshake(peer_addr, stream, conn_side, genesis_header, restrictions_id).await?;
54
55        Ok(connection)
56    }
57}
58
59#[async_trait]
60impl<N: Network, C: ConsensusStorage<N>> OnConnect for Validator<N, C>
61where
62    Self: Outbound<N>,
63{
64    async fn on_connect(&self, peer_addr: SocketAddr) {
65        // Resolve the peer address to the listener address.
66        let Some(peer_ip) = self.router.resolve_to_listener(&peer_addr) else { return };
67        // Promote the peer's status from "connecting" to "connected".
68        self.router().insert_connected_peer(peer_ip);
69        // Retrieve the block locators.
70        let block_locators = match self.sync.get_block_locators() {
71            Ok(block_locators) => Some(block_locators),
72            Err(e) => {
73                error!("Failed to get block locators: {e}");
74                return;
75            }
76        };
77        // Send the first `Ping` message to the peer.
78        self.send_ping(peer_ip, block_locators);
79    }
80}
81
82#[async_trait]
83impl<N: Network, C: ConsensusStorage<N>> Disconnect for Validator<N, C> {
84    /// Any extra operations to be performed during a disconnect.
85    async fn handle_disconnect(&self, peer_addr: SocketAddr) {
86        if let Some(peer_ip) = self.router.resolve_to_listener(&peer_addr) {
87            self.sync.remove_peer(&peer_ip);
88            self.router.remove_connected_peer(peer_ip);
89        }
90    }
91}
92
93#[async_trait]
94impl<N: Network, C: ConsensusStorage<N>> Writing for Validator<N, C> {
95    type Codec = MessageCodec<N>;
96    type Message = Message<N>;
97
98    /// Creates an [`Encoder`] used to write the outbound messages to the target stream.
99    /// The `side` parameter indicates the connection side **from the node's perspective**.
100    fn codec(&self, _addr: SocketAddr, _side: ConnectionSide) -> Self::Codec {
101        Default::default()
102    }
103}
104
105#[async_trait]
106impl<N: Network, C: ConsensusStorage<N>> Reading for Validator<N, C> {
107    type Codec = MessageCodec<N>;
108    type Message = Message<N>;
109
110    /// Creates a [`Decoder`] used to interpret messages from the network.
111    /// The `side` param indicates the connection side **from the node's perspective**.
112    fn codec(&self, _peer_addr: SocketAddr, _side: ConnectionSide) -> Self::Codec {
113        Default::default()
114    }
115
116    /// Processes a message received from the network.
117    async fn process_message(&self, peer_addr: SocketAddr, message: Self::Message) -> io::Result<()> {
118        let clone = self.clone();
119        if matches!(message, Message::BlockRequest(_) | Message::BlockResponse(_)) {
120            // Handle BlockRequest and BlockResponse messages in a separate task to not block the
121            // inbound queue.
122            tokio::spawn(async move {
123                clone.process_message_inner(peer_addr, message).await;
124            });
125        } else {
126            self.process_message_inner(peer_addr, message).await;
127        }
128        Ok(())
129    }
130}
131
132impl<N: Network, C: ConsensusStorage<N>> Validator<N, C> {
133    async fn process_message_inner(
134        &self,
135        peer_addr: SocketAddr,
136        message: <Validator<N, C> as snarkos_node_tcp::protocols::Reading>::Message,
137    ) {
138        // Process the message. Disconnect if the peer violated the protocol.
139        if let Err(error) = self.inbound(peer_addr, message).await {
140            warn!("Failed to process inbound message from '{peer_addr}' - {error}");
141            if let Some(peer_ip) = self.router().resolve_to_listener(&peer_addr) {
142                warn!("Disconnecting from '{peer_ip}' for protocol violation");
143                Outbound::send(self, peer_ip, Message::Disconnect(DisconnectReason::ProtocolViolation.into()));
144                // Disconnect from this peer.
145                self.router().disconnect(peer_ip);
146            }
147        }
148    }
149}
150
151#[async_trait]
152impl<N: Network, C: ConsensusStorage<N>> Routing<N> for Validator<N, C> {}
153
154impl<N: Network, C: ConsensusStorage<N>> Heartbeat<N> for Validator<N, C> {
155    /// The maximum number of peers permitted to maintain connections with.
156    const MAXIMUM_NUMBER_OF_PEERS: usize = 200;
157}
158
159impl<N: Network, C: ConsensusStorage<N>> Outbound<N> for Validator<N, C> {
160    /// Returns a reference to the router.
161    fn router(&self) -> &Router<N> {
162        &self.router
163    }
164
165    /// Returns `true` if the node is synced up to the latest block (within the given tolerance).
166    fn is_block_synced(&self) -> bool {
167        self.sync.is_block_synced()
168    }
169
170    /// Returns the number of blocks this node is behind the greatest peer height.
171    fn num_blocks_behind(&self) -> u32 {
172        self.sync.num_blocks_behind()
173    }
174}
175
176#[async_trait]
177impl<N: Network, C: ConsensusStorage<N>> Inbound<N> for Validator<N, C> {
178    /// Returns `true` if the message version is valid.
179    fn is_valid_message_version(&self, message_version: u32) -> bool {
180        self.router().is_valid_message_version(message_version)
181    }
182
183    /// Retrieves the blocks within the block request range, and returns the block response to the peer.
184    fn block_request(&self, peer_ip: SocketAddr, message: BlockRequest) -> bool {
185        let BlockRequest { start_height, end_height } = &message;
186
187        // Retrieve the blocks within the requested range.
188        let blocks = match self.ledger.get_blocks(*start_height..*end_height) {
189            Ok(blocks) => Data::Object(DataBlocks(blocks)),
190            Err(error) => {
191                error!("Failed to retrieve blocks {start_height} to {end_height} from the ledger - {error}");
192                return false;
193            }
194        };
195        // Send the `BlockResponse` message to the peer.
196        Outbound::send(self, peer_ip, Message::BlockResponse(BlockResponse { request: message, blocks }));
197        true
198    }
199
200    /// Handles a `BlockResponse` message.
201    fn block_response(&self, peer_ip: SocketAddr, blocks: Vec<Block<N>>) -> bool {
202        // Tries to advance with blocks from the sync module.
203        match self.sync.advance_with_sync_blocks(peer_ip, blocks) {
204            Ok(()) => true,
205            Err(error) => {
206                warn!("{error}");
207                false
208            }
209        }
210    }
211
212    /// Processes the block locators and sends back a `Pong` message.
213    fn ping(&self, peer_ip: SocketAddr, message: Ping<N>) -> bool {
214        // Check if the sync module is in router mode.
215        if self.sync.mode().is_router() {
216            // If block locators were provided, then update the peer in the sync pool.
217            if let Some(block_locators) = message.block_locators {
218                // Check the block locators are valid, and update the peer in the sync pool.
219                if let Err(error) = self.sync.update_peer_locators(peer_ip, block_locators) {
220                    warn!("Peer '{peer_ip}' sent invalid block locators: {error}");
221                    return false;
222                }
223            }
224        }
225
226        // Send a `Pong` message to the peer.
227        Outbound::send(self, peer_ip, Message::Pong(Pong { is_fork: Some(false) }));
228        true
229    }
230
231    /// Sleeps for a period and then sends a `Ping` message to the peer.
232    fn pong(&self, peer_ip: SocketAddr, _message: Pong) -> bool {
233        // Spawn an asynchronous task for the `Ping` request.
234        let self_ = self.clone();
235        tokio::spawn(async move {
236            // Sleep for the preset time before sending a `Ping` request.
237            tokio::time::sleep(Duration::from_secs(Self::PING_SLEEP_IN_SECS)).await;
238            // Check that the peer is still connected.
239            if self_.router().is_connected(&peer_ip) {
240                // Retrieve the block locators.
241                match self_.sync.get_block_locators() {
242                    // Send a `Ping` message to the peer.
243                    Ok(block_locators) => self_.send_ping(peer_ip, Some(block_locators)),
244                    Err(e) => error!("Failed to get block locators - {e}"),
245                }
246            }
247        });
248        true
249    }
250
251    /// Retrieves the latest epoch hash and latest block header, and returns the puzzle response to the peer.
252    fn puzzle_request(&self, peer_ip: SocketAddr) -> bool {
253        // Retrieve the latest epoch hash.
254        let epoch_hash = match self.ledger.latest_epoch_hash() {
255            Ok(epoch_hash) => epoch_hash,
256            Err(error) => {
257                error!("Failed to prepare a puzzle request for '{peer_ip}': {error}");
258                return false;
259            }
260        };
261        // Retrieve the latest block header.
262        let block_header = Data::Object(self.ledger.latest_header());
263        // Send the `PuzzleResponse` message to the peer.
264        Outbound::send(self, peer_ip, Message::PuzzleResponse(PuzzleResponse { epoch_hash, block_header }));
265        true
266    }
267
268    /// Disconnects on receipt of a `PuzzleResponse` message.
269    fn puzzle_response(&self, peer_ip: SocketAddr, _epoch_hash: N::BlockHash, _header: Header<N>) -> bool {
270        debug!("Disconnecting '{peer_ip}' for the following reason - {:?}", DisconnectReason::ProtocolViolation);
271        false
272    }
273
274    /// Propagates the unconfirmed solution to all connected validators.
275    async fn unconfirmed_solution(
276        &self,
277        peer_ip: SocketAddr,
278        serialized: UnconfirmedSolution<N>,
279        solution: Solution<N>,
280    ) -> bool {
281        // Add the unconfirmed solution to the memory pool.
282        if let Err(error) = self.consensus.add_unconfirmed_solution(solution).await {
283            trace!("[UnconfirmedSolution] {error}");
284            return true; // Maintain the connection.
285        }
286        let message = Message::UnconfirmedSolution(serialized);
287        // Propagate the "UnconfirmedSolution" to the connected validators.
288        self.propagate_to_validators(message, &[peer_ip]);
289        true
290    }
291
292    /// Handles an `UnconfirmedTransaction` message.
293    async fn unconfirmed_transaction(
294        &self,
295        peer_ip: SocketAddr,
296        serialized: UnconfirmedTransaction<N>,
297        transaction: Transaction<N>,
298    ) -> bool {
299        // Add the unconfirmed transaction to the memory pool.
300        if let Err(error) = self.consensus.add_unconfirmed_transaction(transaction).await {
301            trace!("[UnconfirmedTransaction] {error}");
302            return true; // Maintain the connection.
303        }
304        let message = Message::UnconfirmedTransaction(serialized);
305        // Propagate the "UnconfirmedTransaction" to the connected validators.
306        self.propagate_to_validators(message, &[peer_ip]);
307        true
308    }
309}