Skip to main content

zebra_state/service/
write.rs

1//! Writing blocks to the finalized and non-finalized states.
2
3use std::{
4    path::{Path, PathBuf},
5    sync::Arc,
6};
7
8use indexmap::IndexMap;
9use tokio::sync::{
10    mpsc::{UnboundedReceiver, UnboundedSender},
11    oneshot, watch,
12};
13
14use tracing::Span;
15use zebra_chain::{
16    block::{self, Height},
17    parallel::tree::NoteCommitmentTrees,
18};
19
20use crate::{
21    constants::MAX_BLOCK_REORG_HEIGHT,
22    service::{
23        check,
24        finalized_state::{FinalizedState, ZebraDb},
25        non_finalized_state::NonFinalizedState,
26        precomputed_trees::PrecomputedTrees,
27        queued_blocks::{QueuedCheckpointVerified, QueuedSemanticallyVerified},
28        read, ChainTipBlock, ChainTipSender, InvalidateError, ReconsiderError,
29    },
30    GetBlockTemplateChainInfo, SemanticallyVerifiedBlock, ValidateContextError,
31};
32
33// These types are used in doc links
34#[allow(unused_imports)]
35use crate::service::{
36    chain_tip::{ChainTipChange, LatestChainTip},
37    non_finalized_state::Chain,
38};
39
40/// The maximum size of the parent error map.
41///
42/// We allow enough space for multiple concurrent chain forks with errors.
43const PARENT_ERROR_MAP_LIMIT: usize = MAX_BLOCK_REORG_HEIGHT as usize * 2;
44
45/// Run contextual validation on the prepared block and add it to the
46/// non-finalized state if it is contextually valid.
47#[tracing::instrument(
48    level = "debug",
49    skip(finalized_state, non_finalized_state, prepared),
50    fields(
51        height = ?prepared.height,
52        hash = %prepared.hash,
53        chains = non_finalized_state.chain_count()
54    )
55)]
56pub(crate) fn validate_and_commit_non_finalized(
57    finalized_state: &ZebraDb,
58    non_finalized_state: &mut NonFinalizedState,
59    prepared: SemanticallyVerifiedBlock,
60) -> Result<(), ValidateContextError> {
61    check::initial_contextual_validity(finalized_state, non_finalized_state, &prepared)?;
62    let parent_hash = prepared.block.header.previous_block_hash;
63
64    if finalized_state.finalized_tip_hash() == parent_hash {
65        non_finalized_state.commit_new_chain(prepared, finalized_state)?;
66    } else {
67        non_finalized_state.commit_block(prepared, finalized_state)?;
68    }
69
70    Ok(())
71}
72
73/// Finalizes the best chain's root blocks while [`NonFinalizedState::should_finalize_root`].
74fn finalize_root_blocks(
75    finalized_state: &mut FinalizedState,
76    non_finalized_state: &mut NonFinalizedState,
77    prev_finalized_note_commitment_trees: &mut Option<NoteCommitmentTrees>,
78) {
79    while non_finalized_state.should_finalize_root() {
80        tracing::trace!("finalizing a block past the reorg or index entry limit");
81        let contextually_verified_with_trees = non_finalized_state.finalize();
82        *prev_finalized_note_commitment_trees = finalized_state
83            .commit_finalized_direct(
84                contextually_verified_with_trees,
85                prev_finalized_note_commitment_trees.take(),
86                "commit contextually-verified request",
87            )
88            .expect(
89                "unexpected finalized block commit error: note commitment and history trees were \
90                 already checked by the non-finalized state",
91            )
92            .1
93            .into();
94    }
95}
96
97/// What the block write task did with a non-finalized block, so the state service can update the
98/// blocks and outputs it tracks as sent.
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub(crate) enum NonFinalizedWriteOutcome {
101    /// The block was rejected, or evicted from every chain, so it isn't in the state.
102    Rejected(block::Hash),
103
104    /// The block was committed, and the state published to readers contains it.
105    Committed(block::Hash),
106}
107
108/// Sends the hashes of blocks evicted from the non-finalized state on `non_finalized_rejected_sender`,
109/// so the state service accepts them again if the network extends their chain.
110///
111/// Returns `true` if any blocks were evicted.
112fn forget_evicted_blocks(
113    non_finalized_state: &mut NonFinalizedState,
114    non_finalized_rejected_sender: &UnboundedSender<NonFinalizedWriteOutcome>,
115) -> bool {
116    let evicted = non_finalized_state.take_evicted_block_hashes();
117    for &hash in &evicted {
118        // If the receiver was dropped, the state service is shutting down.
119        let _ = non_finalized_rejected_sender.send(NonFinalizedWriteOutcome::Rejected(hash));
120    }
121
122    !evicted.is_empty()
123}
124
125/// Finalizes root blocks after a commit, then reports and publishes any forks that finalizing
126/// evicted, because [`NonFinalizedState::finalize`] re-inserts the remaining chains under the
127/// fork limits.
128fn finalize_root_blocks_and_forget_evicted(
129    finalized_state: &mut FinalizedState,
130    non_finalized_state: &mut NonFinalizedState,
131    prev_finalized_note_commitment_trees: &mut Option<NoteCommitmentTrees>,
132    non_finalized_rejected_sender: &UnboundedSender<NonFinalizedWriteOutcome>,
133    chain_tip_sender: &mut ChainTipSender,
134    non_finalized_state_sender: &watch::Sender<NonFinalizedState>,
135    backup_dir_path: Option<&Path>,
136) {
137    finalize_root_blocks(
138        finalized_state,
139        non_finalized_state,
140        prev_finalized_note_commitment_trees,
141    );
142
143    if forget_evicted_blocks(non_finalized_state, non_finalized_rejected_sender) {
144        update_latest_chain_channels(
145            non_finalized_state,
146            &finalized_state.db,
147            chain_tip_sender,
148            non_finalized_state_sender,
149            backup_dir_path,
150        );
151    }
152}
153
154/// Update the [`LatestChainTip`], [`ChainTipChange`], and `non_finalized_state_sender`
155/// channels with the latest state. If there is no non-finalized chain, use the
156/// finalized tip.
157///
158/// If `backup_dir_path` is `Some`, the non-finalized state is written to the backup
159/// directory before updating the channels.
160///
161/// Returns the latest chain tip height, or `None` if both states are empty.
162#[instrument(
163    level = "debug",
164    skip(
165        non_finalized_state,
166        finalized_state,
167        chain_tip_sender,
168        non_finalized_state_sender,
169        backup_dir_path,
170    ),
171    fields(chains = non_finalized_state.chain_count())
172)]
173fn update_latest_chain_channels(
174    non_finalized_state: &NonFinalizedState,
175    finalized_state: &ZebraDb,
176    chain_tip_sender: &mut ChainTipSender,
177    non_finalized_state_sender: &watch::Sender<NonFinalizedState>,
178    backup_dir_path: Option<&Path>,
179) -> Option<block::Height> {
180    // The tip only needs the block's transactions and hashes, so don't copy its UTXO maps.
181    let non_finalized_tip = non_finalized_state
182        .best_tip_block()
183        .map(ChainTipBlock::from);
184    let tip_block_height = if let Some(tip) = &non_finalized_tip {
185        Some(tip.height)
186    } else {
187        finalized_state.finalized_tip_height()
188    };
189
190    if let Some(backup_dir_path) = backup_dir_path {
191        non_finalized_state.write_to_backup(backup_dir_path);
192    }
193
194    // If the final receiver was just dropped, ignore the error.
195    let _ = non_finalized_state_sender.send(non_finalized_state.clone());
196
197    if let Some(tip) = non_finalized_tip {
198        chain_tip_sender.set_best_non_finalized_tip(tip);
199    } else {
200        let finalized_tip = finalized_state
201            .tip_block()
202            .expect("the finalized tip must have a complete stored body")
203            .map(crate::CheckpointVerifiedBlock::from)
204            .map(ChainTipBlock::from);
205        chain_tip_sender.clear_best_non_finalized_tip(finalized_tip);
206    }
207
208    tip_block_height
209}
210
211/// A worker task that reads, validates, and writes blocks to the
212/// `finalized_state` or `non_finalized_state`.
213struct WriteBlockWorkerTask {
214    finalized_block_write_receiver: UnboundedReceiver<QueuedCheckpointVerified>,
215    non_finalized_block_write_receiver: UnboundedReceiver<NonFinalizedWriteMessage>,
216    finalized_state: FinalizedState,
217    non_finalized_state: NonFinalizedState,
218    /// Signals the [`crate::service::StateService`] that a finalized block commit failed,
219    /// carrying the durable finalized tip height and hash to reset to.
220    invalid_block_reset_sender: UnboundedSender<(Option<block::Height>, block::Hash)>,
221    /// Signals the [`crate::service::StateService`] that a non-finalized block was rejected by
222    /// the write task, so its hash should be removed from
223    /// `non_finalized_block_write_sent_hashes`.
224    ///
225    /// Without this, a rejected same-hash block locks out a later honest
226    /// re-delivery of a block at the same hash as a "duplicate" until restart
227    /// or reorg.
228    non_finalized_rejected_sender: UnboundedSender<NonFinalizedWriteOutcome>,
229    chain_tip_sender: ChainTipSender,
230    non_finalized_state_sender: watch::Sender<NonFinalizedState>,
231    /// If `Some`, the non-finalized state is written to this backup directory
232    /// synchronously before each channel update, instead of via the async backup task.
233    backup_dir_path: Option<PathBuf>,
234}
235
236/// The message type for the non-finalized block write task channel.
237pub enum NonFinalizedWriteMessage {
238    /// A newly downloaded and semantically verified block prepared for
239    /// contextual validation and insertion into the non-finalized state.
240    Commit(QueuedSemanticallyVerified),
241    /// The hash of a block that should be invalidated and removed from
242    /// the non-finalized state, if present.
243    Invalidate {
244        hash: block::Hash,
245        rsp_tx: oneshot::Sender<Result<block::Hash, InvalidateError>>,
246    },
247    /// The hash of a block that was previously invalidated but should be
248    /// reconsidered and reinserted into the non-finalized state.
249    Reconsider {
250        hash: block::Hash,
251        rsp_tx: oneshot::Sender<Result<Vec<block::Hash>, ReconsiderError>>,
252    },
253    /// A block whose proof of work is valid, but which is still being verified.
254    ///
255    /// The block write task computes the chain info for mining on top of it, and keeps the
256    /// block's note commitment trees for its commit. Computing them here, in order with the
257    /// commits, means the work is always based on the latest committed tip, and the commit of
258    /// the same block never computes its trees at the same time.
259    MiningCandidate {
260        block: Arc<block::Block>,
261        rsp_tx: oneshot::Sender<Option<GetBlockTemplateChainInfo>>,
262    },
263}
264
265impl From<QueuedSemanticallyVerified> for NonFinalizedWriteMessage {
266    fn from(block: QueuedSemanticallyVerified) -> Self {
267        NonFinalizedWriteMessage::Commit(block)
268    }
269}
270
271/// A worker with a task that reads, validates, and writes blocks to the
272/// `finalized_state` or `non_finalized_state` and channels for sending
273/// it blocks.
274#[derive(Clone, Debug)]
275pub(super) struct BlockWriteSender {
276    /// A channel to send blocks to the `block_write_task`,
277    /// so they can be written to the [`NonFinalizedState`].
278    pub non_finalized: Option<tokio::sync::mpsc::UnboundedSender<NonFinalizedWriteMessage>>,
279
280    /// A channel to send blocks to the `block_write_task`,
281    /// so they can be written to the [`FinalizedState`].
282    ///
283    /// This sender is dropped after the state has finished sending all the checkpointed blocks,
284    /// and the lowest semantically verified block arrives.
285    pub finalized: Option<tokio::sync::mpsc::UnboundedSender<QueuedCheckpointVerified>>,
286}
287
288impl BlockWriteSender {
289    /// Creates a new [`BlockWriteSender`] with the given receivers and states.
290    #[instrument(
291        level = "debug",
292        skip_all,
293        fields(
294            network = %non_finalized_state.network
295        )
296    )]
297    pub fn spawn(
298        finalized_state: FinalizedState,
299        non_finalized_state: NonFinalizedState,
300        chain_tip_sender: ChainTipSender,
301        non_finalized_state_sender: watch::Sender<NonFinalizedState>,
302        should_use_finalized_block_write_sender: bool,
303        backup_dir_path: Option<PathBuf>,
304    ) -> (
305        Self,
306        tokio::sync::mpsc::UnboundedReceiver<(Option<block::Height>, block::Hash)>,
307        tokio::sync::mpsc::UnboundedReceiver<NonFinalizedWriteOutcome>,
308        Option<Arc<std::thread::JoinHandle<()>>>,
309    ) {
310        // Security: The number of blocks in these channels is limited by
311        //           the syncer and inbound lookahead limits.
312        let (non_finalized_block_write_sender, non_finalized_block_write_receiver) =
313            tokio::sync::mpsc::unbounded_channel();
314        let (finalized_block_write_sender, finalized_block_write_receiver) =
315            tokio::sync::mpsc::unbounded_channel();
316        let (invalid_block_reset_sender, invalid_block_write_reset_receiver) =
317            tokio::sync::mpsc::unbounded_channel();
318        let (non_finalized_rejected_sender, non_finalized_rejected_receiver) =
319            tokio::sync::mpsc::unbounded_channel();
320
321        let span = Span::current();
322        let task = std::thread::spawn(move || {
323            span.in_scope(|| {
324                WriteBlockWorkerTask {
325                    finalized_block_write_receiver,
326                    non_finalized_block_write_receiver,
327                    finalized_state,
328                    non_finalized_state,
329                    invalid_block_reset_sender,
330                    non_finalized_rejected_sender,
331                    chain_tip_sender,
332                    non_finalized_state_sender,
333                    backup_dir_path,
334                }
335                .run()
336            })
337        });
338
339        (
340            Self {
341                non_finalized: Some(non_finalized_block_write_sender),
342                finalized: should_use_finalized_block_write_sender
343                    .then_some(finalized_block_write_sender),
344            },
345            invalid_block_write_reset_receiver,
346            non_finalized_rejected_receiver,
347            Some(Arc::new(task)),
348        )
349    }
350}
351
352impl WriteBlockWorkerTask {
353    /// Reads blocks from the channels, writes them to the `finalized_state` or `non_finalized_state`,
354    /// sends any errors on the `invalid_block_reset_sender`, then updates the `chain_tip_sender` and
355    /// `non_finalized_state_sender`.
356    #[instrument(
357        level = "debug",
358        skip(self),
359        fields(
360            network = %self.non_finalized_state.network
361        )
362    )]
363    pub fn run(mut self) {
364        let Self {
365            finalized_block_write_receiver,
366            non_finalized_block_write_receiver,
367            finalized_state,
368            non_finalized_state,
369            invalid_block_reset_sender,
370            non_finalized_rejected_sender,
371            chain_tip_sender,
372            non_finalized_state_sender,
373            backup_dir_path,
374        } = &mut self;
375
376        let mut prev_finalized_note_commitment_trees = None;
377
378        // Write all the finalized blocks sent by the state,
379        // until the state closes the finalized block channel's sender.
380        while let Some(ordered_block) = finalized_block_write_receiver.blocking_recv() {
381            // TODO: split these checks into separate functions
382
383            if invalid_block_reset_sender.is_closed() {
384                info!("StateService closed the block reset channel. Is Zebra shutting down?");
385                return;
386            }
387
388            // Discard any children of invalid blocks in the channel
389            //
390            // `commit_finalized()` requires blocks in height order.
391            // So if there has been a block commit error,
392            // we need to drop all the descendants of that block,
393            // until we receive a block at the required next height.
394            let next_valid_height = finalized_state
395                .db
396                .finalized_tip_height()
397                .map(|height| (height + 1).expect("committed heights are valid"))
398                .unwrap_or(Height(0));
399
400            if ordered_block.0.height != next_valid_height {
401                debug!(
402                    ?next_valid_height,
403                    invalid_height = ?ordered_block.0.height,
404                    invalid_hash = ?ordered_block.0.hash,
405                    "got a block that was the wrong height. \
406                     Assuming a parent block failed, and dropping this block",
407                );
408
409                // We don't want to send a reset here, because it could overwrite a valid sent hash
410                std::mem::drop(ordered_block);
411                continue;
412            }
413
414            // Try committing the block
415            match finalized_state
416                .commit_finalized(ordered_block, prev_finalized_note_commitment_trees.take())
417            {
418                Ok((tip_block, note_commitment_trees)) => {
419                    prev_finalized_note_commitment_trees = Some(note_commitment_trees);
420                    chain_tip_sender.set_finalized_tip(tip_block);
421                }
422                Err(error) => {
423                    let finalized_tip = finalized_state.db.tip();
424
425                    // The last block in the queue failed, so we can't commit the next block.
426                    // Instead, we need to reset the state queue,
427                    // and discard any children of the invalid block in the channel.
428                    info!(
429                        ?error,
430                        last_valid_height = ?finalized_tip.map(|tip| tip.0),
431                        last_valid_hash = ?finalized_tip.map(|tip| tip.1),
432                        "committing a block to the finalized state failed, resetting state queue",
433                    );
434
435                    let send_result = invalid_block_reset_sender.send((
436                        finalized_state.db.finalized_tip_height(),
437                        finalized_state.db.finalized_tip_hash(),
438                    ));
439
440                    if send_result.is_err() {
441                        info!(
442                            "StateService closed the block reset channel. Is Zebra shutting down?"
443                        );
444                        return;
445                    }
446                }
447            }
448        }
449
450        // Do this check even if the channel got closed before any finalized blocks were sent.
451        // This can happen if we're past the finalized tip.
452        if invalid_block_reset_sender.is_closed() {
453            info!("StateService closed the block reset channel. Is Zebra shutting down?");
454            return;
455        }
456
457        // A restored backup can hold more blocks than the limits allow, so finalize them before
458        // committing any new blocks.
459        let restored_root = non_finalized_state.root_height();
460        finalize_root_blocks(
461            finalized_state,
462            non_finalized_state,
463            &mut prev_finalized_note_commitment_trees,
464        );
465        if non_finalized_state.root_height() != restored_root {
466            forget_evicted_blocks(non_finalized_state, non_finalized_rejected_sender);
467            update_latest_chain_channels(
468                non_finalized_state,
469                &finalized_state.db,
470                chain_tip_sender,
471                non_finalized_state_sender,
472                backup_dir_path.as_deref(),
473            );
474        }
475
476        // Save any errors to propagate down to queued child blocks
477        let mut parent_error_map: IndexMap<block::Hash, ValidateContextError> = IndexMap::new();
478
479        // The note commitment trees of the latest mining candidate, for its commit to reuse.
480        let mut candidate_trees: Option<PrecomputedTrees> = None;
481
482        while let Some(msg) = non_finalized_block_write_receiver.blocking_recv() {
483            let queued_child_and_rsp_tx = match msg {
484                NonFinalizedWriteMessage::Commit(queued_child) => Some(queued_child),
485                NonFinalizedWriteMessage::MiningCandidate { block, rsp_tx } => {
486                    let candidate = read::difficulty::mining_candidate_chain_info(
487                        non_finalized_state,
488                        &finalized_state.db,
489                        &block,
490                    );
491
492                    let chain_info = match candidate {
493                        Ok((chain_info, trees)) => {
494                            candidate_trees = Some(trees);
495                            Some(chain_info)
496                        }
497                        Err(error) => {
498                            tracing::debug!(?error, "block can't be used for early mining work");
499                            None
500                        }
501                    };
502
503                    let _ = rsp_tx.send(chain_info);
504                    continue;
505                }
506                NonFinalizedWriteMessage::Invalidate { hash, rsp_tx } => {
507                    tracing::info!(?hash, "invalidating a block in the non-finalized state");
508                    let _ = rsp_tx.send(non_finalized_state.invalidate_block(hash));
509                    None
510                }
511                NonFinalizedWriteMessage::Reconsider { hash, rsp_tx } => {
512                    tracing::info!(?hash, "reconsidering a block in the non-finalized state");
513                    let _ = rsp_tx
514                        .send(non_finalized_state.reconsider_block(hash, &finalized_state.db));
515                    None
516                }
517            };
518
519            let Some((queued_child, rsp_tx, contextual)) = queued_child_and_rsp_tx else {
520                forget_evicted_blocks(non_finalized_state, non_finalized_rejected_sender);
521                update_latest_chain_channels(
522                    non_finalized_state,
523                    &finalized_state.db,
524                    chain_tip_sender,
525                    non_finalized_state_sender,
526                    backup_dir_path.as_deref(),
527                );
528                continue;
529            };
530
531            let child_hash = queued_child.hash;
532            let parent_hash = queued_child.block.header.previous_block_hash;
533            let parent_error = parent_error_map.get(&parent_hash);
534
535            // A commit replaces the chain that it extends. The published snapshot can hold the
536            // last reference to that chain. Once the best chain is at the reorg limit, the state
537            // holds it instead, because finalizing a block after each commit copies the chain.
538            // Freeing a chain or a block takes time proportional to its indexes, so what this
539            // commit replaces is kept until its caller has the response.
540            let replaced_snapshot = non_finalized_state_sender.borrow().clone();
541            let replaced_chain = non_finalized_state.best_chain().cloned();
542            let mut replaced_proposal = None;
543
544            // If the parent block was marked as rejected, also reject all its children.
545            //
546            // At this point, we know that all the block's descendants
547            // are invalid, because we checked all the consensus rules before
548            // committing the failing ancestor block to the non-finalized state.
549            //
550            // The children are served by other peers, which often queue them before
551            // the parent arrives, so they get a distinct error that doesn't carry the
552            // parent's misbehaviour score.
553            let result = if let Some(parent_error) = parent_error {
554                Err(parent_error.for_descendant(parent_hash))
555            } else if let Some(contextual) = contextual {
556                // The block was validated as a proposal, so only apply it to its parent chain.
557                candidate_trees = None;
558                non_finalized_state
559                    .commit_prevalidated_contextual(*contextual, &finalized_state.db)
560                    .map(|replaced| replaced_proposal = replaced)
561            } else {
562                tracing::trace!(?child_hash, "validating queued child");
563                // A commit is the only use for a candidate's trees: they are for its own block,
564                // and any other block's commit changes the tip they were computed from.
565                non_finalized_state.precomputed_trees = candidate_trees.take();
566                let result = validate_and_commit_non_finalized(
567                    &finalized_state.db,
568                    non_finalized_state,
569                    queued_child,
570                );
571                non_finalized_state.precomputed_trees = None;
572                result
573            };
574
575            // TODO: fix the test timing bugs that require the result to be sent
576            //       after `update_latest_chain_channels()`,
577            //       and send the result on rsp_tx here
578
579            if let Err(ref error) = result {
580                // If the block is invalid, mark any descendant blocks as rejected.
581                parent_error_map.insert(child_hash, error.clone());
582
583                // Make sure the error map doesn't get too big.
584                if parent_error_map.len() > PARENT_ERROR_MAP_LIMIT {
585                    // We only add one hash at a time, so we only need to remove one extra here.
586                    parent_error_map.shift_remove_index(0);
587                }
588
589                // Signal the StateService to drop this hash from
590                // `non_finalized_block_write_sent_hashes`, so a subsequent
591                // re-delivery of a block at the same hash is not short-circuited
592                // as a "duplicate" against a rejected variant that never reached
593                // any chain.
594                //
595                // If the receiver was dropped (the StateService is shutting
596                // down), ignore the error: the lockout cannot matter once the
597                // service exits.
598                let _ = non_finalized_rejected_sender
599                    .send(NonFinalizedWriteOutcome::Rejected(child_hash));
600
601                // Update the caller with the error.
602                let _ = rsp_tx.send(result.map(|()| child_hash).map_err(Into::into));
603
604                // Skip the things we only need to do for successfully committed blocks
605                continue;
606            }
607
608            // A successfully committed block supersedes any contextual error
609            // recorded for a different block body with the same header hash.
610            parent_error_map.shift_remove(&child_hash);
611
612            forget_evicted_blocks(non_finalized_state, non_finalized_rejected_sender);
613
614            // Committing blocks to the finalized state keeps the same chain,
615            // so we can update the chain seen by the rest of the application now.
616            //
617            // TODO: if this causes state request errors due to chain conflicts,
618            //       fix the `service::read` bugs,
619            //       or do the channel update after the finalized state commit
620            let tip_block_height = update_latest_chain_channels(
621                non_finalized_state,
622                &finalized_state.db,
623                chain_tip_sender,
624                non_finalized_state_sender,
625                backup_dir_path.as_deref(),
626            )
627            .expect("just successfully inserted a non-finalized block above");
628
629            // Readers can now find the block's outputs in the published state, so the state
630            // service doesn't need its own copies.
631            let _ =
632                non_finalized_rejected_sender.send(NonFinalizedWriteOutcome::Committed(child_hash));
633
634            // Update the caller with the result.
635            let _ = rsp_tx.send(result.map(|()| child_hash).map_err(Into::into));
636            drop((replaced_snapshot, replaced_chain, replaced_proposal));
637
638            // A prepared chain that the best chain has passed can't be used any more.
639            non_finalized_state.drop_passed_prepared_chain();
640
641            finalize_root_blocks_and_forget_evicted(
642                finalized_state,
643                non_finalized_state,
644                &mut prev_finalized_note_commitment_trees,
645                non_finalized_rejected_sender,
646                chain_tip_sender,
647                non_finalized_state_sender,
648                backup_dir_path.as_deref(),
649            );
650
651            // Update the metrics if semantic and contextual validation passes
652            //
653            // TODO: split this out into a function?
654            metrics::counter!("state.full_verifier.committed.block.count").increment(1);
655            metrics::counter!("zcash.chain.verified.block.total").increment(1);
656
657            metrics::gauge!("state.full_verifier.committed.block.height")
658                .set(tip_block_height.0 as f64);
659
660            // This height gauge is updated for both fully verified and checkpoint blocks.
661            // These updates can't conflict, because this block write task makes sure that blocks
662            // are committed in order.
663            metrics::gauge!("zcash.chain.verified.block.height").set(tip_block_height.0 as f64);
664
665            tracing::trace!("finished processing queued block");
666        }
667
668        // We're finished receiving non-finalized blocks from the state, and
669        // done writing to the finalized state, so we can force it to shut down.
670        finalized_state.db.shutdown(true);
671        std::mem::drop(self.finalized_state);
672    }
673}
674
675#[cfg(test)]
676mod tests;