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