1use std::{
18 collections::HashMap,
19 future::Future,
20 pin::Pin,
21 sync::Arc,
22 task::{Context, Poll},
23 time::{Duration, Instant},
24};
25
26use futures::future::FutureExt;
27use tokio::sync::{oneshot, watch};
28use tower::{util::BoxService, Service, ServiceExt};
29use tracing::{instrument, Instrument, Span};
30
31#[cfg(any(test, feature = "proptest-impl"))]
32use tower::buffer::Buffer;
33
34use zebra_chain::{
35 block::{self, CountedHeader, HeightDiff},
36 diagnostic::CodeTimer,
37 parameters::{Network, NetworkUpgrade},
38 serialization::ZcashSerialize,
39 subtree::NoteCommitmentSubtreeIndex,
40};
41
42use crate::{
43 constants::{
44 MAX_FIND_BLOCK_HASHES_RESULTS, MAX_FIND_BLOCK_HEADERS_RESULTS, MAX_LEGACY_CHAIN_BLOCKS,
45 },
46 error::{
47 CommitBlockError, CommitCheckpointVerifiedError, InvalidateError, ReconsiderError,
48 ValidateContextError,
49 },
50 request::TimedSpan,
51 response::{MiningCandidateChanges, MiningCandidateGuard, NonFinalizedBlocksListener},
52 service::{
53 block_iter::any_ancestor_blocks,
54 chain_tip::{ChainTipBlock, ChainTipChange, ChainTipSender, LatestChainTip},
55 finalized_state::{FinalizedState, ZebraDb},
56 non_finalized_state::{Chain, NonFinalizedState},
57 pending_utxos::PendingUtxos,
58 queued_blocks::QueuedBlocks,
59 read::find,
60 watch_receiver::WatchReceiver,
61 },
62 AwaitUtxoError, BoxError, CheckpointVerifiedBlock, CommitSemanticallyVerifiedError, Config,
63 GetBlockTemplateChainInfo, KnownBlock, ReadRequest, ReadResponse, Request, Response,
64 SemanticallyVerifiedBlock, StateInitError,
65};
66
67pub mod block_iter;
68pub mod chain_tip;
69pub mod watch_receiver;
70
71pub mod check;
72
73pub(crate) mod finalized_state;
74pub(crate) mod non_finalized_state;
75mod pending_utxos;
76mod precomputed_trees;
77mod queued_blocks;
78pub(crate) mod read;
79mod traits;
80mod write;
81
82#[cfg(any(test, feature = "proptest-impl"))]
83pub mod arbitrary;
84
85#[cfg(test)]
86mod tests;
87
88pub use finalized_state::{OutputLocation, TransactionIndex, TransactionLocation};
89use write::NonFinalizedWriteMessage;
90
91use self::queued_blocks::{QueuedCheckpointVerified, QueuedSemanticallyVerified, SentHashes};
92
93pub use self::traits::{ReadState, State};
94
95#[derive(Debug)]
115pub(crate) struct StateService {
116 network: Network,
120
121 max_checkpoint_height: block::Height,
125
126 full_verifier_utxo_lookahead: block::Height,
132
133 non_finalized_state_queued_blocks: QueuedBlocks,
138
139 finalized_state_queued_blocks: HashMap<block::Hash, QueuedCheckpointVerified>,
144
145 block_write_sender: write::BlockWriteSender,
147
148 finalized_block_write_last_sent_hash: block::Hash,
158
159 finalized_reset_next_height: Option<block::Height>,
164
165 non_finalized_block_write_sent_hashes: SentHashes,
168
169 invalid_block_write_reset_receiver:
174 tokio::sync::mpsc::UnboundedReceiver<(Option<block::Height>, block::Hash)>,
175
176 non_finalized_rejected_receiver:
184 tokio::sync::mpsc::UnboundedReceiver<write::NonFinalizedWriteOutcome>,
185
186 pending_utxos: PendingUtxos,
190
191 last_prune: Instant,
193
194 read_service: ReadStateService,
200
201 mining_candidate_task: Option<tokio::task::JoinHandle<()>>,
207
208 max_finalized_queue_height: f64,
215}
216
217#[derive(Clone, Debug)]
230pub struct ReadStateService {
231 network: Network,
235
236 non_finalized_state_receiver: WatchReceiver<NonFinalizedState>,
243
244 db: ZebraDb,
252
253 block_write_task: Option<Arc<std::thread::JoinHandle<()>>>,
258
259 mining_candidate: watch::Sender<Option<MiningCandidate>>,
263}
264
265#[derive(Clone, Debug)]
267pub(crate) struct MiningCandidate {
268 parent_hash: block::Hash,
270
271 chain_info: GetBlockTemplateChainInfo,
273}
274
275#[cfg(any(test, feature = "proptest-impl"))]
276impl MiningCandidate {
277 pub(crate) fn new_for_tests(
279 parent_hash: block::Hash,
280 chain_info: GetBlockTemplateChainInfo,
281 ) -> Self {
282 Self {
283 parent_hash,
284 chain_info,
285 }
286 }
287}
288
289const MINING_CANDIDATE_TIMEOUT: Duration = Duration::from_secs(1);
296
297async fn publish_mining_candidate(
303 chain_info: oneshot::Receiver<Option<GetBlockTemplateChainInfo>>,
304 parent_hash: block::Hash,
305 mut verification: watch::Receiver<()>,
306 candidates: watch::Sender<Option<MiningCandidate>>,
307) {
308 let Ok(Some(chain_info)) = chain_info.await else {
309 return;
310 };
311
312 if verification.has_changed().is_err() {
315 return;
316 }
317
318 candidates.send_replace(Some(MiningCandidate {
319 parent_hash,
320 chain_info,
321 }));
322
323 let verified = async { while verification.changed().await.is_ok() {} };
324 let _ = tokio::time::timeout(MINING_CANDIDATE_TIMEOUT, verified).await;
325
326 candidates.send_replace(None);
327}
328
329impl Drop for StateService {
330 fn drop(&mut self) {
331 self.invalid_block_write_reset_receiver.close();
338 self.non_finalized_rejected_receiver.close();
339
340 std::mem::drop(self.block_write_sender.finalized.take());
341 std::mem::drop(self.block_write_sender.non_finalized.take());
342
343 self.clear_finalized_block_queue(CommitBlockError::WriteTaskExited);
344 self.clear_non_finalized_block_queue(CommitBlockError::WriteTaskExited);
345
346 info!("dropping the state: logging database metrics");
348 self.log_db_metrics();
349
350 }
353}
354
355impl Drop for ReadStateService {
356 fn drop(&mut self) {
357 if let Some(block_write_task) = self.block_write_task.take() {
362 if let Some(block_write_task_handle) = Arc::into_inner(block_write_task) {
363 self.db.shutdown(true);
367
368 #[cfg(not(test))]
374 info!("waiting for the block write task to finish");
375 #[cfg(test)]
376 debug!("waiting for the block write task to finish");
377
378 if let Err(thread_panic) = block_write_task_handle.join() {
380 std::panic::resume_unwind(thread_panic);
381 } else {
382 debug!("shutting down the state because the block write task has finished");
383 }
384 }
385 } else {
386 self.db.shutdown(false);
390 }
391 }
392}
393
394impl StateService {
395 const PRUNE_INTERVAL: Duration = Duration::from_secs(30);
396
397 pub async fn new(
405 config: Config,
406 network: &Network,
407 max_checkpoint_height: block::Height,
408 checkpoint_verify_concurrency_limit: usize,
409 ) -> (Self, ReadStateService, LatestChainTip, ChainTipChange) {
410 Self::new_with_debug(
411 config,
412 network,
413 max_checkpoint_height,
414 checkpoint_verify_concurrency_limit,
415 false,
416 )
417 .await
418 }
419
420 async fn new_with_debug(
422 config: Config,
423 network: &Network,
424 max_checkpoint_height: block::Height,
425 checkpoint_verify_concurrency_limit: usize,
426 debug_skip_format_upgrades: bool,
427 ) -> (Self, ReadStateService, LatestChainTip, ChainTipChange) {
428 let (finalized_state, finalized_tip, timer) = {
429 let config = config.clone();
430 let network = network.clone();
431 tokio::task::spawn_blocking(move || {
432 let timer = CodeTimer::start();
433 let finalized_state = FinalizedState::new_with_debug(
434 &config,
435 &network,
436 debug_skip_format_upgrades,
437 false,
438 )
439 .expect(
440 "opening the read-write finalized state database failed; check that the \
441 state cache directory is writable and not locked by another Zebra instance, \
442 and that there is free disk space",
443 );
444 timer.finish_desc("opening finalized state database");
445
446 let timer = CodeTimer::start();
447 let finalized_tip = finalized_state
448 .db
449 .tip_block()
450 .expect("the finalized tip must have a complete stored body");
451
452 (finalized_state, finalized_tip, timer)
453 })
454 .await
455 .expect("failed to join blocking task")
456 };
457
458 let finalized_tip_height = finalized_tip
470 .as_ref()
471 .map(|tip| tip.coinbase_height().expect("valid block must have height"));
472 let is_finalized_tip_past_max_checkpoint =
473 finalized_tip_height.is_some_and(|tip_height| tip_height >= max_checkpoint_height);
474 let backup_dir_path = config.non_finalized_state_backup_dir(network);
475
476 if backup_dir_path.is_some() && !is_finalized_tip_past_max_checkpoint {
477 tracing::info!(
478 ?finalized_tip_height,
479 ?max_checkpoint_height,
480 "not restoring the non-finalized state backup, because the finalized tip is absent \
481 or below the max checkpoint height: Zebra will re-download and re-verify the \
482 blocks above its finalized tip"
483 );
484 }
485 let skip_backup_task = config.debug_skip_non_finalized_state_backup_task;
486 let (non_finalized_state, non_finalized_state_sender, non_finalized_state_receiver) =
487 NonFinalizedState::new(network)
488 .with_backup(
489 backup_dir_path.clone(),
490 &finalized_state.db,
491 is_finalized_tip_past_max_checkpoint,
492 config.debug_skip_non_finalized_state_backup_task,
493 )
494 .await;
495
496 let non_finalized_block_write_sent_hashes = SentHashes::new(&non_finalized_state);
497 let initial_tip = non_finalized_state
498 .best_tip_block()
499 .map(|cv_block| cv_block.block.clone())
500 .or(finalized_tip)
501 .map(CheckpointVerifiedBlock::from)
502 .map(ChainTipBlock::from);
503
504 tracing::info!(chain_tip = ?initial_tip.as_ref().map(|tip| (tip.hash, tip.height)), "loaded Zebra state cache");
505
506 let (chain_tip_sender, latest_chain_tip, chain_tip_change) =
507 ChainTipSender::new(initial_tip, network);
508
509 let finalized_state_for_writing = finalized_state.clone();
510 let should_use_finalized_block_write_sender = non_finalized_state.is_chain_set_empty();
511 let sync_backup_dir_path = backup_dir_path.filter(|_| skip_backup_task);
512 let (
513 block_write_sender,
514 invalid_block_write_reset_receiver,
515 non_finalized_rejected_receiver,
516 block_write_task,
517 ) = write::BlockWriteSender::spawn(
518 finalized_state_for_writing,
519 non_finalized_state,
520 chain_tip_sender,
521 non_finalized_state_sender,
522 should_use_finalized_block_write_sender,
523 sync_backup_dir_path,
524 );
525
526 let read_service = ReadStateService::new(
527 &finalized_state,
528 block_write_task,
529 non_finalized_state_receiver,
530 );
531
532 let full_verifier_utxo_lookahead = max_checkpoint_height
533 - HeightDiff::try_from(checkpoint_verify_concurrency_limit)
534 .expect("fits in HeightDiff");
535 let full_verifier_utxo_lookahead =
536 full_verifier_utxo_lookahead.unwrap_or(block::Height::MIN);
537 let non_finalized_state_queued_blocks = QueuedBlocks::default();
538 let pending_utxos = PendingUtxos::default();
539
540 let finalized_block_write_last_sent_hash =
541 tokio::task::spawn_blocking(move || finalized_state.db.finalized_tip_hash())
542 .await
543 .expect("failed to join blocking task");
544
545 let state = Self {
546 network: network.clone(),
547 max_checkpoint_height,
548 full_verifier_utxo_lookahead,
549 non_finalized_state_queued_blocks,
550 finalized_state_queued_blocks: HashMap::new(),
551 block_write_sender,
552 finalized_block_write_last_sent_hash,
553 finalized_reset_next_height: None,
554 non_finalized_block_write_sent_hashes,
555 invalid_block_write_reset_receiver,
556 non_finalized_rejected_receiver,
557 pending_utxos,
558 last_prune: Instant::now(),
559 read_service: read_service.clone(),
560 mining_candidate_task: None,
561 max_finalized_queue_height: f64::NAN,
562 };
563 timer.finish_desc("initializing state service");
564
565 tracing::info!("starting legacy chain check");
566 let timer = CodeTimer::start();
567
568 if let (Some(tip), Some(nu5_activation_height)) = (
569 {
570 let read_state = state.read_service.clone();
571 tokio::task::spawn_blocking(move || read_state.best_tip())
572 .await
573 .expect("task should not panic")
574 },
575 NetworkUpgrade::Nu5.activation_height(network),
576 ) {
577 if let Err(error) = check::legacy_chain(
578 nu5_activation_height,
579 any_ancestor_blocks(
580 &state.read_service.latest_non_finalized_state(),
581 &state.read_service.db,
582 tip.1,
583 ),
584 &state.network,
585 MAX_LEGACY_CHAIN_BLOCKS,
586 ) {
587 let legacy_db_path = state.read_service.db.path().to_path_buf();
588 panic!(
589 "Cached state contains a legacy chain.\n\
590 An outdated Zebra version did not know about a recent network upgrade,\n\
591 so it followed a legacy chain using outdated consensus branch rules.\n\
592 Hint: Delete your database, and restart Zebra to do a full sync.\n\
593 Database path: {legacy_db_path:?}\n\
594 Error: {error:?}",
595 );
596 }
597 }
598
599 tracing::info!("cached state consensus branch is valid: no legacy chain found");
600 timer.finish_desc("legacy chain check");
601
602 let db_for_metrics = read_service.db.clone();
604 tokio::spawn(async move {
605 let mut interval = tokio::time::interval(Duration::from_secs(30));
606 loop {
607 interval.tick().await;
608 db_for_metrics.export_metrics();
609 }
610 });
611
612 (state, read_service, latest_chain_tip, chain_tip_change)
613 }
614
615 pub fn log_db_metrics(&self) {
617 self.read_service.db.print_db_metrics();
618 }
619
620 fn queue_and_commit_to_finalized_state(
624 &mut self,
625 checkpoint_verified: CheckpointVerifiedBlock,
626 ) -> oneshot::Receiver<Result<block::Hash, CommitCheckpointVerifiedError>> {
627 let queued_prev_hash = checkpoint_verified.block.header.previous_block_hash;
633 let queued_height = checkpoint_verified.height;
634
635 self.drain_finalized_resets();
637
638 if let Some(next_height) = self.finalized_reset_next_height {
639 if queued_height > next_height {
640 let (rsp_tx, rsp_rx) = oneshot::channel();
641 Self::send_checkpoint_verified_block_error(
642 (checkpoint_verified, rsp_tx),
643 CommitBlockError::WriteTaskExited,
644 );
645 return rsp_rx;
646 } else if queued_height == next_height {
647 self.finalized_reset_next_height = None;
648 }
649 }
650
651 let (rsp_tx, rsp_rx) = oneshot::channel();
652 let queued = (checkpoint_verified, rsp_tx);
653
654 if self.block_write_sender.finalized.is_some() {
655 if let Some(duplicate_queued) = self
657 .finalized_state_queued_blocks
658 .insert(queued_prev_hash, queued)
659 {
660 Self::send_checkpoint_verified_block_error(
661 duplicate_queued,
662 CommitBlockError::new_duplicate(
663 Some(queued_prev_hash.into()),
664 KnownBlock::Queue,
665 ),
666 );
667 }
668
669 self.drain_finalized_queue_and_commit();
670 } else {
671 Self::send_checkpoint_verified_block_error(
677 queued,
678 CommitBlockError::new_duplicate(None, KnownBlock::Finalized),
679 );
680
681 self.clear_finalized_block_queue(CommitBlockError::new_duplicate(
682 None,
683 KnownBlock::Finalized,
684 ));
685 }
686
687 if self.finalized_state_queued_blocks.is_empty() {
688 self.max_finalized_queue_height = f64::NAN;
689 } else if self.max_finalized_queue_height.is_nan()
690 || self.max_finalized_queue_height < queued_height.0 as f64
691 {
692 self.max_finalized_queue_height = queued_height.0 as f64;
698 }
699
700 metrics::gauge!("state.checkpoint.queued.max.height").set(self.max_finalized_queue_height);
701 metrics::gauge!("state.checkpoint.queued.block.count")
702 .set(self.finalized_state_queued_blocks.len() as f64);
703
704 rsp_rx
705 }
706
707 pub fn drain_finalized_queue_and_commit(&mut self) {
715 use tokio::sync::mpsc::error::SendError;
716
717 if !self.drain_finalized_resets() {
724 return;
725 }
726
727 while let Some(queued_block) = self
728 .finalized_state_queued_blocks
729 .remove(&self.finalized_block_write_last_sent_hash)
730 {
731 let last_sent_finalized_block_height = queued_block.0.height;
732
733 self.finalized_block_write_last_sent_hash = queued_block.0.hash;
734
735 self.reject_queued_non_finalized_children(
737 queued_block.0.hash,
738 last_sent_finalized_block_height,
739 );
740
741 if self.block_write_sender.finalized.is_some()
745 && self.is_close_to_final_checkpoint(last_sent_finalized_block_height)
746 {
747 self.non_finalized_block_write_sent_hashes
748 .add_finalized(&queued_block.0);
749 }
750
751 if let Some(finalized_block_write_sender) = &self.block_write_sender.finalized {
754 let send_result = finalized_block_write_sender.send(queued_block);
755
756 if let Err(SendError(queued)) = send_result {
758 Self::send_checkpoint_verified_block_error(
760 queued,
761 CommitBlockError::WriteTaskExited,
762 );
763
764 self.clear_finalized_block_queue(CommitBlockError::WriteTaskExited);
765 } else {
766 metrics::gauge!("state.checkpoint.sent.block.height")
767 .set(last_sent_finalized_block_height.0 as f64);
768 };
769 }
770 }
771 }
772
773 fn drain_finalized_resets(&mut self) -> bool {
779 use tokio::sync::mpsc::error::TryRecvError;
780
781 loop {
782 match self.invalid_block_write_reset_receiver.try_recv() {
783 Ok((reset_tip_height, reset_tip_hash)) => {
784 self.finalized_block_write_last_sent_hash = reset_tip_hash;
785 self.finalized_reset_next_height = Some(
786 reset_tip_height
787 .map(|height| (height + 1).expect("committed heights are valid"))
788 .unwrap_or(block::Height(0)),
789 );
790 self.non_finalized_block_write_sent_hashes = SentHashes::default();
792 self.clear_finalized_block_queue(CommitBlockError::WriteTaskExited);
795 }
796 Err(TryRecvError::Empty) => return true,
797 Err(TryRecvError::Disconnected) => {
798 info!(
799 "Block commit task closed the block reset channel. Is Zebra shutting down?"
800 );
801 return false;
802 }
803 }
804 }
805 }
806
807 fn drain_non_finalized_rejected_hashes(&mut self) {
821 use tokio::sync::mpsc::error::TryRecvError;
822
823 let mut rejected_hashes = Vec::new();
824
825 loop {
826 match self.non_finalized_rejected_receiver.try_recv() {
827 Ok(write::NonFinalizedWriteOutcome::Rejected(hash)) => rejected_hashes.push(hash),
828 Ok(write::NonFinalizedWriteOutcome::Committed(hash)) => {
829 self.non_finalized_block_write_sent_hashes
830 .forget_utxos(&hash);
831 }
832 Err(TryRecvError::Empty) => break,
833 Err(TryRecvError::Disconnected) => {
834 info!(
835 "Block commit task closed the non-finalized rejected hash channel. \
836 Is Zebra shutting down?"
837 );
838 break;
839 }
840 }
841 }
842
843 self.non_finalized_block_write_sent_hashes
844 .remove_all(rejected_hashes);
845 }
846
847 fn clear_finalized_block_queue(
849 &mut self,
850 error: impl Into<CommitCheckpointVerifiedError> + Clone,
851 ) {
852 for (_hash, queued) in self.finalized_state_queued_blocks.drain() {
853 Self::send_checkpoint_verified_block_error(queued, error.clone());
854 }
855 }
856
857 fn send_checkpoint_verified_block_error(
859 queued: QueuedCheckpointVerified,
860 error: impl Into<CommitCheckpointVerifiedError>,
861 ) {
862 let (finalized, rsp_tx) = queued;
863
864 let _ = rsp_tx.send(Err(error.into()));
867 std::mem::drop(finalized);
868 }
869
870 fn clear_non_finalized_block_queue(
872 &mut self,
873 error: impl Into<CommitSemanticallyVerifiedError> + Clone,
874 ) {
875 for (_hash, queued) in self.non_finalized_state_queued_blocks.drain() {
876 Self::send_semantically_verified_block_error(queued, error.clone());
877 }
878 }
879
880 fn send_semantically_verified_block_error(
882 queued: QueuedSemanticallyVerified,
883 error: impl Into<CommitSemanticallyVerifiedError>,
884 ) {
885 let (finalized, rsp_tx, _) = queued;
886
887 let _ = rsp_tx.send(Err(error.into()));
890 std::mem::drop(finalized);
891 }
892
893 #[instrument(level = "debug", skip(self, semantically_verified, contextual))]
904 fn queue_and_commit_to_non_finalized_state(
905 &mut self,
906 mut semantically_verified: SemanticallyVerifiedBlock,
907 contextual: Option<Box<crate::ContextuallyVerifiedBlock>>,
908 ) -> oneshot::Receiver<Result<block::Hash, CommitSemanticallyVerifiedError>> {
909 tracing::debug!(block = %semantically_verified.block, "queueing block for contextual verification");
910 let parent_hash = semantically_verified.block.header.previous_block_hash;
911
912 self.drain_non_finalized_rejected_hashes();
917
918 if self
919 .non_finalized_block_write_sent_hashes
920 .contains(&semantically_verified.hash)
921 {
922 let (rsp_tx, rsp_rx) = oneshot::channel();
923 let _ = rsp_tx.send(Err(CommitBlockError::new_duplicate(
924 Some(semantically_verified.hash.into()),
925 KnownBlock::WriteChannel,
926 )
927 .into()));
928 return rsp_rx;
929 }
930
931 if self
932 .read_service
933 .db
934 .contains_height(semantically_verified.height)
935 {
936 let (rsp_tx, rsp_rx) = oneshot::channel();
937 let _ = rsp_tx.send(Err(CommitBlockError::new_duplicate(
938 Some(semantically_verified.height.into()),
939 KnownBlock::Finalized,
940 )
941 .into()));
942 return rsp_rx;
943 }
944
945 if let Some(parent_height) = self.read_service.db.height(parent_hash) {
946 if Some(semantically_verified.height) != parent_height + 1 {
947 let (rsp_tx, rsp_rx) = oneshot::channel();
948 let _ = rsp_tx.send(Err(CommitBlockError::ValidateContextError(Box::new(
949 ValidateContextError::NonSequentialFinalizedChild {
950 candidate_height: semantically_verified.height,
951 parent_height,
952 },
953 ))
954 .into()));
955 return rsp_rx;
956 }
957 }
958
959 if let Some(old_request) = self
964 .non_finalized_state_queued_blocks
965 .remove_queued(&semantically_verified.hash)
966 {
967 tracing::debug!("replacing older queued request with new request");
968 if old_request.0.block.auth_data_root() == semantically_verified.block.auth_data_root()
972 {
973 semantically_verified.received_time = old_request
974 .0
975 .received_time
976 .min(semantically_verified.received_time);
977 }
978 Self::send_semantically_verified_block_error(
979 old_request,
980 CommitBlockError::new_duplicate(
981 Some(semantically_verified.hash.into()),
982 KnownBlock::Queue,
983 ),
984 );
985 }
986
987 let mut contextual = contextual;
990 if let Some(contextual) = contextual.as_mut() {
991 contextual.received_time = semantically_verified.received_time;
992 }
993 let hash = semantically_verified.hash;
994
995 let (rsp_tx, rsp_rx) = oneshot::channel();
996 self.non_finalized_state_queued_blocks
997 .queue((semantically_verified, rsp_tx, contextual));
998
999 if self.block_write_sender.finalized.is_some() && self.checkpoint_handoff_is_ready() {
1003 std::mem::drop(self.block_write_sender.finalized.take());
1006 self.non_finalized_block_write_sent_hashes = SentHashes::default();
1008 self.non_finalized_block_write_sent_hashes
1010 .can_fork_chain_at_hashes = true;
1011 for parent_hash in self.non_finalized_state_queued_blocks.parent_hashes() {
1013 if let Some(parent_height) = self.read_service.db.height(parent_hash) {
1014 self.reject_queued_non_finalized_children(parent_hash, parent_height);
1015 }
1016 }
1017 self.send_ready_non_finalized_queued(self.finalized_block_write_last_sent_hash);
1019 self.clear_finalized_block_queue(CommitBlockError::new_duplicate(
1021 None,
1022 KnownBlock::Finalized,
1023 ));
1024 } else if !self.can_fork_chain_at(&parent_hash) {
1025 tracing::trace!("unready to verify, returning early");
1026 } else if self.block_write_sender.finalized.is_none() {
1027 self.send_ready_non_finalized_queued(parent_hash);
1029
1030 let finalized_tip_height = self.read_service.db.finalized_tip_height().expect(
1031 "Finalized state must have at least one block before committing non-finalized state",
1032 );
1033
1034 self.non_finalized_state_queued_blocks
1035 .prune_by_height(finalized_tip_height);
1036
1037 self.non_finalized_block_write_sent_hashes
1038 .prune_by_height(finalized_tip_height);
1039 }
1040
1041 self.non_finalized_state_queued_blocks
1044 .drop_proposal_result(&hash);
1045
1046 self.non_finalized_state_queued_blocks.prune_overflow();
1048
1049 rsp_rx
1050 }
1051
1052 fn checkpoint_handoff_is_ready(&self) -> bool {
1057 self.read_service.db.finalized_tip_hash() == self.finalized_block_write_last_sent_hash
1058 && (self
1059 .read_service
1060 .db
1061 .finalized_tip_height()
1062 .is_some_and(|tip_height| tip_height >= self.max_checkpoint_height)
1063 || (self.max_checkpoint_height == block::Height::MAX
1064 && self
1065 .non_finalized_state_queued_blocks
1066 .has_queued_children(self.finalized_block_write_last_sent_hash)))
1067 }
1068
1069 fn reject_queued_non_finalized_children(
1072 &mut self,
1073 parent_hash: block::Hash,
1074 parent_height: block::Height,
1075 ) {
1076 if !self
1077 .non_finalized_state_queued_blocks
1078 .has_queued_children(parent_hash)
1079 {
1080 return;
1081 }
1082
1083 for queued in self
1084 .non_finalized_state_queued_blocks
1085 .dequeue_children(parent_hash)
1086 {
1087 let candidate_height = queued.0.height;
1088 if Some(candidate_height) == parent_height + 1 {
1089 self.non_finalized_state_queued_blocks.queue(queued);
1090 continue;
1091 }
1092
1093 Self::send_semantically_verified_block_error(
1094 queued,
1095 CommitBlockError::ValidateContextError(Box::new(
1096 ValidateContextError::NonSequentialFinalizedChild {
1097 candidate_height,
1098 parent_height,
1099 },
1100 )),
1101 );
1102 }
1103 }
1104
1105 fn can_fork_chain_at(&self, hash: &block::Hash) -> bool {
1107 self.non_finalized_block_write_sent_hashes
1108 .can_fork_chain_at(hash)
1109 || &self.read_service.db.finalized_tip_hash() == hash
1110 }
1111
1112 fn is_close_to_final_checkpoint(&self, queued_height: block::Height) -> bool {
1120 queued_height >= self.full_verifier_utxo_lookahead
1121 }
1122
1123 #[tracing::instrument(level = "debug", skip(self, new_parent))]
1126 fn send_ready_non_finalized_queued(&mut self, new_parent: block::Hash) {
1127 use tokio::sync::mpsc::error::SendError;
1128 if let Some(non_finalized_block_write_sender) = &self.block_write_sender.non_finalized {
1129 let mut new_parents: Vec<block::Hash> = vec![new_parent];
1130
1131 while let Some(parent_hash) = new_parents.pop() {
1132 let queued_children = self
1133 .non_finalized_state_queued_blocks
1134 .dequeue_children(parent_hash);
1135
1136 for queued_child in queued_children {
1137 let (SemanticallyVerifiedBlock { hash, .. }, _, _) = queued_child;
1138
1139 self.non_finalized_block_write_sent_hashes
1140 .add(&queued_child.0);
1141 let send_result = non_finalized_block_write_sender.send(queued_child.into());
1142
1143 if let Err(SendError(NonFinalizedWriteMessage::Commit(queued))) = send_result {
1144 Self::send_semantically_verified_block_error(
1146 queued,
1147 CommitBlockError::WriteTaskExited,
1148 );
1149
1150 self.clear_non_finalized_block_queue(CommitBlockError::WriteTaskExited);
1151
1152 return;
1153 };
1154
1155 new_parents.push(hash);
1156 }
1157 }
1158
1159 self.non_finalized_block_write_sent_hashes.finish_batch();
1160 };
1161 }
1162
1163 pub fn best_tip(&self) -> Option<(block::Height, block::Hash)> {
1165 self.read_service.best_tip()
1166 }
1167
1168 fn start_mining_candidate(&mut self, block: Arc<block::Block>) -> Option<MiningCandidateGuard> {
1176 let candidates = self.read_service.mining_candidate.clone();
1177
1178 if candidates.receiver_count() == 0 {
1180 return None;
1181 }
1182
1183 if self
1184 .mining_candidate_task
1185 .as_ref()
1186 .is_some_and(|task| !task.is_finished())
1187 {
1188 return None;
1189 }
1190
1191 if self.block_write_sender.finalized.is_some() {
1194 return None;
1195 }
1196
1197 let parent_hash = block.header.previous_block_hash;
1198 let (rsp_tx, rsp_rx) = oneshot::channel();
1199 self.block_write_sender
1200 .non_finalized
1201 .as_ref()?
1202 .send(NonFinalizedWriteMessage::MiningCandidate { block, rsp_tx })
1203 .ok()?;
1204
1205 let (guard, verification) = watch::channel(());
1206
1207 self.mining_candidate_task = Some(tokio::spawn(publish_mining_candidate(
1210 rsp_rx,
1211 parent_hash,
1212 verification,
1213 candidates,
1214 )));
1215
1216 Some(MiningCandidateGuard(guard))
1217 }
1218
1219 fn send_invalidate_block(
1220 &self,
1221 hash: block::Hash,
1222 ) -> oneshot::Receiver<Result<block::Hash, InvalidateError>> {
1223 let (rsp_tx, rsp_rx) = oneshot::channel();
1224
1225 let Some(sender) = &self.block_write_sender.non_finalized else {
1226 let _ = rsp_tx.send(Err(InvalidateError::ProcessingCheckpointedBlocks));
1227 return rsp_rx;
1228 };
1229
1230 if let Err(tokio::sync::mpsc::error::SendError(error)) =
1231 sender.send(NonFinalizedWriteMessage::Invalidate { hash, rsp_tx })
1232 {
1233 let NonFinalizedWriteMessage::Invalidate { rsp_tx, .. } = error else {
1234 unreachable!("should return the same Invalidate message could not be sent");
1235 };
1236
1237 let _ = rsp_tx.send(Err(InvalidateError::SendInvalidateRequestFailed));
1238 }
1239
1240 rsp_rx
1241 }
1242
1243 fn send_reconsider_block(
1244 &self,
1245 hash: block::Hash,
1246 ) -> oneshot::Receiver<Result<Vec<block::Hash>, ReconsiderError>> {
1247 let (rsp_tx, rsp_rx) = oneshot::channel();
1248
1249 let Some(sender) = &self.block_write_sender.non_finalized else {
1250 let _ = rsp_tx.send(Err(ReconsiderError::CheckpointCommitInProgress));
1251 return rsp_rx;
1252 };
1253
1254 if let Err(tokio::sync::mpsc::error::SendError(error)) =
1255 sender.send(NonFinalizedWriteMessage::Reconsider { hash, rsp_tx })
1256 {
1257 let NonFinalizedWriteMessage::Reconsider { rsp_tx, .. } = error else {
1258 unreachable!("should return the same Reconsider message could not be sent");
1259 };
1260
1261 let _ = rsp_tx.send(Err(ReconsiderError::ReconsiderSendFailed));
1262 }
1263
1264 rsp_rx
1265 }
1266
1267 fn assert_block_can_be_validated(&self, block: &SemanticallyVerifiedBlock) {
1269 assert!(
1271 block.height > self.network.mandatory_checkpoint_height(),
1272 "invalid semantically verified block height: the canopy checkpoint is mandatory, pre-canopy \
1273 blocks, and the canopy activation block, must be committed to the state as finalized \
1274 blocks"
1275 );
1276 }
1277
1278 fn known_sent_hash(&self, hash: &block::Hash) -> Option<KnownBlock> {
1279 self.non_finalized_block_write_sent_hashes
1280 .contains(hash)
1281 .then_some(KnownBlock::WriteChannel)
1282 }
1283}
1284
1285impl ReadStateService {
1286 pub(crate) fn new(
1292 finalized_state: &FinalizedState,
1293 block_write_task: Option<Arc<std::thread::JoinHandle<()>>>,
1294 non_finalized_state_receiver: WatchReceiver<NonFinalizedState>,
1295 ) -> Self {
1296 let read_service = Self {
1297 network: finalized_state.network(),
1298 db: finalized_state.db.clone(),
1299 non_finalized_state_receiver,
1300 block_write_task,
1301 mining_candidate: watch::Sender::new(None),
1302 };
1303
1304 tracing::debug!("created new read-only state service");
1305
1306 read_service
1307 }
1308
1309 pub fn best_tip(&self) -> Option<(block::Height, block::Hash)> {
1311 read::best_tip(&self.latest_non_finalized_state(), &self.db)
1312 }
1313
1314 fn latest_non_finalized_state(&self) -> NonFinalizedState {
1316 self.non_finalized_state_receiver.cloned_watch_data()
1317 }
1318
1319 fn latest_best_chain(&self) -> Option<Arc<Chain>> {
1321 self.non_finalized_state_receiver
1322 .borrow_mapped(|non_finalized_state| non_finalized_state.best_chain().cloned())
1323 }
1324
1325 #[cfg(any(test, feature = "proptest-impl"))]
1328 pub fn db(&self) -> &ZebraDb {
1329 &self.db
1330 }
1331
1332 pub fn log_db_metrics(&self) {
1334 self.db.print_db_metrics();
1335 }
1336}
1337
1338impl Service<Request> for StateService {
1339 type Response = Response;
1340 type Error = BoxError;
1341 type Future =
1342 Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
1343
1344 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1345 let poll = self.read_service.poll_ready(cx);
1347
1348 let now = Instant::now();
1350
1351 if self.last_prune + Self::PRUNE_INTERVAL < now {
1352 let tip = self.best_tip();
1353 let old_len = self.pending_utxos.len();
1354
1355 self.pending_utxos.prune();
1356 self.last_prune = now;
1357
1358 let new_len = self.pending_utxos.len();
1359 let prune_count = old_len
1360 .checked_sub(new_len)
1361 .expect("prune does not add any utxo requests");
1362 if prune_count > 0 {
1363 tracing::debug!(
1364 ?old_len,
1365 ?new_len,
1366 ?prune_count,
1367 ?tip,
1368 "pruned utxo requests"
1369 );
1370 } else {
1371 tracing::debug!(len = ?old_len, ?tip, "no utxo requests needed pruning");
1372 }
1373 }
1374
1375 poll
1376 }
1377
1378 #[instrument(name = "state", level = "debug", skip(self, req))]
1379 fn call(&mut self, req: Request) -> Self::Future {
1380 req.count_metric();
1381 let span = Span::current();
1382
1383 let (req, contextual) = match req {
1386 Request::CommitContextuallyVerifiedBlock(contextual) => {
1387 let semantically_verified = SemanticallyVerifiedBlock {
1388 block: contextual.block.clone(),
1389 hash: contextual.hash,
1390 height: contextual.height,
1391 new_outputs: contextual
1395 .new_outputs
1396 .iter()
1397 .map(|(outpoint, utxo)| (*outpoint, utxo.as_ref().clone()))
1398 .collect(),
1399 transaction_hashes: contextual.transaction_hashes.clone(),
1400 received_time: contextual.received_time,
1401 };
1402
1403 (
1404 Request::CommitSemanticallyVerifiedBlock(semantically_verified),
1405 Some(contextual),
1406 )
1407 }
1408 req => (req, None),
1409 };
1410
1411 match req {
1412 Request::CommitSemanticallyVerifiedBlock(semantically_verified) => {
1417 let timer = CodeTimer::start();
1418 self.assert_block_can_be_validated(&semantically_verified);
1419
1420 self.pending_utxos
1421 .check_against_ordered(&semantically_verified.new_outputs);
1422
1423 let rsp_rx = tokio::task::block_in_place(move || {
1435 span.in_scope(|| {
1436 self.queue_and_commit_to_non_finalized_state(
1437 semantically_verified,
1438 contextual,
1439 )
1440 })
1441 });
1442
1443 timer.finish_desc("CommitSemanticallyVerifiedBlock");
1449
1450 let span = Span::current();
1454 async move {
1455 rsp_rx
1456 .await
1457 .map_err(|_recv_error| CommitBlockError::WriteTaskExited.into())
1458 .and_then(|result| result)
1459 .map_err(BoxError::from)
1460 .map(Response::Committed)
1461 }
1462 .instrument(span)
1463 .boxed()
1464 }
1465
1466 Request::CommitCheckpointVerifiedBlock(finalized) => {
1471 let timer = CodeTimer::start();
1472 self.pending_utxos
1486 .check_against_ordered(&finalized.new_outputs);
1487
1488 let rsp_rx = self.queue_and_commit_to_finalized_state(finalized);
1493
1494 timer.finish_desc("CommitCheckpointVerifiedBlock");
1500
1501 async move {
1505 rsp_rx
1506 .await
1507 .map_err(|_recv_error| CommitBlockError::WriteTaskExited.into())
1508 .and_then(|result| result)
1509 .map_err(BoxError::from)
1510 .map(Response::Committed)
1511 }
1512 .instrument(span)
1513 .boxed()
1514 }
1515
1516 Request::AwaitUtxo(outpoint) => {
1521 let timer = CodeTimer::start();
1522 let response_fut = self.pending_utxos.queue(outpoint);
1524 let response_fut = response_fut
1528 .map(|result| result.map_err(BoxError::from))
1529 .instrument(span)
1530 .boxed();
1531
1532 if let Some(utxo) = self.non_finalized_state_queued_blocks.utxo(&outpoint) {
1535 self.pending_utxos.respond(&outpoint, utxo);
1536
1537 timer.finish_desc("AwaitUtxo/queued-non-finalized");
1539
1540 return response_fut;
1541 }
1542
1543 self.drain_finalized_resets();
1545 self.drain_non_finalized_rejected_hashes();
1546
1547 if let Some(utxo) = self.non_finalized_block_write_sent_hashes.utxo(&outpoint) {
1548 self.pending_utxos.respond(&outpoint, utxo);
1549
1550 timer.finish_desc("AwaitUtxo/sent-non-finalized");
1552
1553 return response_fut;
1554 }
1555
1556 let read_service = self.read_service.clone();
1565
1566 async move {
1568 let req = ReadRequest::AnyChainUtxo(outpoint);
1569
1570 let rsp = read_service
1571 .oneshot(req)
1572 .await
1573 .map_err(AwaitUtxoError::ReadStateFailed)?;
1574
1575 if let ReadResponse::AnyChainUtxo(Some(utxo)) = rsp {
1588 timer.finish_desc("AwaitUtxo/any-chain");
1590
1591 return Ok(Response::Utxo(utxo));
1592 }
1593
1594 timer.finish_desc("AwaitUtxo/waiting");
1596
1597 response_fut.await
1598 }
1599 .boxed()
1600 }
1601
1602 Request::KnownBlock(hash) => {
1605 let timer = CodeTimer::start();
1606
1607 self.drain_finalized_resets();
1609 self.drain_non_finalized_rejected_hashes();
1610
1611 let known_sent_hash = self.known_sent_hash(&hash);
1612 let known_queued = self
1613 .non_finalized_state_queued_blocks
1614 .has(hash)
1615 .then_some(KnownBlock::Queue);
1616 let read_service = self.read_service.clone();
1617
1618 async move {
1619 if let Some(loc) = known_sent_hash.or(known_queued) {
1620 return Ok(Response::KnownBlock(Some(loc)));
1621 };
1622
1623 let response = read::non_finalized_state_contains_block_hash(
1624 &read_service.latest_non_finalized_state(),
1625 hash,
1626 )
1627 .or_else(|| read::finalized_state_contains_block_hash(&read_service.db, hash));
1629
1630 timer.finish_desc("Request::KnownBlock");
1631
1632 Ok(Response::KnownBlock(response))
1633 }
1634 .boxed()
1635 }
1636
1637 Request::InvalidateBlock(block_hash) => {
1639 let rsp_rx = tokio::task::block_in_place(move || {
1640 span.in_scope(|| self.send_invalidate_block(block_hash))
1641 });
1642
1643 let span = Span::current();
1647 async move {
1648 rsp_rx
1649 .await
1650 .map_err(|_recv_error| InvalidateError::InvalidateRequestDropped)
1651 .and_then(|result| result)
1652 .map_err(BoxError::from)
1653 .map(Response::Invalidated)
1654 }
1655 .instrument(span)
1656 .boxed()
1657 }
1658
1659 Request::ReconsiderBlock(block_hash) => {
1661 let rsp_rx = tokio::task::block_in_place(move || {
1662 span.in_scope(|| self.send_reconsider_block(block_hash))
1663 });
1664
1665 let span = Span::current();
1669 async move {
1670 rsp_rx
1671 .await
1672 .map_err(|_recv_error| ReconsiderError::ReconsiderResponseDropped)
1673 .and_then(|result| result)
1674 .map_err(BoxError::from)
1675 .map(Response::Reconsidered)
1676 }
1677 .instrument(span)
1678 .boxed()
1679 }
1680
1681 Request::CommitContextuallyVerifiedBlock(_) => {
1682 unreachable!("converted to a semantically verified commit above")
1683 }
1684
1685 Request::MiningCandidate(block) => {
1686 let guard = self.start_mining_candidate(block);
1687
1688 async move { Ok(Response::MiningCandidate(guard)) }.boxed()
1689 }
1690
1691 Request::Tip
1693 | Request::Depth(_)
1694 | Request::BestChainNextMedianTimePast
1695 | Request::BestChainBlockHash(_)
1696 | Request::BlockLocator
1697 | Request::Transaction(_)
1698 | Request::AnyChainTransaction(_)
1699 | Request::UnspentBestChainUtxo(_)
1700 | Request::Block(_)
1701 | Request::AnyChainBlock(_)
1702 | Request::BlockAndSize(_)
1703 | Request::BlockHeader(_)
1704 | Request::FindBlockHashes { .. }
1705 | Request::FindBlockHeaders { .. }
1706 | Request::CheckBestChainTipNullifiersAndAnchors(_)
1707 | Request::CheckBlockProposalValidity(_) => {
1708 let read_service = self.read_service.clone();
1710
1711 async move {
1712 let req = req
1713 .try_into()
1714 .expect("ReadRequest conversion should not fail");
1715
1716 let rsp = read_service.oneshot(req).await?;
1717 let rsp = rsp.try_into().expect("Response conversion should not fail");
1718
1719 Ok(rsp)
1720 }
1721 .boxed()
1722 }
1723 }
1724 }
1725}
1726
1727impl Service<ReadRequest> for ReadStateService {
1728 type Response = ReadResponse;
1729 type Error = BoxError;
1730 type Future =
1731 Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
1732
1733 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1734 let block_write_task = self.block_write_task.take();
1738
1739 if let Some(block_write_task) = block_write_task {
1740 if block_write_task.is_finished() {
1741 if let Some(block_write_task) = Arc::into_inner(block_write_task) {
1742 if let Err(thread_panic) = block_write_task.join() {
1744 std::panic::resume_unwind(thread_panic);
1745 }
1746 }
1747 } else {
1748 self.block_write_task = Some(block_write_task);
1750 }
1751 }
1752
1753 self.db.check_for_panics();
1754
1755 Poll::Ready(Ok(()))
1756 }
1757
1758 #[instrument(name = "read_state", level = "debug", skip(self, req))]
1759 fn call(&mut self, req: ReadRequest) -> Self::Future {
1760 req.count_metric();
1761 let timer = CodeTimer::start_desc(req.variant_name());
1762 let span = Span::current();
1763 let timed_span = TimedSpan::new(timer, span);
1764 let state = self.clone();
1765
1766 if let ReadRequest::NonFinalizedBlocksListener { known_chain_tips } = req {
1767 let non_finalized_blocks_listener = NonFinalizedBlocksListener::spawn(
1770 self.non_finalized_state_receiver.clone(),
1771 known_chain_tips,
1772 );
1773
1774 return async move {
1775 Ok(ReadResponse::NonFinalizedBlocksListener(
1776 non_finalized_blocks_listener,
1777 ))
1778 }
1779 .boxed();
1780 };
1781
1782 let request_handler = move || match req {
1783 ReadRequest::CheckBestTipHeader { header, height } => {
1784 read::difficulty::check_best_tip_header(
1785 &state.latest_non_finalized_state(),
1786 &state.db,
1787 &state.network,
1788 &header,
1789 height,
1790 )?;
1791 Ok(ReadResponse::ValidBestTipHeader)
1792 }
1793
1794 ReadRequest::CheckBestTipBlockCommitments(block) => {
1795 read::difficulty::check_best_tip_block_commitments(
1796 &state.latest_non_finalized_state(),
1797 &state.db,
1798 &state.network,
1799 block,
1800 )?;
1801 Ok(ReadResponse::ValidBestTipBlockCommitments)
1802 }
1803
1804 ReadRequest::UsageInfo => Ok(ReadResponse::UsageInfo(state.db.size())),
1806
1807 ReadRequest::Tip => Ok(ReadResponse::Tip(read::tip(
1809 state.latest_best_chain(),
1810 &state.db,
1811 ))),
1812
1813 ReadRequest::TipPoolValues => {
1815 let (tip_height, tip_hash, value_balance) =
1816 read::tip_with_value_balance(state.latest_best_chain(), &state.db)?
1817 .ok_or(BoxError::from("no chain tip available yet"))?;
1818
1819 Ok(ReadResponse::TipPoolValues {
1820 tip_height,
1821 tip_hash,
1822 value_balance,
1823 })
1824 }
1825
1826 ReadRequest::BlockInfo(hash_or_height) => Ok(ReadResponse::BlockInfo(
1828 read::block_info(state.latest_best_chain(), &state.db, hash_or_height),
1829 )),
1830
1831 ReadRequest::Depth(hash) => Ok(ReadResponse::Depth(read::depth(
1833 state.latest_best_chain(),
1834 &state.db,
1835 hash,
1836 ))),
1837
1838 ReadRequest::BestChainNextMedianTimePast => {
1840 Ok(ReadResponse::BestChainNextMedianTimePast(
1841 read::next_median_time_past(&state.latest_non_finalized_state(), &state.db)?,
1842 ))
1843 }
1844
1845 ReadRequest::Block(hash_or_height) => Ok(ReadResponse::Block(read::block(
1847 state.latest_best_chain(),
1848 &state.db,
1849 hash_or_height,
1850 )?)),
1851
1852 ReadRequest::AnyChainBlock(hash_or_height) => Ok(ReadResponse::Block(read::any_block(
1853 state.latest_non_finalized_state().chain_iter(),
1854 &state.db,
1855 hash_or_height,
1856 )?)),
1857
1858 ReadRequest::BlockAndSize(hash_or_height) => Ok(ReadResponse::BlockAndSize(
1860 read::block_and_size(state.latest_best_chain(), &state.db, hash_or_height)?,
1861 )),
1862
1863 ReadRequest::SpentOutputs(hash_or_height) => {
1865 Ok(ReadResponse::SpentOutputs(read::spent_outputs_for_block(
1866 state.latest_best_chain(),
1867 &state.db,
1868 hash_or_height,
1869 )?))
1870 }
1871
1872 ReadRequest::BlockHeader(hash_or_height) => {
1874 let best_chain = state.latest_best_chain();
1875
1876 let height = hash_or_height
1877 .height_or_else(|hash| {
1878 read::find::height_by_hash(best_chain.clone(), &state.db, hash)
1879 })
1880 .ok_or_else(|| BoxError::from("block hash or height not found"))?;
1881
1882 let hash = hash_or_height
1883 .hash_or_else(|height| {
1884 read::find::hash_by_height(best_chain.clone(), &state.db, height)
1885 })
1886 .ok_or_else(|| BoxError::from("block hash or height not found"))?;
1887
1888 let next_height = height.next()?;
1889 let next_block_hash =
1890 read::find::hash_by_height(best_chain.clone(), &state.db, next_height);
1891
1892 let header = read::block_header(best_chain, &state.db, height.into())
1893 .ok_or_else(|| BoxError::from("block hash or height not found"))?;
1894
1895 Ok(ReadResponse::BlockHeader {
1896 header,
1897 hash,
1898 height,
1899 next_block_hash,
1900 })
1901 }
1902
1903 ReadRequest::Transaction(hash) => Ok(ReadResponse::Transaction(
1905 read::mined_transaction(state.latest_best_chain(), &state.db, hash),
1906 )),
1907
1908 ReadRequest::AnyChainTransaction(hash) => {
1909 Ok(ReadResponse::AnyChainTransaction(read::any_transaction(
1910 state.latest_non_finalized_state().chain_iter(),
1911 &state.db,
1912 hash,
1913 )))
1914 }
1915
1916 ReadRequest::TransactionIdsForBlock(hash_or_height) => Ok(
1918 ReadResponse::TransactionIdsForBlock(read::transaction_hashes_for_block(
1919 state.latest_best_chain(),
1920 &state.db,
1921 hash_or_height,
1922 )),
1923 ),
1924
1925 ReadRequest::AnyChainTransactionIdsForBlock(hash_or_height) => {
1926 Ok(ReadResponse::AnyChainTransactionIdsForBlock(
1927 read::transaction_hashes_for_any_block(
1928 state.latest_non_finalized_state().chain_iter(),
1929 &state.db,
1930 hash_or_height,
1931 ),
1932 ))
1933 }
1934
1935 #[cfg(feature = "indexer")]
1936 ReadRequest::SpendingTransactionId(spend) => Ok(ReadResponse::TransactionId(
1937 read::spending_transaction_hash(state.latest_best_chain(), &state.db, spend),
1938 )),
1939
1940 ReadRequest::UnspentBestChainUtxo(outpoint) => Ok(ReadResponse::UnspentBestChainUtxo(
1941 read::unspent_utxo(state.latest_best_chain(), &state.db, outpoint),
1942 )),
1943
1944 ReadRequest::AnyChainUtxo(outpoint) => Ok(ReadResponse::AnyChainUtxo(read::any_utxo(
1946 state.latest_non_finalized_state(),
1947 &state.db,
1948 outpoint,
1949 ))),
1950
1951 ReadRequest::BlockLocator => Ok(ReadResponse::BlockLocator(
1953 read::block_locator(state.latest_best_chain(), &state.db).unwrap_or_default(),
1954 )),
1955
1956 ReadRequest::FindBlockHashes { known_blocks, stop } => {
1958 Ok(ReadResponse::BlockHashes(read::find_chain_hashes(
1959 state.latest_best_chain(),
1960 &state.db,
1961 known_blocks,
1962 stop,
1963 MAX_FIND_BLOCK_HASHES_RESULTS,
1964 )))
1965 }
1966
1967 ReadRequest::FindBlockHeaders { known_blocks, stop } => Ok(ReadResponse::BlockHeaders(
1969 read::find_chain_headers(
1970 state.latest_best_chain(),
1971 &state.db,
1972 known_blocks,
1973 stop,
1974 MAX_FIND_BLOCK_HEADERS_RESULTS,
1975 )
1976 .into_iter()
1977 .map(|header| CountedHeader { header })
1978 .collect(),
1979 )),
1980
1981 ReadRequest::FindForkPoint { known_blocks } => {
1982 let locator_len: u64 = known_blocks
1985 .len()
1986 .try_into()
1987 .expect("usize always fits in u64 on supported (<=64-bit) platforms");
1988 if locator_len > block::MAX_BLOCK_LOCATOR_LENGTH {
1989 return Err(BoxError::from(format!(
1990 "FindForkPoint locator length {locator_len} exceeds \
1991 MAX_BLOCK_LOCATOR_LENGTH ({})",
1992 block::MAX_BLOCK_LOCATOR_LENGTH,
1993 )));
1994 }
1995
1996 Ok(ReadResponse::ForkPoint(read::find_fork_point(
1997 state.latest_best_chain(),
1998 &state.db,
1999 known_blocks,
2000 )))
2001 }
2002
2003 ReadRequest::SaplingTree(hash_or_height) => Ok(ReadResponse::SaplingTree(
2004 read::sapling_tree(state.latest_best_chain(), &state.db, hash_or_height),
2005 )),
2006
2007 ReadRequest::OrchardTree(hash_or_height) => Ok(ReadResponse::OrchardTree(
2008 read::orchard_tree(state.latest_best_chain(), &state.db, hash_or_height),
2009 )),
2010
2011 ReadRequest::AnyChainSaplingTree(hash) => {
2012 Ok(ReadResponse::SaplingTree(read::any_sapling_tree(
2013 state.latest_non_finalized_state().chain_iter(),
2014 &state.db,
2015 hash,
2016 )))
2017 }
2018
2019 ReadRequest::AnyChainOrchardTree(hash) => {
2020 Ok(ReadResponse::OrchardTree(read::any_orchard_tree(
2021 state.latest_non_finalized_state().chain_iter(),
2022 &state.db,
2023 hash,
2024 )))
2025 }
2026
2027 ReadRequest::IronwoodTree(hash_or_height) => Ok(ReadResponse::IronwoodTree(
2028 read::ironwood_tree(state.latest_best_chain(), &state.db, hash_or_height),
2029 )),
2030
2031 ReadRequest::AnyChainIronwoodTree(hash) => {
2032 Ok(ReadResponse::IronwoodTree(read::any_ironwood_tree(
2033 state.latest_non_finalized_state().chain_iter(),
2034 &state.db,
2035 hash,
2036 )))
2037 }
2038
2039 ReadRequest::SaplingSubtrees { start_index, limit } => {
2040 let end_index = limit
2041 .and_then(|limit| start_index.0.checked_add(limit.0))
2042 .map(NoteCommitmentSubtreeIndex);
2043
2044 let best_chain = state.latest_best_chain();
2045 let sapling_subtrees = if let Some(end_index) = end_index {
2046 read::sapling_subtrees(best_chain, &state.db, start_index..end_index)
2047 } else {
2048 read::sapling_subtrees(best_chain, &state.db, start_index..)
2053 };
2054
2055 Ok(ReadResponse::SaplingSubtrees(sapling_subtrees))
2056 }
2057
2058 ReadRequest::OrchardSubtrees { start_index, limit } => {
2059 let end_index = limit
2060 .and_then(|limit| start_index.0.checked_add(limit.0))
2061 .map(NoteCommitmentSubtreeIndex);
2062
2063 let best_chain = state.latest_best_chain();
2064 let orchard_subtrees = if let Some(end_index) = end_index {
2065 read::orchard_subtrees(best_chain, &state.db, start_index..end_index)
2066 } else {
2067 read::orchard_subtrees(best_chain, &state.db, start_index..)
2072 };
2073
2074 Ok(ReadResponse::OrchardSubtrees(orchard_subtrees))
2075 }
2076
2077 ReadRequest::IronwoodSubtrees { start_index, limit } => {
2078 let end_index = limit
2079 .and_then(|limit| start_index.0.checked_add(limit.0))
2080 .map(NoteCommitmentSubtreeIndex);
2081
2082 let best_chain = state.latest_best_chain();
2083 let ironwood_subtrees = if let Some(end_index) = end_index {
2084 read::ironwood_subtrees(best_chain, &state.db, start_index..end_index)
2085 } else {
2086 read::ironwood_subtrees(best_chain, &state.db, start_index..)
2091 };
2092
2093 Ok(ReadResponse::IronwoodSubtrees(ironwood_subtrees))
2094 }
2095
2096 ReadRequest::AddressBalance(addresses) => {
2098 let (balance, received) =
2099 read::transparent_balance(state.latest_best_chain(), &state.db, addresses)?;
2100 Ok(ReadResponse::AddressBalance { balance, received })
2101 }
2102
2103 ReadRequest::TransactionIdsByAddresses {
2105 addresses,
2106 height_range,
2107 max_entries,
2108 } => read::transparent_tx_ids(
2109 state.latest_best_chain(),
2110 &state.db,
2111 addresses,
2112 height_range,
2113 max_entries,
2114 )
2115 .map(ReadResponse::AddressesTransactionIds),
2116
2117 ReadRequest::UtxosByAddresses {
2119 addresses,
2120 height_range,
2121 max_entries,
2122 } => read::address_utxos(
2123 &state.network,
2124 state.latest_best_chain(),
2125 &state.db,
2126 addresses,
2127 height_range,
2128 max_entries,
2129 )
2130 .map(ReadResponse::AddressUtxos),
2131
2132 ReadRequest::CheckBestChainTipNullifiersAndAnchors(unmined_tx) => {
2133 let latest_non_finalized_best_chain = state.latest_best_chain();
2134
2135 check::nullifier::tx_no_duplicates_in_chain(
2136 &state.db,
2137 latest_non_finalized_best_chain.as_ref(),
2138 &unmined_tx.transaction,
2139 )?;
2140
2141 check::anchors::tx_anchors_refer_to_final_treestates(
2142 &state.db,
2143 latest_non_finalized_best_chain.as_ref(),
2144 &unmined_tx,
2145 )?;
2146
2147 Ok(ReadResponse::ValidBestChainTipNullifiersAndAnchors)
2148 }
2149
2150 ReadRequest::BestChainBlockHash(height) => Ok(ReadResponse::BlockHash(
2152 read::hash_by_height(state.latest_best_chain(), &state.db, height),
2153 )),
2154
2155 ReadRequest::ChainInfo => {
2157 read::difficulty::get_block_template_chain_info(
2169 &state.latest_non_finalized_state(),
2170 &state.db,
2171 &state.network,
2172 )
2173 .map(ReadResponse::ChainInfo)
2174 }
2175
2176 ReadRequest::MiningCandidate => {
2178 let candidate = state.mining_candidate.borrow().clone();
2182 let tip_hash = state.best_tip().map(|(_, hash)| hash);
2183
2184 Ok(ReadResponse::MiningCandidate(
2185 candidate
2186 .filter(|candidate| Some(candidate.parent_hash) == tip_hash)
2187 .map(|candidate| candidate.chain_info),
2188 ))
2189 }
2190
2191 ReadRequest::MiningCandidateChanges => Ok(ReadResponse::MiningCandidateChanges(
2193 MiningCandidateChanges(state.mining_candidate.subscribe()),
2194 )),
2195
2196 ReadRequest::SolutionRate { num_blocks, height } => {
2198 let latest_non_finalized_state = state.latest_non_finalized_state();
2199 let (tip_height, tip_hash) =
2207 match read::tip(latest_non_finalized_state.best_chain(), &state.db) {
2208 Some(tip_hash) => tip_hash,
2209 None => return Ok(ReadResponse::SolutionRate(None)),
2210 };
2211
2212 let start_height = height.map_or(tip_height, |height| height.min(tip_height));
2213 let start_hash = if start_height < tip_height {
2214 read::hash_by_height(
2215 latest_non_finalized_state.best_chain(),
2216 &state.db,
2217 start_height,
2218 )
2219 } else {
2220 Some(tip_hash)
2221 };
2222 let num_blocks = num_blocks.unwrap_or_else(|| {
2223 NetworkUpgrade::averaging_window_for_height(&state.network, start_height)
2224 });
2225
2226 let solution_rate = start_hash.and_then(|start_hash| {
2227 read::difficulty::solution_rate(
2228 &latest_non_finalized_state,
2229 &state.db,
2230 num_blocks,
2231 start_hash,
2232 )
2233 });
2234
2235 Ok(ReadResponse::SolutionRate(solution_rate))
2236 }
2237
2238 ReadRequest::CheckBlockProposalValidity(semantically_verified) => {
2239 tracing::debug!(
2240 "attempting to validate and commit block proposal \
2241 onto a cloned non-finalized state"
2242 );
2243 let mut latest_non_finalized_state = state.latest_non_finalized_state();
2244
2245 let Some((_best_tip_height, best_tip_hash)) =
2247 read::best_tip(&latest_non_finalized_state, &state.db)
2248 else {
2249 return Err(
2250 "state is empty: wait for Zebra to sync before submitting a proposal"
2251 .into(),
2252 );
2253 };
2254
2255 if semantically_verified.block.header.previous_block_hash != best_tip_hash {
2256 return Err("proposal is not based on the current best chain tip: \
2257 previous block hash must be the best chain tip"
2258 .into());
2259 }
2260
2261 latest_non_finalized_state.disable_metrics();
2267
2268 let hash = semantically_verified.hash;
2269 write::validate_and_commit_non_finalized(
2270 &state.db,
2271 &mut latest_non_finalized_state,
2272 semantically_verified,
2273 )?;
2274
2275 let chain = latest_non_finalized_state
2278 .remove_chain_with_tip(hash)
2279 .expect("successful proposal validation inserted its block");
2280 let contextual = chain
2281 .tip_block()
2282 .expect("the chain has the proposal at its tip")
2283 .clone();
2284 latest_non_finalized_state.store_prepared_chain(chain);
2285
2286 Ok(ReadResponse::ValidBlockProposal(Box::new(contextual)))
2287 }
2288
2289 ReadRequest::TipBlockSize => {
2290 let size = state
2291 .best_tip()
2292 .and_then(|(tip_height, _)| {
2293 read::block_info(state.latest_best_chain(), &state.db, tip_height.into())
2294 })
2295 .map(|info| info.size().try_into().expect("u32 should fit in usize"));
2296 let size = match size {
2297 Some(size) => Some(size),
2298 None => find::tip_block(state.latest_best_chain(), &state.db)?
2299 .map(|block| block.zcash_serialized_size()),
2300 };
2301 Ok(ReadResponse::TipBlockSize(size))
2302 }
2303
2304 ReadRequest::NonFinalizedBlocksListener { .. } => {
2305 unreachable!("should return early");
2306 }
2307
2308 ReadRequest::IsTransparentOutputSpent(outpoint) => {
2310 let is_spent = read::unspent_utxo(state.latest_best_chain(), &state.db, outpoint);
2311 Ok(ReadResponse::IsTransparentOutputSpent(is_spent.is_none()))
2312 }
2313 };
2314
2315 timed_span.spawn_blocking(request_handler)
2316 }
2317}
2318
2319pub async fn init(
2335 config: Config,
2336 network: &Network,
2337 max_checkpoint_height: block::Height,
2338 checkpoint_verify_concurrency_limit: usize,
2339) -> (
2340 BoxService<Request, Response, BoxError>,
2341 ReadStateService,
2342 LatestChainTip,
2343 ChainTipChange,
2344) {
2345 let (state_service, read_only_state_service, latest_chain_tip, chain_tip_change) =
2346 StateService::new(
2347 config,
2348 network,
2349 max_checkpoint_height,
2350 checkpoint_verify_concurrency_limit,
2351 )
2352 .await;
2353
2354 (
2355 BoxService::new(state_service),
2356 read_only_state_service,
2357 latest_chain_tip,
2358 chain_tip_change,
2359 )
2360}
2361
2362pub fn init_read_only(
2369 config: Config,
2370 network: &Network,
2371) -> Result<
2372 (
2373 ReadStateService,
2374 ZebraDb,
2375 tokio::sync::watch::Sender<NonFinalizedState>,
2376 ),
2377 StateInitError,
2378> {
2379 let finalized_state = FinalizedState::new_with_debug(&config, network, true, true)?;
2380 let (non_finalized_state_sender, non_finalized_state_receiver) =
2381 tokio::sync::watch::channel(NonFinalizedState::new(network));
2382
2383 Ok((
2384 ReadStateService::new(
2385 &finalized_state,
2386 None,
2387 WatchReceiver::new(non_finalized_state_receiver),
2388 ),
2389 finalized_state.db.clone(),
2390 non_finalized_state_sender,
2391 ))
2392}
2393
2394pub fn spawn_init_read_only(
2401 config: Config,
2402 network: &Network,
2403) -> tokio::task::JoinHandle<
2404 Result<
2405 (
2406 ReadStateService,
2407 ZebraDb,
2408 tokio::sync::watch::Sender<NonFinalizedState>,
2409 ),
2410 StateInitError,
2411 >,
2412> {
2413 let network = network.clone();
2414 tokio::task::spawn_blocking(move || init_read_only(config, &network))
2415}
2416
2417#[cfg(any(test, feature = "proptest-impl"))]
2421pub async fn init_test(
2422 network: &Network,
2423) -> Buffer<BoxService<Request, Response, BoxError>, Request> {
2424 let (state_service, _, _, _) =
2427 StateService::new(Config::ephemeral(), network, block::Height::MAX, 0).await;
2428
2429 Buffer::new(BoxService::new(state_service), 1)
2430}
2431
2432#[cfg(any(test, feature = "proptest-impl"))]
2437pub async fn init_test_services(
2438 network: &Network,
2439) -> (
2440 Buffer<BoxService<Request, Response, BoxError>, Request>,
2441 ReadStateService,
2442 LatestChainTip,
2443 ChainTipChange,
2444) {
2445 let (state_service, read_state_service, latest_chain_tip, chain_tip_change) =
2448 StateService::new(Config::ephemeral(), network, block::Height::MAX, 0).await;
2449
2450 let state_service = Buffer::new(BoxService::new(state_service), 1);
2451
2452 (
2453 state_service,
2454 read_state_service,
2455 latest_chain_tip,
2456 chain_tip_change,
2457 )
2458}