Skip to main content

nimiq_consensus/sync/live/block_queue/
block_request_component.rs

1//! Defines the `BlockRequestComponent`, which handles requesting missing blocks
2//! from peers during synchronization. It maintains a list of active peers, manages a queue
3//! of block requests, and verifies the integrity of responses.
4
5use std::{
6    collections::BTreeSet,
7    fmt::{Debug, Formatter},
8    pin::Pin,
9    sync::Arc,
10    task::{Context, Poll},
11};
12
13use futures::{FutureExt, Stream, StreamExt};
14use nimiq_block::Block;
15use nimiq_blockchain_interface::Direction;
16use nimiq_hash::Blake2bHash;
17use nimiq_network_interface::{
18    network::{Network, NetworkEvent},
19    request::RequestError,
20};
21use nimiq_primitives::{networks::NetworkId, policy::Policy, slots_allocation::Validators};
22use nimiq_utils::spawn;
23use parking_lot::RwLock;
24use thiserror::Error;
25
26use crate::{
27    messages::{RequestMissingBlocks, ResponseBlocksError},
28    sync::{peer_list::PeerList, sync_queue::SyncQueue},
29};
30
31/// Result of a successful missing block request.
32#[derive(Debug)]
33pub struct BlockRequestResult<N: Network> {
34    pub target_block_number: u32,
35    pub target_block_hash: Blake2bHash,
36    pub epoch_validators: Validators,
37    pub blocks: Vec<Block>,
38    pub sender: N::PeerId,
39}
40
41/// Request for a sequence of missing blocks from a peer.
42#[derive(Clone)]
43pub struct MissingBlockRequest {
44    /// The block number of the requested block.
45    pub target_block_number: u32,
46    /// The hash the last block which is requested with this request.
47    pub target_block_hash: Blake2bHash,
48    /// The validators of the epoch the target block is from.
49    pub epoch_validators: Validators,
50    /// List of locator hashes of blocks, sorted from newest to oldest.
51    pub locators: Vec<Blake2bHash>,
52    /// Flag indicating whether bodies must be included or omitted.
53    pub include_body: bool,
54    /// The Direction the request is to be executed in.
55    /// See [RequestMissingBlocks] for details on the effect.
56    pub direction: Direction,
57}
58
59impl Debug for MissingBlockRequest {
60    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
61        let mut dbg = f.debug_struct("MissingBlockRequest");
62        dbg.field("target_block_number", &self.target_block_number);
63        dbg.field("target_block_hash", &self.target_block_hash);
64        dbg.field("num_locators", &self.locators.len());
65        dbg.field("include_body", &self.include_body);
66        dbg.field("direction", &self.direction);
67        dbg.finish()
68    }
69}
70
71/// Response to a missing block request from a peer.
72#[derive(Debug, Clone)]
73pub struct MissingBlockResponse<N: Network> {
74    pub target_block_number: u32,
75    pub target_block_hash: Blake2bHash,
76    pub epoch_validators: Validators,
77    pub blocks: Vec<Block>,
78    pub sender: N::PeerId,
79}
80
81/// Error type for missing block requests during sync
82#[derive(Clone, Debug, Error)]
83pub enum MissingBlockError {
84    #[error("request: {0}")]
85    Request(RequestError),
86    #[error("response: {0}")]
87    Response(ResponseBlocksError),
88}
89
90/// Error returned when a block request fails within the sync queue.
91#[derive(Debug, Error)]
92#[error("Sync queue error. Target block hash: {target_block_hash}, target block number {target_block_number}")]
93pub struct SyncQueueError {
94    /// Target block hash
95    pub target_block_hash: Blake2bHash,
96    /// Target block number
97    pub target_block_number: u32,
98}
99
100/// Peer Tracking & Block Request Component.
101/// We use this component to request missing blocks from peers.
102///
103/// This component has:
104///
105/// - The sync queue which manages the requests and responses.
106/// - The peers list.
107/// - The network stream of events used to remove the peers that have left.  
108/// - Whether we include the body of a block.
109///
110/// The public interface allows to request blocks, which are not immediately returned.
111/// The blocks instead are returned by polling the component.
112pub struct BlockRequestComponent<N: Network> {
113    sync_queue:
114        SyncQueue<N, MissingBlockRequest, MissingBlockResponse<N>, MissingBlockError, NetworkId>, // requesting missing blocks from peers
115    peers: Arc<RwLock<PeerList<N>>>,
116    include_body: bool,
117    /// Pending requests.
118    pending_requests: BTreeSet<Blake2bHash>,
119}
120
121impl<N: Network> BlockRequestComponent<N> {
122    const NUM_PENDING_BLOCKS: usize = 5;
123
124    pub fn new(network: Arc<N>, network_id: NetworkId, include_body: bool) -> Self {
125        let peers = Arc::new(RwLock::new(PeerList::default()));
126        let mut network_event_rx = network.subscribe_events();
127
128        // Poll network events to remove peers.
129        let peers_weak = Arc::downgrade(&peers);
130        spawn(async move {
131            while let Some(result) = network_event_rx.next().await {
132                if let Ok(NetworkEvent::PeerLeft(peer_id)) = result {
133                    // Remove peers that left.
134                    let peers = match peers_weak.upgrade() {
135                        Some(peers) => peers,
136                        None => break,
137                    };
138
139                    trace!(%peer_id, "Removing peer from live sync");
140                    peers.write().remove_peer(&peer_id);
141                }
142            }
143        });
144
145        Self {
146            sync_queue: SyncQueue::with_verification(
147                network,
148                vec![],
149                Arc::clone(&peers),
150                Self::NUM_PENDING_BLOCKS,
151                |request, network, peer_id| {
152                    async move {
153                        match Self::request_missing_blocks_from_peer(
154                            network,
155                            peer_id,
156                            request.target_block_hash.clone(),
157                            request.locators,
158                            request.include_body,
159                            request.direction,
160                        )
161                        .await
162                        {
163                            Ok(Ok(missing_blocks)) => Ok(MissingBlockResponse {
164                                target_block_number: request.target_block_number,
165                                target_block_hash: request.target_block_hash,
166                                epoch_validators: request.epoch_validators,
167                                blocks: missing_blocks,
168                                sender: peer_id,
169                            }),
170                            Ok(Err(error)) => Err(MissingBlockError::Response(error)),
171                            Err(error) => Err(MissingBlockError::Request(error)),
172                        }
173                    }
174                    .boxed()
175                },
176                |request, response, network_id| {
177                    // We check general consistency for the response:
178                    // 1. Check that the blocks end on target block or macro block
179                    // 2. Verify macro block signature (last block)
180                    // 3. Check that hash chain verifies
181                    // We need to pass through the validators once we reach a new epoch
182                    // to be able to verify macro blocks
183
184                    let blocks = &mut response.blocks;
185
186                    // Size checks.
187                    if blocks.is_empty() {
188                        log::debug!("Received empty missing blocks response");
189                        return false;
190                    }
191
192                    if blocks.len() > Policy::blocks_per_batch() as usize {
193                        log::debug!(
194                            blocks_len = blocks.len(),
195                            "Received missing blocks response that is too large"
196                        );
197                        return false;
198                    }
199
200                    for block in blocks.iter() {
201                        if block.has_body() != request.include_body {
202                            log::error!(
203                                is_macro = block.is_macro(),
204                                has_body = block.has_body(),
205                                include_body = request.include_body,
206                                "Received block with body where none was expected or vice versa",
207                            );
208                            return false;
209                        }
210
211                        // Verify the header before the chain is hashed below, to cheaply reject
212                        // malformed blocks (wrong network/version, oversized extra data, or — for
213                        // election blocks — a structurally invalid validator set) without
214                        // buffering them.
215                        // `max_timestamp` is `u64::MAX` because these are historical blocks
216                        // requested by hash/height: the future-drift check is only meaningful for
217                        // live blocks and is re-applied with the real clock at push time
218                        if let Err(error) =
219                            block.verify_header(*network_id, block.is_skip(), u64::MAX)
220                        {
221                            log::error!(
222                                %block,
223                                %error,
224                                "Received missing block with an invalid header"
225                            );
226                            return false;
227                        }
228                    }
229
230                    // Checks that the first block's parent was part of the block locators.
231                    let first_block = blocks.first().unwrap(); // cannot be empty
232                    if !request.locators.contains(first_block.parent_hash()) {
233                        log::error!("Received invalid chain of missing blocks (first block's parent not in block locators)");
234                        return false;
235                    }
236
237                    if first_block.block_number() > request.target_block_number {
238                        log::error!(
239                            first_block = first_block.block_number(),
240                            request.target_block_number,
241                            "Received invalid chain of missing blocks (first block > target)"
242                        );
243                        return false;
244                    }
245
246                    // Check that the last block is valid. If it is at the target height it must
247                    // be the requested target block, i.e. its hash must match the requested one
248                    // (this holds for both macro and micro target blocks). Otherwise it must be
249                    // an intermediate macro block below the target that serves as a valid
250                    // stopping point; the rest of the chain up to the target is fetched by
251                    // follow-up requests.
252                    let last_block = blocks.last_mut().unwrap(); // cannot be empty
253                    let block_hash = last_block.hash_cached();
254                    let valid_last_block =
255                        if last_block.block_number() == request.target_block_number {
256                            block_hash == request.target_block_hash
257                        } else {
258                            last_block.is_macro()
259                        };
260                    if !valid_last_block {
261                        log::error!(
262                            request.target_block_number,
263                            last_block = last_block.block_number(),
264                            %block_hash,
265                            %request.target_block_hash,
266                            "Received invalid missing blocks (invalid target block)"
267                        );
268                        return false;
269                    }
270
271                    // Check that the hash chain of missing blocks is valid.
272                    // Also checks block numbers.
273                    for i in 1..blocks.len() {
274                        let previous_block_hash = blocks[i - 1].hash_cached();
275
276                        if blocks[i].block_number() != blocks[i - 1].block_number() + 1
277                            || blocks[i].block_number() > request.target_block_number
278                            || blocks[i].parent_hash() != &previous_block_hash
279                        {
280                            log::error!("Received invalid chain of missing blocks");
281                            return false;
282                        }
283                    }
284
285                    // If it is a macro block, also check the signatures.
286                    let last_block = response.blocks.last().unwrap(); // cannot be empty
287                    if last_block.is_macro()
288                        && let Err(e) = last_block.verify_validators(&request.epoch_validators)
289                    {
290                        log::error!(
291                            last_block = last_block.block_number(),
292                            error = %e,
293                            "Received invalid chain of missing blocks (macro block does not verify)"
294                        );
295                        return false;
296                    }
297
298                    true
299                },
300                network_id,
301            ),
302            peers,
303            include_body,
304            pending_requests: BTreeSet::new(),
305        }
306    }
307
308    async fn request_missing_blocks_from_peer(
309        network: Arc<N>,
310        peer_id: N::PeerId,
311        target_block_hash: Blake2bHash,
312        locators: Vec<Blake2bHash>,
313        include_body: bool,
314        direction: Direction,
315    ) -> Result<Result<Vec<Block>, ResponseBlocksError>, RequestError> {
316        network
317            .request::<RequestMissingBlocks>(
318                RequestMissingBlocks {
319                    locators,
320                    target_hash: target_block_hash,
321                    include_body,
322                    direction,
323                },
324                peer_id,
325            )
326            .await
327            .map(|response| response.map(|r| r.blocks))
328    }
329
330    pub fn request_missing_blocks(
331        &mut self,
332        target_block_number: u32,
333        target_block_hash: Blake2bHash,
334        locators: Vec<Blake2bHash>,
335        direction: Direction,
336        epoch_validators: Validators,
337        first_peer_id: Option<N::PeerId>,
338    ) {
339        self.pending_requests.insert(target_block_hash.clone());
340        self.sync_queue.add_ids(vec![(
341            MissingBlockRequest {
342                target_block_number,
343                target_block_hash,
344                epoch_validators,
345                locators,
346                direction,
347                include_body: self.include_body,
348            },
349            first_peer_id,
350        )]);
351    }
352
353    pub fn is_pending(&self, target_block_hash: &Blake2bHash) -> bool {
354        self.pending_requests.contains(target_block_hash)
355    }
356
357    pub fn add_peer(&self, peer_id: N::PeerId) {
358        self.peers.write().add_peer(peer_id);
359    }
360
361    pub fn take_peer(&self, peer_id: &N::PeerId) -> Option<N::PeerId> {
362        if self.peers.write().remove_peer(peer_id) {
363            return Some(*peer_id);
364        }
365        None
366    }
367
368    pub fn num_peers(&self) -> usize {
369        self.peers.read().len()
370    }
371
372    pub fn peers(&self) -> Vec<N::PeerId> {
373        self.peers.read().peers().to_vec()
374    }
375
376    pub fn peer_list(&self) -> Arc<RwLock<PeerList<N>>> {
377        Arc::clone(&self.peers)
378    }
379}
380
381impl<N: Network> Stream for BlockRequestComponent<N> {
382    type Item = Result<BlockRequestResult<N>, SyncQueueError>;
383
384    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
385        // Poll self.sync_queue, return results.
386        while let Poll::Ready(result) = self.sync_queue.poll_next_unpin(cx) {
387            match result {
388                // A valid response was received with blocks from a peer.
389                Some(Ok(response)) => {
390                    // Remove this request from the pending set.
391                    self.pending_requests.remove(&response.target_block_hash);
392                    return Poll::Ready(Some(Ok(BlockRequestResult {
393                        target_block_number: response.target_block_number,
394                        target_block_hash: response.target_block_hash,
395                        epoch_validators: response.epoch_validators,
396                        blocks: response.blocks,
397                        sender: response.sender,
398                    })));
399                }
400                // The request failed
401                Some(Err(request)) => {
402                    self.pending_requests.remove(&request.target_block_hash);
403                    debug!(
404                        request.target_block_number,
405                        ?request.target_block_hash,
406                        "Failed to retrieve missing blocks"
407                    );
408                    return Poll::Ready(Some(Err(SyncQueueError {
409                        target_block_hash: request.target_block_hash,
410                        target_block_number: request.target_block_number,
411                    })));
412                }
413                None => {}
414            }
415        }
416
417        Poll::Pending
418    }
419}