Skip to main content

zebra_state/
service.rs

1//! [`tower::Service`]s for Zebra's cached chain state.
2//!
3//! Zebra provides cached state access via two main services:
4//! - [`StateService`]: a read-write service that writes blocks to the state,
5//!   and redirects most read requests to the [`ReadStateService`].
6//! - [`ReadStateService`]: a read-only service that answers from the most
7//!   recent committed block.
8//!
9//! Most users should prefer [`ReadStateService`], unless they need to write blocks to the state.
10//!
11//! Zebra also provides access to the best chain tip via:
12//! - [`LatestChainTip`]: a read-only channel that contains the latest committed
13//!   tip.
14//! - [`ChainTipChange`]: a read-only channel that can asynchronously await
15//!   chain tip changes.
16
17use 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/// A read-write service for Zebra's cached blockchain state.
96///
97/// This service modifies and provides access to:
98/// - the non-finalized state: the most recent blocks, up to
99///   [`MAX_BLOCK_REORG_HEIGHT`](crate::MAX_BLOCK_REORG_HEIGHT) of them.
100///   Zebra allows chain forks in the non-finalized state,
101///   stores it in memory, and re-downloads it when restarted.
102/// - the finalized state: older blocks that have many confirmations.
103///   Zebra stores the single best chain in the finalized state,
104///   and re-loads it from disk when restarted.
105///
106/// Read requests to this service are buffered, then processed concurrently.
107/// Block write requests are buffered, then queued, then processed in order by a separate task.
108///
109/// Most state users can get faster read responses using the [`ReadStateService`],
110/// because its requests do not share a [`tower::buffer::Buffer`] with block write requests.
111///
112/// To quickly get the latest block, use [`LatestChainTip`] or [`ChainTipChange`].
113/// They can read the latest block directly, without queueing any requests.
114#[derive(Debug)]
115pub(crate) struct StateService {
116    // Configuration
117    //
118    /// The configured Zcash network.
119    network: Network,
120
121    /// The height of the final checkpoint, or [`block::Height::MAX`] if there isn't one.
122    ///
123    /// Checkpoint verified blocks are written to the finalized state up to this height.
124    max_checkpoint_height: block::Height,
125
126    /// The height that we start storing UTXOs from finalized blocks.
127    ///
128    /// This height should be lower than the last few checkpoints,
129    /// so the full verifier can verify UTXO spends from those blocks,
130    /// even if they haven't been committed to the finalized state yet.
131    full_verifier_utxo_lookahead: block::Height,
132
133    // Queued Blocks
134    //
135    /// Queued blocks for the [`NonFinalizedState`] that arrived out of order.
136    /// These blocks are awaiting their parent blocks before they can do contextual verification.
137    non_finalized_state_queued_blocks: QueuedBlocks,
138
139    /// Queued blocks for the [`FinalizedState`] that arrived out of order.
140    /// These blocks are awaiting their parent blocks before they can do contextual verification.
141    ///
142    /// Indexed by their parent block hash.
143    finalized_state_queued_blocks: HashMap<block::Hash, QueuedCheckpointVerified>,
144
145    /// Channels to send blocks to the block write task.
146    block_write_sender: write::BlockWriteSender,
147
148    /// The [`block::Hash`] of the most recent block sent on
149    /// `finalized_block_write_sender` or `non_finalized_block_write_sender`.
150    ///
151    /// On startup, this is:
152    /// - the finalized tip, if there are stored blocks, or
153    /// - the genesis block's parent hash, if the database is empty.
154    ///
155    /// If `invalid_block_write_reset_receiver` gets a reset, this is:
156    /// - the hash of the last valid committed block (the parent of the invalid block).
157    finalized_block_write_last_sent_hash: block::Hash,
158
159    /// After a finalized reset, the height the checkpoint verifier restarts from.
160    ///
161    /// Until a block at this height is queued, higher blocks are leftovers of the failed range:
162    /// they can never chain to the reset tip, so they are rejected instead of being queued.
163    finalized_reset_next_height: Option<block::Height>,
164
165    /// A set of block hashes that have been sent to the block write task.
166    /// Hashes of blocks below the finalized tip height are periodically pruned.
167    non_finalized_block_write_sent_hashes: SentHashes,
168
169    /// If an invalid block is sent on `finalized_block_write_sender`,
170    /// this channel gets the height and [`block::Hash`] of the valid finalized tip.
171    //
172    // TODO: add tests for non-finalized resets (#2654)
173    invalid_block_write_reset_receiver:
174        tokio::sync::mpsc::UnboundedReceiver<(Option<block::Height>, block::Hash)>,
175
176    /// Receives the hash of every non-finalized block that the write task
177    /// rejected, so the corresponding entry can be removed from
178    /// `non_finalized_block_write_sent_hashes`.
179    ///
180    /// Without this, a rejected same-hash block locks out a later honest
181    /// re-delivery of a block at the same hash as a "duplicate" until restart
182    /// or reorg.
183    non_finalized_rejected_receiver:
184        tokio::sync::mpsc::UnboundedReceiver<write::NonFinalizedWriteOutcome>,
185
186    // Pending UTXO Request Tracking
187    //
188    /// The set of outpoints with pending requests for their associated transparent::Output.
189    pending_utxos: PendingUtxos,
190
191    /// Instant tracking the last time `pending_utxos` was pruned.
192    last_prune: Instant,
193
194    // Updating Concurrently Readable State
195    //
196    /// A cloneable [`ReadStateService`], used to answer concurrent read requests.
197    ///
198    /// TODO: move users of read [`Request`]s to [`ReadStateService`], and remove `read_service`.
199    read_service: ReadStateService,
200
201    /// The task that publishes and withdraws the current mining candidate's early work.
202    ///
203    /// The state handles one candidate at a time, until this task finishes. That bounds the
204    /// work that blocks with a valid proof of work can queue on the block write task, and means
205    /// a published candidate is never replaced by another block while it is being verified.
206    mining_candidate_task: Option<tokio::task::JoinHandle<()>>,
207
208    // Metrics
209    //
210    /// A metric tracking the maximum height that's currently in `finalized_state_queued_blocks`
211    ///
212    /// Set to `f64::NAN` if `finalized_state_queued_blocks` is empty, because grafana shows NaNs
213    /// as a break in the graph.
214    max_finalized_queue_height: f64,
215}
216
217/// A read-only service for accessing Zebra's cached blockchain state.
218///
219/// This service provides read-only access to:
220/// - the non-finalized state: the most recent blocks, up to
221///   [`MAX_BLOCK_REORG_HEIGHT`](crate::MAX_BLOCK_REORG_HEIGHT) of them.
222/// - the finalized state: older blocks that have many confirmations.
223///
224/// Requests to this service are processed in parallel,
225/// ignoring any blocks queued by the read-write [`StateService`].
226///
227/// This quick response behavior is better for most state users.
228/// It allows other async tasks to make progress while concurrently reading data from disk.
229#[derive(Clone, Debug)]
230pub struct ReadStateService {
231    // Configuration
232    //
233    /// The configured Zcash network.
234    network: Network,
235
236    // Shared Concurrently Readable State
237    //
238    /// A watch channel with a cached copy of the [`NonFinalizedState`].
239    ///
240    /// This state is only updated between requests,
241    /// so it might include some block data that is also on `disk`.
242    non_finalized_state_receiver: WatchReceiver<NonFinalizedState>,
243
244    /// The shared inner on-disk database for the finalized state.
245    ///
246    /// RocksDB allows reads and writes via a shared reference,
247    /// but [`ZebraDb`] doesn't expose any write methods or types.
248    ///
249    /// This chain is updated concurrently with requests,
250    /// so it might include some block data that is also in `best_mem`.
251    db: ZebraDb,
252
253    /// A shared handle to a task that writes blocks to the [`NonFinalizedState`] or [`FinalizedState`],
254    /// once the queues have received all their parent blocks.
255    ///
256    /// Used to check for panics when writing blocks.
257    block_write_task: Option<Arc<std::thread::JoinHandle<()>>>,
258
259    /// The early mining work on a block that is still being verified, if there is any.
260    ///
261    /// The state only computes it while there are subscribers to this channel.
262    mining_candidate: watch::Sender<Option<MiningCandidate>>,
263}
264
265/// Early mining work on a block whose proof of work is valid, but which is still being verified.
266#[derive(Clone, Debug)]
267pub(crate) struct MiningCandidate {
268    /// The hash of the block's parent, which was the best tip when the work was computed.
269    parent_hash: block::Hash,
270
271    /// The state information for building a block template on top of the block.
272    chain_info: GetBlockTemplateChainInfo,
273}
274
275#[cfg(any(test, feature = "proptest-impl"))]
276impl MiningCandidate {
277    /// Returns early mining work for tests.
278    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
289/// How long early mining work on a block stays available while the block is being verified.
290///
291/// Blocks are verified in well under a second. This bounds how long miners build on a block with
292/// a valid proof of work whose verification has stalled, for example on a transparent input that
293/// doesn't exist. A block that takes longer to verify is mined on once it is committed, as it
294/// would be without early work.
295const MINING_CANDIDATE_TIMEOUT: Duration = Duration::from_secs(1);
296
297/// Publishes the early mining work on a block to `candidates`, and withdraws the work when the
298/// verifier's guard is dropped, or after [`MINING_CANDIDATE_TIMEOUT`].
299///
300/// `chain_info` is the block write task's answer for the block, and `verification` is the
301/// receiver for the verifier's [`MiningCandidateGuard`].
302async 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    // The verifier drops the guard when the block is committed or rejected. If it did that
313    // while the work was being computed, there is nothing to publish.
314    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        // The state service owns the state, tasks, and channels,
332        // so dropping it should shut down everything.
333
334        // Close the channels (non-blocking)
335        // This makes the block write thread exit the next time it checks the channels.
336        // We want to do this here so we get any errors or panics from the block write task before it shuts down.
337        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        // Log database metrics before shutting down
347        info!("dropping the state: logging database metrics");
348        self.log_db_metrics();
349
350        // Then drop self.read_service, which checks the block write task for panics,
351        // and tries to shut down the database.
352    }
353}
354
355impl Drop for ReadStateService {
356    fn drop(&mut self) {
357        // The read state service shares the state,
358        // so dropping it should check if we can shut down.
359
360        // TODO: move this into a try_shutdown() method
361        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                // We're the last database user, so we can tell it to shut down (blocking):
364                // - flushes the database to disk, and
365                // - drops the database, which cleans up any database tasks correctly.
366                self.db.shutdown(true);
367
368                // We are the last state with a reference to this thread, so we can
369                // wait until the block write task finishes, then check for panics (blocking).
370                // (We'd also like to abort the thread, but std::thread::JoinHandle can't do that.)
371
372                // This log is verbose during tests.
373                #[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                // TODO: move this into a check_for_panics() method
379                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            // Even if we're not the last database user, try shutting it down.
387            //
388            // TODO: rename this to try_shutdown()?
389            self.db.shutdown(false);
390        }
391    }
392}
393
394impl StateService {
395    const PRUNE_INTERVAL: Duration = Duration::from_secs(30);
396
397    /// Creates a new state service for the state `config` and `network`.
398    ///
399    /// Uses the `max_checkpoint_height` and `checkpoint_verify_concurrency_limit`
400    /// to work out when it is near the final checkpoint.
401    ///
402    /// Returns the read-write and read-only state services,
403    /// and read-only watch channels for its best chain tip.
404    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    /// Creates state services with optional format checks disabled for corruption tests.
421    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        // # Correctness
459        //
460        // The state service must set the finalized block write sender to `None`
461        // if there are blocks in the restored non-finalized state that are above
462        // the max checkpoint height so that non-finalized blocks can be written, otherwise,
463        // Zebra will be unable to commit semantically verified blocks, and its chain sync will stall.
464        //
465        // The state service must not set the finalized block write sender to `None` if there
466        // aren't blocks in the restored non-finalized state that are above the max checkpoint height,
467        // otherwise, unless checkpoint sync is disabled in the zebra-consensus configuration,
468        // Zebra will be unable to commit checkpoint verified blocks, and its chain sync will stall.
469        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        // Spawn a background task to periodically export RocksDB metrics to Prometheus
603        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    /// Call read only state service to log rocksdb database metrics.
616    pub fn log_db_metrics(&self) {
617        self.read_service.db.print_db_metrics();
618    }
619
620    /// Queue a checkpoint verified block for verification and storage in the finalized state.
621    ///
622    /// Returns a channel receiver that provides the result of the block commit.
623    fn queue_and_commit_to_finalized_state(
624        &mut self,
625        checkpoint_verified: CheckpointVerifiedBlock,
626    ) -> oneshot::Receiver<Result<block::Hash, CommitCheckpointVerifiedError>> {
627        // # Correctness & Performance
628        //
629        // This method must not block, access the database, or perform CPU-intensive tasks,
630        // because it is called directly from the tokio executor's Future threads.
631
632        let queued_prev_hash = checkpoint_verified.block.header.previous_block_hash;
633        let queued_height = checkpoint_verified.height;
634
635        // Apply pending resets first, so they can't fail the block queued below.
636        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            // We're still committing checkpoint verified blocks
656            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            // We've finished committing checkpoint verified blocks to the finalized state,
672            // so drop any repeated queued blocks, and return an error.
673            //
674            // TODO: track the latest sent height, and drop any blocks under that height
675            //       every time we send some blocks (like QueuedSemanticallyVerifiedBlocks)
676            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            // if there are still blocks in the queue, then either:
693            //   - the new block was lower than the old maximum, and there was a gap before it,
694            //     so the maximum is still the same (and we skip this code), or
695            //   - the new block is higher than the old maximum, and there is at least one gap
696            //     between the finalized tip and the new maximum
697            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    /// Finds finalized state queue blocks to be committed to the state in order,
708    /// removes them from the queue, and sends them to the block commit task.
709    ///
710    /// After queueing a finalized block, this method checks whether the newly
711    /// queued block (and any of its descendants) can be committed to the state.
712    ///
713    /// Returns an error if the block commit channel has been closed.
714    pub fn drain_finalized_queue_and_commit(&mut self) {
715        use tokio::sync::mpsc::error::SendError;
716
717        // # Correctness & Performance
718        //
719        // This method must not block, access the database, or perform CPU-intensive tasks,
720        // because it is called directly from the tokio executor's Future threads.
721
722        // If a block failed, we need to start again from a valid tip.
723        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            // A queued child that isn't at the next height is invalid and would never be dequeued.
736            self.reject_queued_non_finalized_children(
737                queued_block.0.hash,
738                last_sent_finalized_block_height,
739            );
740
741            // If we're close to the final checkpoint, make the block's UTXOs available for
742            // semantic block verification, even when it is in the channel.
743            // Blocks waiting in the queue are not recorded, so they can be downloaded again.
744            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 we've finished sending finalized blocks, ignore any repeated blocks.
752            // (Blocks can be repeated after a syncer reset.)
753            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 the receiver is closed, we can't send any more blocks.
757                if let Err(SendError(queued)) = send_result {
758                    // If Zebra is shutting down, drop blocks and return an error.
759                    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    /// Applies every reset queued on `invalid_block_write_reset_receiver`: rewinds the last
774    /// sent hash to the finalized tip, forgets the sent hashes, and fails the queued blocks, so
775    /// the rejected block and every block above it can be downloaded again.
776    ///
777    /// Returns `false` if the write task closed the reset channel.
778    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                    // During checkpoint sync, sent hashes at or below the tip are also in the db.
791                    self.non_finalized_block_write_sent_hashes = SentHashes::default();
792                    // Queued blocks are above the tip, and their pending responses would keep
793                    // the syncer from downloading them again.
794                    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    /// Drains every write outcome queued on `non_finalized_rejected_receiver`.
808    ///
809    /// Rejected and evicted blocks are removed from
810    /// `non_finalized_block_write_sent_hashes`. This closes the lockout window where a rejected
811    /// block keeps its hash recorded as "sent", so a subsequent honest re-delivery of a block at
812    /// the same hash is not short-circuited as a false "duplicate". Committed blocks stay sent,
813    /// but their UTXOs are forgotten, because readers then find them in the non-finalized state.
814    ///
815    /// # Correctness & Performance
816    ///
817    /// Like the other drain methods on `StateService`, this must not block,
818    /// access the database, or perform CPU-intensive work, because it is
819    /// called directly from the tokio executor's Future threads.
820    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    /// Drops all finalized state queue blocks, and sends an error on their result channels.
848    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    /// Send an error on a `QueuedCheckpointVerified` block's result channel, and drop the block
858    fn send_checkpoint_verified_block_error(
859        queued: QueuedCheckpointVerified,
860        error: impl Into<CommitCheckpointVerifiedError>,
861    ) {
862        let (finalized, rsp_tx) = queued;
863
864        // The block sender might have already given up on this block,
865        // so ignore any channel send errors.
866        let _ = rsp_tx.send(Err(error.into()));
867        std::mem::drop(finalized);
868    }
869
870    /// Drops all non-finalized state queue blocks, and sends an error on their result channels.
871    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    /// Send an error on a `QueuedSemanticallyVerified` block's result channel, and drop the block
881    fn send_semantically_verified_block_error(
882        queued: QueuedSemanticallyVerified,
883        error: impl Into<CommitSemanticallyVerifiedError>,
884    ) {
885        let (finalized, rsp_tx, _) = queued;
886
887        // The block sender might have already given up on this block,
888        // so ignore any channel send errors.
889        let _ = rsp_tx.send(Err(error.into()));
890        std::mem::drop(finalized);
891    }
892
893    /// Queue a semantically verified block for contextual verification and check if any queued
894    /// blocks are ready to be verified and committed to the state.
895    ///
896    /// This function encodes the logic for [committing non-finalized blocks][1]
897    /// in RFC0005.
898    ///
899    /// [1]: https://zebra.zfnd.org/dev/rfcs/0005-state-updates.html#committing-non-finalized-blocks
900    ///
901    /// `contextual` is the block's contextual validation result, if it was already validated as
902    /// a block proposal.
903    #[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        // Drop hashes of any blocks the write task has rejected before checking
913        // the SentHashes membership below. Without this, a rejected same-hash
914        // block would lock out a later honest re-delivery of a block at the
915        // same hash as a false "duplicate".
916        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        // [`Request::CommitSemanticallyVerifiedBlock`] contract: a request to commit a block which
960        // has been queued but not yet committed to the state fails the older request and replaces
961        // it with the newer request. A block hash does not identify its authorizing data, so
962        // replace the body together with its response channel.
963        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            // Another copy of the same body was received when its first copy was, so it keeps
969            // its place in `Chain::cmp`'s first-received order. A different body doesn't.
970            // Blocks with the same hash compare equal, so compare their authorizing data.
971            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        // The write task commits the validation result instead of the block, so the result gets
988        // the block's receipt time, which can be an earlier copy's.
989        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        // We've finished sending checkpoint verified blocks when:
1000        // - we've sent the verified block for the last checkpoint, and
1001        // - it has been successfully written to disk.
1002        if self.block_write_sender.finalized.is_some() && self.checkpoint_handoff_is_ready() {
1003            // Tell the block write task to stop committing checkpoint verified blocks to the finalized state,
1004            // and move on to committing semantically verified blocks to the non-finalized state.
1005            std::mem::drop(self.block_write_sender.finalized.take());
1006            // Remove any checkpoint-verified block hashes from `non_finalized_block_write_sent_hashes`.
1007            self.non_finalized_block_write_sent_hashes = SentHashes::default();
1008            // Mark `SentHashes` as usable by the `can_fork_chain_at()` method.
1009            self.non_finalized_block_write_sent_hashes
1010                .can_fork_chain_at_hashes = true;
1011            // Children queued while their finalized parent was in the write channel weren't checked.
1012            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            // Send blocks from non-finalized queue
1018            self.send_ready_non_finalized_queued(self.finalized_block_write_last_sent_hash);
1019            // We've finished committing checkpoint verified blocks to finalized state, so drop any repeated queued blocks.
1020            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            // Wait until block commit task is ready to write non-finalized blocks before dequeuing them
1028            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        // A block that is still queued is waiting for its parent, and is validated as usual when
1042        // the parent arrives.
1043        self.non_finalized_state_queued_blocks
1044            .drop_proposal_result(&hash);
1045
1046        // Limit the queue after sending the blocks that are ready, so it can't fail them.
1047        self.non_finalized_state_queued_blocks.prune_overflow();
1048
1049        rsp_rx
1050    }
1051
1052    /// Returns `true` if checkpoint verified blocks are written up to the final checkpoint,
1053    /// so the block write task can switch to non-finalized blocks.
1054    ///
1055    /// With no final checkpoint (`Height::MAX`), it waits for a queued child of the last sent block.
1056    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    /// Rejects the queued non-finalized children of the finalized block `parent_hash` whose
1070    /// height isn't `parent_height + 1`.
1071    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    /// Returns `true` if `hash` is a valid previous block hash for new non-finalized blocks.
1106    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    /// Returns `true` if `queued_height` is near the final checkpoint.
1113    ///
1114    /// The semantic block verifier needs access to UTXOs from checkpoint verified blocks
1115    /// near the final checkpoint, so that it can verify blocks that spend those UTXOs.
1116    ///
1117    /// If it doesn't have the required UTXOs, some blocks will time out,
1118    /// but succeed after a syncer restart.
1119    fn is_close_to_final_checkpoint(&self, queued_height: block::Height) -> bool {
1120        queued_height >= self.full_verifier_utxo_lookahead
1121    }
1122
1123    /// Sends all queued blocks whose parents have recently arrived starting from `new_parent`
1124    /// in breadth-first ordering to the block write task which will attempt to validate and commit them
1125    #[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                        // If Zebra is shutting down, drop blocks and return an error.
1145                        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    /// Return the tip of the current best chain.
1164    pub fn best_tip(&self) -> Option<(block::Height, block::Hash)> {
1165        self.read_service.best_tip()
1166    }
1167
1168    /// Starts computing early mining work on `block`, which has a valid proof of work but is
1169    /// still being verified. Returns a guard that keeps the work available.
1170    ///
1171    /// Returns `None` if nothing is subscribed to early mining work, if the state is already
1172    /// handling another mining candidate, or if the block write task isn't taking non-finalized
1173    /// blocks yet. That task only starts taking them when the first non-finalized block after a
1174    /// restart is committed, so that block doesn't get early work.
1175    fn start_mining_candidate(&mut self, block: Arc<block::Block>) -> Option<MiningCandidateGuard> {
1176        let candidates = self.read_service.mining_candidate.clone();
1177
1178        // Nodes that aren't mining don't need this work.
1179        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        // The block write task is still waiting for finalized blocks, so it wouldn't answer
1192        // until this block's commit arrives.
1193        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        // This task runs until the block write task has answered, so only one candidate is ever
1208        // queued, and then until the work is withdrawn.
1209        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    /// Assert some assumptions about the semantically verified `block` before it is queued.
1268    fn assert_block_can_be_validated(&self, block: &SemanticallyVerifiedBlock) {
1269        // required by `Request::CommitSemanticallyVerifiedBlock` call
1270        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    /// Creates a new read-only state service, using the provided finalized state and
1287    /// block write task handle.
1288    ///
1289    /// Returns the newly created service,
1290    /// and a watch channel for updating the shared recent non-finalized chain.
1291    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    /// Return the tip of the current best chain.
1310    pub fn best_tip(&self) -> Option<(block::Height, block::Hash)> {
1311        read::best_tip(&self.latest_non_finalized_state(), &self.db)
1312    }
1313
1314    /// Gets a clone of the latest non-finalized state from the `non_finalized_state_receiver`
1315    fn latest_non_finalized_state(&self) -> NonFinalizedState {
1316        self.non_finalized_state_receiver.cloned_watch_data()
1317    }
1318
1319    /// Gets a clone of the latest, best non-finalized chain from the `non_finalized_state_receiver`
1320    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    /// Test-only access to the inner database.
1326    /// Can be used to modify the database without doing any consensus checks.
1327    #[cfg(any(test, feature = "proptest-impl"))]
1328    pub fn db(&self) -> &ZebraDb {
1329        &self.db
1330    }
1331
1332    /// Logs rocksdb metrics using the read only state service.
1333    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        // Check for panics in the block write task
1346        let poll = self.read_service.poll_ready(cx);
1347
1348        // Prune outdated UTXO requests
1349        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        // A validated proposal is queued and committed like any other non-finalized block, but
1384        // it keeps its contextual validation result.
1385        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                    // The queue makes the new outputs available to other blocks' verifiers. The
1392                    // result shares its outputs with the chain that validating the proposal
1393                    // built, so the queue gets a copy.
1394                    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            // Uses non_finalized_state_queued_blocks and pending_utxos in the StateService
1413            // Accesses shared writeable state in the StateService, NonFinalizedState, and ZebraDb.
1414            //
1415            // The expected error type for this request is `CommitSemanticallyVerifiedError`.
1416            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                // # Performance
1424                //
1425                // Allow other async tasks to make progress while blocks are being verified
1426                // and written to disk. But wait for the blocks to finish committing,
1427                // so that `StateService` multi-block queries always observe a consistent state.
1428                //
1429                // Since each block is spawned into its own task,
1430                // there shouldn't be any other code running in the same task,
1431                // so we don't need to worry about blocking it:
1432                // https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html
1433
1434                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                // TODO:
1444                //   - check for panics in the block write task here,
1445                //     as well as in poll_ready()
1446
1447                // The work is all done, the future just waits on a channel for the result
1448                timer.finish_desc("CommitSemanticallyVerifiedBlock");
1449
1450                // Await the channel response, flatten the result, map receive errors to
1451                // `CommitSemanticallyVerifiedError::WriteTaskExited`.
1452                // Then flatten the nested Result and convert any errors to a BoxError.
1453                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            // Uses finalized_state_queued_blocks and pending_utxos in the StateService.
1467            // Accesses shared writeable state in the StateService.
1468            //
1469            // The expected error type for this request is `CommitCheckpointVerifiedError`.
1470            Request::CommitCheckpointVerifiedBlock(finalized) => {
1471                let timer = CodeTimer::start();
1472                // # Consensus
1473                //
1474                // A semantic block verification could have called AwaitUtxo
1475                // before this checkpoint verified block arrived in the state.
1476                // So we need to check for pending UTXO requests sent by running
1477                // semantic block verifications.
1478                //
1479                // This check is redundant for most checkpoint verified blocks,
1480                // because semantic verification can only succeed near the final
1481                // checkpoint, when all the UTXOs are available for the verifying block.
1482                //
1483                // (Checkpoint block UTXOs are verified using block hash checkpoints
1484                // and transaction merkle tree block header commitments.)
1485                self.pending_utxos
1486                    .check_against_ordered(&finalized.new_outputs);
1487
1488                // # Performance
1489                //
1490                // This method doesn't block, access the database, or perform CPU-intensive tasks,
1491                // so we can run it directly in the tokio executor's Future threads.
1492                let rsp_rx = self.queue_and_commit_to_finalized_state(finalized);
1493
1494                // TODO:
1495                //   - check for panics in the block write task here,
1496                //     as well as in poll_ready()
1497
1498                // The work is all done, the future just waits on a channel for the result
1499                timer.finish_desc("CommitCheckpointVerifiedBlock");
1500
1501                // Await the channel response, flatten the result, map receive errors to
1502                // `CommitCheckpointVerifiedError::WriteTaskExited`.
1503                // Then flatten the nested Result and convert any errors to a BoxError.
1504                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            // Uses pending_utxos and non_finalized_state_queued_blocks in the StateService.
1517            // If the UTXO isn't in the queued blocks, runs concurrently using the ReadStateService.
1518            //
1519            // The expected error type for this request is `AwaitUtxoError`.
1520            Request::AwaitUtxo(outpoint) => {
1521                let timer = CodeTimer::start();
1522                // Prepare the AwaitUtxo future from PendingUtxos.
1523                let response_fut = self.pending_utxos.queue(outpoint);
1524                // Only instrument `response_fut`, the ReadStateService already
1525                // instruments its requests with the same span.
1526
1527                let response_fut = response_fut
1528                    .map(|result| result.map_err(BoxError::from))
1529                    .instrument(span)
1530                    .boxed();
1531
1532                // Check the non-finalized block queue outside the returned future,
1533                // so we can access mutable state fields.
1534                if let Some(utxo) = self.non_finalized_state_queued_blocks.utxo(&outpoint) {
1535                    self.pending_utxos.respond(&outpoint, utxo);
1536
1537                    // We're finished, the returned future gets the UTXO from the respond() channel.
1538                    timer.finish_desc("AwaitUtxo/queued-non-finalized");
1539
1540                    return response_fut;
1541                }
1542
1543                // Check the sent non-finalized blocks
1544                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                    // We're finished, the returned future gets the UTXO from the respond() channel.
1551                    timer.finish_desc("AwaitUtxo/sent-non-finalized");
1552
1553                    return response_fut;
1554                }
1555
1556                // We ignore any UTXOs in FinalizedState.finalized_state_queued_blocks,
1557                // because it is only used during checkpoint verification.
1558                //
1559                // This creates a rare race condition, but it doesn't seem to happen much in practice.
1560                // See #5126 for details.
1561
1562                // Manually send a request to the ReadStateService,
1563                // to get UTXOs from any non-finalized chain or the finalized chain.
1564                let read_service = self.read_service.clone();
1565
1566                // Run the request in an async block, so we can await the response.
1567                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                    // Optional TODO:
1576                    //  - make pending_utxos.respond() async using a channel,
1577                    //    so we can respond to all waiting requests here
1578                    //
1579                    // This change is not required for correctness, because:
1580                    // - any waiting requests should have returned when the block was sent to the state
1581                    // - otherwise, the request returns immediately if:
1582                    //   - the block is in the non-finalized queue, or
1583                    //   - the block is in any non-finalized chain or the finalized state
1584                    //
1585                    // And if the block is in the finalized queue,
1586                    // that's rare enough that a retry is ok.
1587                    if let ReadResponse::AnyChainUtxo(Some(utxo)) = rsp {
1588                        // We got a UTXO, so we replace the response future with the result own.
1589                        timer.finish_desc("AwaitUtxo/any-chain");
1590
1591                        return Ok(Response::Utxo(utxo));
1592                    }
1593
1594                    // We're finished, but the returned future is waiting on the respond() channel.
1595                    timer.finish_desc("AwaitUtxo/waiting");
1596
1597                    response_fut.await
1598                }
1599                .boxed()
1600            }
1601
1602            // Used by sync, inbound, and block verifier to check if a block is already in the state
1603            // before downloading or validating it.
1604            Request::KnownBlock(hash) => {
1605                let timer = CodeTimer::start();
1606
1607                // Rejected blocks must not be reported as sent, or they never get re-downloaded.
1608                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                    // TODO: Move this to a blocking task, perhaps by moving some of this logic to the ReadStateService.
1628                    .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            // The expected error type for this request is `InvalidateError`
1638            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                // Await the channel response, flatten the result, map receive errors to
1644                // `InvalidateError::InvalidateRequestDropped`.
1645                // Then flatten the nested Result and convert any errors to a BoxError.
1646                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            // The expected error type for this request is `ReconsiderError`
1660            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                // Await the channel response, flatten the result, map receive errors to
1666                // `ReconsiderError::ReconsiderResponseDropped`.
1667                // Then flatten the nested Result and convert any errors to a BoxError.
1668                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            // Runs concurrently using the ReadStateService
1692            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                // Redirect the request to the concurrent ReadStateService
1709                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        // Check for panics in the block write task
1735        //
1736        // TODO: move into a check_for_panics() method
1737        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                    // We are the last state with a reference to this task, so we can propagate any panics
1743                    if let Err(thread_panic) = block_write_task.join() {
1744                        std::panic::resume_unwind(thread_panic);
1745                    }
1746                }
1747            } else {
1748                // It hasn't finished, so we need to put it back
1749                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            // The non-finalized blocks listener is used to notify the state service
1768            // about new blocks that have been added to the non-finalized state.
1769            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            // Used by the `getblockchaininfo` RPC.
1805            ReadRequest::UsageInfo => Ok(ReadResponse::UsageInfo(state.db.size())),
1806
1807            // Used by the StateService.
1808            ReadRequest::Tip => Ok(ReadResponse::Tip(read::tip(
1809                state.latest_best_chain(),
1810                &state.db,
1811            ))),
1812
1813            // Used by `getblockchaininfo` RPC method.
1814            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            // Used by getblock
1827            ReadRequest::BlockInfo(hash_or_height) => Ok(ReadResponse::BlockInfo(
1828                read::block_info(state.latest_best_chain(), &state.db, hash_or_height),
1829            )),
1830
1831            // Used by the StateService.
1832            ReadRequest::Depth(hash) => Ok(ReadResponse::Depth(read::depth(
1833                state.latest_best_chain(),
1834                &state.db,
1835                hash,
1836            ))),
1837
1838            // Used by the StateService.
1839            ReadRequest::BestChainNextMedianTimePast => {
1840                Ok(ReadResponse::BestChainNextMedianTimePast(
1841                    read::next_median_time_past(&state.latest_non_finalized_state(), &state.db)?,
1842                ))
1843            }
1844
1845            // Used by the get_block (raw) RPC and the StateService.
1846            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            // Used by the get_block (raw) RPC and the StateService.
1859            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            // Used by the get_block (verbosity 3) RPC.
1864            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            // Used by the get_block (verbose) RPC and the StateService.
1873            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            // For the get_raw_transaction RPC and the StateService.
1904            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            // Used by the getblock (verbose) RPC.
1917            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            // Manually used by the StateService to implement part of AwaitUtxo.
1945            ReadRequest::AnyChainUtxo(outpoint) => Ok(ReadResponse::AnyChainUtxo(read::any_utxo(
1946                state.latest_non_finalized_state(),
1947                &state.db,
1948                outpoint,
1949            ))),
1950
1951            // Used by the StateService.
1952            ReadRequest::BlockLocator => Ok(ReadResponse::BlockLocator(
1953                read::block_locator(state.latest_best_chain(), &state.db).unwrap_or_default(),
1954            )),
1955
1956            // Used by the StateService.
1957            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            // Used by the StateService.
1968            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                // Reject over-long locators before doing any work, so an untrusted
1983                // caller can't force unbounded lookups.
1984                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                    // If there is no end bound, just return all the trees.
2049                    // If the end bound would overflow, just returns all the trees, because that's what
2050                    // `zcashd` does. (It never calculates an end bound, so it just keeps iterating until
2051                    // the trees run out.)
2052                    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                    // If there is no end bound, just return all the trees.
2068                    // If the end bound would overflow, just returns all the trees, because that's what
2069                    // `zcashd` does. (It never calculates an end bound, so it just keeps iterating until
2070                    // the trees run out.)
2071                    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                    // If there is no end bound, just return all the trees.
2087                    // If the end bound would overflow, just returns all the trees, because that's what
2088                    // `zcashd` does. (It never calculates an end bound, so it just keeps iterating until
2089                    // the trees run out.)
2090                    read::ironwood_subtrees(best_chain, &state.db, start_index..)
2091                };
2092
2093                Ok(ReadResponse::IronwoodSubtrees(ironwood_subtrees))
2094            }
2095
2096            // For the get_address_balance RPC.
2097            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            // For the get_address_tx_ids RPC.
2104            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            // For the get_address_utxos RPC.
2118            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            // Used by the get_block and get_block_hash RPCs.
2151            ReadRequest::BestChainBlockHash(height) => Ok(ReadResponse::BlockHash(
2152                read::hash_by_height(state.latest_best_chain(), &state.db, height),
2153            )),
2154
2155            // Used by get_block_template and getblockchaininfo RPCs.
2156            ReadRequest::ChainInfo => {
2157                // # Correctness
2158                //
2159                // It is ok to do these lookups using multiple database calls. Finalized state updates
2160                // can only add overlapping blocks, and block hashes are unique across all chain forks.
2161                //
2162                // If there is a large overlap between the non-finalized and finalized states,
2163                // where the finalized tip is above the non-finalized tip,
2164                // Zebra is receiving a lot of blocks, or this request has been delayed for a long time.
2165                //
2166                // In that case, the `getblocktemplate` RPC will return an error because Zebra
2167                // is not synced to the tip. That check happens before the RPC makes this request.
2168                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            // Used by the `getblocktemplate` RPC.
2177            ReadRequest::MiningCandidate => {
2178                // Early work is only useful while its block's parent is still the best tip.
2179                // After that, either the block was committed, and work on it is ordinary work
2180                // on the best tip, or another block was, and the block is on a side chain.
2181                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            // Used by the block template updater task.
2192            ReadRequest::MiningCandidateChanges => Ok(ReadResponse::MiningCandidateChanges(
2193                MiningCandidateChanges(state.mining_candidate.subscribe()),
2194            )),
2195
2196            // Used by getmininginfo, getnetworksolps, and getnetworkhashps RPCs.
2197            ReadRequest::SolutionRate { num_blocks, height } => {
2198                let latest_non_finalized_state = state.latest_non_finalized_state();
2199                // # Correctness
2200                //
2201                // It is ok to do these lookups using multiple database calls. Finalized state updates
2202                // can only add overlapping blocks, and block hashes are unique across all chain forks.
2203                //
2204                // The worst that can happen here is that the default `start_hash` will be below
2205                // the chain tip.
2206                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                // The previous block of a valid proposal must be on the best chain tip.
2246                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                // This clone of the non-finalized state is dropped when this closure returns.
2262                // The non-finalized state that's used in the rest of the state (including finalizing
2263                // blocks into the db) is not mutated here.
2264                //
2265                // TODO: Convert `CommitSemanticallyVerifiedError` to a new `ValidateProposalError`?
2266                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                // Keep the chain with the proposal on top, so a commit of the solved proposal
2276                // can use it instead of applying the block to its parent chain again.
2277                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            // Used by `gettxout` RPC method.
2309            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
2319/// Initialize a state service from the provided [`Config`].
2320/// Returns a boxed state service, a read-only state service,
2321/// and receivers for state chain tip updates.
2322///
2323/// Each `network` has its own separate on-disk database.
2324///
2325/// The state uses the `max_checkpoint_height` and `checkpoint_verify_concurrency_limit`
2326/// to work out when it is near the final checkpoint.
2327///
2328/// To share access to the state, wrap the returned service in a `Buffer`,
2329/// or clone the returned [`ReadStateService`].
2330///
2331/// It's possible to construct multiple state services in the same application (as
2332/// long as they, e.g., use different storage locations), but doing so is
2333/// probably not what you want.
2334pub 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
2362/// Initialize a read state service from the provided [`Config`].
2363/// Returns a read-only state service,
2364///
2365/// Each `network` has its own separate on-disk database.
2366///
2367/// To share access to the state, clone the returned [`ReadStateService`].
2368pub 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
2394/// Calls [`init_read_only`] with the provided [`Config`] and [`Network`] from a blocking task.
2395///
2396/// Returns a [`tokio::task::JoinHandle`] whose output is a [`Result`]: awaiting it yields a
2397/// [`JoinError`](tokio::task::JoinError) if the blocking task panicked or was cancelled, and
2398/// otherwise an `Err(`[`StateInitError`]`)` if the read-only state could not be opened (for
2399/// example, a missing read-only database).
2400pub 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/// Returns a [`StateService`] with an ephemeral [`Config`] and a buffer with a single slot.
2418///
2419/// This can be used to create a state service for testing. See also [`init`].
2420#[cfg(any(test, feature = "proptest-impl"))]
2421pub async fn init_test(
2422    network: &Network,
2423) -> Buffer<BoxService<Request, Response, BoxError>, Request> {
2424    // TODO: pass max_checkpoint_height and checkpoint_verify_concurrency limit
2425    //       if we ever need to test final checkpoint sent UTXO queries
2426    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/// Initializes a state service with an ephemeral [`Config`] and a buffer with a single slot,
2433/// then returns the read-write service, read-only service, and tip watch channels.
2434///
2435/// This can be used to create a state service for testing. See also [`init`].
2436#[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    // TODO: pass max_checkpoint_height and checkpoint_verify_concurrency limit
2446    //       if we ever need to test final checkpoint sent UTXO queries
2447    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}