snarkos_node/validator/
router.rs

1// Copyright 2024-2025 Aleo Network Foundation
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    /// Retrieves the blocks within the block request range, and returns the block response to the peer.
179    fn block_request(&self, peer_ip: SocketAddr, message: BlockRequest) -> bool {
180        let BlockRequest { start_height, end_height } = &message;
181
182        // Retrieve the blocks within the requested range.
183        let blocks = match self.ledger.get_blocks(*start_height..*end_height) {
184            Ok(blocks) => Data::Object(DataBlocks(blocks)),
185            Err(error) => {
186                error!("Failed to retrieve blocks {start_height} to {end_height} from the ledger - {error}");
187                return false;
188            }
189        };
190        // Send the `BlockResponse` message to the peer.
191        Outbound::send(self, peer_ip, Message::BlockResponse(BlockResponse { request: message, blocks }));
192        true
193    }
194
195    /// Handles a `BlockResponse` message.
196    fn block_response(&self, peer_ip: SocketAddr, blocks: Vec<Block<N>>) -> bool {
197        // Tries to advance with blocks from the sync module.
198        match self.sync.advance_with_sync_blocks(peer_ip, blocks) {
199            Ok(()) => true,
200            Err(error) => {
201                warn!("{error}");
202                false
203            }
204        }
205    }
206
207    /// Processes the block locators and sends back a `Pong` message.
208    fn ping(&self, peer_ip: SocketAddr, message: Ping<N>) -> bool {
209        // Check if the sync module is in router mode.
210        if self.sync.mode().is_router() {
211            // If block locators were provided, then update the peer in the sync pool.
212            if let Some(block_locators) = message.block_locators {
213                // Check the block locators are valid, and update the peer in the sync pool.
214                if let Err(error) = self.sync.update_peer_locators(peer_ip, block_locators) {
215                    warn!("Peer '{peer_ip}' sent invalid block locators: {error}");
216                    return false;
217                }
218            }
219        }
220
221        // Send a `Pong` message to the peer.
222        Outbound::send(self, peer_ip, Message::Pong(Pong { is_fork: Some(false) }));
223        true
224    }
225
226    /// Sleeps for a period and then sends a `Ping` message to the peer.
227    fn pong(&self, peer_ip: SocketAddr, _message: Pong) -> bool {
228        // Spawn an asynchronous task for the `Ping` request.
229        let self_ = self.clone();
230        tokio::spawn(async move {
231            // Sleep for the preset time before sending a `Ping` request.
232            tokio::time::sleep(Duration::from_secs(Self::PING_SLEEP_IN_SECS)).await;
233            // Check that the peer is still connected.
234            if self_.router().is_connected(&peer_ip) {
235                // Retrieve the block locators.
236                match self_.sync.get_block_locators() {
237                    // Send a `Ping` message to the peer.
238                    Ok(block_locators) => self_.send_ping(peer_ip, Some(block_locators)),
239                    Err(e) => error!("Failed to get block locators - {e}"),
240                }
241            }
242        });
243        true
244    }
245
246    /// Retrieves the latest epoch hash and latest block header, and returns the puzzle response to the peer.
247    fn puzzle_request(&self, peer_ip: SocketAddr) -> bool {
248        // Retrieve the latest epoch hash.
249        let epoch_hash = match self.ledger.latest_epoch_hash() {
250            Ok(epoch_hash) => epoch_hash,
251            Err(error) => {
252                error!("Failed to prepare a puzzle request for '{peer_ip}': {error}");
253                return false;
254            }
255        };
256        // Retrieve the latest block header.
257        let block_header = Data::Object(self.ledger.latest_header());
258        // Send the `PuzzleResponse` message to the peer.
259        Outbound::send(self, peer_ip, Message::PuzzleResponse(PuzzleResponse { epoch_hash, block_header }));
260        true
261    }
262
263    /// Disconnects on receipt of a `PuzzleResponse` message.
264    fn puzzle_response(&self, peer_ip: SocketAddr, _epoch_hash: N::BlockHash, _header: Header<N>) -> bool {
265        debug!("Disconnecting '{peer_ip}' for the following reason - {:?}", DisconnectReason::ProtocolViolation);
266        false
267    }
268
269    /// Propagates the unconfirmed solution to all connected validators.
270    async fn unconfirmed_solution(
271        &self,
272        peer_ip: SocketAddr,
273        serialized: UnconfirmedSolution<N>,
274        solution: Solution<N>,
275    ) -> bool {
276        // Add the unconfirmed solution to the memory pool.
277        if let Err(error) = self.consensus.add_unconfirmed_solution(solution).await {
278            trace!("[UnconfirmedSolution] {error}");
279            return true; // Maintain the connection.
280        }
281        let message = Message::UnconfirmedSolution(serialized);
282        // Propagate the "UnconfirmedSolution" to the connected validators.
283        self.propagate_to_validators(message, &[peer_ip]);
284        true
285    }
286
287    /// Handles an `UnconfirmedTransaction` message.
288    async fn unconfirmed_transaction(
289        &self,
290        peer_ip: SocketAddr,
291        serialized: UnconfirmedTransaction<N>,
292        transaction: Transaction<N>,
293    ) -> bool {
294        // Add the unconfirmed transaction to the memory pool.
295        if let Err(error) = self.consensus.add_unconfirmed_transaction(transaction).await {
296            trace!("[UnconfirmedTransaction] {error}");
297            return true; // Maintain the connection.
298        }
299        let message = Message::UnconfirmedTransaction(serialized);
300        // Propagate the "UnconfirmedTransaction" to the connected validators.
301        self.propagate_to_validators(message, &[peer_ip]);
302        true
303    }
304}