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