nimiq-consensus 2.2.0

Consensus logic of Nimiq's Albatross implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! Implements utilities and logic for pushing blocks and state chunks during live sync.

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()
    }
}

/// Used during state live sync to track which peer provided which chunk,
/// and to locate the chunk's position in the trie.
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> {
    /// Creates a new instance given chunk, start key, and peer ID
    pub fn new(chunk: TrieChunk, start_key: KeyNibbles, peer_id: N::PeerId) -> Self {
        Self {
            chunk,
            start_key,
            peer_id,
        }
    }

    /// Converts this struct into a pair consisting of a `TrieChunkWithStart` and its source peer ID.
    pub fn into_pair(self) -> (TrieChunkWithStart, N::PeerId) {
        (
            TrieChunkWithStart {
                chunk: self.chunk,
                start_key: self.start_key,
            },
            self.peer_id,
        )
    }
}

/// Trait defining the behavior of a live sync queue; manages incoming blocks, tracks peers,
/// and coordinates the integration of blocks into the blockchain.
pub trait LiveSyncQueue<N: Network>: Stream<Item = Self::QueueResult> + Send + Unpin {
    type QueueResult: Send;
    type PushResult;

    /// Converts a queue result into a list of push operations to be run in order.
    fn push_queue_result(
        network: Arc<N>,
        blockchain: BlockchainProxy,
        bls_cache: Arc<Mutex<BlsCache>>,
        result: Self::QueueResult,
    ) -> VecDeque<BoxFuture<'static, Self::PushResult>>;

    /// Called once a push operation completes, to process its outcome and emit a sync event.
    fn process_push_result(&mut self, item: Self::PushResult) -> Option<LiveSyncEvent<N::PeerId>>;

    /// Returns a list of peer IDs currently tracked by the queue.
    fn peers(&self) -> Vec<N::PeerId>;

    /// Returns the number of tracked peers.
    fn num_peers(&self) -> usize;

    /// Adds a peer to the sync queue.
    fn add_peer(&self, peer_id: N::PeerId);

    /// Adds a block stream by replacing the current block stream with a `select` of both streams.
    fn add_block_stream<S>(&mut self, block_stream: S)
    where
        S: Stream<Item = BlockAndSource<N>> + Send + 'static;

    /// Returns whether this queue expects blocks to include bodies.
    fn include_body(&self) -> bool;

    /// Returns `true` if the state sync is complete.
    fn state_complete(&self) -> bool {
        true
    }

    /// Initiates an attempt to resolve a ResolveBlockRequest.
    fn resolve_block(&mut self, request: ResolveBlockRequest<N>);

    /// The maximum number of blocks a peer can be ahead before it is considered out-of-sync.
    fn acceptance_window_size(&self) -> u32;
}

/// Parameters for any of the syncing queues (`BlockQueue` or `StateQueue`).
#[derive(Clone, Debug)]
pub struct QueueConfig {
    /// Buffer size limit
    pub buffer_max: usize,

    /// How many blocks ahead we will buffer.
    pub window_ahead_max: u32,

    /// How many blocks back into the past we tolerate without returning a peer as Outdated.
    pub tolerate_past_max: u32,

    /// Flag to indicate if blocks should carry a body.
    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)] // TODO ban peer related
    chunk_error_peer: Option<<N as Network>::PeerId>,
    block_hash: Blake2bHash,
}

impl<N: Network> BlockchainPushResult<N> {
    /// Creates a push result based on the result of pushing a block without associated chunks.
    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,
        }
    }

    /// Creates a push result based on the result of pushing a block and its associated chunks.
    #[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,
        }
    }

    /// Creates a push result that only involves chunk processing.
    #[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,
        }
    }
}

/// Pushes a single block and respective chunks into the blockchain and validates the message.
#[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;

    // TODO Ban peer depending on type of chunk error?
    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,
        )
    }
}

/// Pushes a single block into the blockchain and validates the message.
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,
        ),
    }
}

/// Pushes a sequence of blocks to the blockchain.
/// This case is different from pushing single blocks in a for loop,
/// because an invalid block automatically invalidates the remainder of the sequence.
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();
    // Hashes of adopted blocks
    let mut adopted_blocks = Vec::new();
    // Hashes of invalid blocks
    let mut invalid_blocks = HashSet::new();
    // Initialize push_result to some random value.
    // It is always overwritten in the first loop iteration.
    let mut push_result = Err(PushError::Orphan);
    let mut push_chunk_result = Ok(ChunksPushResult::EmptyChunks);
    // Try to push blocks, until we encounter an invalid block.
    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 a previous chunk failed, we should discard all subsequent chunks.
        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;

        // The chunk result should give precedence to an error. Otherwise, if least one chunk was pushed,
        // the result should reflect that.
        // Errors cannot be overwritten because we will discard the subsequent chunks.
        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);
            }
        }
    }

    // TODO Ban peer depending on type of chunk error?

    // If there are remaining blocks in the iterator, those are invalid.
    for ((block, _), ..) in block_iter {
        invalid_blocks.insert(block.hash());
    }
    MissingBlocksPushResult::Applied(
        push_result,
        push_chunk_result,
        adopted_blocks,
        invalid_blocks,
    )
}

/// Pushes a sequence of blocks along with their associated state diffs and chunks into the blockchain.
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
}

/// Pushes a sequence of blocks to the blockchain.
/// This case is different from pushing single blocks in a for loop,
/// because an invalid block automatically invalidates the remainder of the sequence.
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(),
        ),
    }
}

/// Pushes the chunks to the current blockchain state.
#[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;

    // TODO Ban peer depending on type of chunk error?

    (push_results.push_chunks_result, push_results.block_hash)
}

pub struct MessageValidator<N: Network> {
    network: Arc<N>,
    /// Whether annouced or requested
    block_source: BlockSource<N>,
}

#[cfg(feature = "full")]
impl<N: Network> PostValidationHook for MessageValidator<N> {
    /// Called after a block has been validated and pushed to the blockchain.
    /// Communicates the acceptance result to the peer that sent the block.
    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(_) => {
                // TODO Ban peer
                MsgAcceptance::Reject
            }
        };

        self.block_source.validate_block(&self.network, acceptance);
    }
}

/// Caches the BLS public keys from the given macro block’s validator list.
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);
    }
}

/// Pushes the a single block and the respective chunks into the blockchain. If a light
/// blockchain was supplied, no chunks are committed.
/// The return value consists of the result of pushing the block, the error of pushing
/// the chunks and the block hash. If no block or chunks are supplied no change will
/// happen to the blockchain and the return will look like `(None, None, current_head_hash)`.
/// Note: this function doesn't prevent a new block from being committed before applying the chunks.
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> {
    // Push the block to the blockchain.
    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) => {
                // We push the block and if it fails we return immediately, without committing chunks.
                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();
                // We push the chunks.
                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) => {
                // We do not push chunks into a light 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));
    }
}