Skip to main content

snarkos_node/validator/
router.rs

1// Copyright (c) 2019-2026 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_network::{PeerPoolHandling, harden_socket};
18use snarkos_node_router::messages::{
19    BlockRequest,
20    BlockResponse,
21    DataBlocks,
22    DisconnectReason,
23    Message,
24    MessageCodec,
25    MessageId,
26    Ping,
27    Pong,
28    UnconfirmedTransaction,
29};
30use snarkos_node_tcp::{ConnectError, Connection, ConnectionSide, Tcp, connections::DisconnectOrigin};
31use snarkvm::{
32    console::network::{ConsensusVersion, Network},
33    ledger::{block::Transaction, narwhal::Data},
34    utilities::flatten_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) -> Result<Connection, ConnectError> {
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        // Make the socket more robust.
55        harden_socket(stream)?;
56        //TODO(kaimast): if this fails, the validator must be corrupted. Handle this with higher severity.
57        let genesis_header = self.ledger.get_header(0).map_err(ConnectError::other)?;
58        let restrictions_id = self.ledger.vm().restrictions().restrictions_id();
59        self.router.handshake(peer_addr, stream, conn_side, genesis_header, restrictions_id).await?;
60
61        Ok(connection)
62    }
63}
64
65#[async_trait]
66impl<N: Network, C: ConsensusStorage<N>> OnConnect for Validator<N, C>
67where
68    Self: Outbound<N>,
69{
70    async fn on_connect(&self, peer_addr: SocketAddr) {
71        // Resolve the peer address to the listener address.
72        if let Some(listener_addr) = self.router().resolve_to_listener(peer_addr)
73            && let Some(peer) = self.router().get_connected_peer(listener_addr)
74            && peer.node_type != NodeType::BootstrapClient
75        {
76            // Send the first `Ping` message to the peer.
77            self.ping.on_peer_connected(listener_addr);
78        }
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, origin: DisconnectOrigin) {
86        debug!("Physically disconnecting from {peer_addr}; origin: {origin:?}");
87
88        if let Some(peer_ip) = self.router.resolve_to_listener(peer_addr) {
89            self.router.downgrade_peer_to_candidate(peer_ip);
90
91            // Validators do not sync from clients in the current design, so do not remove the peer from sync here.
92
93            // Clear cached entries applicable to the peer.
94            self.router.cache().clear_peer_entries(peer_ip);
95            #[cfg(feature = "metrics")]
96            self.router.update_metrics();
97        } else {
98            warn!("Got disconnect for a peer '{peer_addr}' that is not in the peer pool");
99        }
100    }
101}
102
103#[async_trait]
104impl<N: Network, C: ConsensusStorage<N>> Reading for Validator<N, C> {
105    type Codec = MessageCodec<N>;
106    type Message = Message<N>;
107
108    /// Creates a [`Decoder`] used to interpret messages from the network.
109    /// The `side` param indicates the connection side **from the node's perspective**.
110    fn codec(&self, _peer_addr: SocketAddr, _side: ConnectionSide) -> Self::Codec {
111        // A validator syncs blocks exclusively over the committee-gated BFT gateway
112        // (`ConnectionMode::Gateway`); it never issues a `BlockRequest` over the router, so it
113        // never has a legitimate reason to accept a `BlockResponse` there either. Excluding it
114        // rejects one outright the moment its ID is visible, and shrinks this connection's frame
115        // ceiling from the general 128 MiB down to `Ping`'s (the largest type still allowed) - so
116        // an untrusted router peer can no longer use a claimed `BlockResponse` to force either a
117        // 128 MiB allocation or a successful decode that `block_response` below only rejects
118        // afterward.
119        MessageCodec::excluding(&[MessageId::BlockResponse])
120    }
121
122    /// Processes a message received from the network.
123    async fn process_message(&self, peer_addr: SocketAddr, message: Self::Message) -> io::Result<()> {
124        let clone = self.clone();
125        if matches!(message, Message::BlockRequest(_) | Message::BlockResponse(_)) {
126            // Handle BlockRequest and BlockResponse messages in a separate task to not block the
127            // inbound queue.
128            tokio::spawn(async move {
129                clone.process_message_inner(peer_addr, message).await;
130            });
131        } else {
132            self.process_message_inner(peer_addr, message).await;
133        }
134        Ok(())
135    }
136}
137
138impl<N: Network, C: ConsensusStorage<N>> Validator<N, C> {
139    async fn process_message_inner(
140        &self,
141        peer_addr: SocketAddr,
142        message: <Validator<N, C> as snarkos_node_tcp::protocols::Reading>::Message,
143    ) {
144        // Process the message. Disconnect if the peer violated the protocol.
145        if let Err(error) = self.inbound(peer_addr, message).await {
146            warn!("Failed to process inbound message from '{peer_addr}' - {error}");
147            if let Some(peer_ip) = self.router().resolve_to_listener(peer_addr) {
148                warn!("Disconnecting from '{peer_ip}' for protocol violation");
149                self.router().send(peer_ip, Message::Disconnect(DisconnectReason::ProtocolViolation.into()));
150                // Disconnect from this peer.
151                self.router().disconnect(peer_ip);
152            }
153        }
154    }
155}
156
157#[async_trait]
158impl<N: Network, C: ConsensusStorage<N>> Routing<N> for Validator<N, C> {}
159
160impl<N: Network, C: ConsensusStorage<N>> Heartbeat<N> for Validator<N, C> {}
161
162impl<N: Network, C: ConsensusStorage<N>> Outbound<N> for Validator<N, C> {
163    /// Returns a reference to the router.
164    fn router(&self) -> &Router<N> {
165        &self.router
166    }
167
168    /// Returns `true` if the node is synced up to the latest block (within the given tolerance).
169    fn is_block_synced(&self) -> bool {
170        self.sync.is_block_synced()
171    }
172
173    /// Returns the number of blocks this node is behind the greatest peer height,
174    /// or `None` if not connected to peers yet.
175    fn num_blocks_behind(&self) -> Option<u32> {
176        self.sync.num_blocks_behind()
177    }
178
179    /// Returns the current sync speed in blocks per second.
180    fn get_sync_speed(&self) -> f64 {
181        self.sync.get_sync_speed()
182    }
183}
184
185#[async_trait]
186impl<N: Network, C: ConsensusStorage<N>> Inbound<N> for Validator<N, C> {
187    /// Returns `true` if the message version is valid.
188    fn is_valid_message_version(&self, message_version: u32) -> bool {
189        self.router().is_valid_message_version(message_version)
190    }
191
192    /// Retrieves the blocks within the block request range, and returns the block response to the peer.
193    fn block_request(&self, peer_ip: SocketAddr, message: BlockRequest) -> bool {
194        let BlockRequest { start_height, end_height } = &message;
195
196        // Get the latest consensus version, i.e., the one for the last block's height.
197        let latest_consensus_version = match N::CONSENSUS_VERSION(end_height.saturating_sub(1)) {
198            Ok(version) => version,
199            Err(err) => {
200                error!("{}", flatten_error(err.context("Failed to retrieve consensus version")));
201                return false;
202            }
203        };
204
205        // Retrieve the blocks within the requested range.
206        let blocks = match self.ledger.get_blocks(*start_height..*end_height) {
207            Ok(blocks) => DataBlocks(blocks),
208            Err(err) => {
209                let err =
210                    err.context(format!("Failed to retrieve blocks {start_height} to {end_height} from the ledger"));
211                error!("{}", flatten_error(err));
212                return false;
213            }
214        };
215        // Send the `BlockResponse` message to the peer.
216        self.router()
217            .send(peer_ip, Message::BlockResponse(BlockResponse::new(message, blocks, latest_consensus_version)));
218        true
219    }
220
221    /// Handles a `BlockResponse` message.
222    fn block_response(
223        &self,
224        peer_ip: SocketAddr,
225        _blocks: Vec<Block<N>>,
226        _latest_consensus_version: Option<ConsensusVersion>,
227    ) -> bool {
228        warn!("Received a block response through P2P, not BFT, from {peer_ip}");
229        false
230    }
231
232    /// Processes a ping message from a client (or prover) and sends back a `Pong` message.
233    fn ping(&self, peer_ip: SocketAddr, _message: Ping<N>) -> bool {
234        // In gateway/validator mode, we do not need to process client block locators.
235        // Instead, locators are fetched from other validators in `Gateway` using `PrimaryPing` messages.
236
237        // Send a `Pong` message to the peer.
238        self.router().send(peer_ip, Message::Pong(Pong { is_fork: Some(false) }));
239        true
240    }
241
242    /// Process a Pong message (response to a Ping).
243    fn pong(&self, peer_ip: SocketAddr, _message: Pong) -> bool {
244        self.ping.on_pong_received(peer_ip);
245        true
246    }
247
248    /// Retrieves the latest epoch hash and latest block header, and returns the puzzle response to the peer.
249    fn puzzle_request(&self, peer_ip: SocketAddr) -> bool {
250        // Retrieve the latest epoch hash.
251        let epoch_hash = match self.ledger.latest_epoch_hash() {
252            Ok(epoch_hash) => epoch_hash,
253            Err(error) => {
254                error!("Failed to prepare a puzzle request for '{peer_ip}': {error}");
255                return false;
256            }
257        };
258        // Retrieve the latest block header.
259        let block_header = Data::Object(self.ledger.latest_header());
260        // Send the `PuzzleResponse` message to the peer.
261        self.router().send(peer_ip, Message::PuzzleResponse(PuzzleResponse { epoch_hash, block_header }));
262        true
263    }
264
265    /// Disconnects on receipt of a `PuzzleResponse` message.
266    fn puzzle_response(&self, peer_ip: SocketAddr, _epoch_hash: N::BlockHash, _header: Header<N>) -> bool {
267        debug!("Disconnecting '{peer_ip}' for the following reason - {}", DisconnectReason::ProtocolViolation);
268        false
269    }
270
271    /// Propagates the unconfirmed solution to all connected validators.
272    async fn unconfirmed_solution(
273        &self,
274        peer_ip: SocketAddr,
275        serialized: UnconfirmedSolution<N>,
276        solution: Solution<N>,
277    ) -> bool {
278        // Add the unconfirmed solution to the memory pool.
279        if let Err(error) = self.consensus.add_unconfirmed_solution(solution).await {
280            trace!("[UnconfirmedSolution] {error}");
281            return true; // Maintain the connection.
282        }
283        let message = Message::UnconfirmedSolution(serialized);
284        // Propagate the "UnconfirmedSolution" to the connected validators.
285        self.propagate_to_validators(message, &[peer_ip]);
286        true
287    }
288
289    /// Handles an `UnconfirmedTransaction` message.
290    async fn unconfirmed_transaction(
291        &self,
292        peer_ip: SocketAddr,
293        serialized: UnconfirmedTransaction<N>,
294        transaction: Transaction<N>,
295    ) -> bool {
296        // Add the unconfirmed transaction to the memory pool.
297        if let Err(error) = self.consensus.add_unconfirmed_transaction(transaction).await {
298            trace!("[UnconfirmedTransaction] {error}");
299            return true; // Maintain the connection.
300        }
301        let message = Message::UnconfirmedTransaction(serialized);
302        // Propagate the "UnconfirmedTransaction" to the connected validators.
303        self.propagate_to_validators(message, &[peer_ip]);
304        true
305    }
306}