nimiq-consensus 2.2.0

Consensus logic of Nimiq's Albatross implementation
Documentation
use std::sync::Arc;

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_primitives::policy::Policy;

use crate::{
    messages::{BlockError, MacroChain, MacroChainError, RequestMacroChain},
    sync::{
        light::LightMacroSync,
        sync_interface::{EpochIds, MacroSync, MacroSyncReturn},
    },
};

impl<TNetwork: Network> LightMacroSync<TNetwork> {
    /// Requests epoch IDs from a peer by sending a macro chain request.
    /// Performs basic validation on the result and may ban the peer on invalid responses.
    pub(crate) async fn request_epoch_ids(
        blockchain: BlockchainProxy,
        network: Arc<TNetwork>,
        peer_id: TNetwork::PeerId,
    ) -> Option<EpochIds<TNetwork::PeerId>> {
        let (locators, epoch_number) = {
            // Order matters here. The first hash found by the recipient of the request will be
            // used, so they need to be in backwards block height order.
            let blockchain = blockchain.read();
            let election_head = blockchain.election_head();
            let macro_head = blockchain.macro_head();

            // So if there is a checkpoint hash that should be included in addition to the election
            // block hash, it should come first.
            let mut locators = vec![];
            if macro_head.hash() != election_head.hash() {
                locators.push(macro_head.hash());
            }
            // The election block is at the end here
            locators.push(election_head.hash());

            (locators, election_head.epoch_number())
        };

        let result = Self::request_macro_chain(
            Arc::clone(&network),
            peer_id,
            locators,
            Self::MAX_REQUEST_EPOCHS,
        )
        .await;

        match result {
            Ok(Err(error)) => {
                debug!(%error, "Error requesting macro chain");
                Some(EpochIds {
                    locator_found: false,
                    ids: Vec::new(),
                    checkpoint: None,
                    first_epoch_number: 0,
                    sender: peer_id,
                })
            }
            Ok(Ok(macro_chain)) => {
                // Validate that the maximum number of epochs is not exceeded.
                if macro_chain.epochs.len() > Self::MAX_REQUEST_EPOCHS as usize {
                    log::warn!(
                        num_epochs = macro_chain.epochs.len(),
                        %peer_id,
                        "Banning peer because requesting macro chain failed: too many epochs returned"
                    );
                    network
                        .disconnect_peer(peer_id, CloseReason::MaliciousPeer)
                        .await;
                    return None;
                }

                // Sanity-check checkpoint block number:
                //  * is in checkpoint epoch
                //  * is a non-election macro block
                if let Some(checkpoint) = &macro_chain.checkpoint {
                    let checkpoint_epoch = epoch_number + macro_chain.epochs.len() as u32 + 1;
                    if Policy::epoch_at(checkpoint.block_number) != checkpoint_epoch
                        || !Policy::is_macro_block_at(checkpoint.block_number)
                        || Policy::is_election_block_at(checkpoint.block_number)
                    {
                        // Peer provided an invalid checkpoint block number, close connection.
                        log::warn!(
                            block_number = checkpoint.block_number,
                            checkpoint_epoch,
                            %peer_id,
                            "Banning peer because requesting macro chain failed: invalid checkpoint"
                        );
                        network
                            .disconnect_peer(peer_id, CloseReason::MaliciousPeer)
                            .await;
                        return None;
                    }
                }

                log::debug!(
                    received_epochs = macro_chain.epochs.len(),
                    start_epoch = epoch_number + 1,
                    checkpoint = macro_chain.checkpoint.is_some(),
                    sender = %peer_id,
                    "Received epoch_ids"
                );

                Some(EpochIds {
                    locator_found: true,
                    ids: macro_chain.epochs,
                    checkpoint: macro_chain.checkpoint,
                    first_epoch_number: epoch_number as usize + 1,
                    sender: peer_id,
                })
            }
            Err(error) => {
                log::warn!(%error, %peer_id, "Request macro chain failed");
                network.disconnect_peer(peer_id, CloseReason::Error).await;
                None
            }
        }
    }

    /// Creates block header requests for election blocks and an optional checkpoint
    /// received from a peer.
    pub(crate) fn request_macro_headers(
        &mut self,
        mut epoch_ids: EpochIds<TNetwork::PeerId>,
    ) -> Option<MacroSyncReturn<TNetwork::PeerId>> {
        // Read our current blockchain state.
        let (our_epoch_id, our_epoch_number, our_block_number) = {
            let blockchain = self.blockchain.read();
            (
                blockchain.election_head_hash(),
                blockchain.election_head().epoch_number() as usize,
                blockchain.block_number(),
            )
        };

        // Truncate epoch_ids by epoch_number: Discard all epoch_ids prior to our accepted state.
        if !epoch_ids.ids.is_empty() && epoch_ids.first_epoch_number <= our_epoch_number {
            let peers_epoch_number = epoch_ids.last_epoch_number();
            if peers_epoch_number < our_epoch_number
                || (peers_epoch_number == our_epoch_number && epoch_ids.checkpoint.is_none())
            {
                // Peer is behind, emit it as useless.
                debug!(
                    our_epoch_number,
                    peers_epoch_number,
                    peer = %epoch_ids.sender,
                    "Peer is behind"
                );
                return Some(MacroSyncReturn::Outdated(epoch_ids.sender));
            } else {
                // Check that the epoch_id sent by the peer at our current epoch number corresponds to
                // our accepted state. If it doesn't, the peer is on a "permanent" fork, so we ban it.
                let peers_epoch_id =
                    &epoch_ids.ids[our_epoch_number - epoch_ids.first_epoch_number];
                if our_epoch_id != *peers_epoch_id {
                    // TODO Actually ban the peer.
                    debug!(
                        our_epoch_number,
                        %our_epoch_id,
                        %peers_epoch_id,
                        peer = %epoch_ids.sender,
                        "Peer is on a different chain"
                    );
                    return Some(MacroSyncReturn::Outdated(epoch_ids.sender));
                }

                epoch_ids.ids = epoch_ids
                    .ids
                    .split_off(our_epoch_number - epoch_ids.first_epoch_number + 1);
                epoch_ids.first_epoch_number = our_epoch_number + 1;
            }
        }

        // Discard checkpoint block if it is old.
        if let Some(checkpoint) = &epoch_ids.checkpoint
            && checkpoint.block_number <= our_block_number
        {
            epoch_ids.checkpoint = None;
        }

        // After discarding all epoch_ids & checkpoint prior to our current state
        // It could happen that we don't have anything new to learn from this peer
        if epoch_ids.ids.is_empty() && epoch_ids.checkpoint.is_none() {
            log::debug!("Nothing new to learn from this peer, emit it as good");
            return Some(MacroSyncReturn::Good(epoch_ids.sender));
        }

        // The highest block this peer reports: once our head reaches it, the peer is fully synced
        // from our side. Drives the tip-follow re-request in `poll_macro_block_queue`. A checkpoint
        // (a later, non-election macro block) is always higher than the last election block.
        //
        // A peer reporting a nonsensically large epoch number yields a `u32::MAX` target it has no
        // hope of reaching, so it just sits in `waiting_macro_peers` until it disconnects. Harmless:
        // it never gets emitted, but it also wastes nothing (it is requested no blocks).
        let target_block_number = if let Some(checkpoint) = &epoch_ids.checkpoint {
            checkpoint.block_number
        } else {
            Policy::election_block_of(epoch_ids.last_epoch_number() as u32).unwrap_or(u32::MAX)
        };

        log::trace!(%epoch_ids.sender, "Queueing macro block requests");

        // Enqueue the election blocks (and optional checkpoint) into the shared, bounded,
        // failover-capable macro block queue. Deduplicate against blocks already in flight so
        // overlapping epoch_ids from multiple peers don't request the same block twice. The sender
        // is passed as the preferred peer; the queue fails over to others on timeout.
        let mut ids = Vec::new();
        for block_hash in epoch_ids.ids {
            if self.in_flight_macro_blocks.insert(block_hash.clone()) {
                ids.push((block_hash, Some(epoch_ids.sender)));
            }
        }
        if let Some(checkpoint) = &epoch_ids.checkpoint {
            let block_hash = checkpoint.hash.clone();
            if self.in_flight_macro_blocks.insert(block_hash.clone()) {
                ids.push((block_hash, Some(epoch_ids.sender)));
            }
        }

        // If everything this peer reported is already in flight (driven by another peer) and we
        // have already reached its target, it is fully synced now: emit it as good. Otherwise wait
        // until the queue advances our head to its target (see `poll_macro_block_queue`).
        if ids.is_empty() && target_block_number <= our_block_number {
            return Some(MacroSyncReturn::Good(epoch_ids.sender));
        }

        self.waiting_macro_peers
            .insert(epoch_ids.sender, target_block_number);
        self.macro_block_queue.add_ids(ids);

        None
    }

    /// Sends a macro block request to a peer.
    pub async fn request_macro_block(
        network: Arc<TNetwork>,
        peer_id: TNetwork::PeerId,
        hash: Blake2bHash,
    ) -> Result<Result<Block, BlockError>, RequestError> {
        // Macro sync only needs the header, so the body is not requested
        crate::sync::request_block(network, peer_id, hash, false).await
    }

    /// Sends a macro chain request to a peer, using the provided locators and maximum number of epochs.
    pub async fn request_macro_chain(
        network: Arc<TNetwork>,
        peer_id: TNetwork::PeerId,
        locators: Vec<Blake2bHash>,
        max_epochs: u16,
    ) -> Result<Result<MacroChain, MacroChainError>, RequestError> {
        network
            .request::<RequestMacroChain>(
                RequestMacroChain {
                    locators,
                    max_epochs,
                },
                peer_id,
            )
            .await
    }
}