snarkos_node/validator/
router.rs

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