1use 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
38pub const RESERVED_NETWORK_NAMES: [&str; 6] = [
40 "Mainnet",
41 "Testnet",
42 "Regtest",
43 "MainnetKind",
44 "TestnetKind",
45 "RegtestKind",
46];
47
48pub const MAX_NETWORK_NAME_LENGTH: usize = 30;
50
51pub const MAX_HRP_LENGTH: usize = 30;
53
54const REGTEST_GENESIS_HASH: &str =
56 "029f11d80ef9765602235e1bc9727e3eb6ba20839319f761fee920d63401e327";
57
58const TESTNET_GENESIS_HASH: &str =
60 "05a60a92d99d85997cce3b87616c089f6124d7342af37106edc76126334a2c38";
61
62const PRE_BLOSSOM_REGTEST_HALVING_INTERVAL: HeightDiff = 144;
65
66#[derive(Serialize, Deserialize, Clone, Debug)]
68#[serde(deny_unknown_fields)]
69pub struct ConfiguredFundingStreamRecipient {
70 pub receiver: FundingStreamReceiver,
72 pub numerator: u64,
74 pub addresses: Option<Vec<String>>,
76}
77
78impl ConfiguredFundingStreamRecipient {
79 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 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#[derive(Serialize, Deserialize, Clone, Debug)]
130#[serde(deny_unknown_fields)]
131pub struct ConfiguredLockboxDisbursement {
132 pub address: String,
134 pub amount: Amount<NonNegative>,
136}
137
138#[derive(Serialize, Deserialize, Clone, Default, Debug)]
140#[serde(deny_unknown_fields)]
141pub struct ConfiguredFundingStreams {
142 pub height_range: Option<std::ops::Range<Height>>,
144 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 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 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 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 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
312fn 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 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
336fn 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 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
374fn 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 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#[derive(Serialize, Deserialize, Default, Clone, Copy, Debug, PartialEq)]
413#[serde(rename_all = "PascalCase", deny_unknown_fields)]
414pub struct ConfiguredActivationHeights {
415 pub before_overwinter: Option<u32>,
417 pub overwinter: Option<u32>,
419 pub sapling: Option<u32>,
421 pub blossom: Option<u32>,
423 pub heartwood: Option<u32>,
425 pub canopy: Option<u32>,
427 #[serde(rename = "NU5")]
429 pub nu5: Option<u32>,
430 #[serde(rename = "NU6")]
432 pub nu6: Option<u32>,
433 #[serde(rename = "NU6.1")]
435 pub nu6_1: Option<u32>,
436 #[serde(rename = "NU6.2")]
438 pub nu6_2: Option<u32>,
439 #[serde(rename = "NU6.3")]
441 pub nu6_3: Option<u32>,
442 #[serde(rename = "NU7")]
444 pub nu7: Option<u32>,
445 #[serde(rename = "ZFuture")]
447 #[cfg(zcash_unstable = "zfuture")]
448 pub zfuture: Option<u32>,
449}
450
451impl ConfiguredActivationHeights {
452 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#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
500#[serde(untagged)]
501pub enum ConfiguredCheckpoints {
502 Default(bool),
504 Path(std::path::PathBuf),
506 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
528pub(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#[derive(Clone, Debug, Eq, PartialEq)]
544pub struct ParametersBuilder {
545 network_name: String,
547 network_magic: Magic,
549 genesis_hash: block::Hash,
551 activation_heights: BTreeMap<Height, NetworkUpgrade>,
553 slow_start_interval: Height,
555 funding_streams: Vec<FundingStreams>,
557 should_lock_funding_stream_address_period: bool,
560 target_difficulty_limit: ExpandedDifficulty,
562 disable_pow: bool,
564 should_allow_unshielded_coinbase_spends: bool,
567 initial_nsm_value_balance: Option<Amount<NonNegative>>,
569 nsm_reissuance_height: Option<Height>,
571 pre_blossom_halving_interval: HeightDiff,
573 post_blossom_halving_interval: HeightDiff,
575 lockbox_disbursements: Vec<(String, Amount<NonNegative>)>,
577 checkpoints: Arc<CheckpointList>,
579 temporary_orchard_disabling_soft_fork_height: Option<Height>,
581}
582
583impl Default for ParametersBuilder {
584 fn default() -> Self {
586 let mut builder = Self {
587 network_name: "UnknownTestnet".to_string(),
588 network_magic: magics::TESTNET,
589 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 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 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 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 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 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 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 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 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 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 pub fn clear_funding_streams(mut self) -> Self {
808 self.funding_streams = vec![];
809 self
810 }
811
812 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 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 pub fn with_disable_pow(mut self, disable_pow: bool) -> Self {
850 self.disable_pow = disable_pow;
851 self
852 }
853
854 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 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 pub fn with_nsm_reissuance_height(mut self, height: Height) -> Self {
883 self.nsm_reissuance_height = Some(height);
884 self
885 }
886
887 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 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 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 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 pub fn clear_checkpoints(self) -> Result<Self, ParametersBuilderError> {
980 self.with_checkpoints(ConfiguredCheckpoints::Default(false))
981 }
982
983 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 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 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 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 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 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 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 fn to_network_unchecked(&self) -> Network {
1109 Network::new_configured_testnet(self.clone().finish())
1110 }
1111
1112 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 check_funding_streams(&self.funding_streams)?;
1127 for fs in &self.funding_streams {
1128 check_funding_stream_address_period(fs, &network)?;
1129 }
1130
1131 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 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#[derive(Debug, Default, Clone)]
1192pub struct RegtestParameters {
1193 pub activation_heights: ConfiguredActivationHeights,
1195 pub funding_streams: Option<Vec<ConfiguredFundingStreams>>,
1197 pub lockbox_disbursements: Option<Vec<ConfiguredLockboxDisbursement>>,
1199 pub checkpoints: Option<ConfiguredCheckpoints>,
1201 pub extend_funding_stream_addresses_as_required: Option<bool>,
1203 pub should_allow_unshielded_coinbase_spends: Option<bool>,
1206 pub initial_nsm_value_balance: Option<Amount<NonNegative>>,
1208 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#[derive(Clone, Debug, Eq, PartialEq)]
1224pub struct Parameters {
1225 network_name: String,
1227 network_magic: Magic,
1229 genesis_hash: block::Hash,
1231 activation_heights: BTreeMap<Height, NetworkUpgrade>,
1233 slow_start_interval: Height,
1235 slow_start_shift: Height,
1237 funding_streams: Vec<FundingStreams>,
1239 target_difficulty_limit: ExpandedDifficulty,
1241 disable_pow: bool,
1243 should_allow_unshielded_coinbase_spends: bool,
1246 initial_nsm_value_balance: Option<Amount<NonNegative>>,
1248 nsm_reissuance_height: Option<Height>,
1250 calculated_reissuance_height: Option<Height>,
1252 pre_blossom_halving_interval: HeightDiff,
1254 post_blossom_halving_interval: HeightDiff,
1256 lockbox_disbursements: Vec<(String, Amount<NonNegative>)>,
1258 checkpoints: Arc<CheckpointList>,
1260 temporary_orchard_disabling_soft_fork_height: Option<Height>,
1262}
1263
1264static 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 fn default() -> Self {
1277 DEFAULT_TESTNET_PARAMETERS.clone()
1278 }
1279}
1280
1281impl Parameters {
1282 pub fn build() -> ParametersBuilder {
1284 ParametersBuilder::default()
1285 }
1286
1287 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 .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 .disable_temporary_orchard_disabling_soft_fork()
1316 .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(¶meters.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 pub fn is_default_testnet(&self) -> bool {
1348 self == &*DEFAULT_TESTNET_PARAMETERS
1349 }
1350
1351 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 network_magic: _,
1361 genesis_hash,
1362 activation_heights: _,
1364 slow_start_interval,
1365 slow_start_shift,
1366 funding_streams: _,
1367 target_difficulty_limit,
1368 disable_pow,
1369 should_allow_unshielded_coinbase_spends: _,
1371 initial_nsm_value_balance: _,
1373 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 pub fn network_name(&self) -> &str {
1395 &self.network_name
1396 }
1397
1398 pub fn network_magic(&self) -> Magic {
1400 self.network_magic
1401 }
1402
1403 pub fn genesis_hash(&self) -> block::Hash {
1405 self.genesis_hash
1406 }
1407
1408 pub fn activation_heights(&self) -> &BTreeMap<Height, NetworkUpgrade> {
1410 &self.activation_heights
1411 }
1412
1413 pub fn slow_start_interval(&self) -> Height {
1415 self.slow_start_interval
1416 }
1417
1418 pub fn slow_start_shift(&self) -> Height {
1420 self.slow_start_shift
1421 }
1422
1423 pub fn funding_streams(&self) -> &Vec<FundingStreams> {
1425 &self.funding_streams
1426 }
1427
1428 pub fn target_difficulty_limit(&self) -> ExpandedDifficulty {
1430 self.target_difficulty_limit
1431 }
1432
1433 pub fn disable_pow(&self) -> bool {
1435 self.disable_pow
1436 }
1437
1438 pub fn should_allow_unshielded_coinbase_spends(&self) -> bool {
1441 self.should_allow_unshielded_coinbase_spends
1442 }
1443
1444 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 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 pub fn nsm_reissuance_height(&self) -> Option<Height> {
1505 self.nsm_reissuance_height
1506 .or(self.calculated_reissuance_height)
1507 }
1508
1509 pub fn configured_nsm_reissuance_height(&self) -> Option<Height> {
1514 self.nsm_reissuance_height
1515 }
1516
1517 pub fn pre_blossom_halving_interval(&self) -> HeightDiff {
1519 self.pre_blossom_halving_interval
1520 }
1521
1522 pub fn post_blossom_halving_interval(&self) -> HeightDiff {
1524 self.post_blossom_halving_interval
1525 }
1526
1527 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 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 pub fn checkpoints(&self) -> Arc<CheckpointList> {
1551 self.checkpoints.clone()
1552 }
1553
1554 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 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 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 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 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 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 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 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 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}