1use 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
37pub 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 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#[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 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 let last_header = header_iter.peek()?;
124
125 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 total_work -= last_work;
144
145 let work_duration = (max_time - min_time).num_seconds();
146
147 if work_duration <= 0 {
150 return None;
151 }
152
153 Some(total_work.as_u128() / work_duration as u128)
154}
155
156fn 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 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
225pub 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 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 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 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
273pub 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 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
300pub(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 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 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 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 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
383fn 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 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 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 let cur_time = if network.is_regtest() {
432 min_time
433 } else {
434 now.clamp(min_time, max_time)
435 };
436
437 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
462fn 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 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 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 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 if result.cur_time <= std_difficulty_max_time {
540 result.max_time = std_difficulty_max_time.clamp(result.min_time, result.max_time);
545
546 result.cur_time = result.cur_time.clamp(result.min_time, result.max_time);
549 } else {
550 result.min_time = min_difficulty_min_time.clamp(result.min_time, result.max_time);
555
556 result.cur_time = result.cur_time.clamp(result.min_time, result.max_time);
558
559 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 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 const ACTIVE_HEIGHT: Height = Height(2_000_000);
586 const PREV: u32 = 1_600_000_000;
587 const GAP: u32 = 6 * 75;
588
589 fn recent_block_data(network: &Network) -> Vec<(CompactDifficulty, DateTime<Utc>)> {
593 let threshold = network.target_difficulty_limit().to_compact();
594 (0..MAX_POW_ADJUSTMENT_BLOCK_SPAN)
597 .map(|i| (threshold, DateTime32::from(PREV - i as u32).into()))
598 .collect()
599 }
600
601 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 #[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 assert_eq!(result.expected_difficulty, CompactDifficulty::default());
635 assert_eq!(result.cur_time, DateTime32::from(cur));
637 assert_eq!(result.max_time, DateTime32::from(PREV + GAP));
639 }
640
641 #[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 assert_eq!(
657 result.expected_difficulty,
658 network.target_difficulty_limit().to_compact()
659 );
660 assert_eq!(result.min_time, DateTime32::from(PREV + GAP + 1));
662 assert_eq!(result.cur_time, DateTime32::from(cur));
663 }
664
665 #[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 #[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 #[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}