use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use futures::{future::BoxFuture, FutureExt};
use nimiq_block::Block;
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_blockchain_proxy::BlockchainProxy;
use nimiq_genesis::HardcodedElection;
use nimiq_hash::Blake2bHash;
use nimiq_network_interface::{
network::{CloseReason, Network, SubscribeEvents},
request::RequestError,
};
use nimiq_primitives::policy::Policy;
use nimiq_utils::{spawn, stream::FuturesUnordered};
use parking_lot::RwLock;
#[cfg(feature = "full")]
use crate::messages::{HistoryChunk, HistoryChunkError, RequestHistoryChunk};
use crate::{
messages::BlockError,
sync::{
peer_list::PeerList,
sync_interface::{EpochIds, MacroSync},
sync_queue::SyncQueue,
},
};
#[cfg(feature = "full")]
pub struct ValidityChunkRequest {
pub verifier_block_number: u32,
pub root_hash: Blake2bHash,
pub chunk_index: u32,
pub election_in_window: bool,
pub last_chunk_items: Option<usize>,
}
const PENDING_SIZE: usize = 5;
#[derive(Debug)]
pub(crate) enum MacroBlockError {
Request(RequestError),
Block(BlockError),
}
impl std::fmt::Display for MacroBlockError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MacroBlockError::Request(error) => write!(f, "request error: {error}"),
MacroBlockError::Block(error) => write!(f, "block error: {error}"),
}
}
}
pub struct LightMacroSync<TNetwork: Network> {
pub(crate) blockchain: BlockchainProxy,
pub(crate) network: Arc<TNetwork>,
pub(crate) network_event_rx: SubscribeEvents<TNetwork::PeerId>,
pub(crate) epoch_ids_stream:
FuturesUnordered<BoxFuture<'static, Option<EpochIds<TNetwork::PeerId>>>>,
pub(crate) bootstrap_checkpoint: Option<HardcodedElection>,
pub(crate) macro_block_queue: SyncQueue<
TNetwork,
Blake2bHash,
(Blake2bHash, Result<Block, BlockError>, TNetwork::PeerId),
MacroBlockError,
(),
>,
pub(crate) in_flight_macro_blocks: HashSet<Blake2bHash>,
pub(crate) waiting_macro_peers: HashMap<TNetwork::PeerId, u32>,
pub(crate) pending_followup_requests: HashMap<Blake2bHash, Vec<TNetwork::PeerId>>,
#[cfg(feature = "full")]
pub(crate) validity_queue: SyncQueue<
TNetwork,
RequestHistoryChunk,
(
RequestHistoryChunk,
Result<HistoryChunk, HistoryChunkError>,
TNetwork::PeerId,
),
RequestError,
(),
>,
#[cfg(feature = "full")]
pub(crate) validity_requests: Option<ValidityChunkRequest>,
#[cfg(feature = "full")]
pub(crate) syncing_peers: HashSet<TNetwork::PeerId>,
#[cfg(feature = "full")]
pub(crate) synced_validity_peers: Vec<TNetwork::PeerId>,
#[cfg(feature = "full")]
pub(crate) full_sync_threshold: u32,
}
impl<TNetwork: Network> LightMacroSync<TNetwork> {
pub fn new(
blockchain: BlockchainProxy,
network: Arc<TNetwork>,
network_event_rx: SubscribeEvents<TNetwork::PeerId>,
full_sync_threshold: u32,
bootstrap_checkpoint: Option<HardcodedElection>,
) -> Self {
debug_assert!(
bootstrap_checkpoint
.as_ref()
.is_none_or(|cp| Policy::is_election_block_at(cp.block_number)),
"bootstrap checkpoint must be an election block"
);
let macro_block_queue = SyncQueue::with_verification(
Arc::clone(&network),
Vec::<(Blake2bHash, Option<_>)>::new(),
Arc::new(RwLock::new(PeerList::default())),
PENDING_SIZE,
move |block_hash, network, peer_id| {
async move {
match Self::request_macro_block(network, peer_id, block_hash.clone()).await {
Err(error) => Err(MacroBlockError::Request(error)),
Ok(Err(error @ BlockError::ResponseHashMismatch)) => {
Ok((block_hash, Err(error), peer_id))
}
Ok(Err(error)) => Err(MacroBlockError::Block(error)),
Ok(Ok(block)) => Ok((block_hash, Ok(block), peer_id)),
}
}
.boxed()
},
|_, _, _| true,
(),
);
#[cfg(feature = "full")]
let peers = Arc::new(RwLock::new(PeerList::default()));
#[cfg(feature = "full")]
let validity_queue = SyncQueue::new(
Arc::clone(&network),
Vec::<(RequestHistoryChunk, Option<_>)>::new(),
peers,
PENDING_SIZE,
move |request, network, peer_id| {
async move {
let res = Self::request_validity_window_chunk(
network,
peer_id,
request.epoch_number,
request.block_number,
request.chunk_index,
)
.await?;
Ok((request, res, peer_id))
}
.boxed()
},
);
Self {
blockchain,
network,
network_event_rx,
epoch_ids_stream: FuturesUnordered::new(),
#[cfg(feature = "full")]
full_sync_threshold,
bootstrap_checkpoint,
macro_block_queue,
in_flight_macro_blocks: HashSet::new(),
waiting_macro_peers: HashMap::new(),
pending_followup_requests: HashMap::new(),
#[cfg(feature = "full")]
validity_requests: None,
#[cfg(feature = "full")]
syncing_peers: HashSet::new(),
#[cfg(feature = "full")]
validity_queue,
#[cfg(feature = "full")]
synced_validity_peers: Vec::new(),
}
}
pub fn remove_peer(&mut self, peer_id: TNetwork::PeerId) {
self.macro_block_queue.remove_peer(&peer_id);
self.waiting_macro_peers.remove(&peer_id);
}
pub fn disconnect_peer(&mut self, peer_id: TNetwork::PeerId, reason: CloseReason) {
self.remove_peer(peer_id);
let network = Arc::clone(&self.network);
spawn(Box::pin({
async move {
network.disconnect_peer(peer_id, reason).await;
}
}));
}
pub(crate) fn request_epoch_ids_from(&mut self, peer_id: TNetwork::PeerId) {
let future =
Self::request_epoch_ids(self.blockchain.clone(), Arc::clone(&self.network), peer_id)
.boxed();
self.epoch_ids_stream.push(future);
}
}
impl<TNetwork: Network> MacroSync<TNetwork::PeerId> for LightMacroSync<TNetwork> {
const MAX_REQUEST_EPOCHS: u16 = 1000;
fn add_peer(&mut self, peer_id: TNetwork::PeerId) {
self.macro_block_queue.add_peer(peer_id);
if let Some(checkpoint) = &self.bootstrap_checkpoint
&& self.blockchain.read().block_number() < checkpoint.block_number
{
let hash = checkpoint.hash.clone();
let target = checkpoint.block_number;
if self.in_flight_macro_blocks.insert(hash.clone()) {
info!(%peer_id, "Requesting checkpoint block from peer");
self.macro_block_queue.add_ids(vec![(hash, Some(peer_id))]);
}
self.waiting_macro_peers.insert(peer_id, target);
return;
}
info!(%peer_id, "Requesting epoch ids from peer");
self.request_epoch_ids_from(peer_id);
}
fn fallback(&mut self, _peers: Vec<TNetwork::PeerId>) {
unimplemented!()
}
fn drain_peers(&mut self) -> Vec<TNetwork::PeerId> {
unimplemented!()
}
}