1use std::{
6 collections::{BTreeSet, HashMap, HashSet},
7 mem,
8 path::{Path, PathBuf},
9 sync::Arc,
10};
11
12use indexmap::IndexMap;
13use tokio::sync::watch;
14use zebra_chain::{
15 block::{self, Block, Hash, Height},
16 parameters::Network,
17 sprout::{self},
18 transparent,
19};
20
21use crate::{
22 constants::{
23 MAX_BLOCK_REORG_HEIGHT, MAX_INVALIDATED_BLOCKS, MAX_NON_FINALIZED_CHAIN_FORKS,
24 MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS, MAX_NON_FINALIZED_INDEX_ENTRIES,
25 MAX_NON_FINALIZED_INDEX_ENTRIES_TEST_NETWORKS, MIN_NON_FINALIZED_BLOCKS_OVER_INDEX_LIMIT,
26 },
27 error::ReconsiderError,
28 request::{ContextuallyVerifiedBlock, FinalizableBlock},
29 service::{
30 check,
31 finalized_state::{calculate_deferred_pool_balance_change, ZebraDb},
32 InvalidateError,
33 },
34 SemanticallyVerifiedBlock, ValidateContextError, WatchReceiver,
35};
36
37mod backup;
38mod chain;
39
40#[cfg(test)]
41pub(crate) use backup::MIN_DURATION_BETWEEN_BACKUP_UPDATES;
42
43#[cfg(test)]
44mod tests;
45
46pub(crate) use chain::{Chain, SpendingTransactionId};
47
48pub struct NonFinalizedState {
56 chain_set: BTreeSet<Arc<Chain>>,
64
65 invalidated_blocks: IndexMap<Height, Arc<Vec<ContextuallyVerifiedBlock>>>,
68
69 pub(crate) precomputed_trees: Option<crate::service::precomputed_trees::PrecomputedTrees>,
73
74 prepared_chain: watch::Sender<Option<Arc<Chain>>>,
81
82 pub network: Network,
86
87 max_index_entries: Option<usize>,
89
90 evicted_block_hashes: Vec<block::Hash>,
93
94 should_count_metrics: bool,
103
104 #[cfg(feature = "progress-bar")]
106 chain_count_bar: Option<howudoin::Tx>,
107
108 #[cfg(feature = "progress-bar")]
113 chain_fork_length_bars: Vec<howudoin::Tx>,
114}
115
116impl std::fmt::Debug for NonFinalizedState {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 let mut f = f.debug_struct("NonFinalizedState");
119
120 f.field("chain_set", &self.chain_set)
121 .field("network", &self.network);
122
123 f.field("should_count_metrics", &self.should_count_metrics);
124
125 f.finish()
126 }
127}
128
129impl Clone for NonFinalizedState {
130 fn clone(&self) -> Self {
131 Self {
132 chain_set: self.chain_set.clone(),
133 network: self.network.clone(),
134 max_index_entries: self.max_index_entries,
135 evicted_block_hashes: Vec::new(),
137 invalidated_blocks: self.invalidated_blocks.clone(),
138 precomputed_trees: None,
139 prepared_chain: self.prepared_chain.clone(),
140 should_count_metrics: self.should_count_metrics,
141 #[cfg(feature = "progress-bar")]
143 chain_count_bar: None,
144 #[cfg(feature = "progress-bar")]
145 chain_fork_length_bars: Vec::new(),
146 }
147 }
148}
149
150impl NonFinalizedState {
151 pub fn new(network: &Network) -> NonFinalizedState {
153 NonFinalizedState {
154 chain_set: Default::default(),
155 network: network.clone(),
156 max_index_entries: Some(if network.is_a_test_network() {
157 MAX_NON_FINALIZED_INDEX_ENTRIES_TEST_NETWORKS
158 } else {
159 MAX_NON_FINALIZED_INDEX_ENTRIES
160 }),
161 evicted_block_hashes: Vec::new(),
162 invalidated_blocks: Default::default(),
163 precomputed_trees: None,
164 prepared_chain: watch::Sender::new(None),
165 should_count_metrics: true,
166 #[cfg(feature = "progress-bar")]
167 chain_count_bar: None,
168 #[cfg(feature = "progress-bar")]
169 chain_fork_length_bars: Vec::new(),
170 }
171 }
172
173 pub(crate) fn write_to_backup(&self, backup_dir_path: &Path) {
181 let backup_blocks: HashMap<block::Hash, PathBuf> =
182 backup::list_backup_dir_entries(backup_dir_path).collect();
183 backup::update_non_finalized_state_backup(backup_dir_path, self, backup_blocks);
184 }
185
186 pub async fn with_backup(
196 self,
197 backup_dir_path: Option<PathBuf>,
198 finalized_state: &ZebraDb,
199 should_restore_backup: bool,
200 skip_backup_task: bool,
201 ) -> (
202 Self,
203 watch::Sender<NonFinalizedState>,
204 WatchReceiver<NonFinalizedState>,
205 ) {
206 let with_watch_channel = |non_finalized_state: NonFinalizedState| {
207 let (sender, receiver) = watch::channel(non_finalized_state.clone());
208 (non_finalized_state, sender, WatchReceiver::new(receiver))
209 };
210
211 let Some(backup_dir_path) = backup_dir_path else {
212 return with_watch_channel(self);
213 };
214
215 if !should_restore_backup {
216 tracing::info!(
217 ?backup_dir_path,
218 spawning_backup_task = !skip_backup_task,
219 "not restoring non-finalized blocks from backup, any backed up blocks that are \
220 missing from the non-finalized state will be deleted"
221 );
222 } else if skip_backup_task {
223 tracing::info!(
224 ?backup_dir_path,
225 "restoring non-finalized blocks from backup (sync write mode, backup task skipped)"
226 );
227 } else {
228 tracing::info!(
229 ?backup_dir_path,
230 "restoring non-finalized blocks from backup and spawning backup task"
231 );
232 }
233
234 let non_finalized_state = {
235 let backup_dir_path = backup_dir_path.clone();
236 let finalized_state = finalized_state.clone();
237 tokio::task::spawn_blocking(move || {
238 std::fs::create_dir_all(&backup_dir_path)
240 .expect("failed to create non-finalized state backup directory");
241
242 if should_restore_backup {
243 let mut restored =
244 backup::restore_backup(self, &backup_dir_path, &finalized_state);
245 restored.take_evicted_block_hashes();
249 restored
250 } else {
251 self
252 }
253 })
254 .await
255 .expect("failed to join blocking task")
256 };
257
258 let (non_finalized_state, sender, receiver) = with_watch_channel(non_finalized_state);
259
260 if !skip_backup_task {
261 tokio::spawn(backup::run_backup_task(receiver.clone(), backup_dir_path));
262 }
263
264 if !non_finalized_state.is_chain_set_empty() {
265 let num_blocks_restored = non_finalized_state
266 .best_chain()
267 .expect("must have best chain if chain set is not empty")
268 .len();
269
270 tracing::info!(
271 ?num_blocks_restored,
272 "restored blocks from non-finalized backup cache"
273 );
274 } else if should_restore_backup {
275 tracing::info!("no blocks were restored from the non-finalized backup cache");
276 }
277
278 (non_finalized_state, sender, receiver)
279 }
280
281 #[cfg(any(test, feature = "proptest-impl"))]
292 #[allow(dead_code)]
293 pub fn eq_internal_state(&self, other: &NonFinalizedState) -> bool {
294 self.chain_set.len() == other.chain_set.len()
298 && self
299 .chain_set
300 .iter()
301 .zip(other.chain_set.iter())
302 .all(|(self_chain, other_chain)| self_chain.eq_internal_state(other_chain))
303 && self.network == other.network
304 }
305
306 pub fn chain_iter(&self) -> impl Iterator<Item = &Arc<Chain>> {
310 self.chain_set.iter().rev()
311 }
312
313 fn insert_with<F>(&mut self, chain: Arc<Chain>, chain_filter: F)
316 where
317 F: FnOnce(&mut BTreeSet<Arc<Chain>>),
318 {
319 self.chain_set.insert(chain.clone());
320
321 chain_filter(&mut self.chain_set);
322
323 let max_forks = if self.network.is_a_test_network() {
324 MAX_NON_FINALIZED_CHAIN_FORKS_TEST_NETWORKS
325 } else {
326 MAX_NON_FINALIZED_CHAIN_FORKS
327 };
328 loop {
329 let index_entries = self.index_entry_count();
330 let over_index_limit = self
331 .max_index_entries
332 .is_some_and(|max_index_entries| index_entries > max_index_entries);
333 if self.chain_set.len() <= max_forks && !over_index_limit {
334 break;
335 }
336
337 let best_chain = self.chain_set.last().cloned();
340 let Some(evicted) = self
341 .chain_set
342 .iter()
343 .filter(|c| **c != chain && Some(*c) != best_chain.as_ref())
344 .min_by(|a, b| {
345 let received_time = |c: &Chain| c.tip_block().map(|tip| tip.received_time);
346 a.partial_cumulative_work
347 .cmp(&b.partial_cumulative_work)
348 .then_with(|| received_time(a).cmp(&received_time(b)))
349 .then_with(|| a.cmp(b))
350 })
351 .cloned()
352 else {
353 break;
356 };
357
358 self.chain_set.remove(&evicted);
359 if self.should_count_metrics() {
360 metrics::counter!("state.memory.fork.evicted.count").increment(1);
361 }
362
363 let evicted_blocks = evicted
366 .blocks
367 .values()
368 .rev()
369 .map(|block| block.hash)
370 .take_while(|hash| !self.any_chain_contains(hash))
371 .collect::<Vec<_>>();
372 self.evicted_block_hashes.extend(evicted_blocks);
373
374 tracing::warn!(
375 tip = ?evicted.non_finalized_tip_hash(),
376 height = ?evicted.non_finalized_tip_height(),
377 max_forks,
378 index_entries,
379 max_index_entries = ?self.max_index_entries,
380 "the fork limit evicted a chain: if the node stops advancing, restart it"
381 );
382 }
383
384 self.update_metrics_bars();
385 }
386
387 #[cfg(test)]
389 pub(crate) fn set_max_index_entries(&mut self, max_index_entries: Option<usize>) {
390 self.max_index_entries = max_index_entries;
391 }
392
393 pub(crate) fn take_evicted_block_hashes(&mut self) -> Vec<block::Hash> {
399 let mut evicted = mem::take(&mut self.evicted_block_hashes);
400 evicted.retain(|hash| !self.any_chain_contains(hash));
403 evicted
404 }
405
406 fn insert(&mut self, chain: Arc<Chain>) {
408 self.insert_with(chain, |_ignored_chain| { })
409 }
410
411 pub(crate) fn should_finalize_root(&self) -> bool {
415 let Some(best_chain_len) = self.best_chain_len() else {
416 return false;
417 };
418
419 best_chain_len > MAX_BLOCK_REORG_HEIGHT
420 || (best_chain_len > MIN_NON_FINALIZED_BLOCKS_OVER_INDEX_LIMIT
421 && self
422 .max_index_entries
423 .is_some_and(|max_index_entries| self.index_entry_count() > max_index_entries))
424 }
425
426 pub fn finalize(&mut self) -> FinalizableBlock {
429 #[allow(clippy::mutable_key_type)]
433 let chains = mem::take(&mut self.chain_set);
434 let mut chains = chains.into_iter();
435
436 let mut best_chain = chains.next_back().expect("there's at least one chain");
438
439 let mut_best_chain = Arc::make_mut(&mut best_chain);
441
442 let side_chains = chains;
444
445 let (best_chain_root, root_treestate) = mut_best_chain.pop_root();
448
449 let shared_best_chain = best_chain.clone();
451
452 if !best_chain.is_empty() {
454 self.insert(best_chain);
455 }
456
457 for mut side_chain in side_chains.rev() {
459 if side_chain.non_finalized_root_hash() != best_chain_root.hash {
460 drop(side_chain);
463
464 continue;
465 }
466
467 let mut_side_chain = Arc::make_mut(&mut side_chain);
471
472 mut_side_chain.detach_index_entries_at(best_chain_root.height);
476 let (side_chain_root, _treestate) = mut_side_chain.pop_root();
477 assert_eq!(side_chain_root.hash, best_chain_root.hash);
478
479 if mut_side_chain
482 .divergent_index_entries(&shared_best_chain)
483 .is_some_and(|divergent| mut_side_chain.index_removals_since_rebuild >= divergent)
484 {
485 mut_side_chain.share_indexes_with(&shared_best_chain);
486 }
487
488 if !side_chain.is_empty() {
490 self.insert(side_chain);
491 }
492 }
493
494 self.invalidated_blocks
496 .retain(|height, _blocks| *height >= best_chain_root.height);
497
498 self.update_metrics_for_chains();
499
500 FinalizableBlock::new(Arc::unwrap_or_clone(best_chain_root), root_treestate)
502 }
503
504 #[tracing::instrument(level = "debug", skip(self, finalized_state, prepared))]
508 pub fn commit_block(
509 &mut self,
510 prepared: SemanticallyVerifiedBlock,
511 finalized_state: &ZebraDb,
512 ) -> Result<(), ValidateContextError> {
513 let parent_hash = prepared.block.header.previous_block_hash;
514 let (height, hash) = (prepared.height, prepared.hash);
515
516 let parent_chain = self.parent_chain(parent_hash)?;
517
518 let modified_chain = self.validate_and_commit(parent_chain, prepared, finalized_state)?;
521
522 self.insert_with(modified_chain, |chain_set| {
527 chain_set.retain(|chain| chain.non_finalized_tip_hash() != parent_hash)
528 });
529
530 self.update_metrics_for_committed_block(height, hash);
531
532 Ok(())
533 }
534
535 #[allow(clippy::unwrap_in_result)]
540 pub fn invalidate_block(&mut self, block_hash: Hash) -> Result<block::Hash, InvalidateError> {
541 let Some(chain) = self.find_chain(|chain| chain.contains_block_hash(block_hash)) else {
542 return Err(InvalidateError::BlockNotFound(block_hash));
543 };
544
545 let invalidated_blocks = if chain.non_finalized_root_hash() == block_hash {
546 if self.chain_set.len() == 1 {
547 return Err(InvalidateError::OnlyChainRoot(block_hash));
548 }
549
550 self.chain_set.remove(&chain);
551 chain
552 .blocks
553 .values()
554 .map(|block| block.as_ref().clone())
555 .collect()
556 } else {
557 let (new_chain, invalidated_blocks) = chain
558 .invalidate_block(block_hash)
559 .expect("already checked that chain contains hash");
560
561 self.insert_with(Arc::new(new_chain), |chain_set| {
564 chain_set.retain(|c| !c.contains_block_hash(block_hash))
565 });
566
567 invalidated_blocks
568 };
569
570 self.invalidated_blocks.insert(
572 invalidated_blocks
573 .first()
574 .expect("should not be empty")
575 .clone()
576 .height,
577 Arc::new(invalidated_blocks),
578 );
579
580 while self.invalidated_blocks.len() > MAX_INVALIDATED_BLOCKS {
581 self.invalidated_blocks.shift_remove_index(0);
582 }
583
584 self.update_metrics_for_chains();
585 self.update_metrics_bars();
586
587 Ok(block_hash)
588 }
589
590 #[allow(clippy::unwrap_in_result)]
594 pub fn reconsider_block(
595 &mut self,
596 block_hash: block::Hash,
597 finalized_state: &ZebraDb,
598 ) -> Result<Vec<block::Hash>, ReconsiderError> {
599 let (height, invalidated_blocks) = self
603 .invalidated_blocks
604 .iter()
605 .find_map(|(height, blocks)| {
606 if blocks.first()?.hash == block_hash {
607 Some((*height, (**blocks).clone()))
608 } else {
609 None
610 }
611 })
612 .ok_or(ReconsiderError::MissingInvalidatedBlock(block_hash))?;
613
614 let invalidated_block_hashes = invalidated_blocks
615 .iter()
616 .map(|block| block.hash)
617 .collect::<Vec<_>>();
618
619 let invalidated_root = invalidated_blocks
622 .first()
623 .ok_or(ReconsiderError::InvalidatedBlocksEmpty)?;
624
625 let root_parent_hash = invalidated_root.block.header.previous_block_hash;
626
627 let chain_result = if root_parent_hash == finalized_state.finalized_tip_hash() {
630 let chain = Chain::new(
631 &self.network,
632 finalized_state
633 .finalized_tip_height()
634 .ok_or(ReconsiderError::ParentChainNotFound(block_hash))?,
635 finalized_state.note_commitment_trees_for_tip(),
636 finalized_state.history_tree(),
637 finalized_state.finalized_value_pool(),
638 );
639 Arc::new(chain)
640 } else {
641 self.parent_chain(root_parent_hash)
644 .map_err(|_| ReconsiderError::ParentChainNotFound(block_hash))?
645 };
646
647 let mut modified_chain = Arc::unwrap_or_clone(chain_result);
648 for block in invalidated_blocks {
649 modified_chain = modified_chain
650 .push(block)
651 .map_err(ReconsiderError::ReplayFailed)?;
652 }
653
654 let (tip_height, tip_hash) = modified_chain.non_finalized_tip();
655
656 self.invalidated_blocks.shift_remove(&height);
660
661 if let Some(best_chain_root_height) = finalized_state.finalized_tip_height() {
664 self.invalidated_blocks
665 .retain(|height, _blocks| *height >= best_chain_root_height);
666 }
667
668 self.insert_with(Arc::new(modified_chain), |chain_set| {
669 chain_set.retain(|chain| chain.non_finalized_tip_hash() != root_parent_hash)
670 });
671
672 self.update_metrics_for_committed_block(tip_height, tip_hash);
673
674 Ok(invalidated_block_hashes)
675 }
676
677 #[tracing::instrument(level = "debug", skip(self, finalized_state, prepared))]
680 #[allow(clippy::unwrap_in_result)]
681 pub fn commit_new_chain(
682 &mut self,
683 prepared: SemanticallyVerifiedBlock,
684 finalized_state: &ZebraDb,
685 ) -> Result<(), ValidateContextError> {
686 let finalized_tip_height = finalized_state.finalized_tip_height();
687
688 #[cfg(not(test))]
690 let finalized_tip_height = finalized_tip_height.expect("finalized state contains blocks");
691 #[cfg(test)]
692 let finalized_tip_height = finalized_tip_height.unwrap_or(zebra_chain::block::Height(0));
693
694 let chain = Chain::new(
695 &self.network,
696 finalized_tip_height,
697 finalized_state.note_commitment_trees_for_tip(),
698 finalized_state.history_tree(),
699 finalized_state.finalized_value_pool(),
700 );
701
702 let (height, hash) = (prepared.height, prepared.hash);
703
704 let chain = self.validate_and_commit(Arc::new(chain), prepared, finalized_state)?;
706
707 self.insert(chain);
709 self.update_metrics_for_committed_block(height, hash);
710
711 Ok(())
712 }
713
714 #[allow(clippy::unwrap_in_result)]
723 pub(crate) fn commit_prevalidated_contextual(
724 &mut self,
725 contextual: ContextuallyVerifiedBlock,
726 finalized_state: &ZebraDb,
727 ) -> Result<Option<Arc<ContextuallyVerifiedBlock>>, ValidateContextError> {
728 if self
730 .invalidated_blocks
731 .values()
732 .any(|blocks| blocks.iter().any(|block| block.hash == contextual.hash))
733 {
734 return Err(ValidateContextError::BlockPreviouslyInvalidated {
735 block_hash: contextual.hash,
736 });
737 }
738
739 let parent_hash = contextual.block.header.previous_block_hash;
740 let (height, hash) = (contextual.height, contextual.hash);
741
742 let mut replaced_proposal = None;
743 let chain = if parent_hash == finalized_state.finalized_tip_hash() {
744 Chain::new(
745 &self.network,
746 finalized_state
747 .finalized_tip_height()
748 .expect("a validated proposal has a finalized parent"),
749 finalized_state.note_commitment_trees_for_tip(),
750 finalized_state.history_tree(),
751 finalized_state.finalized_value_pool(),
752 )
753 .push(contextual)?
754 } else {
755 let parent_chain = self.parent_chain(parent_hash)?;
756
757 match self.take_prepared_chain_for(&contextual, &parent_chain) {
758 Some(mut prepared_chain) => {
759 replaced_proposal = Some(prepared_chain.rebind_tip(contextual)?);
760 prepared_chain
761 }
762 None => Arc::unwrap_or_clone(parent_chain).push(contextual)?,
763 }
764 };
765
766 self.insert_with(Arc::new(chain), |chain_set| {
767 chain_set.retain(|chain| chain.non_finalized_tip_hash() != parent_hash)
768 });
769 self.update_metrics_for_committed_block(height, hash);
770
771 Ok(replaced_proposal)
772 }
773
774 pub(crate) fn store_prepared_chain(&self, chain: Arc<Chain>) {
777 self.prepared_chain.send_replace(Some(chain));
778 }
779
780 pub(crate) fn drop_passed_prepared_chain(&self) {
787 let Some(best_tip_height) = self
788 .best_chain()
789 .map(|chain| chain.non_finalized_tip_height())
790 else {
791 return;
792 };
793
794 self.prepared_chain.send_if_modified(|prepared| {
795 if prepared
796 .as_ref()
797 .is_some_and(|prepared| prepared.non_finalized_tip_height() < best_tip_height)
798 {
799 *prepared = None;
800 }
801
802 false
804 });
805 }
806
807 #[cfg(test)]
809 pub(crate) fn has_prepared_chain(&self) -> bool {
810 self.prepared_chain.borrow().is_some()
811 }
812
813 fn take_prepared_chain_for(
818 &self,
819 block: &ContextuallyVerifiedBlock,
820 parent_chain: &Chain,
821 ) -> Option<Chain> {
822 let mut prepared_chain = None;
823 self.prepared_chain.send_if_modified(|prepared| {
824 if prepared
825 .as_ref()
826 .is_some_and(|prepared| is_prepared_chain_for(prepared, block, parent_chain))
827 {
828 prepared_chain = prepared.take();
829 }
830
831 false
833 });
834 let mut prepared_chain = Arc::unwrap_or_clone(prepared_chain?);
835
836 while prepared_chain.non_finalized_root_height() < parent_chain.non_finalized_root_height()
839 {
840 prepared_chain.detach_index_entries_at(prepared_chain.non_finalized_root_height());
843 prepared_chain.pop_root();
844 }
845 prepared_chain.last_fork_height = parent_chain.last_fork_height;
847
848 prepared_chain.can_rebind_tip().then_some(prepared_chain)
849 }
850
851 pub(crate) fn remove_chain_with_tip(&mut self, tip: block::Hash) -> Option<Arc<Chain>> {
853 let chain = self.find_chain(|chain| chain.non_finalized_tip_hash() == tip)?;
854 self.chain_set.remove(&chain);
855
856 Some(chain)
857 }
858
859 #[tracing::instrument(
865 level = "debug",
866 skip(self, finalized_state, new_chain, prepared),
867 fields(height = ?prepared.height, hash = %prepared.hash)
868 )]
869 fn validate_and_commit(
870 &self,
871 new_chain: Arc<Chain>,
872 prepared: SemanticallyVerifiedBlock,
873 finalized_state: &ZebraDb,
874 ) -> Result<Arc<Chain>, ValidateContextError> {
875 if self
876 .invalidated_blocks
877 .values()
878 .any(|blocks| blocks.iter().any(|block| block.hash == prepared.hash))
879 {
880 return Err(ValidateContextError::BlockPreviouslyInvalidated {
881 block_hash: prepared.hash,
882 });
883 }
884
885 let spent_utxos = check::utxo::transparent_spend(
889 &prepared,
890 &new_chain,
891 &new_chain.spent_utxos,
892 finalized_state,
893 )?;
894
895 check::anchors::block_sapling_orchard_anchors_refer_to_final_treestates(
897 finalized_state,
898 &new_chain,
899 &prepared,
900 )?;
901
902 let sprout_final_treestates = check::anchors::block_fetch_sprout_final_treestates(
904 finalized_state,
905 &new_chain,
906 &prepared,
907 );
908
909 let (height, block_hash) = (prepared.height, prepared.hash);
910 let transaction_count = prepared.block.transactions.len();
911 let spent_utxo_count = spent_utxos.len();
912 let deferred_pool_balance_change = calculate_deferred_pool_balance_change(
913 height,
914 &self.network,
915 new_chain.chain_value_pools,
916 )
917 .map_err(|subsidy_error| ValidateContextError::InvalidSubsidy {
918 subsidy_error: subsidy_error.into(),
919 height,
920 block_hash,
921 })?;
922
923 let (contextual, block_fees) = ContextuallyVerifiedBlock::with_block_spent_utxos_and_fees(
924 prepared,
925 spent_utxos,
926 deferred_pool_balance_change,
927 &self.network,
928 new_chain.chain_value_pools,
929 )
930 .map_err(|value_balance_error| {
931 ValidateContextError::CalculateBlockChainValueChange {
932 value_balance_error,
933 height,
934 block_hash,
935 transaction_count,
936 spent_utxo_count,
937 }
938 })?;
939
940 if zebra_chain::parameters::subsidy::nsm_reissuance_is_active(height, &self.network) {
942 check::nsm_subsidy_is_valid(
943 &contextual,
944 &self.network,
945 new_chain.chain_value_pools,
946 block_fees.expect("reissuance starts no earlier than NU7 fee accounting"),
947 )?;
948 }
949
950 Self::validate_and_update_parallel(
951 new_chain,
952 contextual,
953 sprout_final_treestates,
954 self.precomputed_trees.as_ref(),
955 )
956 }
957
958 #[allow(clippy::unwrap_in_result)]
960 #[tracing::instrument(
961 skip(new_chain, contextual, sprout_final_treestates, precomputed_trees),
962 fields(height = ?contextual.height, hash = %contextual.hash)
963 )]
964 fn validate_and_update_parallel(
965 new_chain: Arc<Chain>,
966 contextual: ContextuallyVerifiedBlock,
967 sprout_final_treestates: HashMap<sprout::tree::Root, Arc<sprout::tree::NoteCommitmentTree>>,
968 precomputed_trees: Option<&crate::service::precomputed_trees::PrecomputedTrees>,
969 ) -> Result<Arc<Chain>, ValidateContextError> {
970 let mut block_commitment_result = None;
971 let mut sprout_anchor_result = None;
972 let mut chain_push_result = None;
973
974 let block = contextual.block.clone();
976 let network = new_chain.network();
977 let history_tree = new_chain.history_block_commitment_tree();
978
979 let block2 = contextual.block.clone();
980 let height = contextual.height;
981 let transaction_hashes = contextual.transaction_hashes.clone();
982
983 rayon::in_place_scope_fifo(|scope| {
984 scope.spawn_fifo(|_scope| {
985 block_commitment_result = Some(check::block_commitment_is_valid_for_chain_history(
986 block,
987 &network,
988 &history_tree,
989 ));
990 });
991
992 scope.spawn_fifo(|_scope| {
993 sprout_anchor_result =
994 Some(check::anchors::block_sprout_anchors_refer_to_treestates(
995 sprout_final_treestates,
996 block2,
997 transaction_hashes,
998 height,
999 ));
1000 });
1001
1002 scope.spawn_fifo(|_scope| {
1008 let new_chain = Arc::try_unwrap(new_chain)
1011 .unwrap_or_else(|shared_chain| (*shared_chain).clone());
1012 chain_push_result = Some(
1013 new_chain
1014 .push_with_trees(contextual, precomputed_trees)
1015 .map(Arc::new),
1016 );
1017 });
1018 });
1019
1020 block_commitment_result.expect("scope has finished")?;
1022 sprout_anchor_result.expect("scope has finished")?;
1023
1024 chain_push_result.expect("scope has finished")
1025 }
1026
1027 pub fn best_chain_len(&self) -> Option<u32> {
1030 Some(self.best_chain()?.blocks.len() as u32)
1034 }
1035
1036 pub fn root_height(&self) -> Option<block::Height> {
1038 self.best_chain()
1039 .map(|chain| chain.non_finalized_root_height())
1040 }
1041
1042 pub(crate) fn index_entry_count(&self) -> usize {
1045 let mut seen_blocks = HashSet::new();
1046 let mut entries = 0;
1047 for chain in &self.chain_set {
1048 entries += chain.detached_index_entry_count();
1049 for block in chain.blocks.values() {
1050 if seen_blocks.insert(Arc::as_ptr(block)) {
1051 entries += chain.block_index_entry_count(block);
1052 }
1053 }
1054 }
1055 entries
1056 }
1057
1058 pub fn any_chain_contains(&self, hash: &block::Hash) -> bool {
1061 self.chain_set
1062 .iter()
1063 .rev()
1064 .any(|chain| chain.height_by_hash.contains_key(hash))
1065 }
1066
1067 pub fn find_chain<P>(&self, mut predicate: P) -> Option<Arc<Chain>>
1072 where
1073 P: FnMut(&Chain) -> bool,
1074 {
1075 self.chain_set
1077 .iter()
1078 .rev()
1079 .find(|chain| predicate(chain))
1080 .cloned()
1081 }
1082
1083 pub fn any_utxo(&self, outpoint: &transparent::OutPoint) -> Option<transparent::Utxo> {
1088 self.chain_set
1089 .iter()
1090 .rev()
1091 .find_map(|chain| chain.created_utxo(outpoint))
1092 }
1093
1094 #[allow(dead_code)]
1096 pub fn any_block_by_hash(&self, hash: block::Hash) -> Option<Arc<Block>> {
1097 for chain in self.chain_set.iter().rev() {
1099 if let Some(prepared) = chain
1100 .height_by_hash
1101 .get(&hash)
1102 .and_then(|height| chain.blocks.get(height))
1103 {
1104 return Some(prepared.block.clone());
1105 }
1106 }
1107
1108 None
1109 }
1110
1111 #[allow(dead_code)]
1113 pub fn any_prev_block_hash_for_hash(&self, hash: block::Hash) -> Option<block::Hash> {
1114 self.any_block_by_hash(hash)
1116 .map(|block| block.header.previous_block_hash)
1117 }
1118
1119 #[allow(dead_code)]
1121 pub fn best_hash(&self, height: block::Height) -> Option<block::Hash> {
1122 self.best_chain()?
1123 .blocks
1124 .get(&height)
1125 .map(|prepared| prepared.hash)
1126 }
1127
1128 #[allow(dead_code)]
1130 pub fn best_tip(&self) -> Option<(block::Height, block::Hash)> {
1131 let best_chain = self.best_chain()?;
1132 let height = best_chain.non_finalized_tip_height();
1133 let hash = best_chain.non_finalized_tip_hash();
1134
1135 Some((height, hash))
1136 }
1137
1138 #[allow(dead_code)]
1140 pub fn best_tip_block(&self) -> Option<&ContextuallyVerifiedBlock> {
1141 let best_chain = self.best_chain()?;
1142
1143 best_chain.tip_block()
1144 }
1145
1146 #[allow(dead_code)]
1148 pub fn best_height_by_hash(&self, hash: block::Hash) -> Option<block::Height> {
1149 let best_chain = self.best_chain()?;
1150 let height = *best_chain.height_by_hash.get(&hash)?;
1151 Some(height)
1152 }
1153
1154 #[allow(dead_code)]
1156 pub fn any_height_by_hash(&self, hash: block::Hash) -> Option<block::Height> {
1157 for chain in self.chain_set.iter().rev() {
1158 if let Some(height) = chain.height_by_hash.get(&hash) {
1159 return Some(*height);
1160 }
1161 }
1162
1163 None
1164 }
1165
1166 #[cfg(any(test, feature = "proptest-impl"))]
1168 #[allow(dead_code)]
1169 pub fn best_contains_sprout_nullifier(&self, sprout_nullifier: &sprout::Nullifier) -> bool {
1170 self.best_chain()
1171 .map(|best_chain| best_chain.sprout_nullifiers.contains_key(sprout_nullifier))
1172 .unwrap_or(false)
1173 }
1174
1175 #[cfg(any(test, feature = "proptest-impl"))]
1177 #[allow(dead_code)]
1178 pub fn best_contains_sapling_nullifier(
1179 &self,
1180 sapling_nullifier: &zebra_chain::sapling::Nullifier,
1181 ) -> bool {
1182 self.best_chain()
1183 .map(|best_chain| {
1184 best_chain
1185 .sapling_nullifiers
1186 .contains_key(sapling_nullifier)
1187 })
1188 .unwrap_or(false)
1189 }
1190
1191 #[cfg(any(test, feature = "proptest-impl"))]
1193 #[allow(dead_code)]
1194 pub fn best_contains_orchard_nullifier(
1195 &self,
1196 orchard_nullifier: &zebra_chain::orchard::Nullifier,
1197 ) -> bool {
1198 self.best_chain()
1199 .map(|best_chain| {
1200 best_chain
1201 .orchard_nullifiers
1202 .contains_key(orchard_nullifier)
1203 })
1204 .unwrap_or(false)
1205 }
1206
1207 pub fn best_chain(&self) -> Option<&Arc<Chain>> {
1209 self.chain_iter().next()
1210 }
1211
1212 pub fn chain_count(&self) -> usize {
1214 self.chain_set.len()
1215 }
1216
1217 pub fn is_chain_set_empty(&self) -> bool {
1219 self.chain_count() == 0
1220 }
1221
1222 pub fn invalidated_blocks(&self) -> IndexMap<Height, Arc<Vec<ContextuallyVerifiedBlock>>> {
1224 self.invalidated_blocks.clone()
1225 }
1226
1227 fn parent_chain(&self, parent_hash: block::Hash) -> Result<Arc<Chain>, ValidateContextError> {
1232 match self.find_chain(|chain| chain.non_finalized_tip_hash() == parent_hash) {
1233 Some(chain) => Ok(chain.clone()),
1235 None => {
1237 let fork_chain = self
1240 .chain_set
1241 .iter()
1242 .rev()
1243 .find_map(|chain| chain.fork(parent_hash))
1244 .ok_or(ValidateContextError::NotReadyToBeCommitted)?;
1245
1246 Ok(Arc::new(fork_chain))
1247 }
1248 }
1249 }
1250
1251 fn should_count_metrics(&self) -> bool {
1253 self.should_count_metrics
1254 }
1255
1256 fn update_metrics_for_committed_block(&self, height: block::Height, hash: block::Hash) {
1258 if !self.should_count_metrics() {
1259 return;
1260 }
1261
1262 metrics::counter!("state.memory.committed.block.count").increment(1);
1263 metrics::gauge!("state.memory.committed.block.height").set(height.0 as f64);
1264
1265 if self
1266 .best_chain()
1267 .expect("metrics are only updated after initialization")
1268 .non_finalized_tip_hash()
1269 == hash
1270 {
1271 metrics::counter!("state.memory.best.committed.block.count").increment(1);
1272 metrics::gauge!("state.memory.best.committed.block.height").set(height.0 as f64);
1273 }
1274
1275 self.update_metrics_for_chains();
1276 }
1277
1278 fn update_metrics_for_chains(&self) {
1280 if !self.should_count_metrics() {
1281 return;
1282 }
1283
1284 metrics::gauge!("state.memory.chain.count").set(self.chain_set.len() as f64);
1285 metrics::gauge!("state.memory.best.chain.length",)
1286 .set(self.best_chain_len().unwrap_or_default() as f64);
1287 metrics::gauge!("state.memory.index.entries").set(self.index_entry_count() as f64);
1289 metrics::gauge!("state.memory.best.chain.index.entries").set(
1290 self.best_chain()
1291 .map_or(0, |chain| chain.index_entry_count()) as f64,
1292 );
1293
1294 if let Some(best_chain) = self.best_chain() {
1295 let value_pools = best_chain.chain_value_pools;
1296 metrics::gauge!("zcash.pool.value.zatoshis", "name" => "transparent")
1297 .set(u64::from(value_pools.transparent_amount()) as f64);
1298 metrics::gauge!("zcash.pool.value.zatoshis", "name" => "sprout")
1299 .set(u64::from(value_pools.sprout_amount()) as f64);
1300 metrics::gauge!("zcash.pool.value.zatoshis", "name" => "sapling")
1301 .set(u64::from(value_pools.sapling_amount()) as f64);
1302 metrics::gauge!("zcash.pool.value.zatoshis", "name" => "orchard")
1303 .set(u64::from(value_pools.orchard_amount()) as f64);
1304 metrics::gauge!("zcash.pool.value.zatoshis", "name" => "ironwood")
1305 .set(u64::from(value_pools.ironwood_amount()) as f64);
1306
1307 metrics::gauge!("zcash.pool.notes.created", "name" => "sprout")
1308 .set(best_chain.sprout_note_commitment_tree_for_tip().count() as f64);
1309 metrics::gauge!("zcash.pool.notes.created", "name" => "sapling")
1310 .set(best_chain.sapling_note_commitment_tree_for_tip().count() as f64);
1311 metrics::gauge!("zcash.pool.notes.created", "name" => "orchard")
1312 .set(best_chain.orchard_note_commitment_tree_for_tip().count() as f64);
1313 metrics::gauge!("zcash.pool.notes.created", "name" => "ironwood")
1314 .set(best_chain.ironwood_note_commitment_tree_for_tip().count() as f64);
1315 }
1316 }
1317
1318 fn update_metrics_bars(&mut self) {
1321 if !self.should_count_metrics() {
1324 #[allow(clippy::needless_return)]
1325 return;
1326 }
1327
1328 #[cfg(feature = "progress-bar")]
1329 {
1330 use std::cmp::Ordering::*;
1331
1332 if matches!(howudoin::cancelled(), Some(true)) {
1333 self.disable_metrics();
1334 return;
1335 }
1336
1337 if self.chain_count_bar.is_none() {
1339 self.chain_count_bar = Some(howudoin::new_root().label("Chain Forks"));
1340 }
1341
1342 let chain_count_bar = self
1343 .chain_count_bar
1344 .as_ref()
1345 .expect("just initialized if missing");
1346 let finalized_tip_height = self
1347 .best_chain()
1348 .map(|chain| chain.non_finalized_root_height().0 - 1);
1349
1350 chain_count_bar.set_pos(u64::try_from(self.chain_count()).expect("fits in u64"));
1351 if let Some(finalized_tip_height) = finalized_tip_height {
1354 chain_count_bar.desc(format!("Finalized Root {finalized_tip_height}"));
1355 }
1356
1357 let prev_length_bars = self.chain_fork_length_bars.len();
1359
1360 match self.chain_count().cmp(&prev_length_bars) {
1361 Greater => self
1362 .chain_fork_length_bars
1363 .resize_with(self.chain_count(), || {
1364 howudoin::new_with_parent(chain_count_bar.id())
1365 }),
1366 Less => {
1367 let redundant_bars = self.chain_fork_length_bars.split_off(self.chain_count());
1368 for bar in redundant_bars {
1369 bar.close();
1370 }
1371 }
1372 Equal => {}
1373 }
1374
1375 for (chain_length_bar, chain) in
1378 std::iter::zip(self.chain_fork_length_bars.iter(), self.chain_iter())
1379 {
1380 let fork_height = chain
1381 .last_fork_height
1382 .unwrap_or_else(|| chain.non_finalized_tip_height())
1383 .0;
1384
1385 chain_length_bar
1389 .label(format!("Fork {fork_height}"))
1390 .set_pos(u64::try_from(chain.len()).expect("fits in u64"));
1391 let mut desc = String::new();
1401
1402 if let Some(recent_fork_height) = chain.recent_fork_height() {
1403 let recent_fork_length = chain
1404 .recent_fork_length()
1405 .expect("just checked recent fork height");
1406
1407 let mut plural = "s";
1408 if recent_fork_length == 1 {
1409 plural = "";
1410 }
1411
1412 desc.push_str(&format!(
1413 " at {recent_fork_height:?} + {recent_fork_length} block{plural}"
1414 ));
1415 }
1416
1417 chain_length_bar.desc(desc);
1418 }
1419 }
1420 }
1421
1422 pub fn disable_metrics(&mut self) {
1424 self.should_count_metrics = false;
1425
1426 #[cfg(feature = "progress-bar")]
1427 {
1428 let count_bar = self.chain_count_bar.take().into_iter();
1429 let fork_bars = self.chain_fork_length_bars.drain(..);
1430 count_bar.chain(fork_bars).for_each(howudoin::Tx::close);
1431 }
1432 }
1433}
1434
1435fn is_prepared_chain_for(
1441 prepared: &Chain,
1442 block: &ContextuallyVerifiedBlock,
1443 parent_chain: &Chain,
1444) -> bool {
1445 if parent_chain.is_empty() {
1446 return false;
1447 }
1448
1449 let Some(proposal) = prepared.tip_block() else {
1450 return false;
1451 };
1452 let parent_height = parent_chain.non_finalized_tip_height();
1453
1454 same_block_except_proof_of_work(proposal, block)
1455 && parent_height.next().ok() == Some(prepared.non_finalized_tip_height())
1456 && prepared.hash_by_height(parent_height) == Some(parent_chain.non_finalized_tip_hash())
1457 && prepared.non_finalized_root_height() <= parent_chain.non_finalized_root_height()
1458}
1459
1460fn same_block_except_proof_of_work(
1470 proposal: &ContextuallyVerifiedBlock,
1471 block: &ContextuallyVerifiedBlock,
1472) -> bool {
1473 let (proposal_header, header) = (&proposal.block.header, &block.block.header);
1474
1475 proposal.height == block.height
1476 && proposal.transaction_hashes == block.transaction_hashes
1477 && proposal_header.version == header.version
1478 && proposal_header.previous_block_hash == header.previous_block_hash
1479 && proposal_header.merkle_root == header.merkle_root
1480 && proposal_header.commitment_bytes == header.commitment_bytes
1481 && proposal_header.time == header.time
1482 && proposal_header.difficulty_threshold == header.difficulty_threshold
1483}
1484
1485impl Drop for NonFinalizedState {
1486 fn drop(&mut self) {
1487 self.disable_metrics();
1488 }
1489}