Skip to main content

nimiq_consensus/sync/live/
queue.rs

1//! Implements utilities and logic for pushing blocks and state chunks during live sync.
2
3use std::{
4    collections::{HashSet, VecDeque},
5    fmt,
6    sync::Arc,
7};
8
9use futures::{future::BoxFuture, Stream};
10use nimiq_block::Block;
11#[cfg(feature = "full")]
12use nimiq_blockchain::{Blockchain, PostValidationHook};
13#[cfg(feature = "full")]
14use nimiq_blockchain_interface::AbstractBlockchain;
15use nimiq_blockchain_interface::{ChunksPushError, ChunksPushResult, PushError, PushResult};
16use nimiq_blockchain_proxy::BlockchainProxy;
17use nimiq_hash::Blake2bHash;
18use nimiq_light_blockchain::LightBlockchain;
19use nimiq_network_interface::network::{MsgAcceptance, Network};
20use nimiq_primitives::{
21    key_nibbles::KeyNibbles,
22    policy::Policy,
23    trie::{
24        trie_chunk::{TrieChunk, TrieChunkWithStart},
25        trie_diff::TrieDiff,
26    },
27};
28use nimiq_utils::spawn_blocking;
29use parking_lot::Mutex;
30
31use crate::{
32    consensus::ResolveBlockRequest,
33    sync::{
34        live::block_queue::{BlockAndSource, BlockSource},
35        sync_interface::LiveSyncEvent,
36    },
37    BlsCache,
38};
39
40/// Used during state live sync to track which peer provided which chunk,
41/// and to locate the chunk's position in the trie.
42pub struct ChunkAndSource<N: Network> {
43    pub chunk: TrieChunk,
44    pub start_key: KeyNibbles,
45    pub peer_id: N::PeerId,
46}
47
48impl<N: Network> fmt::Debug for ChunkAndSource<N> {
49    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50        f.debug_struct("ChunkAndSource")
51            .field("chunk", &self.chunk)
52            .field("start_key", &self.start_key)
53            .field("peer_id", &self.peer_id)
54            .finish()
55    }
56}
57
58pub enum BlockAndChunksPushResult<N: Network> {
59    Applied(
60        Result<PushResult, PushError>,
61        Result<ChunksPushResult, ChunksPushError>,
62        Blake2bHash,
63    ),
64    NeedsDiff(BlockAndSource<N>, Vec<ChunkAndSource<N>>, Blake2bHash),
65}
66
67pub enum MissingBlocksPushResult<N: Network> {
68    Applied(
69        Result<PushResult, PushError>,
70        Result<ChunksPushResult, ChunksPushError>,
71        Vec<Blake2bHash>,
72        HashSet<Blake2bHash>,
73    ),
74    NeedsDiff(
75        Result<ChunksPushResult, ChunksPushError>,
76        Vec<Blake2bHash>,
77        Vec<(BlockAndSource<N>, Vec<ChunkAndSource<N>>)>,
78    ),
79}
80
81impl<N: Network> ChunkAndSource<N> {
82    /// Creates a new instance given chunk, start key, and peer ID
83    pub fn new(chunk: TrieChunk, start_key: KeyNibbles, peer_id: N::PeerId) -> Self {
84        Self {
85            chunk,
86            start_key,
87            peer_id,
88        }
89    }
90
91    /// Converts this struct into a pair consisting of a `TrieChunkWithStart` and its source peer ID.
92    pub fn into_pair(self) -> (TrieChunkWithStart, N::PeerId) {
93        (
94            TrieChunkWithStart {
95                chunk: self.chunk,
96                start_key: self.start_key,
97            },
98            self.peer_id,
99        )
100    }
101}
102
103/// Trait defining the behavior of a live sync queue; manages incoming blocks, tracks peers,
104/// and coordinates the integration of blocks into the blockchain.
105pub trait LiveSyncQueue<N: Network>: Stream<Item = Self::QueueResult> + Send + Unpin {
106    type QueueResult: Send;
107    type PushResult;
108
109    /// Converts a queue result into a list of push operations to be run in order.
110    fn push_queue_result(
111        network: Arc<N>,
112        blockchain: BlockchainProxy,
113        bls_cache: Arc<Mutex<BlsCache>>,
114        result: Self::QueueResult,
115    ) -> VecDeque<BoxFuture<'static, Self::PushResult>>;
116
117    /// Called once a push operation completes, to process its outcome and emit a sync event.
118    fn process_push_result(&mut self, item: Self::PushResult) -> Option<LiveSyncEvent<N::PeerId>>;
119
120    /// Returns a list of peer IDs currently tracked by the queue.
121    fn peers(&self) -> Vec<N::PeerId>;
122
123    /// Returns the number of tracked peers.
124    fn num_peers(&self) -> usize;
125
126    /// Adds a peer to the sync queue.
127    fn add_peer(&self, peer_id: N::PeerId);
128
129    /// Adds a block stream by replacing the current block stream with a `select` of both streams.
130    fn add_block_stream<S>(&mut self, block_stream: S)
131    where
132        S: Stream<Item = BlockAndSource<N>> + Send + 'static;
133
134    /// Returns whether this queue expects blocks to include bodies.
135    fn include_body(&self) -> bool;
136
137    /// Returns `true` if the state sync is complete.
138    fn state_complete(&self) -> bool {
139        true
140    }
141
142    /// Initiates an attempt to resolve a ResolveBlockRequest.
143    fn resolve_block(&mut self, request: ResolveBlockRequest<N>);
144
145    /// The maximum number of blocks a peer can be ahead before it is considered out-of-sync.
146    fn acceptance_window_size(&self) -> u32;
147}
148
149/// Parameters for any of the syncing queues (`BlockQueue` or `StateQueue`).
150#[derive(Clone, Debug)]
151pub struct QueueConfig {
152    /// Buffer size limit
153    pub buffer_max: usize,
154
155    /// How many blocks ahead we will buffer.
156    pub window_ahead_max: u32,
157
158    /// How many blocks back into the past we tolerate without returning a peer as Outdated.
159    pub tolerate_past_max: u32,
160
161    /// Flag to indicate if blocks should carry a body.
162    pub include_body: bool,
163}
164
165impl Default for QueueConfig {
166    fn default() -> Self {
167        Self {
168            buffer_max: 10 * Policy::blocks_per_batch() as usize,
169            window_ahead_max: 2 * Policy::blocks_per_batch(),
170            tolerate_past_max: Policy::blocks_per_batch(),
171            include_body: true,
172        }
173    }
174}
175
176struct BlockchainPushResult<N: Network> {
177    block_push_result: Option<Result<PushResult, PushError>>,
178    push_chunks_result: Result<ChunksPushResult, ChunksPushError>,
179    retry_with_diff: Option<(BlockAndSource<N>, Vec<ChunkAndSource<N>>)>,
180    #[allow(dead_code)] // TODO ban peer related
181    chunk_error_peer: Option<<N as Network>::PeerId>,
182    block_hash: Blake2bHash,
183}
184
185impl<N: Network> BlockchainPushResult<N> {
186    /// Creates a push result based on the result of pushing a block without associated chunks.
187    fn with_light_block_result(
188        push_result: Result<PushResult, PushError>,
189        block_hash: Blake2bHash,
190    ) -> Self {
191        Self {
192            block_push_result: Some(push_result),
193            push_chunks_result: Ok(ChunksPushResult::EmptyChunks),
194            retry_with_diff: None,
195            block_hash,
196            chunk_error_peer: None,
197        }
198    }
199
200    /// Creates a push result based on the result of pushing a block and its associated chunks.
201    #[cfg(feature = "full")]
202    fn with_block_result(
203        push_result: Result<(PushResult, Result<ChunksPushResult, ChunksPushError>), PushError>,
204        block_hash: Blake2bHash,
205        peer_ids: &[N::PeerId],
206    ) -> Self {
207        let (block_push_result, push_chunks_result, chunk_error_peer) = match push_result {
208            Ok((block_push_result, Err(chunk_error))) => {
209                let peer_id = peer_ids[chunk_error.chunk_index()];
210                (Ok(block_push_result), Err(chunk_error), Some(peer_id))
211            }
212            Ok((block_push_result, push_chunks_result)) => {
213                (Ok(block_push_result), push_chunks_result, None)
214            }
215            Err(push_error) => (Err(push_error), Ok(ChunksPushResult::EmptyChunks), None),
216        };
217
218        Self {
219            block_push_result: Some(block_push_result),
220            push_chunks_result,
221            retry_with_diff: None,
222            block_hash,
223            chunk_error_peer,
224        }
225    }
226
227    /// Creates a push result that only involves chunk processing.
228    #[cfg(feature = "full")]
229    fn with_chunks_result(
230        push_chunks_result: Result<ChunksPushResult, ChunksPushError>,
231        block_hash: Blake2bHash,
232        peer_ids: &[N::PeerId],
233    ) -> Self {
234        let peer_id = if let Err(ref chunk_error) = push_chunks_result {
235            let peer_id = peer_ids[chunk_error.chunk_index()];
236            Some(peer_id)
237        } else {
238            None
239        };
240
241        Self {
242            block_push_result: None,
243            push_chunks_result,
244            retry_with_diff: None,
245            block_hash,
246            chunk_error_peer: peer_id,
247        }
248    }
249
250    #[cfg(feature = "full")]
251    fn with_diff_retry(
252        block: BlockAndSource<N>,
253        chunks: Vec<ChunkAndSource<N>>,
254        block_hash: Blake2bHash,
255    ) -> Self {
256        Self {
257            block_push_result: None,
258            push_chunks_result: Ok(ChunksPushResult::EmptyChunks),
259            retry_with_diff: Some((block, chunks)),
260            block_hash,
261            chunk_error_peer: None,
262        }
263    }
264}
265
266/// Pushes a single block and respective chunks into the blockchain and validates the message.
267#[cfg(feature = "full")]
268pub async fn push_block_and_chunks<N: Network>(
269    network: Arc<N>,
270    blockchain: BlockchainProxy,
271    bls_cache: Arc<Mutex<BlsCache>>,
272    block: Block,
273    block_source: BlockSource<N>,
274    diff: Option<TrieDiff>,
275    chunks: Vec<ChunkAndSource<N>>,
276) -> BlockAndChunksPushResult<N> {
277    let push_results = spawn_blocking(move || {
278        blockchain_push(
279            blockchain,
280            bls_cache,
281            Some((block, block_source.clone())),
282            diff,
283            chunks,
284            Some(MessageValidator {
285                network,
286                block_source,
287            }),
288        )
289    })
290    .await;
291
292    // TODO Ban peer depending on type of chunk error?
293    if let Some((block, chunks)) = push_results.retry_with_diff {
294        BlockAndChunksPushResult::NeedsDiff(block, chunks, push_results.block_hash)
295    } else {
296        BlockAndChunksPushResult::Applied(
297            push_results.block_push_result.unwrap(),
298            push_results.push_chunks_result,
299            push_results.block_hash,
300        )
301    }
302}
303
304/// Pushes a single block into the blockchain and validates the message.
305pub async fn push_block_only<N: Network>(
306    network: Arc<N>,
307    blockchain: BlockchainProxy,
308    bls_cache: Arc<Mutex<BlsCache>>,
309    block: Block,
310    block_source: BlockSource<N>,
311) -> (Result<PushResult, PushError>, Blake2bHash) {
312    let push_results = spawn_blocking(move || {
313        blockchain_push::<N>(
314            blockchain,
315            bls_cache,
316            Some((block, block_source.clone())),
317            None,
318            vec![],
319            Some(MessageValidator {
320                network,
321                block_source,
322            }),
323        )
324    })
325    .await;
326
327    match push_results.retry_with_diff {
328        Some(_) => (
329            Err(PushError::MissingAccountsTrieDiff),
330            push_results.block_hash,
331        ),
332        None => (
333            push_results.block_push_result.unwrap(),
334            push_results.block_hash,
335        ),
336    }
337}
338
339/// Pushes a sequence of blocks to the blockchain.
340/// This case is different from pushing single blocks in a for loop,
341/// because an invalid block automatically invalidates the remainder of the sequence.
342pub async fn push_multiple_blocks_impl<N: Network>(
343    blockchain: BlockchainProxy,
344    bls_cache: Arc<Mutex<BlsCache>>,
345    blocks: Vec<(BlockAndSource<N>, Option<TrieDiff>, Vec<ChunkAndSource<N>>)>,
346) -> MissingBlocksPushResult<N> {
347    let mut block_iter = blocks.into_iter();
348    // Hashes of adopted blocks
349    let mut adopted_blocks = Vec::new();
350    // Hashes of invalid blocks
351    let mut invalid_blocks = HashSet::new();
352    // Initialize push_result to some random value.
353    // It is always overwritten in the first loop iteration.
354    let mut push_result = Err(PushError::Orphan);
355    let mut push_chunk_result = Ok(ChunksPushResult::EmptyChunks);
356    // Try to push blocks, until we encounter an invalid block.
357    for ((block, block_source), diff, mut chunks) in block_iter.by_ref() {
358        log::debug!("Pushing block {} from missing blocks response", block);
359
360        let blockchain2 = blockchain.clone();
361        let bls_cache2 = Arc::clone(&bls_cache);
362
363        // If a previous chunk failed, we should discard all subsequent chunks.
364        if push_chunk_result.is_err() {
365            chunks.clear();
366        }
367        let push_results = spawn_blocking(move || {
368            blockchain_push::<N>(
369                blockchain2,
370                bls_cache2,
371                Some((block, block_source)),
372                diff,
373                chunks,
374                None,
375            )
376        })
377        .await;
378
379        if let Some(retry_block) = push_results.retry_with_diff {
380            let mut retry_blocks = vec![retry_block];
381            retry_blocks.extend(
382                block_iter
383                    .map(|((block, block_source), _diff, chunks)| ((block, block_source), chunks)),
384            );
385
386            return MissingBlocksPushResult::NeedsDiff(
387                push_chunk_result,
388                adopted_blocks,
389                retry_blocks,
390            );
391        }
392
393        push_result = push_results.block_push_result.unwrap();
394        let block_hash = push_results.block_hash;
395
396        // The chunk result should give precedence to an error. Otherwise, if least one chunk was pushed,
397        // the result should reflect that.
398        // Errors cannot be overwritten because we will discard the subsequent chunks.
399        match push_results.push_chunks_result {
400            Ok(ChunksPushResult::Chunks(committed, ignored)) => match push_chunk_result {
401                Ok(ChunksPushResult::Chunks(ref mut old_committed, ref mut old_ignored)) => {
402                    *old_committed += committed;
403                    *old_ignored += ignored;
404                }
405                Ok(_) => push_chunk_result = push_results.push_chunks_result,
406                Err(_) => unreachable!(),
407            },
408            Err(_) => push_chunk_result = push_results.push_chunks_result,
409            Ok(_) => {}
410        }
411
412        match &push_result {
413            Err(e) => {
414                log::warn!("Failed to push missing block {}: {}", block_hash, e);
415                invalid_blocks.insert(block_hash);
416                break;
417            }
418            Ok(_) => {
419                adopted_blocks.push(block_hash);
420            }
421        }
422    }
423
424    // TODO Ban peer depending on type of chunk error?
425
426    // If there are remaining blocks in the iterator, those are invalid.
427    for ((block, _), ..) in block_iter {
428        invalid_blocks.insert(block.hash());
429    }
430    MissingBlocksPushResult::Applied(
431        push_result,
432        push_chunk_result,
433        adopted_blocks,
434        invalid_blocks,
435    )
436}
437
438/// Pushes a sequence of blocks along with their associated state diffs and chunks into the blockchain.
439pub async fn push_multiple_blocks_with_chunks<N: Network>(
440    blockchain: BlockchainProxy,
441    bls_cache: Arc<Mutex<BlsCache>>,
442    blocks: Vec<(BlockAndSource<N>, Option<TrieDiff>, Vec<ChunkAndSource<N>>)>,
443) -> MissingBlocksPushResult<N> {
444    push_multiple_blocks_impl(blockchain, bls_cache, blocks).await
445}
446
447/// Pushes a sequence of blocks to the blockchain.
448/// This case is different from pushing single blocks in a for loop,
449/// because an invalid block automatically invalidates the remainder of the sequence.
450pub async fn push_multiple_blocks<N: Network>(
451    blockchain: BlockchainProxy,
452    bls_cache: Arc<Mutex<BlsCache>>,
453    blocks: Vec<BlockAndSource<N>>,
454) -> (
455    Result<PushResult, PushError>,
456    Vec<Blake2bHash>,
457    HashSet<Blake2bHash>,
458) {
459    let blocks = blocks
460        .into_iter()
461        .map(|block| (block, None, vec![]))
462        .collect();
463    match push_multiple_blocks_impl::<N>(blockchain, bls_cache, blocks).await {
464        MissingBlocksPushResult::Applied(
465            push_result,
466            _push_chunk_result,
467            adopted_blocks,
468            invalid_blocks,
469        ) => (push_result, adopted_blocks, invalid_blocks),
470        MissingBlocksPushResult::NeedsDiff(_push_chunk_result, adopted_blocks, retry_blocks) => (
471            Err(PushError::MissingAccountsTrieDiff),
472            adopted_blocks,
473            retry_blocks
474                .into_iter()
475                .map(|((block, _), _chunks)| block.hash())
476                .collect(),
477        ),
478    }
479}
480
481/// Pushes the chunks to the current blockchain state.
482#[cfg(feature = "full")]
483pub async fn push_chunks_only<N: Network>(
484    blockchain: BlockchainProxy,
485    bls_cache: Arc<Mutex<BlsCache>>,
486    chunks: Vec<ChunkAndSource<N>>,
487) -> (Result<ChunksPushResult, ChunksPushError>, Blake2bHash) {
488    let push_results =
489        spawn_blocking(move || blockchain_push(blockchain, bls_cache, None, None, chunks, None))
490            .await;
491
492    // TODO Ban peer depending on type of chunk error?
493
494    (push_results.push_chunks_result, push_results.block_hash)
495}
496
497pub struct MessageValidator<N: Network> {
498    network: Arc<N>,
499    /// Whether annouced or requested
500    block_source: BlockSource<N>,
501}
502
503#[cfg(feature = "full")]
504impl<N: Network> PostValidationHook for MessageValidator<N> {
505    /// Called after a block has been validated and pushed to the blockchain.
506    /// Communicates the acceptance result to the peer that sent the block.
507    fn post_validation(&self, push_result: Result<&PushResult, &PushError>) {
508        let acceptance = match push_result {
509            Ok(result) => match result {
510                PushResult::Known | PushResult::Extended | PushResult::Rebranched => {
511                    MsgAcceptance::Accept
512                }
513                PushResult::Forked | PushResult::Ignored => MsgAcceptance::Ignore,
514            },
515            Err(_) => {
516                // TODO Ban peer
517                MsgAcceptance::Reject
518            }
519        };
520
521        self.block_source.validate_block(&self.network, acceptance);
522    }
523}
524
525/// Caches the BLS public keys from the given macro block’s validator list.
526fn update_cache(block: &Block, bls_cache: &mut BlsCache) {
527    let Block::Macro(block) = block else {
528        return;
529    };
530    let Some(validators) = &block.header.validators else {
531        return;
532    };
533    for validator in validators.iter() {
534        bls_cache.cache(&validator.voting_key);
535    }
536}
537
538/// Pushes the a single block and the respective chunks into the blockchain. If a light
539/// blockchain was supplied, no chunks are committed.
540/// The return value consists of the result of pushing the block, the error of pushing
541/// the chunks and the block hash. If no block or chunks are supplied no change will
542/// happen to the blockchain and the return will look like `(None, None, current_head_hash)`.
543/// Note: this function doesn't prevent a new block from being committed before applying the chunks.
544fn blockchain_push<N: Network>(
545    blockchain: BlockchainProxy,
546    bls_cache: Arc<Mutex<BlsCache>>,
547    block: Option<BlockAndSource<N>>,
548    diff: Option<TrieDiff>,
549    chunks: Vec<ChunkAndSource<N>>,
550    msg_validator: Option<MessageValidator<N>>,
551) -> BlockchainPushResult<N> {
552    // Push the block to the blockchain.
553    let blockchain_push_result;
554    if let Some((block, block_source)) = block {
555        let block_hash = block.hash();
556        update_cache(&block, &mut bls_cache.lock());
557        match blockchain {
558            #[cfg(feature = "full")]
559            BlockchainProxy::Full(ref blockchain) => {
560                // We push the block and if it fails we return immediately, without committing chunks.
561                match diff {
562                    Some(diff) => {
563                        let (chunks, peer_ids): (Vec<_>, Vec<N::PeerId>) =
564                            chunks.into_iter().map(ChunkAndSource::into_pair).unzip();
565                        let push_result = Blockchain::push_with_chunks(
566                            blockchain.upgradable_read(),
567                            block,
568                            diff,
569                            chunks,
570                            &msg_validator,
571                        );
572                        blockchain_push_result = BlockchainPushResult::with_block_result(
573                            push_result,
574                            block_hash,
575                            &peer_ids,
576                        );
577                    }
578                    None => {
579                        let blockchain = blockchain.upgradable_read();
580                        if !blockchain.accounts_complete() {
581                            return BlockchainPushResult::with_diff_retry(
582                                (block, block_source),
583                                chunks,
584                                block_hash,
585                            );
586                        }
587
588                        if !chunks.is_empty() {
589                            debug!(%block, "Discarded chunks when pushing block because accounts tree is complete.");
590                        }
591
592                        let push_result =
593                            Blockchain::push_with_hook(blockchain, block, &msg_validator)
594                                .map(|r| (r, Ok(ChunksPushResult::EmptyChunks)));
595                        blockchain_push_result =
596                            BlockchainPushResult::with_block_result(push_result, block_hash, &[]);
597                    }
598                }
599            }
600            BlockchainProxy::Light(ref blockchain) => {
601                let push_result = LightBlockchain::push(blockchain.upgradable_read(), block);
602
603                blockchain_push_result =
604                    BlockchainPushResult::with_light_block_result(push_result, block_hash);
605            }
606        }
607    } else {
608        match blockchain {
609            #[cfg(feature = "full")]
610            BlockchainProxy::Full(ref blockchain) => {
611                let (chunks, peer_ids): (Vec<_>, Vec<N::PeerId>) =
612                    chunks.into_iter().map(ChunkAndSource::into_pair).unzip();
613                let bc = blockchain.upgradable_read();
614                let block_hash = bc.head_hash();
615                // We push the chunks.
616                let chunks_push_result = bc.commit_chunks(chunks, &block_hash);
617                blockchain_push_result = BlockchainPushResult::with_chunks_result(
618                    chunks_push_result,
619                    block_hash,
620                    &peer_ids,
621                );
622            }
623            BlockchainProxy::Light(ref _blockchain) => {
624                // We do not push chunks into a light blockchain.
625                unreachable!()
626            }
627        }
628    }
629
630    blockchain_push_result
631}
632
633#[cfg(test)]
634mod tests {
635    use std::sync::Arc;
636
637    use nimiq_blockchain_interface::AbstractBlockchain;
638    use nimiq_network_mock::{MockHub, MockPeerId};
639    use nimiq_test_log::test;
640    use nimiq_test_utils::block_production::TemporaryBlockProducer;
641    use parking_lot::Mutex;
642
643    use super::{push_block_and_chunks, BlockAndChunksPushResult};
644    use crate::{sync::live::block_queue::BlockSource, BlsCache};
645
646    #[test(tokio::test)]
647    async fn incomplete_trie_without_diff_requests_retry() {
648        let producer = TemporaryBlockProducer::new();
649        let incomplete = TemporaryBlockProducer::new_incomplete();
650        let block = producer.next_block(vec![], false);
651        let block_hash = block.hash();
652
653        let mut hub = MockHub::new();
654        let network = Arc::new(hub.new_network());
655
656        let result = push_block_and_chunks(
657            network,
658            incomplete.blockchain.clone().into(),
659            Arc::new(Mutex::new(BlsCache::new_test())),
660            block,
661            BlockSource::requested(MockPeerId(1)),
662            None,
663            vec![],
664        )
665        .await;
666
667        match result {
668            BlockAndChunksPushResult::NeedsDiff(
669                (retry_block, block_source),
670                chunks,
671                retry_hash,
672            ) => {
673                assert_eq!(retry_hash, block_hash);
674                assert_eq!(retry_block.hash(), block_hash);
675                assert!(chunks.is_empty());
676                assert!(
677                    matches!(block_source, BlockSource::Requested { id } if id == MockPeerId(1))
678                );
679            }
680            BlockAndChunksPushResult::Applied(..) => {
681                panic!("diffless push into an incomplete trie must request a retry")
682            }
683        }
684
685        assert!(!incomplete.blockchain.read().contains(&block_hash, true));
686    }
687}