use std::{
collections::{HashSet, VecDeque},
fmt,
sync::Arc,
};
use futures::{future::BoxFuture, Stream};
use nimiq_block::Block;
#[cfg(feature = "full")]
use nimiq_blockchain::{Blockchain, PostValidationHook};
#[cfg(feature = "full")]
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_blockchain_interface::{ChunksPushError, ChunksPushResult, PushError, PushResult};
use nimiq_blockchain_proxy::BlockchainProxy;
use nimiq_hash::Blake2bHash;
use nimiq_light_blockchain::LightBlockchain;
use nimiq_network_interface::network::{MsgAcceptance, Network};
use nimiq_primitives::{
key_nibbles::KeyNibbles,
policy::Policy,
trie::{
trie_chunk::{TrieChunk, TrieChunkWithStart},
trie_diff::TrieDiff,
},
};
use parking_lot::Mutex;
use crate::{
consensus::ResolveBlockRequest,
sync::{
live::block_queue::{BlockAndSource, BlockSource},
sync_interface::LiveSyncEvent,
},
BlsCache,
};
async fn spawn_blocking<R: Send + 'static, F: FnOnce() -> R + Send + 'static>(f: F) -> R {
#[cfg(not(target_family = "wasm"))]
{
tokio::task::spawn_blocking(f).await.unwrap()
}
#[cfg(target_family = "wasm")]
{
f()
}
}
pub struct ChunkAndSource<N: Network> {
pub chunk: TrieChunk,
pub start_key: KeyNibbles,
pub peer_id: N::PeerId,
}
impl<N: Network> fmt::Debug for ChunkAndSource<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ChunkAndSource")
.field("chunk", &self.chunk)
.field("start_key", &self.start_key)
.field("peer_id", &self.peer_id)
.finish()
}
}
pub enum BlockAndChunksPushResult<N: Network> {
Applied(
Result<PushResult, PushError>,
Result<ChunksPushResult, ChunksPushError>,
Blake2bHash,
),
NeedsDiff(BlockAndSource<N>, Vec<ChunkAndSource<N>>, Blake2bHash),
}
pub enum MissingBlocksPushResult<N: Network> {
Applied(
Result<PushResult, PushError>,
Result<ChunksPushResult, ChunksPushError>,
Vec<Blake2bHash>,
HashSet<Blake2bHash>,
),
NeedsDiff(
Result<ChunksPushResult, ChunksPushError>,
Vec<Blake2bHash>,
Vec<(BlockAndSource<N>, Vec<ChunkAndSource<N>>)>,
),
}
impl<N: Network> ChunkAndSource<N> {
pub fn new(chunk: TrieChunk, start_key: KeyNibbles, peer_id: N::PeerId) -> Self {
Self {
chunk,
start_key,
peer_id,
}
}
pub fn into_pair(self) -> (TrieChunkWithStart, N::PeerId) {
(
TrieChunkWithStart {
chunk: self.chunk,
start_key: self.start_key,
},
self.peer_id,
)
}
}
pub trait LiveSyncQueue<N: Network>: Stream<Item = Self::QueueResult> + Send + Unpin {
type QueueResult: Send;
type PushResult;
fn push_queue_result(
network: Arc<N>,
blockchain: BlockchainProxy,
bls_cache: Arc<Mutex<BlsCache>>,
result: Self::QueueResult,
) -> VecDeque<BoxFuture<'static, Self::PushResult>>;
fn process_push_result(&mut self, item: Self::PushResult) -> Option<LiveSyncEvent<N::PeerId>>;
fn peers(&self) -> Vec<N::PeerId>;
fn num_peers(&self) -> usize;
fn add_peer(&self, peer_id: N::PeerId);
fn add_block_stream<S>(&mut self, block_stream: S)
where
S: Stream<Item = BlockAndSource<N>> + Send + 'static;
fn include_body(&self) -> bool;
fn state_complete(&self) -> bool {
true
}
fn resolve_block(&mut self, request: ResolveBlockRequest<N>);
fn acceptance_window_size(&self) -> u32;
}
#[derive(Clone, Debug)]
pub struct QueueConfig {
pub buffer_max: usize,
pub window_ahead_max: u32,
pub tolerate_past_max: u32,
pub include_body: bool,
}
impl Default for QueueConfig {
fn default() -> Self {
Self {
buffer_max: 10 * Policy::blocks_per_batch() as usize,
window_ahead_max: 2 * Policy::blocks_per_batch(),
tolerate_past_max: Policy::blocks_per_batch(),
include_body: true,
}
}
}
struct BlockchainPushResult<N: Network> {
block_push_result: Option<Result<PushResult, PushError>>,
push_chunks_result: Result<ChunksPushResult, ChunksPushError>,
retry_with_diff: Option<(BlockAndSource<N>, Vec<ChunkAndSource<N>>)>,
#[allow(dead_code)] chunk_error_peer: Option<<N as Network>::PeerId>,
block_hash: Blake2bHash,
}
impl<N: Network> BlockchainPushResult<N> {
fn with_light_block_result(
push_result: Result<PushResult, PushError>,
block_hash: Blake2bHash,
) -> Self {
Self {
block_push_result: Some(push_result),
push_chunks_result: Ok(ChunksPushResult::EmptyChunks),
retry_with_diff: None,
block_hash,
chunk_error_peer: None,
}
}
#[cfg(feature = "full")]
fn with_block_result(
push_result: Result<(PushResult, Result<ChunksPushResult, ChunksPushError>), PushError>,
block_hash: Blake2bHash,
peer_ids: &[N::PeerId],
) -> Self {
let (block_push_result, push_chunks_result, chunk_error_peer) = match push_result {
Ok((block_push_result, Err(chunk_error))) => {
let peer_id = peer_ids[chunk_error.chunk_index()];
(Ok(block_push_result), Err(chunk_error), Some(peer_id))
}
Ok((block_push_result, push_chunks_result)) => {
(Ok(block_push_result), push_chunks_result, None)
}
Err(push_error) => (Err(push_error), Ok(ChunksPushResult::EmptyChunks), None),
};
Self {
block_push_result: Some(block_push_result),
push_chunks_result,
retry_with_diff: None,
block_hash,
chunk_error_peer,
}
}
#[cfg(feature = "full")]
fn with_chunks_result(
push_chunks_result: Result<ChunksPushResult, ChunksPushError>,
block_hash: Blake2bHash,
peer_ids: &[N::PeerId],
) -> Self {
let peer_id = if let Err(ref chunk_error) = push_chunks_result {
let peer_id = peer_ids[chunk_error.chunk_index()];
Some(peer_id)
} else {
None
};
Self {
block_push_result: None,
push_chunks_result,
retry_with_diff: None,
block_hash,
chunk_error_peer: peer_id,
}
}
#[cfg(feature = "full")]
fn with_diff_retry(
block: BlockAndSource<N>,
chunks: Vec<ChunkAndSource<N>>,
block_hash: Blake2bHash,
) -> Self {
Self {
block_push_result: None,
push_chunks_result: Ok(ChunksPushResult::EmptyChunks),
retry_with_diff: Some((block, chunks)),
block_hash,
chunk_error_peer: None,
}
}
}
#[cfg(feature = "full")]
pub async fn push_block_and_chunks<N: Network>(
network: Arc<N>,
blockchain: BlockchainProxy,
bls_cache: Arc<Mutex<BlsCache>>,
block: Block,
block_source: BlockSource<N>,
diff: Option<TrieDiff>,
chunks: Vec<ChunkAndSource<N>>,
) -> BlockAndChunksPushResult<N> {
let push_results = spawn_blocking(move || {
blockchain_push(
blockchain,
bls_cache,
Some((block, block_source.clone())),
diff,
chunks,
Some(MessageValidator {
network,
block_source,
}),
)
})
.await;
if let Some((block, chunks)) = push_results.retry_with_diff {
BlockAndChunksPushResult::NeedsDiff(block, chunks, push_results.block_hash)
} else {
BlockAndChunksPushResult::Applied(
push_results.block_push_result.unwrap(),
push_results.push_chunks_result,
push_results.block_hash,
)
}
}
pub async fn push_block_only<N: Network>(
network: Arc<N>,
blockchain: BlockchainProxy,
bls_cache: Arc<Mutex<BlsCache>>,
block: Block,
block_source: BlockSource<N>,
) -> (Result<PushResult, PushError>, Blake2bHash) {
let push_results = spawn_blocking(move || {
blockchain_push::<N>(
blockchain,
bls_cache,
Some((block, block_source.clone())),
None,
vec![],
Some(MessageValidator {
network,
block_source,
}),
)
})
.await;
match push_results.retry_with_diff {
Some(_) => (
Err(PushError::MissingAccountsTrieDiff),
push_results.block_hash,
),
None => (
push_results.block_push_result.unwrap(),
push_results.block_hash,
),
}
}
pub async fn push_multiple_blocks_impl<N: Network>(
blockchain: BlockchainProxy,
bls_cache: Arc<Mutex<BlsCache>>,
blocks: Vec<(BlockAndSource<N>, Option<TrieDiff>, Vec<ChunkAndSource<N>>)>,
) -> MissingBlocksPushResult<N> {
let mut block_iter = blocks.into_iter();
let mut adopted_blocks = Vec::new();
let mut invalid_blocks = HashSet::new();
let mut push_result = Err(PushError::Orphan);
let mut push_chunk_result = Ok(ChunksPushResult::EmptyChunks);
for ((block, block_source), diff, mut chunks) in block_iter.by_ref() {
log::debug!("Pushing block {} from missing blocks response", block);
let blockchain2 = blockchain.clone();
let bls_cache2 = Arc::clone(&bls_cache);
if push_chunk_result.is_err() {
chunks.clear();
}
let push_results = spawn_blocking(move || {
blockchain_push::<N>(
blockchain2,
bls_cache2,
Some((block, block_source)),
diff,
chunks,
None,
)
})
.await;
if let Some(retry_block) = push_results.retry_with_diff {
let mut retry_blocks = vec![retry_block];
retry_blocks.extend(
block_iter
.map(|((block, block_source), _diff, chunks)| ((block, block_source), chunks)),
);
return MissingBlocksPushResult::NeedsDiff(
push_chunk_result,
adopted_blocks,
retry_blocks,
);
}
push_result = push_results.block_push_result.unwrap();
let block_hash = push_results.block_hash;
match push_results.push_chunks_result {
Ok(ChunksPushResult::Chunks(committed, ignored)) => match push_chunk_result {
Ok(ChunksPushResult::Chunks(ref mut old_committed, ref mut old_ignored)) => {
*old_committed += committed;
*old_ignored += ignored;
}
Ok(_) => push_chunk_result = push_results.push_chunks_result,
Err(_) => unreachable!(),
},
Err(_) => push_chunk_result = push_results.push_chunks_result,
Ok(_) => {}
}
match &push_result {
Err(e) => {
log::warn!("Failed to push missing block {}: {}", block_hash, e);
invalid_blocks.insert(block_hash);
break;
}
Ok(_) => {
adopted_blocks.push(block_hash);
}
}
}
for ((block, _), ..) in block_iter {
invalid_blocks.insert(block.hash());
}
MissingBlocksPushResult::Applied(
push_result,
push_chunk_result,
adopted_blocks,
invalid_blocks,
)
}
pub async fn push_multiple_blocks_with_chunks<N: Network>(
blockchain: BlockchainProxy,
bls_cache: Arc<Mutex<BlsCache>>,
blocks: Vec<(BlockAndSource<N>, Option<TrieDiff>, Vec<ChunkAndSource<N>>)>,
) -> MissingBlocksPushResult<N> {
push_multiple_blocks_impl(blockchain, bls_cache, blocks).await
}
pub async fn push_multiple_blocks<N: Network>(
blockchain: BlockchainProxy,
bls_cache: Arc<Mutex<BlsCache>>,
blocks: Vec<BlockAndSource<N>>,
) -> (
Result<PushResult, PushError>,
Vec<Blake2bHash>,
HashSet<Blake2bHash>,
) {
let blocks = blocks
.into_iter()
.map(|block| (block, None, vec![]))
.collect();
match push_multiple_blocks_impl::<N>(blockchain, bls_cache, blocks).await {
MissingBlocksPushResult::Applied(
push_result,
_push_chunk_result,
adopted_blocks,
invalid_blocks,
) => (push_result, adopted_blocks, invalid_blocks),
MissingBlocksPushResult::NeedsDiff(_push_chunk_result, adopted_blocks, retry_blocks) => (
Err(PushError::MissingAccountsTrieDiff),
adopted_blocks,
retry_blocks
.into_iter()
.map(|((block, _), _chunks)| block.hash())
.collect(),
),
}
}
#[cfg(feature = "full")]
pub async fn push_chunks_only<N: Network>(
blockchain: BlockchainProxy,
bls_cache: Arc<Mutex<BlsCache>>,
chunks: Vec<ChunkAndSource<N>>,
) -> (Result<ChunksPushResult, ChunksPushError>, Blake2bHash) {
let push_results =
spawn_blocking(move || blockchain_push(blockchain, bls_cache, None, None, chunks, None))
.await;
(push_results.push_chunks_result, push_results.block_hash)
}
pub struct MessageValidator<N: Network> {
network: Arc<N>,
block_source: BlockSource<N>,
}
#[cfg(feature = "full")]
impl<N: Network> PostValidationHook for MessageValidator<N> {
fn post_validation(&self, push_result: Result<&PushResult, &PushError>) {
let acceptance = match push_result {
Ok(result) => match result {
PushResult::Known | PushResult::Extended | PushResult::Rebranched => {
MsgAcceptance::Accept
}
PushResult::Forked | PushResult::Ignored => MsgAcceptance::Ignore,
},
Err(_) => {
MsgAcceptance::Reject
}
};
self.block_source.validate_block(&self.network, acceptance);
}
}
fn update_cache(block: &Block, bls_cache: &mut BlsCache) {
let Block::Macro(block) = block else {
return;
};
let Some(validators) = &block.header.validators else {
return;
};
for validator in validators.iter() {
bls_cache.cache(&validator.voting_key);
}
}
fn blockchain_push<N: Network>(
blockchain: BlockchainProxy,
bls_cache: Arc<Mutex<BlsCache>>,
block: Option<BlockAndSource<N>>,
diff: Option<TrieDiff>,
chunks: Vec<ChunkAndSource<N>>,
msg_validator: Option<MessageValidator<N>>,
) -> BlockchainPushResult<N> {
let blockchain_push_result;
if let Some((block, block_source)) = block {
let block_hash = block.hash();
update_cache(&block, &mut bls_cache.lock());
match blockchain {
#[cfg(feature = "full")]
BlockchainProxy::Full(ref blockchain) => {
match diff {
Some(diff) => {
let (chunks, peer_ids): (Vec<_>, Vec<N::PeerId>) =
chunks.into_iter().map(ChunkAndSource::into_pair).unzip();
let push_result = Blockchain::push_with_chunks(
blockchain.upgradable_read(),
block,
diff,
chunks,
&msg_validator,
);
blockchain_push_result = BlockchainPushResult::with_block_result(
push_result,
block_hash,
&peer_ids,
);
}
None => {
let blockchain = blockchain.upgradable_read();
if !blockchain.accounts_complete() {
return BlockchainPushResult::with_diff_retry(
(block, block_source),
chunks,
block_hash,
);
}
if !chunks.is_empty() {
debug!(%block, "Discarded chunks when pushing block because accounts tree is complete.");
}
let push_result =
Blockchain::push_with_hook(blockchain, block, &msg_validator)
.map(|r| (r, Ok(ChunksPushResult::EmptyChunks)));
blockchain_push_result =
BlockchainPushResult::with_block_result(push_result, block_hash, &[]);
}
}
}
BlockchainProxy::Light(ref blockchain) => {
let push_result = LightBlockchain::push(blockchain.upgradable_read(), block);
blockchain_push_result =
BlockchainPushResult::with_light_block_result(push_result, block_hash);
}
}
} else {
match blockchain {
#[cfg(feature = "full")]
BlockchainProxy::Full(ref blockchain) => {
let (chunks, peer_ids): (Vec<_>, Vec<N::PeerId>) =
chunks.into_iter().map(ChunkAndSource::into_pair).unzip();
let bc = blockchain.upgradable_read();
let block_hash = bc.head_hash();
let chunks_push_result = bc.commit_chunks(chunks, &block_hash);
blockchain_push_result = BlockchainPushResult::with_chunks_result(
chunks_push_result,
block_hash,
&peer_ids,
);
}
BlockchainProxy::Light(ref _blockchain) => {
unreachable!()
}
}
}
blockchain_push_result
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_network_mock::{MockHub, MockPeerId};
use nimiq_test_log::test;
use nimiq_test_utils::block_production::TemporaryBlockProducer;
use parking_lot::Mutex;
use super::{push_block_and_chunks, BlockAndChunksPushResult};
use crate::{sync::live::block_queue::BlockSource, BlsCache};
#[test(tokio::test)]
async fn incomplete_trie_without_diff_requests_retry() {
let producer = TemporaryBlockProducer::new();
let incomplete = TemporaryBlockProducer::new_incomplete();
let block = producer.next_block(vec![], false);
let block_hash = block.hash();
let mut hub = MockHub::new();
let network = Arc::new(hub.new_network());
let result = push_block_and_chunks(
network,
incomplete.blockchain.clone().into(),
Arc::new(Mutex::new(BlsCache::new_test())),
block,
BlockSource::requested(MockPeerId(1)),
None,
vec![],
)
.await;
match result {
BlockAndChunksPushResult::NeedsDiff(
(retry_block, block_source),
chunks,
retry_hash,
) => {
assert_eq!(retry_hash, block_hash);
assert_eq!(retry_block.hash(), block_hash);
assert!(chunks.is_empty());
assert!(
matches!(block_source, BlockSource::Requested { id } if id == MockPeerId(1))
);
}
BlockAndChunksPushResult::Applied(..) => {
panic!("diffless push into an incomplete trie must request a retry")
}
}
assert!(!incomplete.blockchain.read().contains(&block_hash, true));
}
}