Skip to main content

zebra_chain/parameters/network/
testnet.rs

1//! Types and implementation for Testnet consensus parameters
2
3use std::{
4    collections::{BTreeMap, HashMap},
5    fmt,
6    sync::{Arc, LazyLock},
7};
8
9use crate::{
10    amount::{Amount, NonNegative, MAX_MONEY},
11    block::{self, Height, HeightDiff},
12    parameters::{
13        checkpoint::list::{CheckpointList, TESTNET_CHECKPOINT_LIST},
14        constants::{magics, SLOW_START_INTERVAL, SLOW_START_SHIFT},
15        network::error::ParametersBuilderError,
16        network_upgrade::TESTNET_ACTIVATION_HEIGHTS,
17        subsidy::{
18            constants::mainnet,
19            constants::testnet,
20            constants::{
21                BLOSSOM_POW_TARGET_SPACING_RATIO, FUNDING_STREAM_RECEIVER_DENOMINATOR,
22                NU7_POW_TARGET_SPACING_RATIO, POST_BLOSSOM_HALVING_INTERVAL,
23                PRE_BLOSSOM_HALVING_INTERVAL,
24            },
25            cumulative_scheduled_issuance_zatoshis, funding_stream_address_period,
26            height_for_halving, nsm_reissuance_crossing_height, nu7_funding_stream_end_height,
27            scheduled_block_subsidy, FundingStreamReceiver, FundingStreamRecipient, FundingStreams,
28            ParameterSubsidy, LN2_SCALED, TESTNET_INITIAL_NSM_VALUE_BALANCE,
29        },
30        ConsensusBranchId, Network, NetworkKind, NetworkUpgrade,
31    },
32    transparent,
33    work::difficulty::{ExpandedDifficulty, U256},
34};
35
36use super::magic::Magic;
37
38/// Reserved network names that should not be allowed for configured Testnets.
39pub const RESERVED_NETWORK_NAMES: [&str; 6] = [
40    "Mainnet",
41    "Testnet",
42    "Regtest",
43    "MainnetKind",
44    "TestnetKind",
45    "RegtestKind",
46];
47
48/// Maximum length for a configured network name.
49pub const MAX_NETWORK_NAME_LENGTH: usize = 30;
50
51/// Maximum length for a configured human-readable prefix.
52pub const MAX_HRP_LENGTH: usize = 30;
53
54/// The block hash of the Regtest genesis block, `zcash-cli -regtest getblockhash 0`
55const REGTEST_GENESIS_HASH: &str =
56    "029f11d80ef9765602235e1bc9727e3eb6ba20839319f761fee920d63401e327";
57
58/// The block hash of the Testnet genesis block, `zcash-cli -testnet getblockhash 0`
59const TESTNET_GENESIS_HASH: &str =
60    "05a60a92d99d85997cce3b87616c089f6124d7342af37106edc76126334a2c38";
61
62/// The halving height interval in the regtest is 6 hours.
63/// [zcashd regtest halving interval](https://github.com/zcash/zcash/blob/v5.10.0/src/consensus/params.h#L252)
64const PRE_BLOSSOM_REGTEST_HALVING_INTERVAL: HeightDiff = 144;
65
66/// Configurable funding stream recipient for configured Testnets.
67#[derive(Serialize, Deserialize, Clone, Debug)]
68#[serde(deny_unknown_fields)]
69pub struct ConfiguredFundingStreamRecipient {
70    /// Funding stream receiver, see [`FundingStreams::recipients`] for more details.
71    pub receiver: FundingStreamReceiver,
72    /// The numerator for each funding stream receiver category, see [`FundingStreamRecipient::numerator`] for more details.
73    pub numerator: u64,
74    /// Addresses for the funding stream recipient, see [`FundingStreamRecipient::addresses`] for more details.
75    pub addresses: Option<Vec<String>>,
76}
77
78impl ConfiguredFundingStreamRecipient {
79    /// Creates a new [`ConfiguredFundingStreamRecipient`] with the provided receiver and default
80    /// values for other fields.
81    pub fn new_for(receiver: FundingStreamReceiver) -> Self {
82        use FundingStreamReceiver::*;
83        match receiver {
84            Ecc => Self {
85                receiver: Ecc,
86                numerator: 7,
87                addresses: Some(
88                    testnet::FUNDING_STREAM_ECC_ADDRESSES
89                        .map(ToString::to_string)
90                        .to_vec(),
91                ),
92            },
93            ZcashFoundation => Self {
94                receiver: ZcashFoundation,
95                numerator: 5,
96                addresses: Some(
97                    testnet::FUNDING_STREAM_ZF_ADDRESSES
98                        .map(ToString::to_string)
99                        .to_vec(),
100                ),
101            },
102            MajorGrants => Self {
103                receiver: MajorGrants,
104                numerator: 8,
105                addresses: Some(
106                    testnet::FUNDING_STREAM_MG_ADDRESSES
107                        .map(ToString::to_string)
108                        .to_vec(),
109                ),
110            },
111            Deferred => Self {
112                receiver,
113                numerator: 0,
114                addresses: None,
115            },
116        }
117    }
118
119    /// Converts a [`ConfiguredFundingStreamRecipient`] to a [`FundingStreamReceiver`] and [`FundingStreamRecipient`].
120    pub fn into_recipient(self) -> (FundingStreamReceiver, FundingStreamRecipient) {
121        (
122            self.receiver,
123            FundingStreamRecipient::new(self.numerator, self.addresses.unwrap_or_default()),
124        )
125    }
126}
127
128/// Configurable one-time lockbox disbursement recipients for configured Testnets.
129#[derive(Serialize, Deserialize, Clone, Debug)]
130#[serde(deny_unknown_fields)]
131pub struct ConfiguredLockboxDisbursement {
132    /// The expected address for the lockbox disbursement output
133    pub address: String,
134    /// The expected disbursement amount
135    pub amount: Amount<NonNegative>,
136}
137
138/// Configurable funding streams for configured Testnets.
139#[derive(Serialize, Deserialize, Clone, Default, Debug)]
140#[serde(deny_unknown_fields)]
141pub struct ConfiguredFundingStreams {
142    /// Start and end height for funding streams see [`FundingStreams::height_range`] for more details.
143    pub height_range: Option<std::ops::Range<Height>>,
144    /// Funding stream recipients, see [`FundingStreams::recipients`] for more details.
145    pub recipients: Option<Vec<ConfiguredFundingStreamRecipient>>,
146}
147
148impl From<&FundingStreams> for ConfiguredFundingStreams {
149    fn from(value: &FundingStreams) -> Self {
150        Self {
151            height_range: Some(value.height_range().clone()),
152            recipients: Some(
153                value
154                    .recipients()
155                    .iter()
156                    .map(|(receiver, recipient)| ConfiguredFundingStreamRecipient {
157                        receiver: *receiver,
158                        numerator: recipient.numerator(),
159                        addresses: Some(
160                            recipient
161                                .addresses()
162                                .iter()
163                                .map(ToString::to_string)
164                                .collect(),
165                        ),
166                    })
167                    .collect(),
168            ),
169        }
170    }
171}
172
173impl From<(transparent::Address, Amount<NonNegative>)> for ConfiguredLockboxDisbursement {
174    fn from((address, amount): (transparent::Address, Amount<NonNegative>)) -> Self {
175        Self {
176            address: address.to_string(),
177            amount,
178        }
179    }
180}
181
182impl From<&BTreeMap<Height, NetworkUpgrade>> for ConfiguredActivationHeights {
183    fn from(activation_heights: &BTreeMap<Height, NetworkUpgrade>) -> Self {
184        let mut configured_activation_heights = ConfiguredActivationHeights::default();
185
186        // The map coalesces upgrades at the same height. Restore implicit activations before
187        // Regtest's `for_regtest` fills missing early upgrades from its defaults.
188        let mut configured = activation_heights.iter().peekable();
189        for network_upgrade in NetworkUpgrade::iter() {
190            while configured
191                .peek()
192                .is_some_and(|(_, upgrade)| **upgrade < network_upgrade)
193            {
194                configured.next();
195            }
196            let Some((height, _)) = configured.peek() else {
197                break;
198            };
199            let field = match network_upgrade {
200                NetworkUpgrade::BeforeOverwinter => {
201                    &mut configured_activation_heights.before_overwinter
202                }
203                NetworkUpgrade::Overwinter => &mut configured_activation_heights.overwinter,
204                NetworkUpgrade::Sapling => &mut configured_activation_heights.sapling,
205                NetworkUpgrade::Blossom => &mut configured_activation_heights.blossom,
206                NetworkUpgrade::Heartwood => &mut configured_activation_heights.heartwood,
207                NetworkUpgrade::Canopy => &mut configured_activation_heights.canopy,
208                NetworkUpgrade::Nu5 => &mut configured_activation_heights.nu5,
209                NetworkUpgrade::Nu6 => &mut configured_activation_heights.nu6,
210                NetworkUpgrade::Nu6_1 => &mut configured_activation_heights.nu6_1,
211                NetworkUpgrade::Nu6_2 => &mut configured_activation_heights.nu6_2,
212                NetworkUpgrade::Nu6_3 => &mut configured_activation_heights.nu6_3,
213                NetworkUpgrade::Nu7 => &mut configured_activation_heights.nu7,
214                #[cfg(zcash_unstable = "zfuture")]
215                NetworkUpgrade::ZFuture => &mut configured_activation_heights.zfuture,
216                NetworkUpgrade::Genesis => continue,
217            };
218
219            *field = Some(height.0)
220        }
221
222        configured_activation_heights
223    }
224}
225
226impl From<BTreeMap<Height, NetworkUpgrade>> for ConfiguredActivationHeights {
227    fn from(value: BTreeMap<Height, NetworkUpgrade>) -> Self {
228        Self::from(&value)
229    }
230}
231
232impl ConfiguredFundingStreams {
233    /// Converts a [`ConfiguredFundingStreams`] to a [`FundingStreams`], using the provided default values
234    /// if `height_range` or `recipients` are None.
235    ///
236    /// # Panics
237    ///
238    /// If a default is required but was not passed
239    fn convert_with_default(
240        self,
241        default_funding_streams: Option<FundingStreams>,
242    ) -> FundingStreams {
243        let height_range = self.height_range.unwrap_or_else(|| {
244            default_funding_streams
245                .as_ref()
246                .expect("default required")
247                .height_range()
248                .clone()
249        });
250
251        let recipients = self
252            .recipients
253            .map(|recipients| {
254                recipients
255                    .into_iter()
256                    .map(ConfiguredFundingStreamRecipient::into_recipient)
257                    .collect()
258            })
259            .unwrap_or_else(|| {
260                default_funding_streams
261                    .as_ref()
262                    .expect("default required")
263                    .recipients()
264                    .clone()
265            });
266
267        assert!(
268            height_range.start <= height_range.end,
269            "funding stream end height must be above start height"
270        );
271
272        let funding_streams = FundingStreams::new(height_range.clone(), recipients);
273
274        // check that sum of receiver numerators is valid.
275
276        let sum_numerators: u64 = funding_streams
277            .recipients()
278            .values()
279            .map(|r| r.numerator())
280            .sum();
281
282        assert!(
283            sum_numerators <= FUNDING_STREAM_RECEIVER_DENOMINATOR,
284            "sum of funding stream numerators must not be \
285         greater than denominator of {FUNDING_STREAM_RECEIVER_DENOMINATOR}"
286        );
287
288        funding_streams
289    }
290
291    /// Converts the [`ConfiguredFundingStreams`] to a [`FundingStreams`].
292    ///
293    /// # Panics
294    ///
295    /// If `height_range` is None.
296    pub fn into_funding_streams_unchecked(self) -> FundingStreams {
297        let height_range = self.height_range.expect("must have height range");
298        let recipients = self
299            .recipients
300            .into_iter()
301            .flat_map(|recipients| {
302                recipients
303                    .into_iter()
304                    .map(ConfiguredFundingStreamRecipient::into_recipient)
305            })
306            .collect();
307
308        FundingStreams::new(height_range, recipients)
309    }
310}
311
312/// Returns the number of funding stream address periods there are for the provided network and height range.
313fn num_funding_stream_addresses_required_for_height_range(
314    height_range: &std::ops::Range<Height>,
315    network: &Network,
316) -> usize {
317    if height_range.is_empty() {
318        return 0;
319    }
320
321    // The two periods are only meaningful relative to each other, so the subtraction is done in
322    // signed arithmetic: see `funding_stream_address_period()`.
323    let last_period = funding_stream_address_period(
324        height_range
325            .end
326            .previous()
327            .expect("end height must be above start height and genesis height"),
328        network,
329    );
330    let first_period = funding_stream_address_period(height_range.start, network);
331
332    usize::try_from(1 + last_period - first_period)
333        .expect("a height range's last address period is at or after its first")
334}
335
336/// Checks that the provided [`FundingStreams`] has sufficient recipient addresses for the
337/// funding stream address period of the provided [`Network`].
338fn check_funding_stream_address_period(
339    funding_streams: &FundingStreams,
340    network: &Network,
341) -> Result<(), ParametersBuilderError> {
342    let expected_min_num_addresses = num_funding_stream_addresses_required_for_height_range(
343        funding_streams.height_range(),
344        network,
345    );
346
347    for (&receiver, recipient) in funding_streams.recipients() {
348        if receiver == FundingStreamReceiver::Deferred {
349            // The `Deferred` receiver doesn't need any addresses.
350            continue;
351        }
352
353        let num_addresses = recipient.addresses().len();
354        if num_addresses < expected_min_num_addresses {
355            return Err(ParametersBuilderError::InsufficientFundingStreamAddresses {
356                receiver,
357                required: expected_min_num_addresses,
358                provided: num_addresses,
359            });
360        }
361
362        for address in recipient.addresses() {
363            assert_eq!(
364                address.network_kind(),
365                NetworkKind::Testnet,
366                "configured funding stream addresses must be for Testnet"
367            );
368        }
369    }
370
371    Ok(())
372}
373
374/// Checks effective funding stream ranges and recipient types for Testnet and Regtest.
375fn check_funding_streams(funding_streams: &[FundingStreams]) -> Result<(), ParametersBuilderError> {
376    for (index, streams) in funding_streams.iter().enumerate() {
377        let range = streams.height_range();
378        if !range.is_empty() {
379            // Pairwise checks avoid allocating for these small startup-only schedules;
380            // sort ranges if configurations grow to contain many funding stream groups.
381            if let Some(previous) = funding_streams[..index].iter().find(|previous| {
382                let previous = previous.height_range();
383                !previous.is_empty() && previous.start < range.end && range.start < previous.end
384            }) {
385                return Err(ParametersBuilderError::OverlappingFundingStreamRanges {
386                    first: previous.height_range().clone(),
387                    second: range.clone(),
388                });
389            }
390        }
391
392        for (&receiver, recipient) in streams.recipients() {
393            if receiver == FundingStreamReceiver::Deferred {
394                continue;
395            }
396            if let Some(&address) = recipient
397                .addresses()
398                .iter()
399                .find(|address| matches!(address, transparent::Address::Tex { .. }))
400            {
401                return Err(ParametersBuilderError::UnsupportedFundingStreamAddress {
402                    receiver,
403                    address,
404                });
405            }
406        }
407    }
408    Ok(())
409}
410
411/// Configurable activation heights for Regtest and configured Testnets.
412#[derive(Serialize, Deserialize, Default, Clone, Copy, Debug, PartialEq)]
413#[serde(rename_all = "PascalCase", deny_unknown_fields)]
414pub struct ConfiguredActivationHeights {
415    /// Activation height for `BeforeOverwinter` network upgrade.
416    pub before_overwinter: Option<u32>,
417    /// Activation height for `Overwinter` network upgrade.
418    pub overwinter: Option<u32>,
419    /// Activation height for `Sapling` network upgrade.
420    pub sapling: Option<u32>,
421    /// Activation height for `Blossom` network upgrade.
422    pub blossom: Option<u32>,
423    /// Activation height for `Heartwood` network upgrade.
424    pub heartwood: Option<u32>,
425    /// Activation height for `Canopy` network upgrade.
426    pub canopy: Option<u32>,
427    /// Activation height for `NU5` network upgrade.
428    #[serde(rename = "NU5")]
429    pub nu5: Option<u32>,
430    /// Activation height for `NU6` network upgrade.
431    #[serde(rename = "NU6")]
432    pub nu6: Option<u32>,
433    /// Activation height for `NU6.1` network upgrade.
434    #[serde(rename = "NU6.1")]
435    pub nu6_1: Option<u32>,
436    /// Activation height for `NU6.2` network upgrade.
437    #[serde(rename = "NU6.2")]
438    pub nu6_2: Option<u32>,
439    /// Activation height for `NU6.3` (Ironwood) network upgrade.
440    #[serde(rename = "NU6.3")]
441    pub nu6_3: Option<u32>,
442    /// Activation height for `NU7` network upgrade.
443    #[serde(rename = "NU7")]
444    pub nu7: Option<u32>,
445    /// Activation height for `ZFuture` network upgrade.
446    #[serde(rename = "ZFuture")]
447    #[cfg(zcash_unstable = "zfuture")]
448    pub zfuture: Option<u32>,
449}
450
451impl ConfiguredActivationHeights {
452    /// Converts a [`ConfiguredActivationHeights`] to one that uses the default values for Regtest where
453    /// no activation heights are specified.
454    fn for_regtest(self) -> Self {
455        let Self {
456            before_overwinter,
457            overwinter,
458            sapling,
459            blossom,
460            heartwood,
461            canopy,
462            nu5,
463            nu6,
464            nu6_1,
465            nu6_2,
466            nu6_3,
467            nu7,
468            #[cfg(zcash_unstable = "zfuture")]
469            zfuture,
470        } = self;
471
472        let overwinter = overwinter.or(before_overwinter).or(Some(1));
473        let sapling = sapling.or(overwinter);
474        let blossom = blossom.or(sapling);
475        let heartwood = heartwood.or(blossom);
476        let canopy = canopy.or(heartwood);
477
478        Self {
479            before_overwinter,
480            overwinter,
481            sapling,
482            blossom,
483            heartwood,
484            canopy,
485            nu5,
486            nu6,
487            nu6_1,
488            nu6_2,
489            nu6_3,
490            nu7,
491            #[cfg(zcash_unstable = "zfuture")]
492            zfuture,
493        }
494    }
495}
496
497/// Configurable checkpoints, either a path to a checkpoints file, a "default" keyword to indicate
498/// that Zebra should use the default Testnet checkpoints, or a list of block heights and hashes.
499#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
500#[serde(untagged)]
501pub enum ConfiguredCheckpoints {
502    /// A boolean indicating whether Zebra should use the default Testnet checkpoints.
503    Default(bool),
504    /// A path to a checkpoints file to be used as Zebra's checkpoints.
505    Path(std::path::PathBuf),
506    /// Directly configured block heights and hashes to be used as Zebra's checkpoints.
507    HeightsAndHashes(Vec<(block::Height, block::Hash)>),
508}
509
510impl Default for ConfiguredCheckpoints {
511    fn default() -> Self {
512        Self::Default(false)
513    }
514}
515
516impl From<Arc<CheckpointList>> for ConfiguredCheckpoints {
517    fn from(value: Arc<CheckpointList>) -> Self {
518        Self::HeightsAndHashes(value.iter_cloned().collect())
519    }
520}
521
522impl From<bool> for ConfiguredCheckpoints {
523    fn from(value: bool) -> Self {
524        Self::Default(value)
525    }
526}
527
528/// Returns an error if `upgrade` needs a consensus branch ID and `branch_ids` has none for it.
529///
530/// Every ZIP 221 history tree node commits to its network upgrade's branch ID, so `zebrad` would
531/// panic at the activation block of an upgrade without one. Upgrades before Overwinter need none.
532pub(crate) fn check_branch_id(
533    upgrade: NetworkUpgrade,
534    branch_ids: &HashMap<NetworkUpgrade, ConsensusBranchId>,
535) -> Result<(), ParametersBuilderError> {
536    if upgrade >= NetworkUpgrade::Overwinter && !branch_ids.contains_key(&upgrade) {
537        return Err(ParametersBuilderError::MissingBranchId { upgrade });
538    }
539    Ok(())
540}
541
542/// Builder for the [`Parameters`] struct.
543#[derive(Clone, Debug, Eq, PartialEq)]
544pub struct ParametersBuilder {
545    /// The name of this network to be used by the `Display` trait impl.
546    network_name: String,
547    /// The network magic, acts as an identifier for the network.
548    network_magic: Magic,
549    /// The genesis block hash
550    genesis_hash: block::Hash,
551    /// The network upgrade activation heights for this network, see [`Parameters::activation_heights`] for more details.
552    activation_heights: BTreeMap<Height, NetworkUpgrade>,
553    /// Slow start interval for this network
554    slow_start_interval: Height,
555    /// Funding streams for this network
556    funding_streams: Vec<FundingStreams>,
557    /// A flag indicating whether to allow changes to fields that affect
558    /// the funding stream address period.
559    should_lock_funding_stream_address_period: bool,
560    /// Target difficulty limit for this network
561    target_difficulty_limit: ExpandedDifficulty,
562    /// A flag for disabling proof-of-work checks when Zebra is validating blocks
563    disable_pow: bool,
564    /// Whether to allow transactions with transparent outputs to spend coinbase outputs,
565    /// similar to `fCoinbaseMustBeShielded` in zcashd.
566    should_allow_unshielded_coinbase_spends: bool,
567    /// The NSM value balance seeded at NU7 activation under the halving-preserving issuance ZIP
568    initial_nsm_value_balance: Option<Amount<NonNegative>>,
569    /// An explicit override for the calculated ZIP 237 reissuance height.
570    nsm_reissuance_height: Option<Height>,
571    /// The pre-Blossom halving interval for this network
572    pre_blossom_halving_interval: HeightDiff,
573    /// The post-Blossom halving interval for this network
574    post_blossom_halving_interval: HeightDiff,
575    /// Expected one-time lockbox disbursement outputs in NU6.1 activation block coinbase for this network
576    lockbox_disbursements: Vec<(String, Amount<NonNegative>)>,
577    /// Checkpointed block hashes and heights for this network.
578    checkpoints: Arc<CheckpointList>,
579    /// Height at which the soft-fork to temporarily disable Orchard in transactions activates
580    temporary_orchard_disabling_soft_fork_height: Option<Height>,
581}
582
583impl Default for ParametersBuilder {
584    /// Creates a builder with public Testnet parameters except its name.
585    fn default() -> Self {
586        let mut builder = Self {
587            network_name: "UnknownTestnet".to_string(),
588            network_magic: magics::TESTNET,
589            // # Correctness
590            //
591            // `Genesis` network upgrade activation height must always be 0
592            activation_heights: TESTNET_ACTIVATION_HEIGHTS.iter().cloned().collect(),
593            genesis_hash: TESTNET_GENESIS_HASH
594                .parse()
595                .expect("hard-coded hash parses"),
596            slow_start_interval: SLOW_START_INTERVAL,
597            // Testnet PoWLimit is defined as `2^251 - 1` on page 73 of the protocol specification:
598            // <https://zips.z.cash/protocol/protocol.pdf>
599            //
600            // The PoWLimit must be converted into a compact representation before using it
601            // to perform difficulty filter checks (see https://github.com/zcash/zips/pull/417).
602            target_difficulty_limit: ExpandedDifficulty::from((U256::one() << 251) - 1)
603                .to_compact()
604                .to_expanded()
605                .expect("difficulty limits are valid expanded values"),
606            disable_pow: false,
607            funding_streams: testnet::FUNDING_STREAMS.clone(),
608            should_lock_funding_stream_address_period: false,
609            pre_blossom_halving_interval: PRE_BLOSSOM_HALVING_INTERVAL,
610            post_blossom_halving_interval: POST_BLOSSOM_HALVING_INTERVAL,
611            should_allow_unshielded_coinbase_spends: false,
612            initial_nsm_value_balance: None,
613            nsm_reissuance_height: None,
614            lockbox_disbursements: testnet::NU6_1_LOCKBOX_DISBURSEMENTS
615                .iter()
616                .map(|(addr, amount)| (addr.to_string(), *amount))
617                .collect(),
618            checkpoints: TESTNET_CHECKPOINT_LIST.clone(),
619            temporary_orchard_disabling_soft_fork_height: Some(
620                super::TESTNET_TEMPORARY_ORCHARD_DISABLING_SOFT_FORK_HEIGHT,
621            ),
622        };
623        builder.update_funding_stream_end_height();
624        builder
625    }
626}
627
628impl ParametersBuilder {
629    /// Sets the network name to be used in the [`Parameters`] being built.
630    pub fn with_network_name(
631        mut self,
632        network_name: impl fmt::Display,
633    ) -> Result<Self, ParametersBuilderError> {
634        let network_name = network_name.to_string();
635
636        if RESERVED_NETWORK_NAMES
637            .iter()
638            .any(|reserved| network_name.eq_ignore_ascii_case(reserved))
639        {
640            return Err(ParametersBuilderError::ReservedNetworkName {
641                network_name,
642                reserved_names: RESERVED_NETWORK_NAMES.to_vec(),
643            });
644        }
645
646        if network_name.len() > MAX_NETWORK_NAME_LENGTH {
647            return Err(ParametersBuilderError::NetworkNameTooLong {
648                network_name,
649                max_length: MAX_NETWORK_NAME_LENGTH,
650            });
651        }
652
653        if !network_name
654            .chars()
655            .all(|x| x.is_alphanumeric() || x == '_')
656        {
657            return Err(ParametersBuilderError::InvalidCharacter);
658        }
659
660        self.network_name = network_name;
661        Ok(self)
662    }
663
664    /// Sets the network name to be used in the [`Parameters`] being built.
665    pub fn with_network_magic(
666        mut self,
667        network_magic: Magic,
668    ) -> Result<Self, ParametersBuilderError> {
669        if [magics::MAINNET, magics::REGTEST]
670            .into_iter()
671            .any(|reserved_magic| network_magic == reserved_magic)
672        {
673            return Err(ParametersBuilderError::ReservedNetworkMagic);
674        }
675
676        self.network_magic = network_magic;
677
678        Ok(self)
679    }
680
681    /// Parses the hex-encoded block hash and sets it as the genesis hash in the [`Parameters`] being built.
682    pub fn with_genesis_hash(
683        mut self,
684        genesis_hash: impl fmt::Display,
685    ) -> Result<Self, ParametersBuilderError> {
686        self.genesis_hash = genesis_hash
687            .to_string()
688            .parse()
689            .map_err(|_| ParametersBuilderError::InvalidGenesisHash)?;
690        Ok(self)
691    }
692
693    /// Checks that the provided network upgrade activation heights are in the correct order, then
694    /// sets them as the new network upgrade activation heights.
695    pub fn with_activation_heights(
696        mut self,
697        ConfiguredActivationHeights {
698            before_overwinter,
699            overwinter,
700            sapling,
701            blossom,
702            heartwood,
703            canopy,
704            nu5,
705            nu6,
706            nu6_1,
707            nu6_2,
708            nu6_3,
709            nu7,
710            #[cfg(zcash_unstable = "zfuture")]
711            zfuture,
712        }: ConfiguredActivationHeights,
713    ) -> Result<Self, ParametersBuilderError> {
714        if self.should_lock_funding_stream_address_period {
715            return Err(ParametersBuilderError::LockFundingStreams);
716        }
717
718        // # Correctness
719        //
720        // These must be in order so that later network upgrades overwrite prior ones
721        // if multiple network upgrades are configured with the same activation height.
722        let activation_heights: BTreeMap<_, _> = {
723            let activation_heights = [
724                before_overwinter,
725                overwinter,
726                sapling,
727                blossom,
728                heartwood,
729                canopy,
730                nu5,
731                nu6,
732                nu6_1,
733                nu6_2,
734                nu6_3,
735                nu7,
736                #[cfg(zcash_unstable = "zfuture")]
737                zfuture,
738            ]
739            .into_iter()
740            .zip(NetworkUpgrade::iter().skip(1))
741            .filter_map(|(height, upgrade)| height.map(|height| (height, upgrade)));
742
743            let branch_ids = NetworkUpgrade::branch_id_list();
744            let mut previous_height = Height::MIN;
745            activation_heights
746                .map(|(h, nu)| {
747                    let height = Height::try_from(h)
748                        .map_err(|_| ParametersBuilderError::InvalidActivationHeight)?;
749                    if height == Height::MIN {
750                        return Err(ParametersBuilderError::InvalidHeightZero);
751                    }
752                    if height < previous_height {
753                        return Err(ParametersBuilderError::OutOfOrderUpgrades);
754                    }
755                    check_branch_id(nu, &branch_ids)?;
756                    previous_height = height;
757                    Ok((height, nu))
758                })
759                .collect::<Result<BTreeMap<_, _>, _>>()?
760        };
761
762        // # Correctness
763        //
764        // Height(0) must be reserved for the `NetworkUpgrade::Genesis`.
765        self.activation_heights.split_off(&Height(1));
766        self.activation_heights.extend(activation_heights);
767        self.update_funding_stream_end_height();
768
769        Ok(self)
770    }
771
772    /// Sets the slow start interval to be used in the [`Parameters`] being built.
773    pub fn with_slow_start_interval(mut self, slow_start_interval: Height) -> Self {
774        self.slow_start_interval = slow_start_interval;
775        self
776    }
777
778    /// Sets funding streams to be used in the [`Parameters`] being built.
779    ///
780    /// # Panics
781    ///
782    /// If `funding_streams` is longer than `testnet::FUNDING_STREAMS`, and one
783    /// of the extra streams requires a default value.
784    pub fn with_funding_streams(mut self, funding_streams: Vec<ConfiguredFundingStreams>) -> Self {
785        let nu7 = self.nu7_activation_height();
786        self.funding_streams = funding_streams
787            .into_iter()
788            .enumerate()
789            .map(|(idx, streams)| {
790                let mut default_streams = testnet::FUNDING_STREAMS.get(idx).cloned();
791                if idx + 1 == testnet::FUNDING_STREAMS.len() {
792                    if let Some(streams) = &mut default_streams {
793                        streams.set_end_height(nu7_funding_stream_end_height(
794                            testnet::POST_NU6_1_FUNDING_STREAM_END_HEIGHT,
795                            nu7,
796                        ));
797                    }
798                }
799                streams.convert_with_default(default_streams)
800            })
801            .collect();
802        self.should_lock_funding_stream_address_period = true;
803        self
804    }
805
806    /// Clears funding streams from the [`Parameters`] being built.
807    pub fn clear_funding_streams(mut self) -> Self {
808        self.funding_streams = vec![];
809        self
810    }
811
812    /// Extends the configured funding streams to have as many recipients as are required for their
813    /// height ranges by repeating the recipients that have been configured.
814    ///
815    /// This should be called after configuring the desired network upgrade activation heights.
816    /// Validates the subsidy schedule as in [`Self::to_network`] before extending addresses.
817    pub fn extend_funding_streams(mut self) -> Result<Self, ParametersBuilderError> {
818        self.check_nsm_reissuance_height()?;
819        let network = self.to_network_unchecked();
820        self.validate_halving_interval(&network)?;
821
822        for funding_streams in &mut self.funding_streams {
823            funding_streams.extend_recipient_addresses(
824                num_funding_stream_addresses_required_for_height_range(
825                    funding_streams.height_range(),
826                    &network,
827                ),
828            );
829        }
830
831        Ok(self)
832    }
833
834    /// Sets the target difficulty limit to be used in the [`Parameters`] being built.
835    // TODO: Accept a hex-encoded String instead?
836    pub fn with_target_difficulty_limit(
837        mut self,
838        target_difficulty_limit: impl Into<ExpandedDifficulty>,
839    ) -> Result<Self, ParametersBuilderError> {
840        self.target_difficulty_limit = target_difficulty_limit
841            .into()
842            .to_compact()
843            .to_expanded()
844            .ok_or(ParametersBuilderError::InvaildDifficultyLimits)?;
845        Ok(self)
846    }
847
848    /// Sets the `disable_pow` flag to be used in the [`Parameters`] being built.
849    pub fn with_disable_pow(mut self, disable_pow: bool) -> Self {
850        self.disable_pow = disable_pow;
851        self
852    }
853
854    /// Sets whether coinbase outputs may be spent into transparent outputs in the
855    /// [`Parameters`] being built (the inverse of zcashd's `-regtestshieldcoinbase`).
856    pub fn with_unshielded_coinbase_spends(
857        mut self,
858        should_allow_unshielded_coinbase_spends: bool,
859    ) -> Self {
860        self.should_allow_unshielded_coinbase_spends = should_allow_unshielded_coinbase_spends;
861        self
862    }
863
864    /// Sets the NSM value balance seeded at NU7 activation under the halving-preserving issuance
865    /// ZIP, `INITIAL_NSM_VALUE_BALANCE`.
866    ///
867    /// Testnets using public Testnet magic inherit its historical reserve. Other Testnets and
868    /// Regtest default to zero. An explicit value overrides either default.
869    pub fn with_initial_nsm_value_balance(
870        mut self,
871        initial_nsm_value_balance: Amount<NonNegative>,
872    ) -> Self {
873        self.initial_nsm_value_balance = Some(initial_nsm_value_balance);
874        self
875    }
876
877    /// Sets the height from which the halving-preserving issuance ZIP reissues the NSM value
878    /// balance, `DEPLOYMENT_BLOCK_HEIGHT`.
879    ///
880    /// Without an override, ZIP 237 derives the height from the scheduled-issuance crossover.
881    /// An explicit override for accelerated testing must not precede NU7 activation.
882    pub fn with_nsm_reissuance_height(mut self, height: Height) -> Self {
883        self.nsm_reissuance_height = Some(height);
884        self
885    }
886
887    /// Checks that any configured NSM reissuance height is at or after the NU7 activation
888    /// height.
889    fn check_nsm_reissuance_height(&self) -> Result<(), ParametersBuilderError> {
890        let Some(deployment_height) = self.nsm_reissuance_height else {
891            return Ok(());
892        };
893        if deployment_height == Height::MIN || deployment_height > Height::MAX {
894            return Err(ParametersBuilderError::InvalidActivationHeight);
895        }
896
897        let nu7_activation_height = self.nu7_activation_height();
898
899        if nu7_activation_height.is_none_or(|nu7_height| deployment_height < nu7_height) {
900            return Err(ParametersBuilderError::NsmReissuanceHeightBeforeNu7);
901        }
902
903        Ok(())
904    }
905
906    /// Sets the pre- and post-Blossom halving intervals for the [`Parameters`] being built.
907    ///
908    /// Returns an error if the interval is nonpositive, exceeds [`Height::MAX`], or funding
909    /// streams already lock it. [`Self::to_network`] and [`Self::extend_funding_streams`] also
910    /// validate the full subsidy schedule, funding stream address period, and NSM coefficient.
911    pub fn with_halving_interval(
912        mut self,
913        pre_blossom_halving_interval: HeightDiff,
914    ) -> Result<Self, ParametersBuilderError> {
915        if self.should_lock_funding_stream_address_period {
916            return Err(ParametersBuilderError::HalvingIntervalAfterFundingStreams);
917        }
918        if pre_blossom_halving_interval <= 0
919            || pre_blossom_halving_interval > HeightDiff::from(Height::MAX.0)
920        {
921            return Err(ParametersBuilderError::InvalidHalvingInterval);
922        }
923
924        self.pre_blossom_halving_interval = pre_blossom_halving_interval;
925        self.post_blossom_halving_interval =
926            self.pre_blossom_halving_interval * (BLOSSOM_POW_TARGET_SPACING_RATIO as HeightDiff);
927        Ok(self)
928    }
929
930    /// Sets the expected one-time lockbox disbursement outputs for this network
931    pub fn with_lockbox_disbursements(
932        mut self,
933        lockbox_disbursements: Vec<ConfiguredLockboxDisbursement>,
934    ) -> Self {
935        self.lockbox_disbursements = lockbox_disbursements
936            .into_iter()
937            .map(|ConfiguredLockboxDisbursement { address, amount }| (address, amount))
938            .collect();
939        self
940    }
941
942    /// Sets the checkpoints for the network as the provided [`ConfiguredCheckpoints`].
943    pub fn with_checkpoints(
944        mut self,
945        checkpoints: impl Into<ConfiguredCheckpoints>,
946    ) -> Result<Self, ParametersBuilderError> {
947        self.checkpoints = match checkpoints.into() {
948            ConfiguredCheckpoints::Default(true) => TESTNET_CHECKPOINT_LIST.clone(),
949            ConfiguredCheckpoints::Default(false) => Arc::new(
950                CheckpointList::from_list([(block::Height(0), self.genesis_hash)])
951                    .map_err(|_| ParametersBuilderError::FailedToParseDefaultCheckpoint)?,
952            ),
953            ConfiguredCheckpoints::Path(path_buf) => {
954                let Ok(raw_checkpoints_str) = std::fs::read_to_string(&path_buf) else {
955                    return Err(ParametersBuilderError::FailedToReadCheckpointFile {
956                        path_buf: path_buf.clone(),
957                    });
958                };
959
960                Arc::new(
961                    raw_checkpoints_str
962                        .parse::<CheckpointList>()
963                        .map_err(|err| ParametersBuilderError::FailedToParseCheckpointFile {
964                            path_buf: path_buf.clone(),
965                            err: err.to_string(),
966                        })?,
967                )
968            }
969            ConfiguredCheckpoints::HeightsAndHashes(items) => Arc::new(
970                CheckpointList::from_list(items)
971                    .map_err(|_| ParametersBuilderError::InvalidCustomCheckpoints)?,
972            ),
973        };
974
975        Ok(self)
976    }
977
978    /// Clears checkpoints from the [`Parameters`] being built, keeping the genesis checkpoint.
979    pub fn clear_checkpoints(self) -> Result<Self, ParametersBuilderError> {
980        self.with_checkpoints(ConfiguredCheckpoints::Default(false))
981    }
982
983    /// Sets the height for this network at which the soft fork that temporarily disables
984    /// Orchard transactions will activate.
985    pub fn with_temporary_orchard_disabling_soft_fork_height(mut self, height: Height) -> Self {
986        self.temporary_orchard_disabling_soft_fork_height = Some(height);
987        self
988    }
989
990    /// Disables the soft fork that would temporarily disable Orchard transactions.
991    pub fn disable_temporary_orchard_disabling_soft_fork(mut self) -> Self {
992        self.temporary_orchard_disabling_soft_fork_height = None;
993        self
994    }
995
996    fn validate_halving_interval(&self, network: &Network) -> Result<(), ParametersBuilderError> {
997        if height_for_halving(1, network).is_none()
998            || (!self.funding_streams.is_empty()
999                && network.funding_stream_address_change_interval() == 0)
1000            || (self.nu7_activation_height().is_some()
1001                && u64::try_from(network.post_nu7_halving_interval())
1002                    .map_or(true, |interval| interval == 0 || interval > LN2_SCALED))
1003        {
1004            return Err(ParametersBuilderError::InvalidHalvingInterval);
1005        }
1006
1007        // The signed halving numerator is smallest at the slow-start shift. Reject schedules
1008        // where it would produce a negative index, rather than panicking in the subsidy helpers.
1009        let shift = network.slow_start_shift();
1010        let blossom = NetworkUpgrade::Blossom
1011            .activation_height(network)
1012            .ok_or(ParametersBuilderError::InvalidHalvingInterval)?;
1013        let mut numerator = 0;
1014        let mut interval = self.pre_blossom_halving_interval;
1015        if shift >= blossom {
1016            numerator = blossom - shift;
1017            interval = self.post_blossom_halving_interval;
1018        }
1019        if let Some(nu7) = NetworkUpgrade::Nu7
1020            .activation_height(network)
1021            .filter(|&height| height <= shift)
1022        {
1023            let ratio = HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO);
1024            numerator = numerator * ratio + (nu7 - shift) * (ratio - 1);
1025            interval = network.post_nu7_halving_interval();
1026        }
1027        if numerator / interval < 0 {
1028            return Err(ParametersBuilderError::InvalidHalvingInterval);
1029        }
1030
1031        let mut total = cumulative_scheduled_issuance_zatoshis(Height::MAX, network)
1032            .map_err(|_| ParametersBuilderError::InvalidSubsidySchedule)?;
1033        // Genesis is unspendable and is excluded from the monetary cap.
1034        let genesis = scheduled_block_subsidy(Height::MIN, network)
1035            .map_err(|_| ParametersBuilderError::InvalidSubsidySchedule)?;
1036        total = total
1037            .checked_sub(u64::from(genesis))
1038            .ok_or(ParametersBuilderError::InvalidSubsidySchedule)?;
1039        if i128::from(total) > i128::from(MAX_MONEY) {
1040            return Err(ParametersBuilderError::InvalidSubsidySchedule);
1041        }
1042        Ok(())
1043    }
1044
1045    /// Returns NU7's configured height without constructing or cloning a network.
1046    fn nu7_activation_height(&self) -> Option<Height> {
1047        self.activation_heights
1048            .iter()
1049            .find_map(|(&height, &upgrade)| (upgrade == NetworkUpgrade::Nu7).then_some(height))
1050    }
1051
1052    /// Keeps inherited ranges normalized before compatibility checks and serialization.
1053    /// Called only before explicit funding streams lock the activation schedule.
1054    fn update_funding_stream_end_height(&mut self) {
1055        let nu7 = self.nu7_activation_height();
1056        if let Some(streams) = self.funding_streams.last_mut() {
1057            streams.set_end_height(nu7_funding_stream_end_height(
1058                testnet::POST_NU6_1_FUNDING_STREAM_END_HEIGHT,
1059                nu7,
1060            ));
1061        }
1062    }
1063
1064    /// Converts the builder to a [`Parameters`] struct
1065    fn finish(self) -> Parameters {
1066        let Self {
1067            network_name,
1068            network_magic,
1069            genesis_hash,
1070            activation_heights,
1071            slow_start_interval,
1072            funding_streams,
1073            should_lock_funding_stream_address_period: _,
1074            target_difficulty_limit,
1075            disable_pow,
1076            should_allow_unshielded_coinbase_spends,
1077            initial_nsm_value_balance,
1078            nsm_reissuance_height,
1079            pre_blossom_halving_interval,
1080            post_blossom_halving_interval,
1081            lockbox_disbursements,
1082            checkpoints,
1083            temporary_orchard_disabling_soft_fork_height,
1084        } = self;
1085        Parameters {
1086            network_name,
1087            network_magic,
1088            genesis_hash,
1089            activation_heights,
1090            slow_start_interval,
1091            slow_start_shift: Height(slow_start_interval.0 / 2),
1092            funding_streams,
1093            target_difficulty_limit,
1094            disable_pow,
1095            should_allow_unshielded_coinbase_spends,
1096            initial_nsm_value_balance,
1097            nsm_reissuance_height,
1098            calculated_reissuance_height: None,
1099            pre_blossom_halving_interval,
1100            post_blossom_halving_interval,
1101            lockbox_disbursements,
1102            checkpoints,
1103            temporary_orchard_disabling_soft_fork_height,
1104        }
1105    }
1106
1107    /// Converts the builder to a configured [`Network::Testnet`]
1108    fn to_network_unchecked(&self) -> Network {
1109        Network::new_configured_testnet(self.clone().finish())
1110    }
1111
1112    /// Checks subsidy, funding stream, and checkpoint parameters and builds a configured Testnet.
1113    ///
1114    /// Scheduled issuance through [`Height::MAX`] must not exceed [`MAX_MONEY`]. The scheduled
1115    /// genesis subsidy is excluded. Reissuance also requires a post-NU7 halving interval no
1116    /// greater than [`LN2_SCALED`],
1117    /// so its integer coefficient is nonzero.
1118    /// Effective funding stream ranges must not overlap, and non-deferred recipients must use
1119    /// P2SH or P2PKH addresses.
1120    pub fn to_network(self) -> Result<Network, ParametersBuilderError> {
1121        self.check_nsm_reissuance_height()?;
1122        let mut network = self.to_network_unchecked();
1123        self.validate_halving_interval(&network)?;
1124
1125        // Final check that the configured funding streams will be valid for these Testnet parameters.
1126        check_funding_streams(&self.funding_streams)?;
1127        for fs in &self.funding_streams {
1128            check_funding_stream_address_period(fs, &network)?;
1129        }
1130
1131        // Final check that the configured checkpoints are valid for this network.
1132        if network.checkpoint_list().hash(Height(0)) != Some(network.genesis_hash()) {
1133            return Err(ParametersBuilderError::CheckpointGenesisMismatch);
1134        }
1135        if network.checkpoint_list().max_height() < network.mandatory_checkpoint_height() {
1136            return Err(ParametersBuilderError::InsufficientCheckpointCoverage);
1137        }
1138
1139        Parameters::calculate_reissuance_height(&mut network)?;
1140
1141        Ok(network)
1142    }
1143
1144    /// Returns true if these [`Parameters`] should be compatible with the default Testnet parameters.
1145    pub fn is_compatible_with_default_parameters(&self) -> bool {
1146        let Self {
1147            network_name: _,
1148            network_magic,
1149            genesis_hash,
1150            activation_heights,
1151            slow_start_interval,
1152            funding_streams,
1153            should_lock_funding_stream_address_period: _,
1154            target_difficulty_limit,
1155            disable_pow,
1156            should_allow_unshielded_coinbase_spends,
1157            initial_nsm_value_balance: _,
1158            nsm_reissuance_height,
1159            pre_blossom_halving_interval,
1160            post_blossom_halving_interval,
1161            lockbox_disbursements,
1162            checkpoints: _,
1163            temporary_orchard_disabling_soft_fork_height,
1164        } = Self::default();
1165
1166        let nsm_parameters_match = self
1167            .initial_nsm_value_balance
1168            .map_or(TESTNET_INITIAL_NSM_VALUE_BALANCE, u64::from)
1169            == TESTNET_INITIAL_NSM_VALUE_BALANCE
1170            && self.nsm_reissuance_height == nsm_reissuance_height;
1171
1172        self.activation_heights == activation_heights
1173            && self.network_magic == network_magic
1174            && self.genesis_hash == genesis_hash
1175            && self.slow_start_interval == slow_start_interval
1176            && self.funding_streams == funding_streams
1177            && self.target_difficulty_limit == target_difficulty_limit
1178            && self.disable_pow == disable_pow
1179            && self.should_allow_unshielded_coinbase_spends
1180                == should_allow_unshielded_coinbase_spends
1181            && nsm_parameters_match
1182            && self.pre_blossom_halving_interval == pre_blossom_halving_interval
1183            && self.post_blossom_halving_interval == post_blossom_halving_interval
1184            && self.lockbox_disbursements == lockbox_disbursements
1185            && self.temporary_orchard_disabling_soft_fork_height
1186                == temporary_orchard_disabling_soft_fork_height
1187    }
1188}
1189
1190/// A struct of parameters for configuring Regtest in Zebra.
1191#[derive(Debug, Default, Clone)]
1192pub struct RegtestParameters {
1193    /// The configured network upgrade activation heights to use on Regtest
1194    pub activation_heights: ConfiguredActivationHeights,
1195    /// Configured funding streams
1196    pub funding_streams: Option<Vec<ConfiguredFundingStreams>>,
1197    /// Expected one-time lockbox disbursement outputs in NU6.1 activation block coinbase for Regtest
1198    pub lockbox_disbursements: Option<Vec<ConfiguredLockboxDisbursement>>,
1199    /// Configured checkpointed block heights and hashes.
1200    pub checkpoints: Option<ConfiguredCheckpoints>,
1201    /// Whether funding stream addresses should be repeated to fill all required funding stream periods.
1202    pub extend_funding_stream_addresses_as_required: Option<bool>,
1203    /// Whether to allow coinbase spends to have transparent outputs (inverse of
1204    /// zcashd's `-regtestshieldcoinbase`).
1205    pub should_allow_unshielded_coinbase_spends: Option<bool>,
1206    /// The NSM value balance seeded at NU7 activation under the halving-preserving issuance ZIP.
1207    pub initial_nsm_value_balance: Option<Amount<NonNegative>>,
1208    /// The height from which the halving-preserving issuance ZIP reissues the NSM value balance.
1209    /// If unset, ZIP 237 derives the height; short custom schedules may have no crossing.
1210    pub nsm_reissuance_height: Option<Height>,
1211}
1212
1213impl From<ConfiguredActivationHeights> for RegtestParameters {
1214    fn from(value: ConfiguredActivationHeights) -> Self {
1215        Self {
1216            activation_heights: value,
1217            ..Default::default()
1218        }
1219    }
1220}
1221
1222/// Network consensus parameters for test networks such as Regtest and the default Testnet.
1223#[derive(Clone, Debug, Eq, PartialEq)]
1224pub struct Parameters {
1225    /// The name of this network to be used by the `Display` trait impl.
1226    network_name: String,
1227    /// The network magic, acts as an identifier for the network.
1228    network_magic: Magic,
1229    /// The genesis block hash
1230    genesis_hash: block::Hash,
1231    /// The network upgrade activation heights for this network.
1232    activation_heights: BTreeMap<Height, NetworkUpgrade>,
1233    /// Slow start interval for this network
1234    slow_start_interval: Height,
1235    /// Slow start shift for this network, always half the slow start interval
1236    slow_start_shift: Height,
1237    /// Funding streams for this network
1238    funding_streams: Vec<FundingStreams>,
1239    /// Target difficulty limit for this network
1240    target_difficulty_limit: ExpandedDifficulty,
1241    /// A flag for disabling proof-of-work checks when Zebra is validating blocks
1242    disable_pow: bool,
1243    /// Whether to allow transactions with transparent outputs to spend coinbase outputs,
1244    /// similar to `fCoinbaseMustBeShielded` in zcashd.
1245    should_allow_unshielded_coinbase_spends: bool,
1246    /// The NSM value balance seeded at NU7 activation under the halving-preserving issuance ZIP
1247    initial_nsm_value_balance: Option<Amount<NonNegative>>,
1248    /// An explicit override for the calculated ZIP 237 reissuance height.
1249    nsm_reissuance_height: Option<Height>,
1250    /// The immutable scheduled-issuance crossover, calculated once when parameters are built.
1251    calculated_reissuance_height: Option<Height>,
1252    /// Pre-Blossom halving interval for this network
1253    pre_blossom_halving_interval: HeightDiff,
1254    /// Post-Blossom halving interval for this network
1255    post_blossom_halving_interval: HeightDiff,
1256    /// Expected one-time lockbox disbursement outputs in NU6.1 activation block coinbase for this network
1257    lockbox_disbursements: Vec<(String, Amount<NonNegative>)>,
1258    /// List of checkpointed block heights and hashes
1259    checkpoints: Arc<CheckpointList>,
1260    /// Height at which the soft-fork to temporarily disable Orchard in transactions activates
1261    temporary_orchard_disabling_soft_fork_height: Option<Height>,
1262}
1263
1264/// Build directly from the uncached builder so initialization never re-enters this cache.
1265static DEFAULT_TESTNET_PARAMETERS: LazyLock<Parameters> = LazyLock::new(|| {
1266    Parameters {
1267        network_name: "Testnet".to_string(),
1268        ..Parameters::build().finish()
1269    }
1270    .with_calculated_reissuance_height()
1271    .expect("the hard-coded public Testnet subsidy schedule is valid")
1272});
1273
1274impl Default for Parameters {
1275    /// Returns an instance of the default public testnet [`Parameters`].
1276    fn default() -> Self {
1277        DEFAULT_TESTNET_PARAMETERS.clone()
1278    }
1279}
1280
1281impl Parameters {
1282    /// Creates a new [`ParametersBuilder`].
1283    pub fn build() -> ParametersBuilder {
1284        ParametersBuilder::default()
1285    }
1286
1287    /// Accepts a [`ConfiguredActivationHeights`].
1288    ///
1289    /// Creates an instance of [`Parameters`] with `Regtest` values.
1290    /// Returns an error for overlapping effective funding stream ranges or unsupported
1291    /// non-deferred recipient addresses, as on configured Testnets.
1292    pub fn new_regtest(
1293        RegtestParameters {
1294            activation_heights,
1295            funding_streams,
1296            lockbox_disbursements,
1297            checkpoints,
1298            extend_funding_stream_addresses_as_required,
1299            should_allow_unshielded_coinbase_spends,
1300            initial_nsm_value_balance,
1301            nsm_reissuance_height,
1302        }: RegtestParameters,
1303    ) -> Result<Self, ParametersBuilderError> {
1304        let mut parameters = Self::build()
1305            .with_genesis_hash(REGTEST_GENESIS_HASH)?
1306            // This value is chosen to match zcashd, see: <https://github.com/zcash/zcash/blob/master/src/chainparams.cpp#L654>
1307            .with_target_difficulty_limit(U256::from_big_endian(&[0x0f; 32]))?
1308            .with_disable_pow(true)
1309            .with_unshielded_coinbase_spends(
1310                should_allow_unshielded_coinbase_spends.unwrap_or(true),
1311            )
1312            .with_slow_start_interval(Height::MIN)
1313            // Like the default Testnet activation heights stripped below, the default Testnet's
1314            // temporary Orchard-disabling soft fork does not apply to Regtest.
1315            .disable_temporary_orchard_disabling_soft_fork()
1316            // Removes default Testnet activation heights if not configured,
1317            // most network upgrades are disabled by default for Regtest in zcashd
1318            .with_activation_heights(activation_heights.for_regtest())?
1319            .with_halving_interval(PRE_BLOSSOM_REGTEST_HALVING_INTERVAL)?
1320            .with_funding_streams(funding_streams.unwrap_or_default())
1321            .with_lockbox_disbursements(lockbox_disbursements.unwrap_or_default())
1322            .with_checkpoints(checkpoints.unwrap_or_default())?;
1323
1324        if Some(true) == extend_funding_stream_addresses_as_required {
1325            parameters = parameters.extend_funding_streams()?;
1326        }
1327        if let Some(initial_nsm_value_balance) = initial_nsm_value_balance {
1328            parameters = parameters.with_initial_nsm_value_balance(initial_nsm_value_balance);
1329        }
1330
1331        if let Some(nsm_reissuance_height) = nsm_reissuance_height {
1332            parameters = parameters.with_nsm_reissuance_height(nsm_reissuance_height);
1333        }
1334
1335        parameters.check_nsm_reissuance_height()?;
1336        check_funding_streams(&parameters.funding_streams)?;
1337
1338        Self {
1339            network_name: "Regtest".to_string(),
1340            network_magic: magics::REGTEST,
1341            ..parameters.finish()
1342        }
1343        .with_calculated_reissuance_height()
1344    }
1345
1346    /// Returns true if the instance of [`Parameters`] represents the default public Testnet.
1347    pub fn is_default_testnet(&self) -> bool {
1348        self == &*DEFAULT_TESTNET_PARAMETERS
1349    }
1350
1351    /// Returns true if the instance of [`Parameters`] represents Regtest.
1352    pub fn is_regtest(&self) -> bool {
1353        if self.network_magic != magics::REGTEST {
1354            return false;
1355        }
1356
1357        let Self {
1358            network_name,
1359            // Already checked network magic above
1360            network_magic: _,
1361            genesis_hash,
1362            // Activation heights are configurable on Regtest
1363            activation_heights: _,
1364            slow_start_interval,
1365            slow_start_shift,
1366            funding_streams: _,
1367            target_difficulty_limit,
1368            disable_pow,
1369            // Configurable on Regtest
1370            should_allow_unshielded_coinbase_spends: _,
1371            // Configurable on Regtest
1372            initial_nsm_value_balance: _,
1373            // Configurable on Regtest
1374            nsm_reissuance_height: _,
1375            calculated_reissuance_height: _,
1376            pre_blossom_halving_interval,
1377            post_blossom_halving_interval,
1378            lockbox_disbursements: _,
1379            checkpoints: _,
1380            temporary_orchard_disabling_soft_fork_height: _,
1381        } = Self::new_regtest(Default::default()).expect("default regtest parameters are valid");
1382
1383        self.network_name == network_name
1384            && self.genesis_hash == genesis_hash
1385            && self.slow_start_interval == slow_start_interval
1386            && self.slow_start_shift == slow_start_shift
1387            && self.target_difficulty_limit == target_difficulty_limit
1388            && self.disable_pow == disable_pow
1389            && self.pre_blossom_halving_interval == pre_blossom_halving_interval
1390            && self.post_blossom_halving_interval == post_blossom_halving_interval
1391    }
1392
1393    /// Returns the network name
1394    pub fn network_name(&self) -> &str {
1395        &self.network_name
1396    }
1397
1398    /// Returns the network magic
1399    pub fn network_magic(&self) -> Magic {
1400        self.network_magic
1401    }
1402
1403    /// Returns the genesis hash
1404    pub fn genesis_hash(&self) -> block::Hash {
1405        self.genesis_hash
1406    }
1407
1408    /// Returns the network upgrade activation heights
1409    pub fn activation_heights(&self) -> &BTreeMap<Height, NetworkUpgrade> {
1410        &self.activation_heights
1411    }
1412
1413    /// Returns slow start interval for this network
1414    pub fn slow_start_interval(&self) -> Height {
1415        self.slow_start_interval
1416    }
1417
1418    /// Returns slow start shift for this network
1419    pub fn slow_start_shift(&self) -> Height {
1420        self.slow_start_shift
1421    }
1422
1423    /// Returns funding streams for this network.
1424    pub fn funding_streams(&self) -> &Vec<FundingStreams> {
1425        &self.funding_streams
1426    }
1427
1428    /// Returns the target difficulty limit for this network
1429    pub fn target_difficulty_limit(&self) -> ExpandedDifficulty {
1430        self.target_difficulty_limit
1431    }
1432
1433    /// Returns true if proof-of-work validation should be disabled for this network
1434    pub fn disable_pow(&self) -> bool {
1435        self.disable_pow
1436    }
1437
1438    /// Returns true if this network should allow transactions with transparent outputs
1439    /// that spend coinbase outputs.
1440    pub fn should_allow_unshielded_coinbase_spends(&self) -> bool {
1441        self.should_allow_unshielded_coinbase_spends
1442    }
1443
1444    /// Returns `INITIAL_NSM_VALUE_BALANCE` for this network: the NSM value balance seeded at NU7
1445    /// activation under the halving-preserving issuance ZIP.
1446    ///
1447    /// Omitted settings use the public Testnet seed for public Testnet magic, otherwise zero.
1448    pub fn initial_nsm_value_balance(&self) -> Amount<NonNegative> {
1449        self.initial_nsm_value_balance.unwrap_or_else(|| {
1450            if self.network_magic == magics::TESTNET {
1451                Amount::try_from(TESTNET_INITIAL_NSM_VALUE_BALANCE)
1452                    .expect("the measured Testnet seed is a valid amount")
1453            } else {
1454                Amount::zero()
1455            }
1456        })
1457    }
1458
1459    /// Returns the explicit seed override, preserving omission during configuration round trips.
1460    pub fn configured_initial_nsm_value_balance(&self) -> Option<Amount<NonNegative>> {
1461        self.initial_nsm_value_balance
1462    }
1463
1464    fn with_calculated_reissuance_height(self) -> Result<Self, ParametersBuilderError> {
1465        if self.nsm_reissuance_height.is_some()
1466            || !self
1467                .activation_heights
1468                .values()
1469                .any(|upgrade| *upgrade == NetworkUpgrade::Nu7)
1470        {
1471            return Ok(self);
1472        }
1473        let mut network = Network::Testnet(Arc::new(self));
1474        Self::calculate_reissuance_height(&mut network)?;
1475        let Network::Testnet(parameters) = network else {
1476            unreachable!("this method just constructed a Testnet")
1477        };
1478        Ok(Arc::unwrap_or_clone(parameters))
1479    }
1480
1481    fn calculate_reissuance_height(network: &mut Network) -> Result<(), ParametersBuilderError> {
1482        let Network::Testnet(parameters) = network else {
1483            unreachable!("only Testnet parameter construction calls this method")
1484        };
1485        if parameters.nsm_reissuance_height.is_some() {
1486            return Ok(());
1487        }
1488        let height = nsm_reissuance_crossing_height(network)
1489            .map_err(|_| ParametersBuilderError::InvalidSubsidySchedule)?;
1490        let Network::Testnet(parameters) = network else {
1491            unreachable!("calculating the height does not change the network variant")
1492        };
1493        Arc::get_mut(parameters)
1494            .expect("parameter construction has not shared its Arc")
1495            .calculated_reissuance_height = height;
1496        Ok(())
1497    }
1498
1499    /// Returns `DEPLOYMENT_BLOCK_HEIGHT` for this network: the height from which the
1500    /// halving-preserving issuance ZIP reissues the NSM value balance.
1501    ///
1502    /// Uses the explicit testing override when supplied, otherwise the calculated ZIP 237
1503    /// crossover. No NU7 activation or no crossing before the fourth halving returns `None`.
1504    pub fn nsm_reissuance_height(&self) -> Option<Height> {
1505        self.nsm_reissuance_height
1506            .or(self.calculated_reissuance_height)
1507    }
1508
1509    /// Returns the explicitly configured NSM reissuance height, excluding the calculated ZIP 237
1510    /// crossover.
1511    ///
1512    /// Configuration serialization uses this to preserve an omitted height on round trips.
1513    pub fn configured_nsm_reissuance_height(&self) -> Option<Height> {
1514        self.nsm_reissuance_height
1515    }
1516
1517    /// Returns the pre-Blossom halving interval for this network
1518    pub fn pre_blossom_halving_interval(&self) -> HeightDiff {
1519        self.pre_blossom_halving_interval
1520    }
1521
1522    /// Returns the post-Blossom halving interval for this network
1523    pub fn post_blossom_halving_interval(&self) -> HeightDiff {
1524        self.post_blossom_halving_interval
1525    }
1526
1527    /// Returns the expected total value of the sum of all NU6.1 one-time lockbox disbursement output values for this network.
1528    pub fn lockbox_disbursement_total_amount(&self) -> Amount<NonNegative> {
1529        self.lockbox_disbursements()
1530            .into_iter()
1531            .map(|(_addr, amount)| amount)
1532            .reduce(|a, b| (a + b).expect("sum of configured amounts should be valid"))
1533            .unwrap_or_default()
1534    }
1535
1536    /// Returns the expected NU6.1 lockbox disbursement outputs for this network.
1537    pub fn lockbox_disbursements(&self) -> Vec<(transparent::Address, Amount<NonNegative>)> {
1538        self.lockbox_disbursements
1539            .iter()
1540            .map(|(addr, amount)| {
1541                (
1542                    addr.parse().expect("hard-coded address must deserialize"),
1543                    *amount,
1544                )
1545            })
1546            .collect()
1547    }
1548
1549    /// Returns the checkpoints for this network.
1550    pub fn checkpoints(&self) -> Arc<CheckpointList> {
1551        self.checkpoints.clone()
1552    }
1553
1554    /// Returns the height at which the soft-fork to temporarily disable Orchard in
1555    /// transactions activates.
1556    pub fn temporary_orchard_disabling_soft_fork_height(&self) -> Option<Height> {
1557        self.temporary_orchard_disabling_soft_fork_height
1558    }
1559}
1560
1561impl Network {
1562    /// Returns the parameters of this network if it is a Testnet.
1563    pub fn parameters(&self) -> Option<Arc<Parameters>> {
1564        if let Self::Testnet(parameters) = self {
1565            Some(parameters.clone())
1566        } else {
1567            None
1568        }
1569    }
1570
1571    /// Returns true if proof-of-work validation should be disabled for this network
1572    pub fn disable_pow(&self) -> bool {
1573        if let Self::Testnet(params) = self {
1574            params.disable_pow()
1575        } else {
1576            false
1577        }
1578    }
1579
1580    /// Returns slow start interval for this network
1581    pub fn slow_start_interval(&self) -> Height {
1582        if let Self::Testnet(params) = self {
1583            params.slow_start_interval()
1584        } else {
1585            SLOW_START_INTERVAL
1586        }
1587    }
1588
1589    /// Returns slow start shift for this network
1590    pub fn slow_start_shift(&self) -> Height {
1591        if let Self::Testnet(params) = self {
1592            params.slow_start_shift()
1593        } else {
1594            SLOW_START_SHIFT
1595        }
1596    }
1597
1598    /// Returns post-Canopy funding streams for this network at the provided height
1599    pub fn funding_streams(&self, height: Height) -> Option<&FundingStreams> {
1600        self.all_funding_streams()
1601            .iter()
1602            .find(|&streams| streams.height_range().contains(&height))
1603    }
1604
1605    /// Returns post-Canopy funding streams for this network at the provided height
1606    pub fn all_funding_streams(&self) -> &Vec<FundingStreams> {
1607        if let Self::Testnet(params) = self {
1608            params.funding_streams()
1609        } else {
1610            &mainnet::FUNDING_STREAMS
1611        }
1612    }
1613
1614    /// Returns true if this network should allow transactions with transparent outputs
1615    /// that spend coinbase outputs.
1616    pub fn should_allow_unshielded_coinbase_spends(&self) -> bool {
1617        if let Self::Testnet(params) = self {
1618            params.should_allow_unshielded_coinbase_spends()
1619        } else {
1620            false
1621        }
1622    }
1623
1624    /// Returns the list of founders' reward addresses for this network.
1625    pub fn founder_address_list(&self) -> &[&str] {
1626        match self {
1627            Network::Mainnet => &mainnet::FOUNDER_ADDRESS_LIST,
1628            Network::Testnet(_) => &testnet::FOUNDER_ADDRESS_LIST,
1629        }
1630    }
1631}