snarkos_node/prover/
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::*;
17
18use snarkos_node_router::messages::{
19    BlockRequest,
20    DisconnectReason,
21    Message,
22    MessageCodec,
23    Ping,
24    Pong,
25    PuzzleRequest,
26    UnconfirmedTransaction,
27};
28use snarkos_node_tcp::{Connection, ConnectionSide, Tcp};
29use snarkvm::prelude::{Field, Network, Zero, block::Transaction};
30
31use std::{io, net::SocketAddr};
32
33impl<N: Network, C: ConsensusStorage<N>> P2P for Prover<N, C> {
34    /// Returns a reference to the TCP instance.
35    fn tcp(&self) -> &Tcp {
36        self.router.tcp()
37    }
38}
39
40#[async_trait]
41impl<N: Network, C: ConsensusStorage<N>> Handshake for Prover<N, C> {
42    /// Performs the handshake protocol.
43    async fn perform_handshake(&self, mut connection: Connection) -> io::Result<Connection> {
44        // Perform the handshake.
45        let peer_addr = connection.addr();
46        let conn_side = connection.side();
47        let stream = self.borrow_stream(&mut connection);
48        let genesis_header = *self.genesis.header();
49        let restrictions_id = Field::zero(); // Provers may bypass restrictions, since they do not validate transactions.
50        self.router.handshake(peer_addr, stream, conn_side, genesis_header, restrictions_id).await?;
51
52        Ok(connection)
53    }
54}
55
56#[async_trait]
57impl<N: Network, C: ConsensusStorage<N>> OnConnect for Prover<N, C>
58where
59    Self: Outbound<N>,
60{
61    async fn on_connect(&self, peer_addr: SocketAddr) {
62        // Resolve the peer address to the listener address.
63        if let Some(listener_addr) = self.router().resolve_to_listener(peer_addr) {
64            if let Some(peer) = self.router().get_connected_peer(listener_addr) {
65                if peer.node_type != NodeType::BootstrapClient {
66                    // Send the first `Ping` message to the peer.
67                    self.ping.on_peer_connected(listener_addr);
68                }
69            }
70        }
71    }
72}
73
74#[async_trait]
75impl<N: Network, C: ConsensusStorage<N>> Disconnect for Prover<N, C> {
76    /// Any extra operations to be performed during a disconnect.
77    async fn handle_disconnect(&self, peer_addr: SocketAddr) {
78        if let Some(peer_ip) = self.router.resolve_to_listener(peer_addr) {
79            self.sync.remove_peer(&peer_ip);
80            self.router.downgrade_peer_to_candidate(peer_ip);
81            // Clear cached entries applicable to the peer.
82            self.router.cache().clear_peer_entries(peer_ip);
83            #[cfg(feature = "metrics")]
84            self.router.update_metrics();
85        }
86    }
87}
88
89#[async_trait]
90impl<N: Network, C: ConsensusStorage<N>> Reading for Prover<N, C> {
91    type Codec = MessageCodec<N>;
92    type Message = Message<N>;
93
94    /// Creates a [`Decoder`] used to interpret messages from the network.
95    /// The `side` param indicates the connection side **from the node's perspective**.
96    fn codec(&self, _peer_addr: SocketAddr, _side: ConnectionSide) -> Self::Codec {
97        Default::default()
98    }
99
100    /// Processes a message received from the network.
101    async fn process_message(&self, peer_addr: SocketAddr, message: Self::Message) -> io::Result<()> {
102        // Process the message. Disconnect if the peer violated the protocol.
103        if let Err(error) = self.inbound(peer_addr, message).await {
104            if let Some(peer_ip) = self.router().resolve_to_listener(peer_addr) {
105                warn!("Disconnecting from '{peer_addr}' - {error}");
106                self.router().send(peer_ip, Message::Disconnect(DisconnectReason::ProtocolViolation.into()));
107                // Disconnect from this peer.
108                self.router().disconnect(peer_ip);
109            }
110        }
111        Ok(())
112    }
113}
114
115#[async_trait]
116impl<N: Network, C: ConsensusStorage<N>> Routing<N> for Prover<N, C> {}
117
118impl<N: Network, C: ConsensusStorage<N>> Heartbeat<N> for Prover<N, C> {
119    /// This function updates the puzzle if network has updated.
120    fn handle_puzzle_request(&self) {
121        // Find the sync peers.
122        if let Some((sync_peers, _)) = self.sync.find_sync_peers() {
123            // Choose the peer with the highest block height.
124            if let Some((peer_ip, _)) = sync_peers.into_iter().max_by_key(|(_, height)| *height) {
125                // Request the puzzle from the peer.
126                self.router().send(peer_ip, Message::PuzzleRequest(PuzzleRequest));
127            }
128        }
129    }
130}
131
132impl<N: Network, C: ConsensusStorage<N>> Outbound<N> for Prover<N, C> {
133    /// Returns a reference to the router.
134    fn router(&self) -> &Router<N> {
135        &self.router
136    }
137
138    /// Returns `true` if the node is synced up to the latest block (within the given tolerance).
139    fn is_block_synced(&self) -> bool {
140        true
141    }
142
143    /// Returns the number of blocks this node is behind the greatest peer height,
144    /// or `None` if not connected to peers yet.
145    fn num_blocks_behind(&self) -> Option<u32> {
146        //TODO(kaimast): should this return None instead?
147        Some(0)
148    }
149
150    /// Returns the current sync speed in blocks per second.
151    fn get_sync_speed(&self) -> f64 {
152        0.0
153    }
154}
155
156#[async_trait]
157impl<N: Network, C: ConsensusStorage<N>> Inbound<N> for Prover<N, C> {
158    /// Returns `true` if the message version is valid.
159    fn is_valid_message_version(&self, message_version: u32) -> bool {
160        self.router().is_valid_message_version(message_version)
161    }
162
163    /// Handles a `BlockRequest` message.
164    fn block_request(&self, peer_ip: SocketAddr, _message: BlockRequest) -> bool {
165        debug!("Disconnecting '{peer_ip}' for the following reason - {:?}", DisconnectReason::ProtocolViolation);
166        false
167    }
168
169    /// Handles a `BlockResponse` message.
170    fn block_response(&self, peer_ip: SocketAddr, _blocks: Vec<Block<N>>) -> bool {
171        debug!("Disconnecting '{peer_ip}' for the following reason - {:?}", DisconnectReason::ProtocolViolation);
172        false
173    }
174
175    /// Processes the block locators and sends back a `Pong` message.
176    fn ping(&self, peer_ip: SocketAddr, message: Ping<N>) -> bool {
177        // If block locators were provided, then update the peer in the sync pool.
178        if let Some(block_locators) = message.block_locators {
179            // Check the block locators are valid, and update the peer in the sync pool.
180            if let Err(error) = self.sync.update_peer_locators(peer_ip, &block_locators) {
181                warn!("Peer '{peer_ip}' sent invalid block locators: {error}");
182                return false;
183            }
184        }
185
186        // Send a `Pong` message to the peer.
187        self.router().send(peer_ip, Message::Pong(Pong { is_fork: Some(false) }));
188        true
189    }
190
191    /// Sleeps for a period and then sends a `Ping` message to the peer.
192    fn pong(&self, peer_ip: SocketAddr, _message: Pong) -> bool {
193        self.ping.on_pong_received(peer_ip);
194        true
195    }
196
197    /// Disconnects on receipt of a `PuzzleRequest` message.
198    fn puzzle_request(&self, peer_ip: SocketAddr) -> bool {
199        debug!("Disconnecting '{peer_ip}' for the following reason - {:?}", DisconnectReason::ProtocolViolation);
200        false
201    }
202
203    /// Saves the latest epoch hash and latest block header in the node.
204    fn puzzle_response(&self, peer_ip: SocketAddr, epoch_hash: N::BlockHash, header: Header<N>) -> bool {
205        // Retrieve the block height.
206        let block_height = header.height();
207
208        info!(
209            "Puzzle (Block {block_height}, Coinbase Target {}, Proof Target {})",
210            header.coinbase_target(),
211            header.proof_target()
212        );
213
214        // Save the latest epoch hash in the node.
215        self.latest_epoch_hash.write().replace(epoch_hash);
216        // Save the latest block header in the node.
217        self.latest_block_header.write().replace(header);
218
219        trace!("Received 'PuzzleResponse' from '{peer_ip}' (Block {block_height})");
220        true
221    }
222
223    /// Propagates the unconfirmed solution to all connected validators.
224    async fn unconfirmed_solution(
225        &self,
226        peer_ip: SocketAddr,
227        serialized: UnconfirmedSolution<N>,
228        solution: Solution<N>,
229    ) -> bool {
230        // Retrieve the latest epoch hash.
231        let epoch_hash = *self.latest_epoch_hash.read();
232        // Retrieve the latest proof target.
233        let proof_target = self.latest_block_header.read().as_ref().map(|header| header.proof_target());
234
235        if let (Some(epoch_hash), Some(proof_target)) = (epoch_hash, proof_target) {
236            // Ensure that the solution is valid for the given epoch.
237            let puzzle = self.puzzle.clone();
238            let is_valid =
239                tokio::task::spawn_blocking(move || puzzle.check_solution(&solution, epoch_hash, proof_target)).await;
240
241            match is_valid {
242                // If the solution is valid, propagate the `UnconfirmedSolution`.
243                Ok(Ok(())) => {
244                    let message = Message::UnconfirmedSolution(serialized);
245                    // Propagate the "UnconfirmedSolution".
246                    self.propagate(message, &[peer_ip]);
247                }
248                Ok(Err(_)) => {
249                    trace!("Invalid solution '{}' for the proof target.", solution.id())
250                }
251                // If error occurs after the first 10 blocks of the epoch, log it as a warning, otherwise ignore.
252                Err(error) => {
253                    if let Some(height) = self.latest_block_header.read().as_ref().map(|header| header.height()) {
254                        if height % N::NUM_BLOCKS_PER_EPOCH > 10 {
255                            warn!("Failed to verify the solution - {error}")
256                        }
257                    }
258                }
259            }
260        }
261        true
262    }
263
264    /// Handles an `UnconfirmedTransaction` message.
265    async fn unconfirmed_transaction(
266        &self,
267        _peer_ip: SocketAddr,
268        _serialized: UnconfirmedTransaction<N>,
269        _transaction: Transaction<N>,
270    ) -> bool {
271        true
272    }
273}