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};
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        // Send the first `Ping` message to the peer.
68        self.ping.on_peer_connected(peer_ip);
69    }
70}
71
72#[async_trait]
73impl<N: Network, C: ConsensusStorage<N>> Disconnect for Validator<N, C> {
74    /// Any extra operations to be performed during a disconnect.
75    async fn handle_disconnect(&self, peer_addr: SocketAddr) {
76        if let Some(peer_ip) = self.router.resolve_to_listener(&peer_addr) {
77            self.sync.remove_peer(&peer_ip);
78            self.router.remove_connected_peer(peer_ip);
79        }
80    }
81}
82
83#[async_trait]
84impl<N: Network, C: ConsensusStorage<N>> Reading for Validator<N, C> {
85    type Codec = MessageCodec<N>;
86    type Message = Message<N>;
87
88    /// Creates a [`Decoder`] used to interpret messages from the network.
89    /// The `side` param indicates the connection side **from the node's perspective**.
90    fn codec(&self, _peer_addr: SocketAddr, _side: ConnectionSide) -> Self::Codec {
91        Default::default()
92    }
93
94    /// Processes a message received from the network.
95    async fn process_message(&self, peer_addr: SocketAddr, message: Self::Message) -> io::Result<()> {
96        let clone = self.clone();
97        if matches!(message, Message::BlockRequest(_) | Message::BlockResponse(_)) {
98            // Handle BlockRequest and BlockResponse messages in a separate task to not block the
99            // inbound queue.
100            tokio::spawn(async move {
101                clone.process_message_inner(peer_addr, message).await;
102            });
103        } else {
104            self.process_message_inner(peer_addr, message).await;
105        }
106        Ok(())
107    }
108}
109
110impl<N: Network, C: ConsensusStorage<N>> Validator<N, C> {
111    async fn process_message_inner(
112        &self,
113        peer_addr: SocketAddr,
114        message: <Validator<N, C> as snarkos_node_tcp::protocols::Reading>::Message,
115    ) {
116        // Process the message. Disconnect if the peer violated the protocol.
117        if let Err(error) = self.inbound(peer_addr, message).await {
118            warn!("Failed to process inbound message from '{peer_addr}' - {error}");
119            if let Some(peer_ip) = self.router().resolve_to_listener(&peer_addr) {
120                warn!("Disconnecting from '{peer_ip}' for protocol violation");
121                self.router().send(peer_ip, Message::Disconnect(DisconnectReason::ProtocolViolation.into()));
122                // Disconnect from this peer.
123                self.router().disconnect(peer_ip);
124            }
125        }
126    }
127}
128
129#[async_trait]
130impl<N: Network, C: ConsensusStorage<N>> Routing<N> for Validator<N, C> {}
131
132impl<N: Network, C: ConsensusStorage<N>> Heartbeat<N> for Validator<N, C> {
133    /// The maximum number of peers permitted to maintain connections with.
134    const MAXIMUM_NUMBER_OF_PEERS: usize = 200;
135}
136
137impl<N: Network, C: ConsensusStorage<N>> Outbound<N> for Validator<N, C> {
138    /// Returns a reference to the router.
139    fn router(&self) -> &Router<N> {
140        &self.router
141    }
142
143    /// Returns `true` if the node is synced up to the latest block (within the given tolerance).
144    fn is_block_synced(&self) -> bool {
145        self.sync.is_block_synced()
146    }
147
148    /// Returns the number of blocks this node is behind the greatest peer height,
149    /// or `None` if not connected to peers yet.
150    fn num_blocks_behind(&self) -> Option<u32> {
151        self.sync.num_blocks_behind()
152    }
153}
154
155#[async_trait]
156impl<N: Network, C: ConsensusStorage<N>> Inbound<N> for Validator<N, C> {
157    /// Returns `true` if the message version is valid.
158    fn is_valid_message_version(&self, message_version: u32) -> bool {
159        self.router().is_valid_message_version(message_version)
160    }
161
162    /// Retrieves the blocks within the block request range, and returns the block response to the peer.
163    fn block_request(&self, peer_ip: SocketAddr, message: BlockRequest) -> bool {
164        let BlockRequest { start_height, end_height } = &message;
165
166        // Retrieve the blocks within the requested range.
167        let blocks = match self.ledger.get_blocks(*start_height..*end_height) {
168            Ok(blocks) => Data::Object(DataBlocks(blocks)),
169            Err(error) => {
170                error!("Failed to retrieve blocks {start_height} to {end_height} from the ledger - {error}");
171                return false;
172            }
173        };
174        // Send the `BlockResponse` message to the peer.
175        self.router().send(peer_ip, Message::BlockResponse(BlockResponse { request: message, blocks }));
176        true
177    }
178
179    /// Handles a `BlockResponse` message.
180    fn block_response(&self, peer_ip: SocketAddr, _blocks: Vec<Block<N>>) -> bool {
181        warn!("Received a block response through P2P, not BFT, from {peer_ip}");
182        false
183    }
184
185    /// Processes a ping message from a client (or prover) and sends back a `Pong` message.
186    fn ping(&self, peer_ip: SocketAddr, _message: Ping<N>) -> bool {
187        // In gateway/validator mode, we do not need to process client block locators.
188        // Instead, locators are fetched from other validators in `Gateway` using `PrimaryPing` messages.
189
190        // Send a `Pong` message to the peer.
191        self.router().send(peer_ip, Message::Pong(Pong { is_fork: Some(false) }));
192        true
193    }
194
195    /// Process a Pong message (response to a Ping).
196    fn pong(&self, peer_ip: SocketAddr, _message: Pong) -> bool {
197        self.ping.on_pong_received(peer_ip);
198        true
199    }
200
201    /// Retrieves the latest epoch hash and latest block header, and returns the puzzle response to the peer.
202    fn puzzle_request(&self, peer_ip: SocketAddr) -> bool {
203        // Retrieve the latest epoch hash.
204        let epoch_hash = match self.ledger.latest_epoch_hash() {
205            Ok(epoch_hash) => epoch_hash,
206            Err(error) => {
207                error!("Failed to prepare a puzzle request for '{peer_ip}': {error}");
208                return false;
209            }
210        };
211        // Retrieve the latest block header.
212        let block_header = Data::Object(self.ledger.latest_header());
213        // Send the `PuzzleResponse` message to the peer.
214        self.router().send(peer_ip, Message::PuzzleResponse(PuzzleResponse { epoch_hash, block_header }));
215        true
216    }
217
218    /// Disconnects on receipt of a `PuzzleResponse` message.
219    fn puzzle_response(&self, peer_ip: SocketAddr, _epoch_hash: N::BlockHash, _header: Header<N>) -> bool {
220        debug!("Disconnecting '{peer_ip}' for the following reason - {:?}", DisconnectReason::ProtocolViolation);
221        false
222    }
223
224    /// Propagates the unconfirmed solution to all connected validators.
225    async fn unconfirmed_solution(
226        &self,
227        peer_ip: SocketAddr,
228        serialized: UnconfirmedSolution<N>,
229        solution: Solution<N>,
230    ) -> bool {
231        // Add the unconfirmed solution to the memory pool.
232        if let Err(error) = self.consensus.add_unconfirmed_solution(solution).await {
233            trace!("[UnconfirmedSolution] {error}");
234            return true; // Maintain the connection.
235        }
236        let message = Message::UnconfirmedSolution(serialized);
237        // Propagate the "UnconfirmedSolution" to the connected validators.
238        self.propagate_to_validators(message, &[peer_ip]);
239        true
240    }
241
242    /// Handles an `UnconfirmedTransaction` message.
243    async fn unconfirmed_transaction(
244        &self,
245        peer_ip: SocketAddr,
246        serialized: UnconfirmedTransaction<N>,
247        transaction: Transaction<N>,
248    ) -> bool {
249        // Add the unconfirmed transaction to the memory pool.
250        if let Err(error) = self.consensus.add_unconfirmed_transaction(transaction).await {
251            trace!("[UnconfirmedTransaction] {error}");
252            return true; // Maintain the connection.
253        }
254        let message = Message::UnconfirmedTransaction(serialized);
255        // Propagate the "UnconfirmedTransaction" to the connected validators.
256        self.propagate_to_validators(message, &[peer_ip]);
257        true
258    }
259}