1use 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
17const 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#[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 Genesis,
46 BeforeOverwinter,
51 Overwinter,
53 Sapling,
55 Blossom,
57 Heartwood,
59 Canopy,
61 #[serde(rename = "NU5")]
63 Nu5,
64 #[serde(rename = "NU6")]
66 Nu6,
67 #[serde(rename = "NU6.1")]
69 Nu6_1,
70 #[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 fmt::Debug::fmt(self, f)
91 }
92}
93
94#[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
116pub const NU6_1_ACTIVATION_HEIGHT_TESTNET: block::Height = block::Height(3_536_500);
120
121#[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#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
147pub struct ConsensusBranchId(pub(crate) u32);
148
149impl ConsensusBranchId {
150 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
215pub(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
238const PRE_BLOSSOM_POW_TARGET_SPACING: i64 = 150;
240
241pub const POST_BLOSSOM_POW_TARGET_SPACING: u32 = 75;
243
244pub const POW_AVERAGING_WINDOW: usize = 17;
248
249const TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER: i32 = 6;
254
255const TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT: block::Height = block::Height(299_188);
259
260pub const TESTNET_MAX_TIME_START_HEIGHT: block::Height = block::Height(653_606);
265
266impl Network {
267 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 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 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 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 pub fn next_upgrade(self) -> Option<Self> {
320 Self::iter().skip_while(|&nu| self != nu).nth(1)
321 }
322
323 pub fn previous_upgrade(self) -> Option<Self> {
325 Self::iter().rev().skip_while(|&nu| self != nu).nth(1)
326 }
327
328 #[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 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 pub fn is_activation_height(network: &Network, height: block::Height) -> bool {
372 network.activation_list().contains_key(&height)
373 }
374
375 pub(crate) fn branch_id_list() -> HashMap<NetworkUpgrade, ConsensusBranchId> {
384 CONSENSUS_BRANCH_IDS.iter().cloned().collect()
385 }
386
387 pub fn branch_id(&self) -> Option<ConsensusBranchId> {
391 NetworkUpgrade::branch_id_list().get(self).cloned()
392 }
393
394 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 pub fn target_spacing_for_height(network: &Network, height: block::Height) -> Duration {
413 NetworkUpgrade::current(network, height).target_spacing()
414 }
415
416 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 pub fn minimum_difficulty_spacing_for_height(
440 network: &Network,
441 height: block::Height,
442 ) -> Option<Duration> {
443 match (network, height) {
444 (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 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 pub fn averaging_window_timespan(&self) -> Duration {
493 self.target_spacing() * POW_AVERAGING_WINDOW.try_into().expect("fits in i32")
494 }
495
496 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 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 }
525 }
526}
527
528impl ConsensusBranchId {
529 pub const RPC_MISSING_ID: ConsensusBranchId = ConsensusBranchId(0);
538
539 pub fn current(network: &Network, height: block::Height) -> Option<ConsensusBranchId> {
543 NetworkUpgrade::current(network, height).branch_id()
544 }
545}