1use 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
40pub 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 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 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
103pub trait LiveSyncQueue<N: Network>: Stream<Item = Self::QueueResult> + Send + Unpin {
106 type QueueResult: Send;
107 type PushResult;
108
109 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 fn process_push_result(&mut self, item: Self::PushResult) -> Option<LiveSyncEvent<N::PeerId>>;
119
120 fn peers(&self) -> Vec<N::PeerId>;
122
123 fn num_peers(&self) -> usize;
125
126 fn add_peer(&self, peer_id: N::PeerId);
128
129 fn add_block_stream<S>(&mut self, block_stream: S)
131 where
132 S: Stream<Item = BlockAndSource<N>> + Send + 'static;
133
134 fn include_body(&self) -> bool;
136
137 fn state_complete(&self) -> bool {
139 true
140 }
141
142 fn resolve_block(&mut self, request: ResolveBlockRequest<N>);
144
145 fn acceptance_window_size(&self) -> u32;
147}
148
149#[derive(Clone, Debug)]
151pub struct QueueConfig {
152 pub buffer_max: usize,
154
155 pub window_ahead_max: u32,
157
158 pub tolerate_past_max: u32,
160
161 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)] chunk_error_peer: Option<<N as Network>::PeerId>,
182 block_hash: Blake2bHash,
183}
184
185impl<N: Network> BlockchainPushResult<N> {
186 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 #[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 #[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#[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 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
304pub 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
339pub 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 let mut adopted_blocks = Vec::new();
350 let mut invalid_blocks = HashSet::new();
352 let mut push_result = Err(PushError::Orphan);
355 let mut push_chunk_result = Ok(ChunksPushResult::EmptyChunks);
356 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 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 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 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
438pub 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
447pub 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#[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 (push_results.push_chunks_result, push_results.block_hash)
495}
496
497pub struct MessageValidator<N: Network> {
498 network: Arc<N>,
499 block_source: BlockSource<N>,
501}
502
503#[cfg(feature = "full")]
504impl<N: Network> PostValidationHook for MessageValidator<N> {
505 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 MsgAcceptance::Reject
518 }
519 };
520
521 self.block_source.validate_block(&self.network, acceptance);
522 }
523}
524
525fn 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
538fn 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 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 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 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 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}