Skip to main content

zebra_chain/parameters/
network_upgrade.rs

1//! Network upgrade consensus parameters for Zcash.
2
3use NetworkUpgrade::*;
4
5use crate::block;
6use crate::parameters::{Network, Network::*};
7use crate::serialization::BytesInDisplayOrder;
8
9use std::collections::{BTreeMap, HashMap};
10use std::fmt;
11
12use chrono::{DateTime, Duration, Utc};
13use hex::{FromHex, ToHex};
14
15use strum::{EnumIter, IntoEnumIterator};
16
17#[cfg(any(test, feature = "proptest-impl"))]
18use proptest_derive::Arbitrary;
19
20/// A Zcash network upgrade.
21///
22/// Network upgrades change the Zcash network protocol or consensus rules. Note that they have no
23/// designated codenames from NU5 onwards.
24///
25/// Enum variants must be ordered by activation height.
26#[derive(
27    Copy, Clone, EnumIter, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, Ord, PartialOrd,
28)]
29#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
30pub enum NetworkUpgrade {
31    /// The Zcash protocol for a Genesis block.
32    ///
33    /// Zcash genesis blocks use a different set of consensus rules from
34    /// other BeforeOverwinter blocks, so we treat them like a separate network
35    /// upgrade.
36    Genesis,
37    /// The Zcash protocol before the Overwinter upgrade.
38    ///
39    /// We avoid using `Sprout`, because the specification says that Sprout
40    /// is the name of the pre-Sapling protocol, before and after Overwinter.
41    BeforeOverwinter,
42    /// The Zcash protocol after the Overwinter upgrade.
43    Overwinter,
44    /// The Zcash protocol after the Sapling upgrade.
45    Sapling,
46    /// The Zcash protocol after the Blossom upgrade.
47    Blossom,
48    /// The Zcash protocol after the Heartwood upgrade.
49    Heartwood,
50    /// The Zcash protocol after the Canopy upgrade.
51    Canopy,
52    /// The Zcash protocol after the NU5 upgrade.
53    #[serde(rename = "NU5")]
54    Nu5,
55    /// The Zcash protocol after the NU6 upgrade.
56    #[serde(rename = "NU6")]
57    Nu6,
58    /// The Zcash protocol after the NU6.1 upgrade.
59    #[serde(rename = "NU6.1")]
60    Nu6_1,
61    /// The Zcash protocol after the NU6.2 upgrade.
62    #[serde(rename = "NU6.2")]
63    Nu6_2,
64    /// The Zcash protocol after the NU6.3 (Ironwood) upgrade.
65    #[serde(rename = "NU6.3")]
66    Nu6_3,
67    /// The Zcash protocol after the NU7 upgrade.
68    #[serde(rename = "NU7")]
69    Nu7,
70
71    #[cfg(zcash_unstable = "zfuture")]
72    ZFuture,
73}
74
75impl TryFrom<u32> for NetworkUpgrade {
76    type Error = crate::Error;
77
78    fn try_from(branch_id: u32) -> Result<Self, Self::Error> {
79        CONSENSUS_BRANCH_IDS
80            .iter()
81            .find(|id| id.1 == ConsensusBranchId(branch_id))
82            .map(|nu| nu.0)
83            .ok_or(Self::Error::InvalidConsensusBranchId)
84    }
85}
86
87impl fmt::Display for NetworkUpgrade {
88    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89        // Same as the debug representation for now
90        fmt::Debug::fmt(self, f)
91    }
92}
93
94/// Mainnet network upgrade activation heights.
95///
96/// This is actually a bijective map, but it is const, so we use a vector, and
97/// do the uniqueness check in the unit tests.
98///
99/// # Correctness
100///
101/// Don't use this directly; use NetworkUpgrade::activation_list() so that
102/// we can switch to fake activation heights for some tests.
103#[allow(unused)]
104pub(super) const MAINNET_ACTIVATION_HEIGHTS: &[(block::Height, NetworkUpgrade)] = {
105    use super::constants::activation_heights::mainnet::*;
106    &[
107        (block::Height(0), Genesis),
108        (BEFORE_OVERWINTER, BeforeOverwinter),
109        (OVERWINTER, Overwinter),
110        (SAPLING, Sapling),
111        (BLOSSOM, Blossom),
112        (HEARTWOOD, Heartwood),
113        (CANOPY, Canopy),
114        (NU5, Nu5),
115        (NU6, Nu6),
116        (NU6_1, Nu6_1),
117        (NU6_2, Nu6_2),
118        (NU6_3, Nu6_3),
119        (NU7, Nu7),
120    ]
121};
122/// Testnet network upgrade activation heights.
123///
124/// This is actually a bijective map, but it is const, so we use a vector, and
125/// do the uniqueness check in the unit tests.
126///
127/// # Correctness
128///
129/// Don't use this directly; use NetworkUpgrade::activation_list() so that
130/// we can switch to fake activation heights for some tests.
131#[allow(unused)]
132pub(super) const TESTNET_ACTIVATION_HEIGHTS: &[(block::Height, NetworkUpgrade)] = {
133    use super::constants::activation_heights::testnet::*;
134    &[
135        (block::Height(0), Genesis),
136        (BEFORE_OVERWINTER, BeforeOverwinter),
137        (OVERWINTER, Overwinter),
138        (SAPLING, Sapling),
139        (BLOSSOM, Blossom),
140        (HEARTWOOD, Heartwood),
141        (CANOPY, Canopy),
142        (NU5, Nu5),
143        (NU6, Nu6),
144        (NU6_1, Nu6_1),
145        (NU6_2, Nu6_2),
146        (NU6_3, Nu6_3),
147        (NU7, Nu7),
148    ]
149};
150
151/// The Consensus Branch Id, used to bind transactions and blocks to a
152/// particular network upgrade.
153#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
154pub struct ConsensusBranchId(pub(crate) u32);
155
156impl BytesInDisplayOrder<false, 4> for ConsensusBranchId {
157    fn bytes_in_serialized_order(&self) -> [u8; 4] {
158        self.0.to_be_bytes()
159    }
160
161    fn from_bytes_in_serialized_order(bytes: [u8; 4]) -> Self {
162        ConsensusBranchId(u32::from_be_bytes(bytes))
163    }
164}
165
166impl From<ConsensusBranchId> for u32 {
167    fn from(branch: ConsensusBranchId) -> u32 {
168        branch.0
169    }
170}
171
172impl From<u32> for ConsensusBranchId {
173    fn from(branch: u32) -> Self {
174        ConsensusBranchId(branch)
175    }
176}
177
178impl ToHex for &ConsensusBranchId {
179    fn encode_hex<T: FromIterator<char>>(&self) -> T {
180        self.bytes_in_display_order().encode_hex()
181    }
182
183    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
184        self.bytes_in_display_order().encode_hex_upper()
185    }
186}
187
188impl ToHex for ConsensusBranchId {
189    fn encode_hex<T: FromIterator<char>>(&self) -> T {
190        self.bytes_in_display_order().encode_hex()
191    }
192
193    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
194        self.bytes_in_display_order().encode_hex_upper()
195    }
196}
197
198impl FromHex for ConsensusBranchId {
199    type Error = <[u8; 4] as FromHex>::Error;
200
201    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
202        let branch = <[u8; 4]>::from_hex(hex)?;
203        Ok(ConsensusBranchId(u32::from_be_bytes(branch)))
204    }
205}
206
207impl fmt::Display for ConsensusBranchId {
208    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
209        f.write_str(&self.encode_hex::<String>())
210    }
211}
212
213impl TryFrom<ConsensusBranchId> for zcash_protocol::consensus::BranchId {
214    type Error = crate::Error;
215
216    fn try_from(id: ConsensusBranchId) -> Result<Self, Self::Error> {
217        zcash_protocol::consensus::BranchId::try_from(u32::from(id))
218            .map_err(|_| Self::Error::InvalidConsensusBranchId)
219    }
220}
221
222/// Network Upgrade Consensus Branch Ids.
223///
224/// Branch ids are the same for mainnet and testnet. If there is a testnet
225/// rollback after a bug, the branch id changes.
226///
227/// Branch ids were introduced in the Overwinter upgrade, so there are no
228/// Genesis or BeforeOverwinter branch ids.
229///
230/// This is actually a bijective map, but it is const, so we use a vector, and
231/// do the uniqueness check in the unit tests.
232pub(crate) const CONSENSUS_BRANCH_IDS: &[(NetworkUpgrade, ConsensusBranchId)] = &[
233    (Overwinter, ConsensusBranchId(0x5ba81b19)),
234    (Sapling, ConsensusBranchId(0x76b809bb)),
235    (Blossom, ConsensusBranchId(0x2bb40e60)),
236    (Heartwood, ConsensusBranchId(0xf5b9230b)),
237    (Canopy, ConsensusBranchId(0xe9ff75a6)),
238    (Nu5, ConsensusBranchId(0xc2d6d0b4)),
239    (Nu6, ConsensusBranchId(0xc8e71055)),
240    (Nu6_1, ConsensusBranchId(0x4dec4df0)),
241    (Nu6_2, ConsensusBranchId(0x5437f330)),
242    // The NU6.3 (Ironwood) consensus branch id, matching zcash_protocol's `BranchId::Nu6_3`.
243    (Nu6_3, ConsensusBranchId(0x37a5165b)),
244    // ZIP 259, matching zcash_protocol's `BranchId::Nu7`.
245    (Nu7, ConsensusBranchId(0x77190ad9)),
246    #[cfg(zcash_unstable = "zfuture")]
247    (ZFuture, ConsensusBranchId(0xfffffffd)),
248];
249
250/// The target block spacing before Blossom.
251const PRE_BLOSSOM_POW_TARGET_SPACING: i64 = 150;
252
253/// The target block spacing after Blossom activation, and before NU7.
254pub const POST_BLOSSOM_POW_TARGET_SPACING: u32 = 75;
255
256/// The target block spacing after NU7 activation.
257///
258/// `PostNU7PoWTargetSpacing` in [ZIP 218].
259///
260/// [ZIP 218]: https://zips.z.cash/zip-0218
261pub const POST_NU7_POW_TARGET_SPACING: u32 = 25;
262
263/// The ratio between the post-Blossom and post-NU7 target block spacings.
264///
265/// `NU7PoWTargetSpacingRatio` in [ZIP 218].
266///
267/// [ZIP 218]: https://zips.z.cash/zip-0218
268pub const NU7_POW_TARGET_SPACING_RATIO: u32 =
269    POST_BLOSSOM_POW_TARGET_SPACING / POST_NU7_POW_TARGET_SPACING;
270
271/// The averaging window for difficulty threshold arithmetic mean calculations, before NU7.
272///
273/// `PoWAveragingWindow` in the Zcash specification.
274///
275/// Use [`NetworkUpgrade::averaging_window`] instead of this constant for consensus checks: from
276/// NU7 onward the window is [`POST_NU7_POW_AVERAGING_WINDOW`] ([ZIP 218]).
277///
278/// [ZIP 218]: https://zips.z.cash/zip-0218
279pub const POW_AVERAGING_WINDOW: usize = 17;
280
281/// The averaging window for difficulty threshold arithmetic mean calculations, from NU7 onward.
282///
283/// `PostNU7PoWAveragingWindow` in [ZIP 218]. It is six times the pre-NU7 window of 17, so with
284/// the target spacing cut to a third, the wall-clock smoothing window doubles from 1,275 to
285/// 2,550 seconds. ZIP 218 widens it deliberately: keeping the window at 17 blocks would have
286/// left a third of the wall-clock smoothing and tripled the difficulty noise.
287///
288/// [ZIP 218]: https://zips.z.cash/zip-0218
289pub const POST_NU7_POW_AVERAGING_WINDOW: usize = 102;
290
291/// The largest averaging window used by any network upgrade.
292///
293/// Used to size the buffers that hold difficulty adjustment context.
294pub const MAX_POW_AVERAGING_WINDOW: usize = POST_NU7_POW_AVERAGING_WINDOW;
295
296/// The multiplier used to derive the testnet minimum difficulty block time gap
297/// threshold before NU7.
298///
299/// Based on <https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network>
300const TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER: i32 = 6;
301
302/// The NU7 Testnet gap multiplier, preserving the 450-second threshold at 25-second spacing.
303///
304/// Specified by <https://github.com/zcash/zips/pull/1382>.
305const POST_NU7_TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER: i32 = 18;
306
307/// The start height for the testnet minimum difficulty consensus rule.
308///
309/// Based on <https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network>
310const TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT: block::Height = block::Height(299_188);
311
312/// The activation height for the block maximum time rule on Testnet.
313///
314/// Part of the block header consensus rules in the Zcash specification at
315/// <https://zips.z.cash/protocol/protocol.pdf#blockheader>
316pub const TESTNET_MAX_TIME_START_HEIGHT: block::Height = block::Height(653_606);
317
318impl Network {
319    /// Returns a map between activation heights and network upgrades for `network`,
320    /// in ascending height order.
321    ///
322    /// If the activation height of a future upgrade is not known, that
323    /// network upgrade does not appear in the list.
324    ///
325    /// This is actually a bijective map.
326    ///
327    /// Note: This skips implicit network upgrade activations, use [`Network::full_activation_list`]
328    ///       to get an explicit list of all network upgrade activations.
329    pub fn activation_list(&self) -> BTreeMap<block::Height, NetworkUpgrade> {
330        match self {
331            Mainnet => MAINNET_ACTIVATION_HEIGHTS.iter().cloned().collect(),
332            Testnet(params) => params.activation_heights().clone(),
333        }
334    }
335
336    /// Returns a vector of all implicit and explicit network upgrades for `network`,
337    /// in ascending height order.
338    pub fn full_activation_list(&self) -> Vec<(block::Height, NetworkUpgrade)> {
339        NetworkUpgrade::iter()
340            .filter_map(|nu| Some((NetworkUpgrade::activation_height(&nu, self)?, nu)))
341            .collect()
342    }
343}
344
345impl NetworkUpgrade {
346    /// Returns the current network upgrade and its activation height for `network` and `height`.
347    pub fn current_with_activation_height(
348        network: &Network,
349        height: block::Height,
350    ) -> (NetworkUpgrade, block::Height) {
351        network
352            .activation_list()
353            .range(..=height)
354            .map(|(&h, &nu)| (nu, h))
355            .next_back()
356            .expect("every height has a current network upgrade")
357    }
358
359    /// Returns the current network upgrade for `network` and `height`.
360    pub fn current(network: &Network, height: block::Height) -> NetworkUpgrade {
361        network
362            .activation_list()
363            .range(..=height)
364            .map(|(_, nu)| *nu)
365            .next_back()
366            .expect("every height has a current network upgrade")
367    }
368
369    /// Returns the next expected network upgrade after this network upgrade.
370    pub fn next_upgrade(self) -> Option<Self> {
371        Self::iter().skip_while(|&nu| self != nu).nth(1)
372    }
373
374    /// Returns the previous network upgrade before this network upgrade.
375    pub fn previous_upgrade(self) -> Option<Self> {
376        Self::iter().rev().skip_while(|&nu| self != nu).nth(1)
377    }
378
379    /// Returns the next network upgrade for `network` and `height`.
380    ///
381    /// Returns None if the next upgrade has not been implemented in Zebra
382    /// yet.
383    #[cfg(test)]
384    pub fn next(network: &Network, height: block::Height) -> Option<NetworkUpgrade> {
385        use std::ops::Bound::*;
386
387        network
388            .activation_list()
389            .range((Excluded(height), Unbounded))
390            .map(|(_, nu)| *nu)
391            .next()
392    }
393
394    /// Returns the activation height for this network upgrade on `network`, or
395    ///
396    /// Returns the activation height of the first network upgrade that follows
397    /// this network upgrade if there is no activation height for this network upgrade
398    /// such as on Regtest or a configured Testnet where multiple network upgrades have the
399    /// same activation height, or if one is omitted when others that follow it are included.
400    ///
401    /// Returns None if this network upgrade is a future upgrade, and its
402    /// activation height has not been set yet.
403    ///
404    /// Returns None if this network upgrade has not been configured on a Testnet or Regtest.
405    pub fn activation_height(&self, network: &Network) -> Option<block::Height> {
406        network
407            .activation_list()
408            .iter()
409            .find(|(_, nu)| nu == &self)
410            .map(|(height, _)| *height)
411            .or_else(|| {
412                self.next_upgrade()
413                    .and_then(|next_nu| next_nu.activation_height(network))
414            })
415    }
416
417    /// Returns `true` if `height` is the activation height of any network upgrade
418    /// on `network`.
419    ///
420    /// Use [`NetworkUpgrade::activation_height`] to get the specific network
421    /// upgrade.
422    pub fn is_activation_height(network: &Network, height: block::Height) -> bool {
423        network.activation_list().contains_key(&height)
424    }
425
426    /// Returns an unordered mapping between NetworkUpgrades and their ConsensusBranchIds.
427    ///
428    /// Branch ids are the same for mainnet and testnet.
429    ///
430    /// If network upgrade does not have a branch id, that network upgrade does
431    /// not appear in the list.
432    ///
433    /// This is actually a bijective map.
434    pub(crate) fn branch_id_list() -> HashMap<NetworkUpgrade, ConsensusBranchId> {
435        CONSENSUS_BRANCH_IDS.iter().cloned().collect()
436    }
437
438    /// Returns the consensus branch id for this network upgrade.
439    ///
440    /// Returns None if this network upgrade has no consensus branch id.
441    pub fn branch_id(&self) -> Option<ConsensusBranchId> {
442        NetworkUpgrade::branch_id_list().get(self).cloned()
443    }
444
445    /// Returns the target block spacing for the network upgrade.
446    ///
447    /// Based on [`PRE_BLOSSOM_POW_TARGET_SPACING`] and
448    /// [`POST_BLOSSOM_POW_TARGET_SPACING`] from the Zcash specification.
449    pub fn target_spacing(&self) -> Duration {
450        let spacing_seconds = match self {
451            Genesis | BeforeOverwinter | Overwinter | Sapling => PRE_BLOSSOM_POW_TARGET_SPACING,
452            Blossom | Heartwood | Canopy | Nu5 | Nu6 | Nu6_1 | Nu6_2 | Nu6_3 => {
453                POST_BLOSSOM_POW_TARGET_SPACING.into()
454            }
455            // ZIP 218 drops the target spacing to 25 seconds from NU7 onward.
456            Nu7 => POST_NU7_POW_TARGET_SPACING.into(),
457
458            #[cfg(zcash_unstable = "zfuture")]
459            ZFuture => POST_NU7_POW_TARGET_SPACING.into(),
460        };
461
462        Duration::seconds(spacing_seconds)
463    }
464
465    /// Returns the target block spacing for `network` and `height`.
466    ///
467    /// See [`NetworkUpgrade::target_spacing`] for details.
468    pub fn target_spacing_for_height(network: &Network, height: block::Height) -> Duration {
469        NetworkUpgrade::current(network, height).target_spacing()
470    }
471
472    /// Returns all the target block spacings for `network` and the heights where they start.
473    pub fn target_spacings(
474        network: &Network,
475    ) -> impl Iterator<Item = (block::Height, Duration)> + '_ {
476        [
477            (NetworkUpgrade::Genesis, PRE_BLOSSOM_POW_TARGET_SPACING),
478            (
479                NetworkUpgrade::Blossom,
480                POST_BLOSSOM_POW_TARGET_SPACING.into(),
481            ),
482            (NetworkUpgrade::Nu7, POST_NU7_POW_TARGET_SPACING.into()),
483        ]
484        .into_iter()
485        .filter_map(move |(upgrade, spacing_seconds)| {
486            let activation_height = upgrade.activation_height(network)?;
487            let target_spacing = Duration::seconds(spacing_seconds);
488            Some((activation_height, target_spacing))
489        })
490    }
491
492    /// Returns the total target block spacing of the blocks after `from` up to and including
493    /// `to`, charging each block the spacing at its own height. Negative when `to` is below `from`.
494    pub fn duration_between_heights(
495        network: &Network,
496        from: block::Height,
497        to: block::Height,
498    ) -> Duration {
499        let low = i64::from(from.0.min(to.0));
500        let high = i64::from(from.0.max(to.0));
501
502        let target_spacings: Vec<_> = NetworkUpgrade::target_spacings(network).collect();
503        let seconds: i64 = target_spacings
504            .iter()
505            .enumerate()
506            .map(|(index, (start_height, target_spacing))| {
507                // The heights in `low + 1..=high` that use this target spacing.
508                let first = i64::from(start_height.0).max(low + 1);
509                let last = target_spacings
510                    .get(index + 1)
511                    .map_or(high, |(next_height, _)| {
512                        (i64::from(next_height.0) - 1).min(high)
513                    });
514
515                (last - first + 1).max(0) * target_spacing.num_seconds()
516            })
517            .sum();
518
519        Duration::seconds(if to < from { -seconds } else { seconds })
520    }
521
522    /// Returns the minimum difficulty block spacing for `network` and `height`.
523    /// Returns `None` if the testnet minimum difficulty consensus rule is not active.
524    ///
525    /// Uses six target spacings before NU7 and eighteen from NU7 onward, preserving the
526    /// 450-second threshold after Blossom.
527    ///
528    /// Based on <https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network>
529    /// and the NU7 update in <https://github.com/zcash/zips/pull/1382>.
530    pub fn minimum_difficulty_spacing_for_height(
531        network: &Network,
532        height: block::Height,
533    ) -> Option<Duration> {
534        match (network, height) {
535            // TODO: Move `TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT` to a field on testnet::Parameters (#8364)
536            (Network::Testnet(_params), height)
537                if height < TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT =>
538            {
539                None
540            }
541            (Network::Mainnet, _) => None,
542            (Network::Testnet(_params), _) => {
543                let network_upgrade = NetworkUpgrade::current(network, height);
544                let multiplier = if network_upgrade >= Nu7 {
545                    POST_NU7_TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER
546                } else {
547                    TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER
548                };
549                Some(network_upgrade.target_spacing() * multiplier)
550            }
551        }
552    }
553
554    /// Returns true if the gap between `block_time` and `previous_block_time` is
555    /// greater than the Testnet minimum difficulty time gap. This time gap
556    /// depends on the `network` and `block_height`.
557    ///
558    /// Returns false on Mainnet, when `block_height` is less than the minimum
559    /// difficulty start height, and when the time gap is too small.
560    ///
561    /// `block_time` can be less than, equal to, or greater than
562    /// `previous_block_time`, because block times are provided by miners.
563    ///
564    /// Implements the Testnet minimum difficulty adjustment from ZIPs 205 and 208.
565    ///
566    /// Spec Note: Some parts of ZIPs 205 and 208 previously specified an incorrect
567    /// check for the time gap. This function implements the correct "greater than"
568    /// check.
569    pub fn is_testnet_min_difficulty_block(
570        network: &Network,
571        block_height: block::Height,
572        block_time: DateTime<Utc>,
573        previous_block_time: DateTime<Utc>,
574    ) -> bool {
575        let block_time_gap = block_time - previous_block_time;
576        if let Some(min_difficulty_gap) =
577            NetworkUpgrade::minimum_difficulty_spacing_for_height(network, block_height)
578        {
579            block_time_gap > min_difficulty_gap
580        } else {
581            false
582        }
583    }
584
585    /// Returns the difficulty averaging window for the network upgrade.
586    ///
587    /// `PoWAveragingWindow(height)` from the Zcash specification, as redefined by [ZIP 218].
588    ///
589    /// [ZIP 218]: https://zips.z.cash/zip-0218
590    pub fn averaging_window(&self) -> usize {
591        if self >= &NetworkUpgrade::Nu7 {
592            POST_NU7_POW_AVERAGING_WINDOW
593        } else {
594            POW_AVERAGING_WINDOW
595        }
596    }
597
598    /// Returns the difficulty averaging window for `network` and `height`.
599    ///
600    /// See [`NetworkUpgrade::averaging_window`] for details.
601    pub fn averaging_window_for_height(network: &Network, height: block::Height) -> usize {
602        NetworkUpgrade::current(network, height).averaging_window()
603    }
604
605    /// Returns the averaging window timespan for the network upgrade.
606    ///
607    /// `AveragingWindowTimespan` from the Zcash specification.
608    pub fn averaging_window_timespan(&self) -> Duration {
609        self.target_spacing() * self.averaging_window().try_into().expect("fits in i32")
610    }
611
612    /// Returns the averaging window timespan for `network` and `height`.
613    ///
614    /// See [`NetworkUpgrade::averaging_window_timespan`] for details.
615    pub fn averaging_window_timespan_for_height(
616        network: &Network,
617        height: block::Height,
618    ) -> Duration {
619        NetworkUpgrade::current(network, height).averaging_window_timespan()
620    }
621
622    /// Returns an iterator over [`NetworkUpgrade`] variants.
623    pub fn iter() -> impl DoubleEndedIterator<Item = NetworkUpgrade> {
624        <Self as IntoEnumIterator>::iter()
625    }
626}
627
628impl From<zcash_protocol::consensus::NetworkUpgrade> for NetworkUpgrade {
629    fn from(nu: zcash_protocol::consensus::NetworkUpgrade) -> Self {
630        match nu {
631            zcash_protocol::consensus::NetworkUpgrade::Overwinter => Self::Overwinter,
632            zcash_protocol::consensus::NetworkUpgrade::Sapling => Self::Sapling,
633            zcash_protocol::consensus::NetworkUpgrade::Blossom => Self::Blossom,
634            zcash_protocol::consensus::NetworkUpgrade::Heartwood => Self::Heartwood,
635            zcash_protocol::consensus::NetworkUpgrade::Canopy => Self::Canopy,
636            zcash_protocol::consensus::NetworkUpgrade::Nu5 => Self::Nu5,
637            zcash_protocol::consensus::NetworkUpgrade::Nu6 => Self::Nu6,
638            zcash_protocol::consensus::NetworkUpgrade::Nu6_1 => Self::Nu6_1,
639            zcash_protocol::consensus::NetworkUpgrade::Nu6_2 => Self::Nu6_2,
640            zcash_protocol::consensus::NetworkUpgrade::Nu6_3 => Self::Nu6_3,
641            zcash_protocol::consensus::NetworkUpgrade::Nu7 => Self::Nu7,
642            #[cfg(zcash_unstable = "zfuture")]
643            zcash_protocol::consensus::NetworkUpgrade::ZFuture => Self::ZFuture,
644        }
645    }
646}
647
648impl ConsensusBranchId {
649    /// The value used by `zcashd` RPCs for missing consensus branch IDs.
650    ///
651    /// # Consensus
652    ///
653    /// This value must only be used in RPCs.
654    ///
655    /// The consensus rules handle missing branch IDs by rejecting blocks and transactions,
656    /// so this substitute value must not be used in consensus-critical code.
657    pub const RPC_MISSING_ID: ConsensusBranchId = ConsensusBranchId(0);
658
659    /// Returns the current consensus branch id for `network` and `height`.
660    ///
661    /// Returns None if the network has no branch id at this height.
662    pub fn current(network: &Network, height: block::Height) -> Option<ConsensusBranchId> {
663        NetworkUpgrade::current(network, height).branch_id()
664    }
665}