zebra_chain/parameters/
network.rs

1//! Consensus parameters for each Zcash network.
2
3use std::{fmt, str::FromStr, sync::Arc};
4
5use thiserror::Error;
6
7use crate::{
8    block::{self, Height},
9    parameters::NetworkUpgrade,
10};
11
12pub mod magic;
13pub mod subsidy;
14pub mod testnet;
15
16#[cfg(test)]
17mod tests;
18
19/// An enum describing the kind of network, whether it's the production mainnet or a testnet.
20// Note: The order of these variants is important for correct bincode (de)serialization
21//       of history trees in the db format.
22// TODO: Replace bincode (de)serialization of `HistoryTreeParts` in a db format upgrade?
23#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
24pub enum NetworkKind {
25    /// The production mainnet.
26    #[default]
27    Mainnet,
28
29    /// A test network.
30    Testnet,
31
32    /// Regtest mode
33    Regtest,
34}
35
36impl From<Network> for NetworkKind {
37    fn from(network: Network) -> Self {
38        network.kind()
39    }
40}
41
42/// An enum describing the possible network choices.
43#[derive(Clone, Default, Eq, PartialEq, Serialize)]
44#[serde(into = "NetworkKind")]
45pub enum Network {
46    /// The production mainnet.
47    #[default]
48    Mainnet,
49
50    /// A test network such as the default public testnet,
51    /// a configured testnet, or Regtest.
52    Testnet(Arc<testnet::Parameters>),
53}
54
55impl NetworkKind {
56    /// Returns the human-readable prefix for Base58Check-encoded transparent
57    /// pay-to-public-key-hash payment addresses for the network.
58    pub fn b58_pubkey_address_prefix(self) -> [u8; 2] {
59        match self {
60            Self::Mainnet => zcash_primitives::constants::mainnet::B58_PUBKEY_ADDRESS_PREFIX,
61            Self::Testnet | Self::Regtest => {
62                zcash_primitives::constants::testnet::B58_PUBKEY_ADDRESS_PREFIX
63            }
64        }
65    }
66
67    /// Returns the human-readable prefix for Base58Check-encoded transparent pay-to-script-hash
68    /// payment addresses for the network.
69    pub fn b58_script_address_prefix(self) -> [u8; 2] {
70        match self {
71            Self::Mainnet => zcash_primitives::constants::mainnet::B58_SCRIPT_ADDRESS_PREFIX,
72            Self::Testnet | Self::Regtest => {
73                zcash_primitives::constants::testnet::B58_SCRIPT_ADDRESS_PREFIX
74            }
75        }
76    }
77
78    /// Return the network name as defined in
79    /// [BIP70](https://github.com/bitcoin/bips/blob/master/bip-0070.mediawiki#paymentdetailspaymentrequest)
80    pub fn bip70_network_name(&self) -> String {
81        if *self == Self::Mainnet {
82            "main".to_string()
83        } else {
84            "test".to_string()
85        }
86    }
87
88    /// Returns the 2 bytes prefix for Bech32m-encoded transparent TEX
89    /// payment addresses for the network as defined in [ZIP-320](https://zips.z.cash/zip-0320.html).
90    pub fn tex_address_prefix(self) -> [u8; 2] {
91        // TODO: Add this bytes to `zcash_primitives::constants`?
92        match self {
93            Self::Mainnet => [0x1c, 0xb8],
94            Self::Testnet | Self::Regtest => [0x1d, 0x25],
95        }
96    }
97}
98
99impl From<NetworkKind> for &'static str {
100    fn from(network: NetworkKind) -> &'static str {
101        // These should be different from the `Display` impl for `Network` so that its lowercase form
102        // can't be parsed as the default Testnet in the `Network` `FromStr` impl, it's easy to
103        // distinguish them in logs, and so it's generally harder to confuse the two.
104        match network {
105            NetworkKind::Mainnet => "MainnetKind",
106            NetworkKind::Testnet => "TestnetKind",
107            NetworkKind::Regtest => "RegtestKind",
108        }
109    }
110}
111
112impl fmt::Display for NetworkKind {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.write_str((*self).into())
115    }
116}
117
118impl<'a> From<&'a Network> for &'a str {
119    fn from(network: &'a Network) -> &'a str {
120        match network {
121            Network::Mainnet => "Mainnet",
122            Network::Testnet(params) => params.network_name(),
123        }
124    }
125}
126
127impl fmt::Display for Network {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str(self.into())
130    }
131}
132
133impl std::fmt::Debug for Network {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        match self {
136            Self::Mainnet => write!(f, "{self}"),
137            Self::Testnet(params) if params.is_regtest() => f
138                .debug_struct("Regtest")
139                .field("activation_heights", params.activation_heights())
140                .finish(),
141            Self::Testnet(params) if params.is_default_testnet() => {
142                write!(f, "{self}")
143            }
144            Self::Testnet(params) => f.debug_tuple("ConfiguredTestnet").field(params).finish(),
145        }
146    }
147}
148
149impl Network {
150    /// Creates a new [`Network::Testnet`] with the default Testnet [`testnet::Parameters`].
151    pub fn new_default_testnet() -> Self {
152        Self::Testnet(Arc::new(testnet::Parameters::default()))
153    }
154
155    /// Creates a new configured [`Network::Testnet`] with the provided Testnet [`testnet::Parameters`].
156    pub fn new_configured_testnet(params: testnet::Parameters) -> Self {
157        Self::Testnet(Arc::new(params))
158    }
159
160    /// Creates a new [`Network::Testnet`] with `Regtest` parameters and the provided network upgrade activation heights.
161    pub fn new_regtest(
162        configured_activation_heights: testnet::ConfiguredActivationHeights,
163    ) -> Self {
164        Self::new_configured_testnet(testnet::Parameters::new_regtest(
165            configured_activation_heights,
166        ))
167    }
168
169    /// Returns true if the network is the default Testnet, or false otherwise.
170    pub fn is_default_testnet(&self) -> bool {
171        if let Self::Testnet(params) = self {
172            params.is_default_testnet()
173        } else {
174            false
175        }
176    }
177
178    /// Returns true if the network is Regtest, or false otherwise.
179    pub fn is_regtest(&self) -> bool {
180        if let Self::Testnet(params) = self {
181            params.is_regtest()
182        } else {
183            false
184        }
185    }
186
187    /// Returns the [`NetworkKind`] for this network.
188    pub fn kind(&self) -> NetworkKind {
189        match self {
190            Network::Mainnet => NetworkKind::Mainnet,
191            Network::Testnet(params) if params.is_regtest() => NetworkKind::Regtest,
192            Network::Testnet(_) => NetworkKind::Testnet,
193        }
194    }
195
196    /// Returns [`NetworkKind::Testnet`] on Testnet and Regtest, or [`NetworkKind::Mainnet`] on Mainnet.
197    ///
198    /// This is used for transparent addresses, as the address prefix is the same on Regtest as it is on Testnet.
199    pub fn t_addr_kind(&self) -> NetworkKind {
200        match self {
201            Network::Mainnet => NetworkKind::Mainnet,
202            Network::Testnet(_) => NetworkKind::Testnet,
203        }
204    }
205
206    /// Returns an iterator over [`Network`] variants.
207    pub fn iter() -> impl Iterator<Item = Self> {
208        [Self::Mainnet, Self::new_default_testnet()].into_iter()
209    }
210
211    /// Returns true if the maximum block time rule is active for `network` and `height`.
212    ///
213    /// Always returns true if `network` is the Mainnet.
214    /// If `network` is the Testnet, the `height` should be at least
215    /// TESTNET_MAX_TIME_START_HEIGHT to return true.
216    /// Returns false otherwise.
217    ///
218    /// Part of the consensus rules at <https://zips.z.cash/protocol/protocol.pdf#blockheader>
219    pub fn is_max_block_time_enforced(&self, height: block::Height) -> bool {
220        match self {
221            Network::Mainnet => true,
222            // TODO: Move `TESTNET_MAX_TIME_START_HEIGHT` to a field on testnet::Parameters (#8364)
223            Network::Testnet(_params) => height >= super::TESTNET_MAX_TIME_START_HEIGHT,
224        }
225    }
226
227    /// Get the default port associated to this network.
228    pub fn default_port(&self) -> u16 {
229        match self {
230            Network::Mainnet => 8233,
231            // TODO: Add a `default_port` field to `testnet::Parameters` to return here. (zcashd uses 18344 for Regtest)
232            Network::Testnet(_params) => 18233,
233        }
234    }
235
236    /// Get the mandatory minimum checkpoint height for this network.
237    ///
238    /// Mandatory checkpoints are a Zebra-specific feature.
239    /// If a Zcash consensus rule only applies before the mandatory checkpoint,
240    /// Zebra can skip validation of that rule.
241    /// This is necessary because Zebra can't fully validate the blocks prior to Canopy.
242    // TODO:
243    // - Support constructing pre-Canopy coinbase tx and block templates and return `Height::MAX` instead of panicking
244    //   when Canopy activation height is `None` (#8434)
245    pub fn mandatory_checkpoint_height(&self) -> Height {
246        // Currently this is just before Canopy activation
247        NetworkUpgrade::Canopy
248            .activation_height(self)
249            .expect("Canopy activation height must be present on all networks")
250            .previous()
251            .expect("Canopy activation height must be above min height")
252    }
253
254    /// Return the network name as defined in
255    /// [BIP70](https://github.com/bitcoin/bips/blob/master/bip-0070.mediawiki#paymentdetailspaymentrequest)
256    pub fn bip70_network_name(&self) -> String {
257        self.kind().bip70_network_name()
258    }
259
260    /// Return the lowercase network name.
261    pub fn lowercase_name(&self) -> String {
262        self.to_string().to_ascii_lowercase()
263    }
264
265    /// Returns `true` if this network is a testing network.
266    pub fn is_a_test_network(&self) -> bool {
267        *self != Network::Mainnet
268    }
269
270    /// Returns the Sapling activation height for this network.
271    // TODO: Return an `Option` here now that network upgrade activation heights are configurable on Regtest and custom Testnets
272    pub fn sapling_activation_height(&self) -> Height {
273        super::NetworkUpgrade::Sapling
274            .activation_height(self)
275            .expect("Sapling activation height needs to be set")
276    }
277}
278
279// This is used for parsing a command-line argument for the `TipHeight` command in zebrad.
280impl FromStr for Network {
281    type Err = InvalidNetworkError;
282
283    fn from_str(string: &str) -> Result<Self, Self::Err> {
284        match string.to_lowercase().as_str() {
285            "mainnet" => Ok(Network::Mainnet),
286            "testnet" => Ok(Network::new_default_testnet()),
287            _ => Err(InvalidNetworkError(string.to_owned())),
288        }
289    }
290}
291
292#[derive(Clone, Debug, Error)]
293#[error("Invalid network: {0}")]
294pub struct InvalidNetworkError(String);
295
296impl zcash_protocol::consensus::Parameters for Network {
297    fn network_type(&self) -> zcash_protocol::consensus::NetworkType {
298        self.kind().into()
299    }
300
301    fn activation_height(
302        &self,
303        nu: zcash_protocol::consensus::NetworkUpgrade,
304    ) -> Option<zcash_protocol::consensus::BlockHeight> {
305        NetworkUpgrade::from(nu)
306            .activation_height(self)
307            .map(|Height(h)| zcash_protocol::consensus::BlockHeight::from_u32(h))
308    }
309}