Skip to main content

zebra_state/service/read/
difficulty.rs

1//! Get context and calculate difficulty for the next block.
2
3use std::sync::Arc;
4
5use chrono::{DateTime, Utc};
6
7use zebra_chain::{
8    block::{self, Hash, Height},
9    history_tree::HistoryTree,
10    parameters::{Network, NetworkUpgrade},
11    primitives::zcash_history::BlockCommitmentTreeRoots,
12    serialization::{DateTime32, Duration32},
13    work::difficulty::{CompactDifficulty, PartialCumulativeWork, Work},
14};
15
16use crate::{
17    service::{
18        block_iter::any_chain_ancestor_iter,
19        check::{
20            block_commitment_is_valid_for_chain_history,
21            difficulty::{
22                pow_adjustment_block_span, BLOCK_MAX_TIME_SINCE_MEDIAN, POW_MEDIAN_BLOCK_SPAN,
23            },
24            difficulty_threshold_and_time_are_valid, AdjustedDifficulty,
25        },
26        finalized_state::ZebraDb,
27        precomputed_trees::PrecomputedTrees,
28        read::{
29            self, find::calculate_median_time_past, tree::history_tree,
30            FINALIZED_STATE_QUERY_RETRIES,
31        },
32        NonFinalizedState,
33    },
34    BoxError, GetBlockTemplateChainInfo,
35};
36
37/// Returns the [`GetBlockTemplateChainInfo`] for the current best chain.
38///
39/// # Panics
40///
41/// - If we don't have enough blocks in the state.
42pub fn get_block_template_chain_info(
43    non_finalized_state: &NonFinalizedState,
44    db: &ZebraDb,
45    network: &Network,
46) -> Result<GetBlockTemplateChainInfo, BoxError> {
47    let mut best_relevant_chain_and_history_tree_result =
48        best_relevant_chain_and_history_tree(non_finalized_state, db, network);
49
50    // Retry the finalized state query if it was interrupted by a finalizing block.
51    //
52    // TODO: refactor this into a generic retry(finalized_closure, process_and_check_closure) fn
53    for _ in 0..FINALIZED_STATE_QUERY_RETRIES {
54        if best_relevant_chain_and_history_tree_result.is_ok() {
55            break;
56        }
57
58        best_relevant_chain_and_history_tree_result =
59            best_relevant_chain_and_history_tree(non_finalized_state, db, network);
60    }
61
62    let (best_tip_height, best_tip_hash, best_relevant_chain, best_tip_history_tree) =
63        best_relevant_chain_and_history_tree_result?;
64
65    let chain_value_pools = {
66        let (_, tip_hash, chain_value_pools) =
67            read::find::tip_with_value_balance(non_finalized_state.best_chain(), db)?
68                .ok_or("Zebra's state is empty, wait until it syncs to the chain tip")?;
69
70        if tip_hash != best_tip_hash {
71            return Err("Zebra is committing too many blocks to the state, \
72                        wait until it syncs to the chain tip"
73                .into());
74        }
75
76        chain_value_pools
77    };
78
79    difficulty_time_and_history_tree(
80        best_relevant_chain,
81        best_tip_height,
82        best_tip_hash,
83        network,
84        best_tip_history_tree,
85        chain_value_pools,
86        DateTime32::now(),
87    )
88}
89
90/// Accepts a `non_finalized_state`, [`ZebraDb`], `num_blocks`, and a block hash to start at.
91///
92/// Iterates over up to the last `num_blocks` blocks, summing up their total work.
93/// Divides that total by the number of seconds between the timestamp of the
94/// first block in the iteration and 1 block below the last block.
95///
96/// Returns the solution rate per second for the current best chain, or `None` if
97/// the `start_hash` and at least 1 block below it are not found in the chain.
98#[allow(unused)]
99pub fn solution_rate(
100    non_finalized_state: &NonFinalizedState,
101    db: &ZebraDb,
102    num_blocks: usize,
103    start_hash: Hash,
104) -> Option<u128> {
105    // Take 1 extra header for calculating the number of seconds between when mining on the first
106    // block likely started. The work for the extra header is not added to `total_work`.
107    //
108    // Since we can't take more headers than are actually in the chain, this automatically limits
109    // `num_blocks` to the chain length, like `zcashd` does.
110    let mut header_iter =
111        any_chain_ancestor_iter::<block::Header>(non_finalized_state, db, start_hash)
112            .take(num_blocks.checked_add(1).unwrap_or(num_blocks))
113            .peekable();
114
115    let get_work = |header: &block::Header| {
116        header
117            .difficulty_threshold
118            .to_work()
119            .expect("work has already been validated")
120    };
121
122    // If there are no blocks in the range, we can't return a useful result.
123    let last_header = header_iter.peek()?;
124
125    // Initialize the cumulative variables.
126    let mut min_time = last_header.time;
127    let mut max_time = last_header.time;
128
129    let mut last_work = Work::zero();
130    let mut total_work = PartialCumulativeWork::zero();
131
132    for header in header_iter {
133        min_time = min_time.min(header.time);
134        max_time = max_time.max(header.time);
135
136        last_work = get_work(&header);
137        total_work += last_work;
138    }
139
140    // We added an extra header so we could estimate when mining on the first block
141    // in the window of `num_blocks` likely started. But we don't want to add the work
142    // for that header.
143    total_work -= last_work;
144
145    let work_duration = (max_time - min_time).num_seconds();
146
147    // Avoid division by zero errors and negative average work.
148    // This also handles the case where there's only one block in the range.
149    if work_duration <= 0 {
150        return None;
151    }
152
153    Some(total_work.as_u128() / work_duration as u128)
154}
155
156/// Do a consistency check by checking the finalized tip before and after all other database
157/// queries.
158///
159/// Returns the best chain tip, recent header difficulties and times in reverse height order,
160/// and the tip history tree.
161/// Returns an error if the tip obtained before and after is not the same.
162///
163/// # Panics
164///
165/// - If we don't have enough blocks in the state.
166fn best_relevant_chain_and_history_tree(
167    non_finalized_state: &NonFinalizedState,
168    db: &ZebraDb,
169    network: &Network,
170) -> Result<
171    (
172        Height,
173        block::Hash,
174        Vec<(CompactDifficulty, DateTime<Utc>)>,
175        Arc<HistoryTree>,
176    ),
177    BoxError,
178> {
179    let state_tip_before_queries = read::best_tip(non_finalized_state, db).ok_or_else(|| {
180        BoxError::from("Zebra's state is empty, wait until it syncs to the chain tip")
181    })?;
182
183    // The candidate block is the one after the tip, and ZIP 218 makes the span depend on its
184    // height, so only fetch as many headers as that height actually needs.
185    let candidate_height = state_tip_before_queries.0.next()?;
186    let block_span = pow_adjustment_block_span(network, candidate_height);
187
188    let best_relevant_chain = any_chain_ancestor_iter::<block::Header>(
189        non_finalized_state,
190        db,
191        state_tip_before_queries.1,
192    )
193    .take(block_span)
194    .map(|header| (header.difficulty_threshold, header.time))
195    .collect::<Vec<_>>();
196
197    if best_relevant_chain.is_empty() {
198        return Err("missing genesis block, wait until it is committed".into());
199    };
200
201    let history_tree = history_tree(
202        non_finalized_state.best_chain(),
203        db,
204        state_tip_before_queries.into(),
205    )
206    .expect("tip hash should exist in the chain");
207
208    let state_tip_after_queries =
209        read::best_tip(non_finalized_state, db).expect("already checked for an empty tip");
210
211    if state_tip_before_queries != state_tip_after_queries {
212        return Err("Zebra is committing too many blocks to the state, \
213                    wait until it syncs to the chain tip"
214            .into());
215    }
216
217    Ok((
218        state_tip_before_queries.0,
219        state_tip_before_queries.1,
220        best_relevant_chain,
221        history_tree,
222    ))
223}
224
225/// Checks that `header` at `height` is a direct child of the best tip, and that its difficulty
226/// threshold and time are valid in that context.
227///
228/// Returns the history tree of the best tip, which is the parent of the candidate block.
229/// This does not check the header's proof of work.
230pub fn check_best_tip_header(
231    non_finalized_state: &NonFinalizedState,
232    db: &ZebraDb,
233    network: &Network,
234    header: &block::Header,
235    height: Height,
236) -> Result<Arc<HistoryTree>, BoxError> {
237    let extends_tip = |tip_height: Height, tip_hash: block::Hash| {
238        header.previous_block_hash == tip_hash && tip_height.next().ok() == Some(height)
239    };
240
241    // Reject a header that doesn't extend the best tip before loading the blocks for the
242    // difficulty adjustment and the history tree. Peers send these headers, and most stale ones
243    // stop here.
244    if read::best_tip(non_finalized_state, db)
245        .is_some_and(|(tip_height, tip_hash)| !extends_tip(tip_height, tip_hash))
246    {
247        return Err("header does not extend the committed best tip".into());
248    }
249
250    // The finalized tip can change between the two reads, so check the loaded tip as well.
251    let (tip_height, tip_hash, relevant_data, history_tree) =
252        best_relevant_chain_and_history_tree(non_finalized_state, db, network)?;
253
254    if !extends_tip(tip_height, tip_hash) {
255        return Err("header does not extend the committed best tip".into());
256    }
257
258    // The difficulty adjustment needs a representable time, and its work calculation needs a
259    // valid threshold. Peers control both fields.
260    if header.difficulty_threshold.to_work().is_none() || DateTime32::try_from(header.time).is_err()
261    {
262        return Err("header has an invalid difficulty threshold or time".into());
263    }
264
265    difficulty_threshold_and_time_are_valid(
266        header.difficulty_threshold,
267        AdjustedDifficulty::new_from_header_time(header.time, tip_height, network, relevant_data),
268    )?;
269
270    Ok(history_tree)
271}
272
273/// Checks that `block` is an NU5 or later direct child of the best tip, and that its header commits
274/// to the best tip's chain history and to the block's own authorizing data.
275///
276/// This does not check the block's proof of work, Merkle root, or transactions.
277pub fn check_best_tip_block_commitments(
278    non_finalized_state: &NonFinalizedState,
279    db: &ZebraDb,
280    network: &Network,
281    block: Arc<block::Block>,
282) -> Result<(), BoxError> {
283    let height = block
284        .coinbase_height()
285        .ok_or("block has no coinbase height")?;
286
287    // Earlier blocks do not commit to their transactions' authorizing data.
288    if NetworkUpgrade::current(network, height) < NetworkUpgrade::Nu5 {
289        return Err("block is before the NU5 block commitments".into());
290    }
291
292    let history_tree =
293        check_best_tip_header(non_finalized_state, db, network, &block.header, height)?;
294
295    block_commitment_is_valid_for_chain_history(block, network, &history_tree)?;
296
297    Ok(())
298}
299
300/// Returns the [`GetBlockTemplateChainInfo`] for mining on top of `block`, and the note commitment
301/// trees after `block`, without committing it.
302///
303/// `block` must have a valid proof of work and transaction Merkle root, and its shielded data
304/// must be within the block limits. This checks the contextual rules for its header, which don't
305/// depend on its transactions being valid: it extends the best tip, its difficulty threshold and
306/// time are the expected ones, and its header commits to the chain history and to its
307/// authorizing data.
308///
309/// The returned chain info has empty chain value pools, so this returns an error if the subsidy
310/// of the block after `block` depends on them.
311pub(crate) fn mining_candidate_chain_info(
312    non_finalized_state: &NonFinalizedState,
313    db: &ZebraDb,
314    block: &Arc<block::Block>,
315) -> Result<(GetBlockTemplateChainInfo, PrecomputedTrees), BoxError> {
316    let network = &non_finalized_state.network;
317    let height = block
318        .coinbase_height()
319        .ok_or("block has no coinbase height")?;
320    let child_height = height.next()?;
321
322    // The value pools after `block` are only known once its transactions are verified.
323    if zebra_chain::parameters::subsidy::nsm_reissuance_is_active(child_height, network) {
324        return Err("the next block's subsidy depends on unverified chain value pools".into());
325    }
326
327    let mut history_tree =
328        check_best_tip_header(non_finalized_state, db, network, &block.header, height)?;
329    block_commitment_is_valid_for_chain_history(block.clone(), network, &history_tree)?;
330
331    // Start from the same parent trees as the commit of `block`, so the commit can reuse the
332    // result. The commit only reuses it if its own parent trees are equal.
333    let parent_trees = match non_finalized_state.best_chain() {
334        Some(chain) => chain.note_commitment_trees_for_tip(),
335        None => db.note_commitment_trees_for_tip(),
336    };
337    let trees = PrecomputedTrees::compute(block.clone(), parent_trees)?;
338
339    let sapling_root = trees.output().sapling.root();
340    // Blocks from Sapling to Heartwood commit to the Sapling root, rather than the chain history.
341    if let block::Commitment::FinalSaplingRoot(expected_root) = block.commitment(network)? {
342        if expected_root != sapling_root {
343            return Err("block commits to another Sapling note commitment tree root".into());
344        }
345    }
346
347    Arc::make_mut(&mut history_tree).push(
348        network,
349        block.clone(),
350        BlockCommitmentTreeRoots {
351            sapling: &sapling_root,
352            orchard: &trees.output().orchard.root(),
353            ironwood: &trees.output().ironwood.root(),
354        },
355    )?;
356
357    // The difficulty adjustment for the next block uses `block` and its ancestors.
358    let relevant_data = std::iter::once((block.header.difficulty_threshold, block.header.time))
359        .chain(
360            any_chain_ancestor_iter::<block::Header>(
361                non_finalized_state,
362                db,
363                block.header.previous_block_hash,
364            )
365            .map(|header| (header.difficulty_threshold, header.time)),
366        )
367        .take(pow_adjustment_block_span(network, child_height))
368        .collect();
369
370    let chain_info = difficulty_time_and_history_tree(
371        relevant_data,
372        height,
373        block.hash(),
374        network,
375        history_tree,
376        Default::default(),
377        DateTime32::now(),
378    )?;
379
380    Ok((chain_info, trees))
381}
382
383/// Returns the [`GetBlockTemplateChainInfo`] for the supplied `relevant_data`, tip, `network`,
384/// `history_tree`, and captured local time `now`, or an error if no valid timestamp is available.
385///
386/// The `relevant_data` has header difficulties and times in reverse height order from the tip.
387///
388/// See [`get_block_template_chain_info()`] for details.
389fn difficulty_time_and_history_tree(
390    relevant_data: Vec<(CompactDifficulty, DateTime<Utc>)>,
391    tip_height: Height,
392    tip_hash: block::Hash,
393    network: &Network,
394    history_tree: Arc<HistoryTree>,
395    chain_value_pools: zebra_chain::value_balance::ValueBalance<zebra_chain::amount::NonNegative>,
396    now: DateTime32,
397) -> Result<GetBlockTemplateChainInfo, BoxError> {
398    // > For each block other than the genesis block , nTime MUST be strictly greater than
399    // > the median-time-past of that block.
400    // https://zips.z.cash/protocol/protocol.pdf#blockheader
401    let median_time_past = calculate_median_time_past(
402        relevant_data
403            .iter()
404            .take(POW_MEDIAN_BLOCK_SPAN)
405            .map(|(_, time)| *time)
406            .collect(),
407    );
408
409    let min_time = median_time_past
410        .checked_add(Duration32::from_seconds(1))
411        .ok_or("median-time-past leaves no representable block timestamp")?;
412
413    // The context-free local-clock bound applies independently of the network's MTP rule.
414    let max_time = now.saturating_add(Duration32::from_hours(2));
415    let candidate_height = (tip_height + 1).ok_or("next block height is out of range")?;
416    let max_time = if network.is_max_block_time_enforced(candidate_height) {
417        max_time.min(
418            median_time_past.saturating_add(Duration32::from_seconds(BLOCK_MAX_TIME_SINCE_MEDIAN)),
419        )
420    } else {
421        max_time
422    };
423
424    if min_time > max_time {
425        return Err("median-time-past is too far ahead of the local clock".into());
426    }
427
428    // Match zcashd's Regtest behavior by advancing time minimally rather than jumping
429    // from the historical genesis timestamp to the wall clock. This keeps mined
430    // timestamps tightly clustered just above the median-time-past.
431    let cur_time = if network.is_regtest() {
432        min_time
433    } else {
434        now.clamp(min_time, max_time)
435    };
436
437    // Now that we have a valid time, get the difficulty for that time.
438    let difficulty_adjustment = AdjustedDifficulty::new_from_header_time(
439        cur_time.into(),
440        tip_height,
441        network,
442        relevant_data.iter().cloned(),
443    );
444    let expected_difficulty = difficulty_adjustment.expected_difficulty_threshold();
445
446    let mut result = GetBlockTemplateChainInfo {
447        tip_hash,
448        tip_height,
449        chain_history_root: history_tree.hash(),
450        expected_difficulty,
451        cur_time,
452        min_time,
453        max_time,
454        chain_value_pools,
455    };
456
457    adjust_difficulty_and_time_for_testnet(&mut result, network, tip_height, relevant_data);
458
459    Ok(result)
460}
461
462/// Adjust the difficulty and time for the testnet minimum difficulty rule.
463///
464/// The `relevant_data` has recent block difficulties and times in reverse order from the tip.
465fn adjust_difficulty_and_time_for_testnet(
466    result: &mut GetBlockTemplateChainInfo,
467    network: &Network,
468    previous_block_height: Height,
469    relevant_data: Vec<(CompactDifficulty, DateTime<Utc>)>,
470) {
471    if network == &Network::Mainnet {
472        return;
473    }
474
475    // On testnet, changing the block time can also change the difficulty.
476    // From height 299188, a block is minimum-difficulty only when its time is strictly more than
477    // six target spacings after its parent before NU7, or eighteen target spacings from NU7.
478    // The threshold is 900 seconds before Blossom and remains 450 seconds from Blossom onward.
479    //
480    // In rare cases, this could make some testnet miners produce invalid blocks,
481    // if they use the full 90 minute time gap in the consensus rules.
482    // (The zcashd getblocktemplate RPC reference doesn't have a max_time field,
483    // so there is no standard way of telling miners that the max_time is smaller.)
484    //
485    // So Zebra adjusts the min or max times to produce a valid time range for the difficulty.
486    // There is still a small chance that miners will produce an invalid block, if they are
487    // just below the max time, and don't check it.
488
489    // The tip is the first relevant data block, because they are in reverse order.
490    let previous_block_time = relevant_data.first().expect("has at least one block").1;
491    let previous_block_time: DateTime32 = previous_block_time
492        .try_into()
493        .expect("valid blocks have in-range times");
494
495    let candidate_height = (previous_block_height + 1).expect("next block height is valid");
496    let Some(minimum_difficulty_spacing) =
497        NetworkUpgrade::minimum_difficulty_spacing_for_height(network, candidate_height)
498    else {
499        // Returns early if the testnet minimum difficulty consensus rule is not active
500        return;
501    };
502
503    let minimum_difficulty_spacing: Duration32 = minimum_difficulty_spacing
504        .try_into()
505        .expect("small positive values are in-range");
506
507    // The first minimum difficulty time is strictly greater than the spacing.
508    // If that threshold is beyond DateTime32, every representable time uses standard difficulty.
509    let std_difficulty_max_time = previous_block_time.saturating_add(minimum_difficulty_spacing);
510    let min_difficulty_min_time =
511        std_difficulty_max_time.saturating_add(Duration32::from_seconds(1));
512
513    // Offer a minimum-difficulty template only once `cur_time` is strictly past
514    // `previous_block_time + minimum_difficulty_spacing` (the latest time a standard-difficulty
515    // block may use; a minimum-difficulty block's time must be strictly greater).
516    //
517    // Switching to a minimum-difficulty template before `cur_time` has reached that point would
518    // require clamping `cur_time` up to `min_time`, i.e. future-dating the block timestamp ahead
519    // of real time purely to obtain minimum difficulty.
520    //
521    // Zebra used to do this, switching 150 seconds early (`2 * PoWTargetSpacing` after Blossom),
522    // via a former `EXTRA_TIME_TO_MINE_A_BLOCK` constant. On a chain with any sustained hashrate,
523    // that behaviour produced a stream of future-dated minimum-difficulty blocks, each of which
524    // sharply reduced the difficulty (the difficulty average is over targets and includes
525    // minimum-difficulty blocks), depressing the difficulty far below equilibrium. See
526    // <https://github.com/zcash/zips/issues/1321>.
527    //
528    // This does not change the underlying difficulty averaging: a genuine gap greater than
529    // the threshold still yields a minimum-difficulty block that reduces the difficulty.
530    // It only stops Zebra from proactively generating such blocks by future-dating timestamps.
531    //
532    // `cur_time` was already clamped into `[min_time, max_time]` by the caller
533    // (`difficulty_time_and_history_tree`); we don't restore the un-clamped `now` before
534    // choosing standard vs. minimum difficulty below, because whichever way that clamp
535    // moved `cur_time`, the outcome is benign:
536    // - clamped up to `min_time`: more likely a minimum-difficulty block, which makes
537    //   mining easier;
538    // - clamped down to `max_time`: almost always a minimum-difficulty block.
539    if result.cur_time <= std_difficulty_max_time {
540        // Standard difficulty: the cur and max time need to exclude min difficulty blocks
541
542        // The maximum time can only be decreased, and only as far as min_time.
543        // The old minimum is still required by other consensus rules.
544        result.max_time = std_difficulty_max_time.clamp(result.min_time, result.max_time);
545
546        // The current time only needs to be decreased if the max_time decreased past it.
547        // Decreasing the current time can't change the difficulty.
548        result.cur_time = result.cur_time.clamp(result.min_time, result.max_time);
549    } else {
550        // Minimum difficulty: the min and cur time need to exclude std difficulty blocks
551
552        // The minimum time can only be increased, and only as far as max_time.
553        // The old maximum is still required by other consensus rules.
554        result.min_time = min_difficulty_min_time.clamp(result.min_time, result.max_time);
555
556        // The current time only needs to be increased if the min_time increased past it.
557        result.cur_time = result.cur_time.clamp(result.min_time, result.max_time);
558
559        // And then the difficulty needs to be updated for cur_time.
560        result.expected_difficulty = AdjustedDifficulty::new_from_header_time(
561            result.cur_time.into(),
562            previous_block_height,
563            network,
564            relevant_data.iter().cloned(),
565        )
566        .expected_difficulty_threshold();
567    }
568}
569
570#[cfg(test)]
571mod tests {
572    //! Unit tests for the Testnet minimum-difficulty template adjustment. They construct the
573    //! [`GetBlockTemplateChainInfo`] and block context with fixed times, exercising
574    //! `adjust_difficulty_and_time_for_testnet` deterministically without reading the real
575    //! clock (the `DateTime32::now()` call lives only in its caller).
576
577    mod vectors;
578
579    use super::*;
580    use crate::service::check::difficulty::MAX_POW_ADJUSTMENT_BLOCK_SPAN;
581    use zebra_chain::work::difficulty::ParameterDifficulty as _;
582
583    // A Testnet height at which the minimum-difficulty rule is active (>= 299188) and the
584    // target spacing is the post-Blossom 75 s, so the minimum-difficulty gap is 6 * 75 = 450 s.
585    const ACTIVE_HEIGHT: Height = Height(2_000_000);
586    const PREV: u32 = 1_600_000_000;
587    const GAP: u32 = 6 * 75;
588
589    /// Recent block difficulties and times in reverse order from the tip, with the most
590    /// recent (first) block time equal to `PREV`. The difficulty thresholds are irrelevant
591    /// to the minimum-difficulty rule under test.
592    fn recent_block_data(network: &Network) -> Vec<(CompactDifficulty, DateTime<Utc>)> {
593        let threshold = network.target_difficulty_limit().to_compact();
594        // Enough blocks for the largest span any height could need, so the test data is never
595        // the limiting factor.
596        (0..MAX_POW_ADJUSTMENT_BLOCK_SPAN)
597            .map(|i| (threshold, DateTime32::from(PREV - i as u32).into()))
598            .collect()
599    }
600
601    /// A [`GetBlockTemplateChainInfo`] with candidate time `cur_time` and a wide
602    /// `[min_time, max_time]` window around `PREV`, so the only clamping under test comes
603    /// from the minimum-difficulty adjustment. `expected_difficulty` starts at a sentinel.
604    fn chain_info(cur_time: u32) -> GetBlockTemplateChainInfo {
605        GetBlockTemplateChainInfo {
606            tip_hash: Hash([0; 32]),
607            tip_height: Height(0),
608            chain_history_root: None,
609            expected_difficulty: CompactDifficulty::default(),
610            cur_time: DateTime32::from(cur_time),
611            min_time: DateTime32::from(PREV - 100),
612            max_time: DateTime32::from(PREV + BLOCK_MAX_TIME_SINCE_MEDIAN),
613            chain_value_pools: Default::default(),
614        }
615    }
616
617    /// A candidate time inside the old "eager" window (`PREV + 300 .. PREV + 450`) must stay
618    /// standard-difficulty and must not be future-dated. Zebra used to switch this to a
619    /// minimum-difficulty template with `cur_time` clamped up to `PREV + 451`.
620    #[test]
621    fn eager_window_stays_standard_difficulty_and_is_not_future_dated() {
622        let network = Network::new_default_testnet();
623        let cur = PREV + 400;
624        let mut result = chain_info(cur);
625
626        adjust_difficulty_and_time_for_testnet(
627            &mut result,
628            &network,
629            ACTIVE_HEIGHT,
630            recent_block_data(&network),
631        );
632
633        // Still standard difficulty: expected_difficulty left untouched (sentinel unchanged).
634        assert_eq!(result.expected_difficulty, CompactDifficulty::default());
635        // Not future-dated: cur_time unchanged, still before the consensus threshold.
636        assert_eq!(result.cur_time, DateTime32::from(cur));
637        // max_time clamped down to the standard-difficulty boundary (PREV + 450).
638        assert_eq!(result.max_time, DateTime32::from(PREV + GAP));
639    }
640
641    /// A candidate time strictly past `PREV + 450` switches to a minimum-difficulty template.
642    #[test]
643    fn past_the_threshold_switches_to_minimum_difficulty() {
644        let network = Network::new_default_testnet();
645        let cur = PREV + 500;
646        let mut result = chain_info(cur);
647
648        adjust_difficulty_and_time_for_testnet(
649            &mut result,
650            &network,
651            ACTIVE_HEIGHT,
652            recent_block_data(&network),
653        );
654
655        // Minimum difficulty: expected_difficulty recomputed to the PoWLimit.
656        assert_eq!(
657            result.expected_difficulty,
658            network.target_difficulty_limit().to_compact()
659        );
660        // min_time raised to PREV + 451; cur_time is already past it, so it is unchanged.
661        assert_eq!(result.min_time, DateTime32::from(PREV + GAP + 1));
662        assert_eq!(result.cur_time, DateTime32::from(cur));
663    }
664
665    /// The gap is a strict `>`: exactly `PREV + 450` is standard, `PREV + 451` is minimum.
666    #[test]
667    fn threshold_is_inclusive_for_standard_difficulty() {
668        let network = Network::new_default_testnet();
669
670        let mut at_threshold = chain_info(PREV + GAP);
671        adjust_difficulty_and_time_for_testnet(
672            &mut at_threshold,
673            &network,
674            ACTIVE_HEIGHT,
675            recent_block_data(&network),
676        );
677        assert_eq!(
678            at_threshold.expected_difficulty,
679            CompactDifficulty::default()
680        );
681
682        let mut past_threshold = chain_info(PREV + GAP + 1);
683        adjust_difficulty_and_time_for_testnet(
684            &mut past_threshold,
685            &network,
686            ACTIVE_HEIGHT,
687            recent_block_data(&network),
688        );
689        assert_eq!(
690            past_threshold.expected_difficulty,
691            network.target_difficulty_limit().to_compact()
692        );
693    }
694
695    /// The adjustment only applies to test networks: on Mainnet it is a no-op.
696    #[test]
697    fn mainnet_is_a_no_op() {
698        let network = Network::Mainnet;
699        let cur = PREV + 400;
700        let mut result = chain_info(cur);
701
702        adjust_difficulty_and_time_for_testnet(
703            &mut result,
704            &network,
705            ACTIVE_HEIGHT,
706            recent_block_data(&network),
707        );
708
709        assert_eq!(result.expected_difficulty, CompactDifficulty::default());
710        assert_eq!(result.cur_time, DateTime32::from(cur));
711        assert_eq!(result.min_time, DateTime32::from(PREV - 100));
712        assert_eq!(
713            result.max_time,
714            DateTime32::from(PREV + BLOCK_MAX_TIME_SINCE_MEDIAN)
715        );
716    }
717
718    /// Below `TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT` (299188) the rule is inactive, so the
719    /// adjustment is a no-op even on Testnet.
720    #[test]
721    fn below_start_height_is_a_no_op() {
722        let network = Network::new_default_testnet();
723        let cur = PREV + 400;
724        let mut result = chain_info(cur);
725
726        adjust_difficulty_and_time_for_testnet(
727            &mut result,
728            &network,
729            Height(100_000),
730            recent_block_data(&network),
731        );
732
733        assert_eq!(result.expected_difficulty, CompactDifficulty::default());
734        assert_eq!(result.cur_time, DateTime32::from(cur));
735        assert_eq!(
736            result.max_time,
737            DateTime32::from(PREV + BLOCK_MAX_TIME_SINCE_MEDIAN)
738        );
739    }
740}