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    ]
120};
121/// Testnet network upgrade activation heights.
122///
123/// This is actually a bijective map, but it is const, so we use a vector, and
124/// do the uniqueness check in the unit tests.
125///
126/// # Correctness
127///
128/// Don't use this directly; use NetworkUpgrade::activation_list() so that
129/// we can switch to fake activation heights for some tests.
130#[allow(unused)]
131pub(super) const TESTNET_ACTIVATION_HEIGHTS: &[(block::Height, NetworkUpgrade)] = {
132    use super::constants::activation_heights::testnet::*;
133    &[
134        (block::Height(0), Genesis),
135        (BEFORE_OVERWINTER, BeforeOverwinter),
136        (OVERWINTER, Overwinter),
137        (SAPLING, Sapling),
138        (BLOSSOM, Blossom),
139        (HEARTWOOD, Heartwood),
140        (CANOPY, Canopy),
141        (NU5, Nu5),
142        (NU6, Nu6),
143        (NU6_1, Nu6_1),
144        (NU6_2, Nu6_2),
145        (NU6_3, Nu6_3),
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_protocol::consensus::BranchId {
212    type Error = crate::Error;
213
214    fn try_from(id: ConsensusBranchId) -> Result<Self, Self::Error> {
215        zcash_protocol::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    (Nu6_2, ConsensusBranchId(0x5437f330)),
240    // The NU6.3 (Ironwood) consensus branch id, matching zcash_protocol's `BranchId::Nu6_3`.
241    (Nu6_3, ConsensusBranchId(0x37a5165b)),
242    // TODO: set below to (Nu7, ConsensusBranchId(0x77190ad8)), once the same value is set in librustzcash
243    #[cfg(any(test, feature = "zebra-test"))]
244    (Nu7, ConsensusBranchId(0xfffffffe)),
245    // Distinct test placeholder so it never collides with the `Nu7` placeholder above
246    // (which is gated on `test`/`zebra-test`, independent of `zfuture`); a collision would break
247    // the `branch_id_bijective` test under `--cfg zcash_unstable="zfuture"`.
248    #[cfg(zcash_unstable = "zfuture")]
249    (ZFuture, ConsensusBranchId(0xfffffffd)),
250];
251
252/// The target block spacing before Blossom.
253const PRE_BLOSSOM_POW_TARGET_SPACING: i64 = 150;
254
255/// The target block spacing after Blossom activation.
256pub const POST_BLOSSOM_POW_TARGET_SPACING: u32 = 75;
257
258/// The averaging window for difficulty threshold arithmetic mean calculations.
259///
260/// `PoWAveragingWindow` in the Zcash specification.
261pub const POW_AVERAGING_WINDOW: usize = 17;
262
263/// The multiplier used to derive the testnet minimum difficulty block time gap
264/// threshold.
265///
266/// Based on <https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network>
267const TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER: i32 = 6;
268
269/// The start height for the testnet minimum difficulty consensus rule.
270///
271/// Based on <https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network>
272const TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT: block::Height = block::Height(299_188);
273
274/// The activation height for the block maximum time rule on Testnet.
275///
276/// Part of the block header consensus rules in the Zcash specification at
277/// <https://zips.z.cash/protocol/protocol.pdf#blockheader>
278pub const TESTNET_MAX_TIME_START_HEIGHT: block::Height = block::Height(653_606);
279
280impl Network {
281    /// Returns a map between activation heights and network upgrades for `network`,
282    /// in ascending height order.
283    ///
284    /// If the activation height of a future upgrade is not known, that
285    /// network upgrade does not appear in the list.
286    ///
287    /// This is actually a bijective map.
288    ///
289    /// Note: This skips implicit network upgrade activations, use [`Network::full_activation_list`]
290    ///       to get an explicit list of all network upgrade activations.
291    pub fn activation_list(&self) -> BTreeMap<block::Height, NetworkUpgrade> {
292        match self {
293            Mainnet => MAINNET_ACTIVATION_HEIGHTS.iter().cloned().collect(),
294            Testnet(params) => params.activation_heights().clone(),
295        }
296    }
297
298    /// Returns a vector of all implicit and explicit network upgrades for `network`,
299    /// in ascending height order.
300    pub fn full_activation_list(&self) -> Vec<(block::Height, NetworkUpgrade)> {
301        NetworkUpgrade::iter()
302            .filter_map(|nu| Some((NetworkUpgrade::activation_height(&nu, self)?, nu)))
303            .collect()
304    }
305}
306
307impl NetworkUpgrade {
308    /// Returns the current network upgrade and its activation height for `network` and `height`.
309    pub fn current_with_activation_height(
310        network: &Network,
311        height: block::Height,
312    ) -> (NetworkUpgrade, block::Height) {
313        network
314            .activation_list()
315            .range(..=height)
316            .map(|(&h, &nu)| (nu, h))
317            .next_back()
318            .expect("every height has a current network upgrade")
319    }
320
321    /// Returns the current network upgrade for `network` and `height`.
322    pub fn current(network: &Network, height: block::Height) -> NetworkUpgrade {
323        network
324            .activation_list()
325            .range(..=height)
326            .map(|(_, nu)| *nu)
327            .next_back()
328            .expect("every height has a current network upgrade")
329    }
330
331    /// Returns the next expected network upgrade after this network upgrade.
332    pub fn next_upgrade(self) -> Option<Self> {
333        Self::iter().skip_while(|&nu| self != nu).nth(1)
334    }
335
336    /// Returns the previous network upgrade before this network upgrade.
337    pub fn previous_upgrade(self) -> Option<Self> {
338        Self::iter().rev().skip_while(|&nu| self != nu).nth(1)
339    }
340
341    /// Returns the next network upgrade for `network` and `height`.
342    ///
343    /// Returns None if the next upgrade has not been implemented in Zebra
344    /// yet.
345    #[cfg(test)]
346    pub fn next(network: &Network, height: block::Height) -> Option<NetworkUpgrade> {
347        use std::ops::Bound::*;
348
349        network
350            .activation_list()
351            .range((Excluded(height), Unbounded))
352            .map(|(_, nu)| *nu)
353            .next()
354    }
355
356    /// Returns the activation height for this network upgrade on `network`, or
357    ///
358    /// Returns the activation height of the first network upgrade that follows
359    /// this network upgrade if there is no activation height for this network upgrade
360    /// such as on Regtest or a configured Testnet where multiple network upgrades have the
361    /// same activation height, or if one is omitted when others that follow it are included.
362    ///
363    /// Returns None if this network upgrade is a future upgrade, and its
364    /// activation height has not been set yet.
365    ///
366    /// Returns None if this network upgrade has not been configured on a Testnet or Regtest.
367    pub fn activation_height(&self, network: &Network) -> Option<block::Height> {
368        network
369            .activation_list()
370            .iter()
371            .find(|(_, nu)| nu == &self)
372            .map(|(height, _)| *height)
373            .or_else(|| {
374                self.next_upgrade()
375                    .and_then(|next_nu| next_nu.activation_height(network))
376            })
377    }
378
379    /// Returns `true` if `height` is the activation height of any network upgrade
380    /// on `network`.
381    ///
382    /// Use [`NetworkUpgrade::activation_height`] to get the specific network
383    /// upgrade.
384    pub fn is_activation_height(network: &Network, height: block::Height) -> bool {
385        network.activation_list().contains_key(&height)
386    }
387
388    /// Returns an unordered mapping between NetworkUpgrades and their ConsensusBranchIds.
389    ///
390    /// Branch ids are the same for mainnet and testnet.
391    ///
392    /// If network upgrade does not have a branch id, that network upgrade does
393    /// not appear in the list.
394    ///
395    /// This is actually a bijective map.
396    pub(crate) fn branch_id_list() -> HashMap<NetworkUpgrade, ConsensusBranchId> {
397        CONSENSUS_BRANCH_IDS.iter().cloned().collect()
398    }
399
400    /// Returns the consensus branch id for this network upgrade.
401    ///
402    /// Returns None if this network upgrade has no consensus branch id.
403    pub fn branch_id(&self) -> Option<ConsensusBranchId> {
404        NetworkUpgrade::branch_id_list().get(self).cloned()
405    }
406
407    /// Returns the target block spacing for the network upgrade.
408    ///
409    /// Based on [`PRE_BLOSSOM_POW_TARGET_SPACING`] and
410    /// [`POST_BLOSSOM_POW_TARGET_SPACING`] from the Zcash specification.
411    pub fn target_spacing(&self) -> Duration {
412        let spacing_seconds = match self {
413            Genesis | BeforeOverwinter | Overwinter | Sapling => PRE_BLOSSOM_POW_TARGET_SPACING,
414            Blossom | Heartwood | Canopy | Nu5 | Nu6 | Nu6_1 | Nu6_2 | Nu6_3 | Nu7 => {
415                POST_BLOSSOM_POW_TARGET_SPACING.into()
416            }
417
418            #[cfg(zcash_unstable = "zfuture")]
419            ZFuture => POST_BLOSSOM_POW_TARGET_SPACING.into(),
420        };
421
422        Duration::seconds(spacing_seconds)
423    }
424
425    /// Returns the target block spacing for `network` and `height`.
426    ///
427    /// See [`NetworkUpgrade::target_spacing`] for details.
428    pub fn target_spacing_for_height(network: &Network, height: block::Height) -> Duration {
429        NetworkUpgrade::current(network, height).target_spacing()
430    }
431
432    /// Returns all the target block spacings for `network` and the heights where they start.
433    pub fn target_spacings(
434        network: &Network,
435    ) -> impl Iterator<Item = (block::Height, Duration)> + '_ {
436        [
437            (NetworkUpgrade::Genesis, PRE_BLOSSOM_POW_TARGET_SPACING),
438            (
439                NetworkUpgrade::Blossom,
440                POST_BLOSSOM_POW_TARGET_SPACING.into(),
441            ),
442        ]
443        .into_iter()
444        .filter_map(move |(upgrade, spacing_seconds)| {
445            let activation_height = upgrade.activation_height(network)?;
446            let target_spacing = Duration::seconds(spacing_seconds);
447            Some((activation_height, target_spacing))
448        })
449    }
450
451    /// Returns the minimum difficulty block spacing for `network` and `height`.
452    /// Returns `None` if the testnet minimum difficulty consensus rule is not active.
453    ///
454    /// Based on <https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network>
455    pub fn minimum_difficulty_spacing_for_height(
456        network: &Network,
457        height: block::Height,
458    ) -> Option<Duration> {
459        match (network, height) {
460            // TODO: Move `TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT` to a field on testnet::Parameters (#8364)
461            (Network::Testnet(_params), height)
462                if height < TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT =>
463            {
464                None
465            }
466            (Network::Mainnet, _) => None,
467            (Network::Testnet(_params), _) => {
468                let network_upgrade = NetworkUpgrade::current(network, height);
469                Some(network_upgrade.target_spacing() * TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER)
470            }
471        }
472    }
473
474    /// Returns true if the gap between `block_time` and `previous_block_time` is
475    /// greater than the Testnet minimum difficulty time gap. This time gap
476    /// depends on the `network` and `block_height`.
477    ///
478    /// Returns false on Mainnet, when `block_height` is less than the minimum
479    /// difficulty start height, and when the time gap is too small.
480    ///
481    /// `block_time` can be less than, equal to, or greater than
482    /// `previous_block_time`, because block times are provided by miners.
483    ///
484    /// Implements the Testnet minimum difficulty adjustment from ZIPs 205 and 208.
485    ///
486    /// Spec Note: Some parts of ZIPs 205 and 208 previously specified an incorrect
487    /// check for the time gap. This function implements the correct "greater than"
488    /// check.
489    pub fn is_testnet_min_difficulty_block(
490        network: &Network,
491        block_height: block::Height,
492        block_time: DateTime<Utc>,
493        previous_block_time: DateTime<Utc>,
494    ) -> bool {
495        let block_time_gap = block_time - previous_block_time;
496        if let Some(min_difficulty_gap) =
497            NetworkUpgrade::minimum_difficulty_spacing_for_height(network, block_height)
498        {
499            block_time_gap > min_difficulty_gap
500        } else {
501            false
502        }
503    }
504
505    /// Returns the averaging window timespan for the network upgrade.
506    ///
507    /// `AveragingWindowTimespan` from the Zcash specification.
508    pub fn averaging_window_timespan(&self) -> Duration {
509        self.target_spacing() * POW_AVERAGING_WINDOW.try_into().expect("fits in i32")
510    }
511
512    /// Returns the averaging window timespan for `network` and `height`.
513    ///
514    /// See [`NetworkUpgrade::averaging_window_timespan`] for details.
515    pub fn averaging_window_timespan_for_height(
516        network: &Network,
517        height: block::Height,
518    ) -> Duration {
519        NetworkUpgrade::current(network, height).averaging_window_timespan()
520    }
521
522    /// Returns an iterator over [`NetworkUpgrade`] variants.
523    pub fn iter() -> impl DoubleEndedIterator<Item = NetworkUpgrade> {
524        <Self as IntoEnumIterator>::iter()
525    }
526}
527
528impl From<zcash_protocol::consensus::NetworkUpgrade> for NetworkUpgrade {
529    fn from(nu: zcash_protocol::consensus::NetworkUpgrade) -> Self {
530        match nu {
531            zcash_protocol::consensus::NetworkUpgrade::Overwinter => Self::Overwinter,
532            zcash_protocol::consensus::NetworkUpgrade::Sapling => Self::Sapling,
533            zcash_protocol::consensus::NetworkUpgrade::Blossom => Self::Blossom,
534            zcash_protocol::consensus::NetworkUpgrade::Heartwood => Self::Heartwood,
535            zcash_protocol::consensus::NetworkUpgrade::Canopy => Self::Canopy,
536            zcash_protocol::consensus::NetworkUpgrade::Nu5 => Self::Nu5,
537            zcash_protocol::consensus::NetworkUpgrade::Nu6 => Self::Nu6,
538            zcash_protocol::consensus::NetworkUpgrade::Nu6_1 => Self::Nu6_1,
539            zcash_protocol::consensus::NetworkUpgrade::Nu6_2 => Self::Nu6_2,
540            zcash_protocol::consensus::NetworkUpgrade::Nu6_3 => Self::Nu6_3,
541            #[cfg(zcash_unstable = "nu7")]
542            zcash_protocol::consensus::NetworkUpgrade::Nu7 => Self::Nu7,
543            #[cfg(zcash_unstable = "zfuture")]
544            zcash_protocol::consensus::NetworkUpgrade::ZFuture => Self::ZFuture,
545        }
546    }
547}
548
549impl ConsensusBranchId {
550    /// The value used by `zcashd` RPCs for missing consensus branch IDs.
551    ///
552    /// # Consensus
553    ///
554    /// This value must only be used in RPCs.
555    ///
556    /// The consensus rules handle missing branch IDs by rejecting blocks and transactions,
557    /// so this substitute value must not be used in consensus-critical code.
558    pub const RPC_MISSING_ID: ConsensusBranchId = ConsensusBranchId(0);
559
560    /// Returns the current consensus branch id for `network` and `height`.
561    ///
562    /// Returns None if the network has no branch id at this height.
563    pub fn current(network: &Network, height: block::Height) -> Option<ConsensusBranchId> {
564        NetworkUpgrade::current(network, height).branch_id()
565    }
566}