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