Skip to main content

nimiq_consensus/sync/live/diff_queue/
diff_request_component.rs

1use std::{cmp::min, sync::Arc};
2
3use futures::future::BoxFuture;
4use nimiq_network_interface::network::Network;
5use nimiq_primitives::{trie::trie_diff::TrieDiff, TreeProof};
6use parking_lot::RwLock;
7use tokio::sync::Semaphore;
8
9use super::{RequestTrieDiff, ResponseTrieDiff};
10use crate::sync::{
11    live::block_queue::BlockAndSource,
12    peer_list::{PeerList, PeerListIndex},
13};
14
15/// Errors that can occur while requesting a trie diff from peers.
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
17pub enum DiffRequestError {
18    /// The maximum number of diff request attempts was reached.
19    MaxTriesExceeded,
20}
21
22/// Maximum total number of request attempts per diff request. Peer-list changes may cause the same
23/// peer to be selected more than once.
24const MAX_TRIES: usize = 15;
25
26/// Handles requesting `TrieDiff` for blocks from peers during live sync.
27pub struct DiffRequestComponent<N: Network> {
28    network: Arc<N>,
29    peers: Arc<RwLock<PeerList<N>>>,
30    current_peer_index: PeerListIndex,
31    /// Bounds locally active request futures. Dropping a future releases its permit, but cannot
32    /// withdraw a request that has already been handed to the network.
33    concurrent_requests: Arc<Semaphore>,
34}
35
36impl<N: Network> DiffRequestComponent<N> {
37    const NUM_PENDING_DIFFS: usize = 5;
38
39    /// Creates a new `DiffRequestComponent` with a limit on concurrent diff requests.
40    pub fn new(network: Arc<N>, peers: Arc<RwLock<PeerList<N>>>) -> Self {
41        DiffRequestComponent {
42            network,
43            peers,
44            current_peer_index: PeerListIndex::default(),
45            concurrent_requests: Arc::new(Semaphore::new(Self::NUM_PENDING_DIFFS)),
46        }
47    }
48
49    pub fn request_diff(
50        &mut self,
51    ) -> impl FnMut(&BlockAndSource<N>) -> BoxFuture<'static, Result<TrieDiff, DiffRequestError>> + use<N>
52    {
53        let mut starting_peer_index = self.current_peer_index.clone();
54        self.current_peer_index.increment();
55
56        let peers = Arc::clone(&self.peers);
57        let network = Arc::clone(&self.network);
58        let concurrent_requests = Arc::clone(&self.concurrent_requests);
59
60        move |(block, block_source)| {
61            let peers = Arc::clone(&peers);
62
63            // If we know the peer that sent us this block, we ask them first.
64            let mut current_peer_index = peers
65                .read()
66                .index_of(&block_source.peer_id())
67                .unwrap_or_else(|| {
68                    starting_peer_index.increment();
69                    starting_peer_index.clone()
70                });
71
72            let network = Arc::clone(&network);
73            let concurrent_requests = Arc::clone(&concurrent_requests);
74            let block_desc = format!("{block}");
75            let block_hash = block.hash();
76            let block_diff_root = block.diff_root().clone();
77
78            Box::pin(async move {
79                // Controls the number of concurrent diff requests.
80                let _request_permit = concurrent_requests.acquire().await.unwrap();
81                let mut num_tries = 0;
82
83                loop {
84                    // Get the current peer based on the index.
85                    let peer_id = peers.read().get(&current_peer_index);
86                    let peer_id = match peer_id {
87                        Some(peer_id) => peer_id,
88                        None => {
89                            // No request can be sent in this iteration, so wait for a peer. A peer
90                            // removed after an invalid response is handled by the post-attempt
91                            // retry check below before the loop can reach this branch again.
92                            let peers_became_nonempty = peers.read().wait_for_peers();
93                            if let Some(peers_became_nonempty) = peers_became_nonempty {
94                                debug!(block = %block_desc, "couldn't fetch diff: waiting for peers");
95
96                                // This wait is intentionally unbounded: having no peers is not a
97                                // failed request attempt. Keep the semaphore permit while parked so
98                                // at most `NUM_PENDING_DIFFS` diff requests wait for peers.
99                                peers_became_nonempty.await;
100                            }
101                            continue;
102                        }
103                    };
104                    current_peer_index.increment();
105
106                    // Send the diff request to the selected peer.
107                    let result = network
108                        .request(
109                            RequestTrieDiff {
110                                block_hash: block_hash.clone(),
111                            },
112                            peer_id,
113                        )
114                        .await;
115
116                    num_tries += 1;
117
118                    match result {
119                        // If the peer returns a partial diff, validate it.
120                        Ok(ResponseTrieDiff::PartialDiff(diff)) => {
121                            // Verify that the returned diff matches the block’s expected diff root.
122                            if TreeProof::new(diff.0.iter()).root_hash() == block_diff_root {
123                                // If valid, return the diff.
124                                return Ok(diff);
125                            }
126                            // A tree-proof mismatch is cryptographically tied to the response
127                            // contents; an honest peer cannot produce it by accident.
128                            warn!(%peer_id, block = %block_desc, %num_tries, "couldn't fetch diff: invalid diff, removing peer");
129                            peers.write().remove_peer(&peer_id);
130                        }
131                        Ok(ResponseTrieDiff::IncompleteState) => {
132                            debug!(%peer_id, block = %block_desc, %num_tries, "couldn't fetch diff: incomplete state")
133                        }
134                        Ok(ResponseTrieDiff::UnknownBlockHash) => {
135                            debug!(%peer_id, block = %block_desc, %num_tries, "couldn't fetch diff: unknown block hash")
136                        }
137                        Err(error) => {
138                            debug!(%peer_id, block = %block_desc, %num_tries, ?error, "couldn't fetch diff: {}", error)
139                        }
140                    }
141
142                    // Recompute the limit after processing the response because an invalid diff
143                    // may have removed the selected peer. If it was the last peer, `max_tries`
144                    // becomes zero and this completed attempt terminates instead of entering the
145                    // no-peer waiting branch on the next iteration.
146                    let max_tries = min(MAX_TRIES, peers.read().len());
147                    if num_tries >= max_tries {
148                        debug!(block = %block_desc, %num_tries, %max_tries, "couldn't fetch diff: giving up after maximum tries");
149                        return Err(DiffRequestError::MaxTriesExceeded);
150                    }
151                }
152            })
153        }
154    }
155
156    /// Returns the current peer list used for diff requests.
157    pub fn peer_list(&self) -> Arc<RwLock<PeerList<N>>> {
158        Arc::clone(&self.peers)
159    }
160}