nimiq-consensus 2.2.0

Consensus logic of Nimiq's Albatross implementation
Documentation
use std::{
    collections::HashSet,
    future::Future,
    mem,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use futures::{future::BoxFuture, FutureExt, StreamExt};
use nimiq_block::Block;
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_blockchain_proxy::BlockchainProxy;
use nimiq_hash::Blake2bHash;
use nimiq_network_interface::{
    network::{CloseReason, Network},
    request::RequestError,
};
use nimiq_utils::{spawn, stream::FuturesUnordered};

use crate::messages::{BlockError, RequestHead, ResponseHead};

/// Requests the head blocks for a set of peers.
/// Calculates the number of known/unknown blocks and a vector of unknown blocks.
pub struct HeadRequests<TNetwork: Network + 'static> {
    peers: Vec<TNetwork::PeerId>,
    head_hashes: FuturesUnordered<BoxFuture<'static, (usize, Result<ResponseHead, RequestError>)>>,
    head_blocks: FuturesUnordered<
        BoxFuture<
            'static,
            (
                Result<Result<Block, BlockError>, RequestError>,
                TNetwork::PeerId,
            ),
        >,
    >,
    requested_hashes: HashSet<Blake2bHash>,
    blockchain: BlockchainProxy,
    network: Arc<TNetwork>,
    num_known_blocks: usize,
    num_unknown_blocks: usize,
    unknown_blocks: Vec<(Block, TNetwork::PeerId)>,
    include_body: bool,
}
/// Contains the number of known and unknown blocks,
/// and a list of unknown blocks paired with the peer they came from.
pub struct HeadRequestsResult<TNetwork: Network + 'static> {
    pub num_known_blocks: usize,
    pub num_unknown_blocks: usize,
    pub unknown_blocks: Vec<(Block, TNetwork::PeerId)>,
}

impl<TNetwork: Network + 'static> HeadRequests<TNetwork> {
    /// Creates a new `HeadRequest` instance for a given set of peers.
    pub fn new(
        peers: Vec<TNetwork::PeerId>,
        network: Arc<TNetwork>,
        blockchain: BlockchainProxy,
    ) -> Self {
        let head_hashes = peers
            .iter()
            .enumerate()
            .map(|(i, peer_id)| {
                let peer_id = *peer_id;
                let network = Arc::clone(&network);
                async move { (i, Self::request_head(network, peer_id).await) }.boxed()
            })
            .collect();

        #[cfg(feature = "full")]
        let include_body = matches!(blockchain, BlockchainProxy::Full(_));
        #[cfg(not(feature = "full"))]
        let include_body = false;

        HeadRequests {
            peers,
            head_hashes,
            head_blocks: Default::default(),
            requested_hashes: Default::default(),
            blockchain,
            network,
            num_known_blocks: 0,
            num_unknown_blocks: 0,
            unknown_blocks: Default::default(),
            include_body,
        }
    }

    /// Returns `true` if all head and block requests have been processed.
    pub fn is_finished(&self) -> bool {
        self.head_hashes.is_empty() && self.head_blocks.is_empty()
    }

    /// Used to retrieve the peer's current head block information.
    async fn request_head(
        network: Arc<TNetwork>,
        peer_id: TNetwork::PeerId,
    ) -> Result<ResponseHead, RequestError> {
        network
            .request::<RequestHead>(RequestHead {}, peer_id)
            .await
    }
}

impl<TNetwork: Network + 'static> Future for HeadRequests<TNetwork> {
    type Output = HeadRequestsResult<TNetwork>;

    /// Polls the future for head requests. First collects head hashes from peers,
    /// checks if each hash is known or unknown, and schedules a block request if unknown.
    /// Then polls for block responses, collecting valid ones and banning peers that respond
    /// with mismatched data. When all requests have been processed, the future returns with the result;
    /// otherwise, it remains pending.
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // We poll the hashes first.
        while let Poll::Ready(Some((i, result))) = self.head_hashes.poll_next_unpin(cx) {
            // If we got a result, check it and classify it as known block/unknown block.
            match result {
                Ok(head) => {
                    let hash = head.block_hash;
                    if self.blockchain.read().get_block(&hash, false).is_ok() {
                        self.num_known_blocks += 1;
                    } else {
                        // Request unknown blocks from peer that gave it to us.
                        self.num_unknown_blocks += 1;
                        if !self.requested_hashes.contains(&hash) {
                            self.requested_hashes.insert(hash.clone());
                            let network = Arc::clone(&self.network);
                            let peer_id = self.peers[i];
                            let include_body = self.include_body;
                            self.head_blocks.push(
                                async move {
                                    (
                                        crate::sync::request_block(
                                            network,
                                            peer_id,
                                            hash,
                                            include_body,
                                        )
                                        .await,
                                        peer_id,
                                    )
                                }
                                .boxed(),
                            );
                        }
                    }
                }
                Err(error) => {
                    trace!(%error, "Failed head hash request");
                } // We don't count failed requests.
            }
        }

        // Then poll blocks.
        while let Poll::Ready(Some(result)) = self.head_blocks.poll_next_unpin(cx) {
            match result {
                (Ok(Ok(block)), peer_id) => {
                    self.unknown_blocks.push((block, peer_id));
                }
                // We disconnect from the malicious peer in case of deliberate lying
                (Ok(Err(BlockError::ResponseHashMismatch)), peer_id) => {
                    warn!(%peer_id,
                        "Banning peer due to wrong reply to requested block",
                    );

                    let network = Arc::clone(&self.network);
                    spawn(Box::pin({
                        async move {
                            network
                                .disconnect_peer(peer_id, CloseReason::MaliciousPeer)
                                .await;
                        }
                    }));
                }
                // We don't do anything with failed requests.
                (Ok(Err(error)), peer_id) => {
                    trace!(%error, %peer_id, "Block request failed on remote side")
                }
                (Err(error), peer_id) => {
                    trace!(%error, %peer_id, "Failed block request");
                }
            }
        }

        // We're done if both queues are empty.
        if self.is_finished() {
            return Poll::Ready(HeadRequestsResult {
                num_known_blocks: self.num_known_blocks,
                num_unknown_blocks: self.num_unknown_blocks,
                unknown_blocks: mem::take(&mut self.unknown_blocks),
            });
        }

        Poll::Pending
    }
}