Skip to main content

zebra_state/service/read/
find.rs

1//! Finding and reading block hashes and headers, in response to peer requests.
2//!
3//! In the functions in this module:
4//!
5//! The block write task commits blocks to the finalized state before updating
6//! `chain` with a cached copy of the best non-finalized chain from
7//! `NonFinalizedState.chain_set`. Then the block commit task can commit additional blocks to
8//! the finalized state after we've cloned the `chain`.
9//!
10//! This means that some blocks can be in both:
11//! - the cached [`Chain`], and
12//! - the shared finalized [`ZebraDb`] reference.
13
14use std::{
15    iter,
16    ops::{RangeBounds, RangeInclusive},
17    sync::Arc,
18};
19
20use chrono::{DateTime, Utc};
21use zebra_chain::{
22    amount::NonNegative,
23    block::{self, Block, Height},
24    serialization::DateTime32,
25    value_balance::ValueBalance,
26};
27
28use crate::{
29    constants,
30    service::{
31        block_iter::any_chain_ancestor_iter,
32        check::{difficulty::POW_MEDIAN_BLOCK_SPAN, AdjustedDifficulty},
33        finalized_state::ZebraDb,
34        non_finalized_state::{Chain, NonFinalizedState},
35        read::{self, block::block_header, FINALIZED_STATE_QUERY_RETRIES},
36    },
37    BoxError, KnownBlock,
38};
39
40#[cfg(test)]
41mod tests;
42
43/// Returns the tip of the best chain in the non-finalized or finalized state.
44pub fn best_tip(
45    non_finalized_state: &NonFinalizedState,
46    db: &ZebraDb,
47) -> Option<(block::Height, block::Hash)> {
48    tip(non_finalized_state.best_chain(), db)
49}
50
51/// Returns the tip of `chain`.
52/// If there is no chain, returns the tip of `db`.
53pub fn tip<C>(chain: Option<C>, db: &ZebraDb) -> Option<(Height, block::Hash)>
54where
55    C: AsRef<Chain>,
56{
57    // # Correctness
58    //
59    // If there is an overlap between the non-finalized and finalized states,
60    // where the finalized tip is above the non-finalized tip,
61    // Zebra is receiving a lot of blocks, or this request has been delayed for a long time,
62    // so it is acceptable to return either tip.
63    chain
64        .map(|chain| chain.as_ref().non_finalized_tip())
65        .or_else(|| db.tip())
66}
67
68/// Returns the tip block of `chain`.
69/// If there is no chain, returns the tip of `db`.
70///
71/// Returns an error if primary data is incomplete. An incomplete secondary view returns `None`.
72pub fn tip_block<C>(
73    chain: Option<C>,
74    db: &ZebraDb,
75) -> Result<Option<Arc<Block>>, crate::BlockReadError>
76where
77    C: AsRef<Chain>,
78{
79    // # Correctness
80    //
81    // If there is an overlap between the non-finalized and finalized states,
82    // where the finalized tip is above the non-finalized tip,
83    // Zebra is receiving a lot of blocks, or this request has been delayed for a long time,
84    // so it is acceptable to return either tip.
85    chain
86        .and_then(|chain| chain.as_ref().tip_block().map(|b| b.block.clone()))
87        .map_or_else(|| db.tip_block(), |block| Ok(Some(block)))
88}
89
90/// Returns the tip [`Height`] of `chain`.
91/// If there is no chain, returns the tip of `db`.
92pub fn tip_height<C>(chain: Option<C>, db: &ZebraDb) -> Option<Height>
93where
94    C: AsRef<Chain>,
95{
96    tip(chain, db).map(|(height, _hash)| height)
97}
98
99/// Returns the tip [`block::Hash`] of `chain`.
100/// If there is no chain, returns the tip of `db`.
101#[allow(dead_code)]
102pub fn tip_hash<C>(chain: Option<C>, db: &ZebraDb) -> Option<block::Hash>
103where
104    C: AsRef<Chain>,
105{
106    tip(chain, db).map(|(_height, hash)| hash)
107}
108
109/// Returns the tip of `chain` with its [`ValueBalance`].
110/// If there is no chain, returns the tip of `db`.
111pub fn tip_with_value_balance<C>(
112    chain: Option<C>,
113    db: &ZebraDb,
114) -> Result<Option<(Height, block::Hash, ValueBalance<NonNegative>)>, BoxError>
115where
116    C: AsRef<Chain>,
117{
118    match chain.map(|chain| chain.as_ref().non_finalized_tip_with_value_balance()) {
119        tip_with_value_balance @ Some(_) => Ok(tip_with_value_balance),
120        None => {
121            // Retry the finalized state query if it was interrupted by a finalizing block.
122            //
123            // TODO: refactor this into a generic retry(finalized_closure, process_and_check_closure) fn
124            for _ in 0..=FINALIZED_STATE_QUERY_RETRIES {
125                let tip @ Some((tip_height, tip_hash)) = db.tip() else {
126                    return Ok(None);
127                };
128
129                let value_balance = db.finalized_value_pool();
130
131                if tip == db.tip() {
132                    return Ok(Some((tip_height, tip_hash, value_balance)));
133                }
134            }
135
136            Err("Zebra is committing too many blocks to the state, \
137                    wait until it syncs to the chain tip"
138                .into())
139        }
140    }
141}
142
143/// Return the depth of block `hash` from the chain tip.
144/// Searches `chain` for `hash`, then searches `db`.
145pub fn depth<C>(chain: Option<C>, db: &ZebraDb, hash: block::Hash) -> Option<u32>
146where
147    C: AsRef<Chain>,
148{
149    let chain = chain.as_ref();
150
151    // # Correctness
152    //
153    // It is ok to do this lookup in two different calls. Finalized state updates
154    // can only add overlapping blocks, and hashes are unique.
155
156    let tip = tip_height(chain, db)?;
157    let height = height_by_hash(chain, db, hash)?;
158
159    Some(tip.0 - height.0)
160}
161
162/// Returns the location of the block if present in the non-finalized state.
163/// Returns None if the block hash is not found in the non-finalized state.
164pub fn non_finalized_state_contains_block_hash(
165    non_finalized_state: &NonFinalizedState,
166    hash: block::Hash,
167) -> Option<KnownBlock> {
168    let mut chains_iter = non_finalized_state.chain_iter();
169    let is_hash_in_chain = |chain: &Arc<Chain>| chain.contains_block_hash(hash);
170
171    // Equivalent to `chain_set.iter().next_back()` in `NonFinalizedState.best_chain()` method.
172    let best_chain = chains_iter.next();
173
174    match best_chain.map(is_hash_in_chain) {
175        Some(true) => Some(KnownBlock::BestChain),
176        Some(false) if chains_iter.any(is_hash_in_chain) => Some(KnownBlock::SideChain),
177        Some(false) | None => None,
178    }
179}
180
181/// Returns the location of the block if present in the finalized state.
182/// Returns None if the block hash is not found in the finalized state.
183pub fn finalized_state_contains_block_hash(db: &ZebraDb, hash: block::Hash) -> Option<KnownBlock> {
184    db.contains_hash(hash).then_some(KnownBlock::Finalized)
185}
186
187/// Return the height for the block at `hash`, if `hash` is in `chain` or `db`.
188pub fn height_by_hash<C>(chain: Option<C>, db: &ZebraDb, hash: block::Hash) -> Option<Height>
189where
190    C: AsRef<Chain>,
191{
192    // # Correctness
193    //
194    // Finalized state updates can only add overlapping blocks, and hashes are unique.
195
196    chain
197        .and_then(|chain| chain.as_ref().height_by_hash(hash))
198        .or_else(|| db.height(hash))
199}
200
201/// Return the hash for the block at `height`, if `height` is in `chain` or `db`.
202pub fn hash_by_height<C>(chain: Option<C>, db: &ZebraDb, height: Height) -> Option<block::Hash>
203where
204    C: AsRef<Chain>,
205{
206    // # Correctness
207    //
208    // Finalized state updates can only add overlapping blocks, and heights are unique
209    // in the current `chain`.
210    //
211    // If there is an overlap between the non-finalized and finalized states,
212    // where the finalized tip is above the non-finalized tip,
213    // Zebra is receiving a lot of blocks, or this request has been delayed for a long time,
214    // so it is acceptable to return hashes from either chain.
215
216    chain
217        .and_then(|chain| chain.as_ref().hash_by_height(height))
218        .or_else(|| db.hash(height))
219}
220
221/// Return true if `hash` is in `chain` or `db`.
222pub fn chain_contains_hash<C>(chain: Option<C>, db: &ZebraDb, hash: block::Hash) -> bool
223where
224    C: AsRef<Chain>,
225{
226    // # Correctness
227    //
228    // Finalized state updates can only add overlapping blocks, and hashes are unique.
229    //
230    // If there is an overlap between the non-finalized and finalized states,
231    // where the finalized tip is above the non-finalized tip,
232    // Zebra is receiving a lot of blocks, or this request has been delayed for a long time,
233    // so it is acceptable to return hashes from either chain.
234
235    chain
236        .map(|chain| chain.as_ref().height_by_hash.contains_key(&hash))
237        .unwrap_or(false)
238        || db.contains_hash(hash)
239}
240
241/// Create a block locator from `chain` and `db`.
242///
243/// A block locator is used to efficiently find an intersection of two node's chains.
244/// It contains a list of block hashes at decreasing heights, skipping some blocks,
245/// so that any intersection can be located, no matter how long or different the chains are.
246pub fn block_locator<C>(chain: Option<C>, db: &ZebraDb) -> Option<Vec<block::Hash>>
247where
248    C: AsRef<Chain>,
249{
250    let chain = chain.as_ref();
251
252    // # Correctness
253    //
254    // It is ok to do these lookups using multiple database calls. Finalized state updates
255    // can only add overlapping blocks, and hashes are unique.
256    //
257    // If there is an overlap between the non-finalized and finalized states,
258    // where the finalized tip is above the non-finalized tip,
259    // Zebra is receiving a lot of blocks, or this request has been delayed for a long time,
260    // so it is acceptable to return a set of hashes from multiple chains.
261    //
262    // Multiple heights can not map to the same hash, even in different chains,
263    // because the block height is covered by the block hash,
264    // via the transaction merkle tree commitments.
265    let tip_height = tip_height(chain, db)?;
266
267    let heights = block_locator_heights(tip_height);
268    let mut hashes = Vec::with_capacity(heights.len());
269
270    for height in heights {
271        if let Some(hash) = hash_by_height(chain, db, height) {
272            hashes.push(hash);
273        }
274    }
275
276    Some(hashes)
277}
278
279/// Get the heights of the blocks for constructing a block_locator list.
280///
281/// Zebra uses a decreasing list of block heights, starting at the tip, and skipping some heights.
282/// See [`block_locator()`] for details.
283pub fn block_locator_heights(tip_height: block::Height) -> Vec<block::Height> {
284    // The initial height in the returned `vec` is the tip height,
285    // and the final height is `MAX_BLOCK_REORG_HEIGHT` below the tip.
286    //
287    // The initial distance between heights is 1, and it doubles between each subsequent height.
288    // So the number of returned heights is approximately `log_2(MAX_BLOCK_REORG_HEIGHT)`.
289
290    // Limit the maximum locator depth.
291    let min_locator_height = tip_height
292        .0
293        .saturating_sub(constants::MAX_BLOCK_REORG_HEIGHT);
294
295    // Create an exponentially decreasing set of heights.
296    let exponential_locators = iter::successors(Some(1u32), |h| h.checked_mul(2))
297        .flat_map(move |step| tip_height.0.checked_sub(step));
298
299    // Start at the tip, add decreasing heights, and end MAX_BLOCK_REORG_HEIGHT below the tip.
300    let locators = iter::once(tip_height.0)
301        .chain(exponential_locators)
302        .take_while(move |&height| height > min_locator_height)
303        .chain(iter::once(min_locator_height))
304        .map(block::Height)
305        .collect();
306
307    tracing::debug!(
308        ?tip_height,
309        ?min_locator_height,
310        ?locators,
311        "created block locator"
312    );
313
314    locators
315}
316
317/// Find the first hash that's in the peer's `known_blocks`, and in `chain` or `db`.
318///
319/// Returns `None` if:
320///   * there is no matching hash in the chain, or
321///   * the state is empty.
322fn find_chain_intersection<C>(
323    chain: Option<C>,
324    db: &ZebraDb,
325    known_blocks: Vec<block::Hash>,
326) -> Option<block::Hash>
327where
328    C: AsRef<Chain>,
329{
330    // We can get a block locator request before we have downloaded the genesis block
331    if chain.is_none() && db.is_empty() {
332        return None;
333    }
334
335    let chain = chain.as_ref();
336
337    known_blocks
338        .iter()
339        .find(|&&hash| chain_contains_hash(chain, db, hash))
340        .cloned()
341}
342
343/// Returns a range of [`Height`]s in the chain,
344/// starting after the `intersection` hash on the chain.
345///
346/// See [`find_chain_hashes()`] for details.
347fn find_chain_height_range<C>(
348    chain: Option<C>,
349    db: &ZebraDb,
350    intersection: Option<block::Hash>,
351    stop: Option<block::Hash>,
352    max_len: u32,
353) -> impl RangeBounds<u32> + Iterator<Item = u32>
354where
355    C: AsRef<Chain>,
356{
357    #[allow(clippy::reversed_empty_ranges)]
358    const EMPTY_RANGE: RangeInclusive<u32> = 1..=0;
359
360    assert!(max_len > 0, "max_len must be at least 1");
361
362    let chain = chain.as_ref();
363
364    // We can get a block locator request before we have downloaded the genesis block
365    let chain_tip_height = if let Some(height) = tip_height(chain, db) {
366        height
367    } else {
368        tracing::debug!(
369            response_len = ?0,
370            "responding to peer GetBlocks or GetHeaders with empty state",
371        );
372
373        return EMPTY_RANGE;
374    };
375
376    // Find the intersection height
377    let intersection_height = match intersection {
378        Some(intersection_hash) => match height_by_hash(chain, db, intersection_hash) {
379            Some(intersection_height) => Some(intersection_height),
380
381            // A recently committed block dropped the intersection we previously found
382            None => {
383                info!(
384                    ?intersection,
385                    ?stop,
386                    ?max_len,
387                    "state found intersection but then dropped it, ignoring request",
388                );
389                return EMPTY_RANGE;
390            }
391        },
392        // There is no intersection
393        None => None,
394    };
395
396    // Now find the start and maximum heights
397    let (start_height, max_height) = match intersection_height {
398        // start after the intersection_height, and return max_len hashes or headers
399        Some(intersection_height) => (
400            Height(intersection_height.0 + 1),
401            Height(intersection_height.0 + max_len),
402        ),
403        // start at genesis, and return max_len hashes or headers
404        None => (Height(0), Height(max_len - 1)),
405    };
406
407    let stop_height = stop.and_then(|hash| height_by_hash(chain, db, hash));
408
409    // Compute the final height, making sure it is:
410    //   * at or below our chain tip, and
411    //   * at or below the height of the stop hash.
412    let final_height = std::cmp::min(max_height, chain_tip_height);
413    let final_height = stop_height
414        .map(|stop_height| std::cmp::min(final_height, stop_height))
415        .unwrap_or(final_height);
416
417    // TODO: implement Step for Height, when Step stabilises
418    //       https://github.com/rust-lang/rust/issues/42168
419    let height_range = start_height.0..=final_height.0;
420    let response_len = height_range.clone().count();
421
422    tracing::debug!(
423        ?start_height,
424        ?final_height,
425        ?response_len,
426        ?chain_tip_height,
427        ?stop_height,
428        ?intersection_height,
429        ?intersection,
430        ?stop,
431        ?max_len,
432        "responding to peer GetBlocks or GetHeaders",
433    );
434
435    // Check the function implements the Find protocol
436    assert!(
437        response_len <= max_len.try_into().expect("fits in usize"),
438        "a Find response must not exceed the maximum response length",
439    );
440
441    height_range
442}
443
444/// Returns a list of [`block::Hash`]es in the chain,
445/// following the `intersection` with the chain.
446///
447/// See [`find_chain_hashes()`] for details.
448fn collect_chain_hashes<C>(
449    chain: Option<C>,
450    db: &ZebraDb,
451    intersection: Option<block::Hash>,
452    stop: Option<block::Hash>,
453    max_len: u32,
454) -> Vec<block::Hash>
455where
456    C: AsRef<Chain>,
457{
458    let chain = chain.as_ref();
459
460    let height_range = find_chain_height_range(chain, db, intersection, stop, max_len);
461
462    // All the hashes should be in the chain.
463    // If they are not, we don't want to return them.
464    let hashes: Vec<block::Hash> = height_range.into_iter().map_while(|height| {
465        let hash = hash_by_height(chain, db, Height(height));
466
467        // A recently committed block dropped the intersection we previously found.
468        if hash.is_none() {
469            info!(
470                ?intersection,
471                ?stop,
472                ?max_len,
473                "state found height range, but then partially dropped it, returning partial response",
474            );
475        }
476
477        tracing::trace!(
478            ?hash,
479            ?height,
480            ?intersection,
481            ?stop,
482            ?max_len,
483            "adding hash to peer Find response",
484        );
485
486        hash
487    }).collect();
488
489    // Check the function implements the Find protocol
490    assert!(
491        intersection
492            .map(|hash| !hashes.contains(&hash))
493            .unwrap_or(true),
494        "the list must not contain the intersection hash",
495    );
496
497    if let (Some(stop), Some((_, hashes_except_last))) = (stop, hashes.split_last()) {
498        assert!(
499            !hashes_except_last.contains(&stop),
500            "if the stop hash is in the list, it must be the final hash",
501        );
502    }
503
504    hashes
505}
506
507/// Returns a list of [`block::Header`]s in the chain,
508/// following the `intersection` with the chain.
509///
510/// See [`find_chain_hashes()`] for details.
511fn collect_chain_headers<C>(
512    chain: Option<C>,
513    db: &ZebraDb,
514    intersection: Option<block::Hash>,
515    stop: Option<block::Hash>,
516    max_len: u32,
517) -> Vec<Arc<block::Header>>
518where
519    C: AsRef<Chain>,
520{
521    let chain = chain.as_ref();
522
523    let height_range = find_chain_height_range(chain, db, intersection, stop, max_len);
524
525    // We don't check that this function implements the Find protocol,
526    // because fetching extra hashes (or re-calculating hashes) is expensive.
527    // (This was one of the most expensive and longest-running functions in the state.)
528
529    // All the headers should be in the chain.
530    // If they are not, we don't want to return them.
531    height_range.into_iter().map_while(|height| {
532        let header = block_header(chain, db, Height(height).into());
533
534        // A recently committed block dropped the intersection we previously found
535        if header.is_none() {
536            info!(
537                ?intersection,
538                ?stop,
539                ?max_len,
540                "state found height range, but then partially dropped it, returning partial response",
541            );
542        }
543
544        tracing::trace!(
545            ?height,
546            ?intersection,
547            ?stop,
548            ?max_len,
549            "adding header to peer Find response",
550        );
551
552        header
553    }).collect()
554}
555
556/// Finds the first hash that's in the peer's `known_blocks` and the chain.
557/// Returns a list of hashes that follow that intersection, from the chain.
558///
559/// Starts from the first matching hash in the chain, ignoring all other hashes in
560/// `known_blocks`. If there is no matching hash in the chain, starts from the genesis
561/// hash.
562///
563/// Includes finalized and non-finalized blocks.
564///
565/// Stops the list of hashes after:
566///   * adding the tip,
567///   * adding the `stop` hash to the list, if it is in the chain, or
568///   * adding `max_len` hashes to the list.
569///
570/// Returns an empty list if the state is empty,
571/// and a partial or empty list if the found heights are concurrently modified.
572pub fn find_chain_hashes<C>(
573    chain: Option<C>,
574    db: &ZebraDb,
575    known_blocks: Vec<block::Hash>,
576    stop: Option<block::Hash>,
577    max_len: u32,
578) -> Vec<block::Hash>
579where
580    C: AsRef<Chain>,
581{
582    // # Correctness
583    //
584    // See the note in `block_locator()`.
585
586    let chain = chain.as_ref();
587    let intersection = find_chain_intersection(chain, db, known_blocks);
588
589    collect_chain_hashes(chain, db, intersection, stop, max_len)
590}
591
592/// Finds the fork point between the locator `known_blocks` and the best chain.
593///
594/// `known_blocks` is a block locator: hashes ordered from highest height to lowest
595/// height. Returns the height and hash of the highest locator entry that is on the best
596/// chain (in `chain` or the finalized `db`) — the most recent common ancestor — or
597/// `None` if no locator entry is on the best chain.
598///
599/// Returns `None` if the state is empty.
600pub fn find_fork_point<C>(
601    chain: Option<C>,
602    db: &ZebraDb,
603    known_blocks: Vec<block::Hash>,
604) -> Option<(Height, block::Hash)>
605where
606    C: AsRef<Chain>,
607{
608    // # Correctness
609    //
610    // See the note in `block_locator()`.
611
612    let chain = chain.as_ref();
613
614    let fork_hash = find_chain_intersection(chain, db, known_blocks)?;
615    let fork_height = height_by_hash(chain, db, fork_hash)?;
616
617    Some((fork_height, fork_hash))
618}
619
620/// Finds the first hash that's in the peer's `known_blocks` and the chain.
621/// Returns a list of headers that follow that intersection, from the chain.
622///
623/// See [`find_chain_hashes()`] for details.
624pub fn find_chain_headers<C>(
625    chain: Option<C>,
626    db: &ZebraDb,
627    known_blocks: Vec<block::Hash>,
628    stop: Option<block::Hash>,
629    max_len: u32,
630) -> Vec<Arc<block::Header>>
631where
632    C: AsRef<Chain>,
633{
634    // # Correctness
635    //
636    // Headers are looked up by their hashes using a unique mapping,
637    // so it is not possible for multiple hashes to look up the same header,
638    // even across different chains.
639    //
640    // See also the note in `block_locator()`.
641
642    let chain = chain.as_ref();
643    let intersection = find_chain_intersection(chain, db, known_blocks);
644
645    collect_chain_headers(chain, db, intersection, stop, max_len)
646}
647
648/// Returns the median-time-past of the *next* block to be added to the best chain in
649/// `non_finalized_state` or `db`.
650///
651/// # Panics
652///
653/// - If we don't have enough blocks in the state.
654pub fn next_median_time_past(
655    non_finalized_state: &NonFinalizedState,
656    db: &ZebraDb,
657) -> Result<DateTime32, BoxError> {
658    let mut best_relevant_chain_result = best_relevant_chain(non_finalized_state, db);
659
660    // Retry the finalized state query if it was interrupted by a finalizing block.
661    //
662    // TODO: refactor this into a generic retry(finalized_closure, process_and_check_closure) fn
663    for _ in 0..FINALIZED_STATE_QUERY_RETRIES {
664        if best_relevant_chain_result.is_ok() {
665            break;
666        }
667
668        best_relevant_chain_result = best_relevant_chain(non_finalized_state, db);
669    }
670
671    Ok(calculate_median_time_past(best_relevant_chain_result?))
672}
673
674/// Do a consistency check by checking the finalized tip before and after all other database queries.
675///
676/// Returns recent header times in reverse height order from the tip.
677/// Returns an error if the tip obtained before and after is not the same.
678///
679/// # Panics
680///
681/// - If we don't have enough blocks in the state.
682fn best_relevant_chain(
683    non_finalized_state: &NonFinalizedState,
684    db: &ZebraDb,
685) -> Result<Vec<DateTime<Utc>>, BoxError> {
686    let state_tip_before_queries = read::best_tip(non_finalized_state, db).ok_or_else(|| {
687        BoxError::from("Zebra's state is empty, wait until it syncs to the chain tip")
688    })?;
689
690    let best_relevant_chain = any_chain_ancestor_iter::<block::Header>(
691        non_finalized_state,
692        db,
693        state_tip_before_queries.1,
694    )
695    .take(POW_MEDIAN_BLOCK_SPAN)
696    .map(|header| header.time)
697    .collect::<Vec<_>>();
698
699    if best_relevant_chain.is_empty() {
700        return Err("missing genesis block, wait until it is committed".into());
701    };
702
703    let state_tip_after_queries =
704        read::best_tip(non_finalized_state, db).expect("already checked for an empty tip");
705
706    if state_tip_before_queries != state_tip_after_queries {
707        return Err("Zebra is committing too many blocks to the state, \
708                    wait until it syncs to the chain tip"
709            .into());
710    }
711
712    Ok(best_relevant_chain)
713}
714
715/// Returns the median-time-past for the provided header times.
716///
717/// The `relevant_times` has header times in reverse height order.
718///
719/// See [`next_median_time_past()`] for details.
720pub(crate) fn calculate_median_time_past(relevant_times: Vec<DateTime<Utc>>) -> DateTime32 {
721    // > Define the median-time-past of a block to be the median of the nTime fields of the
722    // > preceding PoWMedianBlockSpan blocks (or all preceding blocks if there are fewer than
723    // > PoWMedianBlockSpan). The median-time-past of a genesis block is not defined.
724    // https://zips.z.cash/protocol/protocol.pdf#blockheader
725    let median_time_past = AdjustedDifficulty::median_time(relevant_times);
726
727    DateTime32::try_from(median_time_past).expect("valid blocks have in-range times")
728}