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::{
18    PeerPoolHandling,
19    messages::{
20        BlockRequest,
21        BlockResponse,
22        DataBlocks,
23        DisconnectReason,
24        Message,
25        MessageCodec,
26        Ping,
27        Pong,
28        UnconfirmedTransaction,
29    },
30};
31use snarkos_node_tcp::{Connection, ConnectionSide, Tcp};
32use snarkvm::{
33    ledger::narwhal::Data,
34    prelude::{Network, block::Transaction, error},
35};
36
37use std::{io, net::SocketAddr};
38
39impl<N: Network, C: ConsensusStorage<N>> P2P for Validator<N, C> {
40    /// Returns a reference to the TCP instance.
41    fn tcp(&self) -> &Tcp {
42        self.router.tcp()
43    }
44}
45
46#[async_trait]
47impl<N: Network, C: ConsensusStorage<N>> Handshake for Validator<N, C> {
48    /// Performs the handshake protocol.
49    async fn perform_handshake(&self, mut connection: Connection) -> io::Result<Connection> {
50        // Perform the handshake.
51        let peer_addr = connection.addr();
52        let conn_side = connection.side();
53        let stream = self.borrow_stream(&mut connection);
54        let genesis_header = self.ledger.get_header(0).map_err(|e| error(format!("{e}")))?;
55        let restrictions_id = self.ledger.vm().restrictions().restrictions_id();
56        self.router.handshake(peer_addr, stream, conn_side, genesis_header, restrictions_id).await?;
57
58        Ok(connection)
59    }
60}
61
62#[async_trait]
63impl<N: Network, C: ConsensusStorage<N>> OnConnect for Validator<N, C>
64where
65    Self: Outbound<N>,
66{
67    async fn on_connect(&self, peer_addr: SocketAddr) {
68        // Resolve the peer address to the listener address.
69        if let Some(listener_addr) = self.router().resolve_to_listener(peer_addr) {
70            if let Some(peer) = self.router().get_connected_peer(listener_addr) {
71                if peer.node_type != NodeType::BootstrapClient {
72                    // Send the first `Ping` message to the peer.
73                    self.ping.on_peer_connected(listener_addr);
74                }
75            }
76        }
77    }
78}
79
80#[async_trait]
81impl<N: Network, C: ConsensusStorage<N>> Disconnect for Validator<N, C> {
82    /// Any extra operations to be performed during a disconnect.
83    async fn handle_disconnect(&self, peer_addr: SocketAddr) {
84        if let Some(peer_ip) = self.router.resolve_to_listener(peer_addr) {
85            self.sync.remove_peer(&peer_ip);
86            self.router.downgrade_peer_to_candidate(peer_ip);
87            // Clear cached entries applicable to the peer.
88            self.router.cache().clear_peer_entries(peer_ip);
89            #[cfg(feature = "metrics")]
90            self.router.update_metrics();
91        }
92    }
93}
94
95#[async_trait]
96impl<N: Network, C: ConsensusStorage<N>> Reading for Validator<N, C> {
97    type Codec = MessageCodec<N>;
98    type Message = Message<N>;
99
100    /// Creates a [`Decoder`] used to interpret messages from the network.
101    /// The `side` param indicates the connection side **from the node's perspective**.
102    fn codec(&self, _peer_addr: SocketAddr, _side: ConnectionSide) -> Self::Codec {
103        Default::default()
104    }
105
106    /// Processes a message received from the network.
107    async fn process_message(&self, peer_addr: SocketAddr, message: Self::Message) -> io::Result<()> {
108        let clone = self.clone();
109        if matches!(message, Message::BlockRequest(_) | Message::BlockResponse(_)) {
110            // Handle BlockRequest and BlockResponse messages in a separate task to not block the
111            // inbound queue.
112            tokio::spawn(async move {
113                clone.process_message_inner(peer_addr, message).await;
114            });
115        } else {
116            self.process_message_inner(peer_addr, message).await;
117        }
118        Ok(())
119    }
120}
121
122impl<N: Network, C: ConsensusStorage<N>> Validator<N, C> {
123    async fn process_message_inner(
124        &self,
125        peer_addr: SocketAddr,
126        message: <Validator<N, C> as snarkos_node_tcp::protocols::Reading>::Message,
127    ) {
128        // Process the message. Disconnect if the peer violated the protocol.
129        if let Err(error) = self.inbound(peer_addr, message).await {
130            warn!("Failed to process inbound message from '{peer_addr}' - {error}");
131            if let Some(peer_ip) = self.router().resolve_to_listener(peer_addr) {
132                warn!("Disconnecting from '{peer_ip}' for protocol violation");
133                self.router().send(peer_ip, Message::Disconnect(DisconnectReason::ProtocolViolation.into()));
134                // Disconnect from this peer.
135                self.router().disconnect(peer_ip);
136            }
137        }
138    }
139}
140
141#[async_trait]
142impl<N: Network, C: ConsensusStorage<N>> Routing<N> for Validator<N, C> {}
143
144impl<N: Network, C: ConsensusStorage<N>> Heartbeat<N> for Validator<N, C> {}
145
146impl<N: Network, C: ConsensusStorage<N>> Outbound<N> for Validator<N, C> {
147    /// Returns a reference to the router.
148    fn router(&self) -> &Router<N> {
149        &self.router
150    }
151
152    /// Returns `true` if the node is synced up to the latest block (within the given tolerance).
153    fn is_block_synced(&self) -> bool {
154        self.sync.is_block_synced()
155    }
156
157    /// Returns the number of blocks this node is behind the greatest peer height,
158    /// or `None` if not connected to peers yet.
159    fn num_blocks_behind(&self) -> Option<u32> {
160        self.sync.num_blocks_behind()
161    }
162
163    /// Returns the current sync speed in blocks per second.
164    fn get_sync_speed(&self) -> f64 {
165        self.sync.get_sync_speed()
166    }
167}
168
169#[async_trait]
170impl<N: Network, C: ConsensusStorage<N>> Inbound<N> for Validator<N, C> {
171    /// Returns `true` if the message version is valid.
172    fn is_valid_message_version(&self, message_version: u32) -> bool {
173        self.router().is_valid_message_version(message_version)
174    }
175
176    /// Retrieves the blocks within the block request range, and returns the block response to the peer.
177    fn block_request(&self, peer_ip: SocketAddr, message: BlockRequest) -> bool {
178        let BlockRequest { start_height, end_height } = &message;
179
180        // Retrieve the blocks within the requested range.
181        let blocks = match self.ledger.get_blocks(*start_height..*end_height) {
182            Ok(blocks) => Data::Object(DataBlocks(blocks)),
183            Err(error) => {
184                error!("Failed to retrieve blocks {start_height} to {end_height} from the ledger - {error}");
185                return false;
186            }
187        };
188        // Send the `BlockResponse` message to the peer.
189        self.router().send(peer_ip, Message::BlockResponse(BlockResponse { request: message, blocks }));
190        true
191    }
192
193    /// Handles a `BlockResponse` message.
194    fn block_response(&self, peer_ip: SocketAddr, _blocks: Vec<Block<N>>) -> bool {
195        warn!("Received a block response through P2P, not BFT, from {peer_ip}");
196        false
197    }
198
199    /// Processes a ping message from a client (or prover) and sends back a `Pong` message.
200    fn ping(&self, peer_ip: SocketAddr, _message: Ping<N>) -> bool {
201        // In gateway/validator mode, we do not need to process client block locators.
202        // Instead, locators are fetched from other validators in `Gateway` using `PrimaryPing` messages.
203
204        // Send a `Pong` message to the peer.
205        self.router().send(peer_ip, Message::Pong(Pong { is_fork: Some(false) }));
206        true
207    }
208
209    /// Process a Pong message (response to a Ping).
210    fn pong(&self, peer_ip: SocketAddr, _message: Pong) -> bool {
211        self.ping.on_pong_received(peer_ip);
212        true
213    }
214
215    /// Retrieves the latest epoch hash and latest block header, and returns the puzzle response to the peer.
216    fn puzzle_request(&self, peer_ip: SocketAddr) -> bool {
217        // Retrieve the latest epoch hash.
218        let epoch_hash = match self.ledger.latest_epoch_hash() {
219            Ok(epoch_hash) => epoch_hash,
220            Err(error) => {
221                error!("Failed to prepare a puzzle request for '{peer_ip}': {error}");
222                return false;
223            }
224        };
225        // Retrieve the latest block header.
226        let block_header = Data::Object(self.ledger.latest_header());
227        // Send the `PuzzleResponse` message to the peer.
228        self.router().send(peer_ip, Message::PuzzleResponse(PuzzleResponse { epoch_hash, block_header }));
229        true
230    }
231
232    /// Disconnects on receipt of a `PuzzleResponse` message.
233    fn puzzle_response(&self, peer_ip: SocketAddr, _epoch_hash: N::BlockHash, _header: Header<N>) -> bool {
234        debug!("Disconnecting '{peer_ip}' for the following reason - {:?}", DisconnectReason::ProtocolViolation);
235        false
236    }
237
238    /// Propagates the unconfirmed solution to all connected validators.
239    async fn unconfirmed_solution(
240        &self,
241        peer_ip: SocketAddr,
242        serialized: UnconfirmedSolution<N>,
243        solution: Solution<N>,
244    ) -> bool {
245        // Add the unconfirmed solution to the memory pool.
246        if let Err(error) = self.consensus.add_unconfirmed_solution(solution).await {
247            trace!("[UnconfirmedSolution] {error}");
248            return true; // Maintain the connection.
249        }
250        let message = Message::UnconfirmedSolution(serialized);
251        // Propagate the "UnconfirmedSolution" to the connected validators.
252        self.propagate_to_validators(message, &[peer_ip]);
253        true
254    }
255
256    /// Handles an `UnconfirmedTransaction` message.
257    async fn unconfirmed_transaction(
258        &self,
259        peer_ip: SocketAddr,
260        serialized: UnconfirmedTransaction<N>,
261        transaction: Transaction<N>,
262    ) -> bool {
263        // Add the unconfirmed transaction to the memory pool.
264        if let Err(error) = self.consensus.add_unconfirmed_transaction(transaction).await {
265            trace!("[UnconfirmedTransaction] {error}");
266            return true; // Maintain the connection.
267        }
268        let message = Message::UnconfirmedTransaction(serialized);
269        // Propagate the "UnconfirmedTransaction" to the connected validators.
270        self.propagate_to_validators(message, &[peer_ip]);
271        true
272    }
273}