Skip to main content

zebra_chain/parameters/network/
subsidy.rs

1//! Calculations for Block Subsidy and Funding Streams
2//!
3//! This module contains the consensus parameters which are required for
4//! verification.
5//!
6//! Some consensus parameters change based on network upgrades. Each network
7//! upgrade happens at a particular block height. Some parameters have a value
8//! (or function) before the upgrade height, at the upgrade height, and after
9//! the upgrade height. (For example, the value of the reserved field in the
10//! block header during the Heartwood upgrade.)
11//!
12//! Typically, consensus parameters are accessed via a function that takes a
13//! `Network` and `block::Height`.
14
15pub(crate) mod constants;
16
17mod check;
18#[cfg(test)]
19mod tests;
20
21use std::{collections::HashMap, sync::LazyLock};
22
23use crate::{
24    amount::{self, Amount, NegativeAllowed, NonNegative, MAX_MONEY},
25    block::{Height, HeightDiff},
26    parameters::{Network, NetworkUpgrade},
27    transparent,
28    value_balance::ValueBalance,
29};
30
31pub use check::{miner_fees_are_valid, subsidy_is_valid, CoinbaseTransactionError};
32
33use constants::{
34    BLOSSOM_POW_TARGET_SPACING_RATIO, FUNDING_STREAM_RECEIVER_DENOMINATOR,
35    FUNDING_STREAM_SPECIFICATION, LOCKBOX_SPECIFICATION, MAX_BLOCK_SUBSIDY,
36    NU7_POW_TARGET_SPACING_RATIO, POST_BLOSSOM_HALVING_INTERVAL, POST_NU7_HALVING_INTERVAL,
37    PRE_BLOSSOM_HALVING_INTERVAL,
38};
39
40/// The funding stream receiver categories.
41#[derive(Serialize, Deserialize, Clone, Copy, Debug, Eq, Hash, PartialEq)]
42pub enum FundingStreamReceiver {
43    /// The Electric Coin Company (Bootstrap Foundation) funding stream.
44    #[serde(rename = "ECC")]
45    Ecc,
46
47    /// The Zcash Foundation funding stream.
48    ZcashFoundation,
49
50    /// The Major Grants (Zcash Community Grants) funding stream.
51    MajorGrants,
52
53    /// The deferred pool contribution, see [ZIP-1015](https://zips.z.cash/zip-1015) for more details.
54    Deferred,
55}
56
57impl FundingStreamReceiver {
58    /// Returns a human-readable name and a specification URL for the receiver, as described in
59    /// [ZIP-1014] and [`zcashd`] before NU6. After NU6, the specification is in the [ZIP-1015].
60    ///
61    /// [ZIP-1014]: https://zips.z.cash/zip-1014#abstract
62    /// [`zcashd`]: https://github.com/zcash/zcash/blob/3f09cfa00a3c90336580a127e0096d99e25a38d6/src/consensus/funding.cpp#L13-L32
63    /// [ZIP-1015]: https://zips.z.cash/zip-1015
64    pub fn info(&self, is_post_nu6: bool) -> (&'static str, &'static str) {
65        if is_post_nu6 {
66            (
67                match self {
68                    FundingStreamReceiver::Ecc => "Electric Coin Company",
69                    FundingStreamReceiver::ZcashFoundation => "Zcash Foundation",
70                    FundingStreamReceiver::MajorGrants => "Zcash Community Grants NU6",
71                    FundingStreamReceiver::Deferred => "Lockbox NU6",
72                },
73                LOCKBOX_SPECIFICATION,
74            )
75        } else {
76            (
77                match self {
78                    FundingStreamReceiver::Ecc => "Electric Coin Company",
79                    FundingStreamReceiver::ZcashFoundation => "Zcash Foundation",
80                    FundingStreamReceiver::MajorGrants => "Major Grants",
81                    FundingStreamReceiver::Deferred => "Lockbox NU6",
82                },
83                FUNDING_STREAM_SPECIFICATION,
84            )
85        }
86    }
87
88    /// Returns true if this [`FundingStreamReceiver`] is [`FundingStreamReceiver::Deferred`].
89    pub fn is_deferred(&self) -> bool {
90        matches!(self, Self::Deferred)
91    }
92}
93
94/// Funding stream recipients and height ranges.
95#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
96pub struct FundingStreams {
97    /// Start and end Heights for funding streams
98    /// as described in [protocol specification §7.10.1][7.10.1].
99    ///
100    /// [7.10.1]: https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams
101    height_range: std::ops::Range<Height>,
102    /// Funding stream recipients by [`FundingStreamReceiver`].
103    recipients: HashMap<FundingStreamReceiver, FundingStreamRecipient>,
104}
105
106impl FundingStreams {
107    /// Creates a new [`FundingStreams`].
108    pub fn new(
109        height_range: std::ops::Range<Height>,
110        recipients: HashMap<FundingStreamReceiver, FundingStreamRecipient>,
111    ) -> Self {
112        Self {
113            height_range,
114            recipients,
115        }
116    }
117
118    /// Creates a new empty [`FundingStreams`] representing no funding streams.
119    pub fn empty() -> Self {
120        Self::new(Height::MAX..Height::MAX, HashMap::new())
121    }
122
123    /// Returns height range where these [`FundingStreams`] should apply.
124    pub fn height_range(&self) -> &std::ops::Range<Height> {
125        &self.height_range
126    }
127
128    /// Updates the exclusive end height of a canonical funding stream.
129    pub(super) fn set_end_height(&mut self, end: Height) {
130        self.height_range.end = end;
131    }
132
133    /// Returns recipients of these [`FundingStreams`].
134    pub fn recipients(&self) -> &HashMap<FundingStreamReceiver, FundingStreamRecipient> {
135        &self.recipients
136    }
137
138    /// Returns a recipient with the provided receiver.
139    pub fn recipient(&self, receiver: FundingStreamReceiver) -> Option<&FundingStreamRecipient> {
140        self.recipients.get(&receiver)
141    }
142
143    /// Accepts a target number of addresses that all recipients of this funding stream
144    /// except the [`FundingStreamReceiver::Deferred`] receiver should have.
145    ///
146    /// Extends the addresses for all funding stream recipients by repeating their
147    /// existing addresses until reaching the provided target number of addresses.
148    pub fn extend_recipient_addresses(&mut self, target_len: usize) {
149        for (receiver, recipient) in &mut self.recipients {
150            if receiver.is_deferred() {
151                continue;
152            }
153
154            recipient.extend_addresses(target_len);
155        }
156    }
157}
158
159/// A funding stream recipient as specified in [protocol specification §7.10.1][7.10.1]
160///
161/// [7.10.1]: https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams
162#[derive(Deserialize, Clone, Debug, Eq, PartialEq)]
163pub struct FundingStreamRecipient {
164    /// The numerator for each funding stream receiver category
165    /// as described in [protocol specification §7.10.1][7.10.1].
166    ///
167    /// [7.10.1]: https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams
168    numerator: u64,
169    /// Addresses for the funding stream recipient
170    addresses: Vec<transparent::Address>,
171}
172
173impl FundingStreamRecipient {
174    /// Creates a new [`FundingStreamRecipient`].
175    pub fn new<I, T>(numerator: u64, addresses: I) -> Self
176    where
177        T: ToString,
178        I: IntoIterator<Item = T>,
179    {
180        Self {
181            numerator,
182            addresses: addresses
183                .into_iter()
184                .map(|addr| {
185                    let addr = addr.to_string();
186                    addr.parse()
187                        .expect("funding stream address must deserialize")
188                })
189                .collect(),
190        }
191    }
192
193    /// Returns the numerator for this funding stream.
194    pub fn numerator(&self) -> u64 {
195        self.numerator
196    }
197
198    /// Returns the receiver of this funding stream.
199    pub fn addresses(&self) -> &[transparent::Address] {
200        &self.addresses
201    }
202
203    /// Accepts a target number of addresses that this recipient should have.
204    ///
205    /// Extends the addresses for this funding stream recipient by repeating
206    /// existing addresses until reaching the provided target number of addresses.
207    ///
208    /// # Panics
209    ///
210    /// If a nonzero target requires extending an empty address list.
211    pub fn extend_addresses(&mut self, target_len: usize) {
212        assert!(
213            target_len == 0 || !self.addresses.is_empty(),
214            "cannot extend addresses for empty recipient"
215        );
216
217        self.addresses = self
218            .addresses
219            .iter()
220            .cycle()
221            .take(target_len)
222            .cloned()
223            .collect();
224    }
225}
226
227/// Functionality specific to block subsidy-related consensus rules
228pub trait ParameterSubsidy {
229    /// Returns the minimum height after the first halving
230    /// as described in [protocol specification §7.10][7.10]
231    ///
232    /// [7.10]: <https://zips.z.cash/protocol/protocol.pdf#fundingstreams>
233    fn height_for_first_halving(&self) -> Height;
234
235    /// Returns the halving interval after Blossom
236    fn post_blossom_halving_interval(&self) -> HeightDiff;
237
238    /// Returns the halving interval before Blossom
239    fn pre_blossom_halving_interval(&self) -> HeightDiff;
240
241    /// Returns the halving interval after NU7.
242    ///
243    /// `PostNU7HalvingInterval` in [ZIP 218].
244    ///
245    /// [ZIP 218]: https://zips.z.cash/zip-0218
246    fn post_nu7_halving_interval(&self) -> HeightDiff;
247
248    /// Returns the NU7 activation height, if it is configured.
249    fn nu7_activation_height(&self) -> Option<Height>;
250
251    /// Returns the address change interval for funding streams
252    /// as described in [protocol specification §7.10][7.10].
253    ///
254    /// > FSRecipientChangeInterval := PostBlossomHalvingInterval / 48
255    ///
256    /// [7.10]: https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams
257    fn funding_stream_address_change_interval(&self) -> HeightDiff;
258}
259
260/// Network methods related to Block Subsidy and Funding Streams
261impl ParameterSubsidy for Network {
262    fn height_for_first_halving(&self) -> Height {
263        // Derived rather than hard-coded, so that ZIP 218's stretched halving schedule applies
264        // here too and this can not disagree with `halving()`.
265        //
266        // <https://zips.z.cash/protocol/protocol.pdf#zip214fundingstreams>
267        height_for_halving(1, self).expect("the first halving height is representable")
268    }
269
270    fn post_blossom_halving_interval(&self) -> HeightDiff {
271        match self {
272            Network::Mainnet => POST_BLOSSOM_HALVING_INTERVAL,
273            Network::Testnet(params) => params.post_blossom_halving_interval(),
274        }
275    }
276
277    fn pre_blossom_halving_interval(&self) -> HeightDiff {
278        match self {
279            Network::Mainnet => PRE_BLOSSOM_HALVING_INTERVAL,
280            Network::Testnet(params) => params.pre_blossom_halving_interval(),
281        }
282    }
283
284    fn post_nu7_halving_interval(&self) -> HeightDiff {
285        match self {
286            Network::Mainnet => POST_NU7_HALVING_INTERVAL,
287            Network::Testnet(params) => {
288                params.post_blossom_halving_interval()
289                    * HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO)
290            }
291        }
292    }
293
294    fn nu7_activation_height(&self) -> Option<Height> {
295        NetworkUpgrade::Nu7.activation_height(self)
296    }
297
298    fn funding_stream_address_change_interval(&self) -> HeightDiff {
299        self.post_blossom_halving_interval() / 48
300    }
301}
302
303/// Returns the address change period
304/// as described in [protocol specification §7.10][7.10]
305///
306/// The result is signed, and callers only ever use the *difference* between two periods. It can
307/// be negative below the first funding stream: on a configured Testnet whose upgrades are packed
308/// into a few hundred blocks, ZIP 218 pushes the first halving above every height the network
309/// reaches once NU7 activates before it. Clamping a negative period to zero would silently
310/// collapse those differences, so the sign is preserved here and the conversion is left to the
311/// callers, which know the range they are counting over.
312///
313/// [7.10]: https://zips.z.cash/protocol/protocol.pdf#fundingstreams
314pub fn funding_stream_address_period<N: ParameterSubsidy>(
315    height: Height,
316    network: &N,
317) -> HeightDiff {
318    if let Some(nu7) = network.nu7_activation_height().filter(|&nu7| height >= nu7) {
319        return nu7_funding_stream_address_period(height, nu7, network);
320    }
321
322    let height_after_first_halving = height - network.height_for_first_halving();
323
324    (height_after_first_halving + network.post_blossom_halving_interval())
325        .div_euclid(network.funding_stream_address_change_interval())
326}
327
328/// Returns the funding address period from NU7 onward, as redefined by [ZIP 207].
329///
330/// Pre-NU7 progress is scaled into post-NU7 blocks, preserving the partial period at activation.
331/// Signed Euclidean division preserves floor rounding for accelerated custom schedules.
332///
333/// [ZIP 207]: https://zips.z.cash/zip-0207
334fn nu7_funding_stream_address_period<N: ParameterSubsidy>(
335    height: Height,
336    nu7: Height,
337    network: &N,
338) -> HeightDiff {
339    let ratio = HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO);
340    let pre_nu7_blocks =
341        nu7 - network.height_for_first_halving() + network.post_blossom_halving_interval();
342    let post_nu7_blocks = height - nu7;
343
344    (ratio * pre_nu7_blocks + post_nu7_blocks)
345        .div_euclid(ratio * network.funding_stream_address_change_interval())
346}
347
348/// Extends a canonical revision-2 funding stream to the ZIP 218 third halving.
349/// A stream that expired before NU7 is not reactivated (ZIP 214 revision 3).
350pub(super) fn nu7_funding_stream_end_height(original_end: Height, nu7: Option<Height>) -> Height {
351    match nu7.filter(|&activation| activation < original_end) {
352        Some(activation) => (activation
353            + (original_end - activation) * HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO))
354        .expect("canonical funding stream end heights scaled by three fit in Height"),
355        None => original_end,
356    }
357}
358/// Returns the position in the address slice for each funding stream
359/// as described in [protocol specification §7.10][7.10]
360///
361/// [7.10]: https://zips.z.cash/protocol/protocol.pdf#fundingstreams
362fn funding_stream_address_index(
363    height: Height,
364    network: &Network,
365    receiver: FundingStreamReceiver,
366) -> Option<usize> {
367    if receiver == FundingStreamReceiver::Deferred {
368        return None;
369    }
370
371    let funding_streams = network.funding_streams(height)?;
372    let num_addresses = funding_streams.recipient(receiver)?.addresses().len();
373
374    // The two periods are only meaningful relative to each other, so the subtraction is done in
375    // signed arithmetic: see `funding_stream_address_period()`.
376    let index = usize::try_from(
377        1 + funding_stream_address_period(height, network)
378            - funding_stream_address_period(funding_streams.height_range().start, network),
379    )
380    .ok()?;
381
382    assert!(index > 0 && index <= num_addresses);
383    // spec formula will output an index starting at 1 but
384    // Zebra indices for addresses start at zero, return converted.
385    Some(index - 1)
386}
387
388/// Return the address corresponding to given height, network and funding stream receiver.
389///
390/// This function only returns transparent addresses, because the current Zcash funding streams
391/// only use transparent addresses,
392pub fn funding_stream_address(
393    height: Height,
394    network: &Network,
395    receiver: FundingStreamReceiver,
396) -> Option<&transparent::Address> {
397    let index = funding_stream_address_index(height, network, receiver)?;
398    let funding_streams = network.funding_streams(height)?;
399    funding_streams.recipient(receiver)?.addresses().get(index)
400}
401
402/// The first block height of the halving at the provided halving index for a network.
403///
404/// See `Halving(height)`, as described in [protocol specification §7.8][7.8]
405///
406/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
407pub fn height_for_halving(halving: u32, network: &Network) -> Option<Height> {
408    if halving == 0 {
409        return Some(Height(0));
410    }
411
412    let slow_start_shift = i64::from(network.slow_start_shift().0);
413    let blossom_height = i64::from(NetworkUpgrade::Blossom.activation_height(network)?.0);
414    let pre_blossom_halving_interval = network.pre_blossom_halving_interval();
415    let halving_index = i64::from(halving);
416
417    let unscaled_height = halving_index
418        .checked_mul(pre_blossom_halving_interval)?
419        .checked_add(slow_start_shift)?;
420
421    let height = if unscaled_height > blossom_height {
422        (unscaled_height - blossom_height)
423            .checked_mul(i64::from(BLOSSOM_POW_TARGET_SPACING_RATIO))?
424            .checked_add(blossom_height)?
425    } else {
426        unscaled_height
427    };
428
429    // ZIP 218: once NU7 is active, the blocks after its activation height are three times as
430    // frequent, so the remaining blocks of this halving are stretched by the same ratio.
431    let height = match NetworkUpgrade::Nu7.activation_height(network) {
432        Some(nu7_height) if height > i64::from(nu7_height.0) => {
433            let nu7_height = i64::from(nu7_height.0);
434
435            (height - nu7_height)
436                .checked_mul(i64::from(NU7_POW_TARGET_SPACING_RATIO))?
437                .checked_add(nu7_height)?
438        }
439        _ => height,
440    };
441
442    let height = u32::try_from(height).ok()?;
443    height.try_into().ok()
444}
445
446/// Returns the `fs.Value(height)` for each stream receiver
447/// as described in [protocol specification §7.8][7.8]
448///
449/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
450pub fn funding_stream_values(
451    height: Height,
452    network: &Network,
453    expected_block_subsidy: Amount<NonNegative>,
454) -> Result<HashMap<FundingStreamReceiver, Amount<NonNegative>>, amount::Error> {
455    let mut results = HashMap::new();
456
457    if expected_block_subsidy.is_zero() {
458        return Ok(results);
459    }
460
461    if NetworkUpgrade::current(network, height) >= NetworkUpgrade::Canopy {
462        let funding_streams = network.funding_streams(height);
463        if let Some(funding_streams) = funding_streams {
464            for (&receiver, recipient) in funding_streams.recipients() {
465                // - Spec equation: `fs.value = floor(block_subsidy(height)*(fs.numerator/fs.denominator))`:
466                //   https://zips.z.cash/protocol/protocol.pdf#subsidies
467                // - In Rust, "integer division rounds towards zero":
468                //   https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#arithmetic-and-logical-binary-operators
469                //   This is the same as `floor()`, because these numbers are all positive.
470                let amount_value = ((expected_block_subsidy * recipient.numerator())?
471                    / FUNDING_STREAM_RECEIVER_DENOMINATOR)?;
472
473                results.insert(receiver, amount_value);
474            }
475        }
476    }
477
478    Ok(results)
479}
480
481/// Block subsidy errors.
482#[derive(thiserror::Error, Clone, Debug, PartialEq, Eq)]
483#[allow(missing_docs)]
484pub enum SubsidyError {
485    #[error("no coinbase transaction in block")]
486    NoCoinbase,
487
488    #[error("funding stream expected output not found")]
489    FundingStreamNotFound,
490
491    #[error("founders reward output not found")]
492    FoundersRewardNotFound,
493
494    #[error("one-time lockbox disbursement output not found")]
495    OneTimeLockboxDisbursementNotFound,
496
497    #[error("miner fees are invalid")]
498    InvalidMinerFees,
499
500    #[error("addition of amounts overflowed")]
501    Overflow,
502
503    #[error("subtraction of amounts underflowed")]
504    Underflow,
505
506    #[error("unsupported height")]
507    UnsupportedHeight,
508
509    #[error("{0}")]
510    Other(String),
511
512    #[error("invalid amount")]
513    InvalidAmount(#[from] amount::Error),
514
515    #[error(
516        "the block subsidy at height {0:?} depends on the chain value pools after its parent block"
517    )]
518    ParentChainValuePoolsRequired(Height),
519}
520
521/// `INITIAL_NSM_VALUE_BALANCE` on Mainnet: the block subsidy and fees left unclaimed by coinbase
522/// transactions before NU6, which seeds the NSM value balance at NU7 activation under the
523/// [halving-preserving issuance ZIP][zip].
524///
525/// Since [ZIP 236] made claiming the full coinbase value a consensus rule, this is the fixed amount
526/// `sum(ScheduledBlockSubsidy(0..=H)) - IssuedSupply(H)` for any `H` from the last pre-NU6 height
527/// (2,726,399) up to NU7 activation.
528///
529/// Measured from the historical chain value pools at height 2,726,399.
530///
531/// [zip]: https://zips.z.cash/zip-0237
532/// [ZIP 236]: https://zips.z.cash/zip-0236
533pub const MAINNET_INITIAL_NSM_VALUE_BALANCE: u64 = 36_858_445_520;
534
535/// The unclaimed pre-NU6 subsidy and fees on public Testnet, measured at height 2,975,999.
536pub const TESTNET_INITIAL_NSM_VALUE_BALANCE: u64 = 55_768_414_957;
537
538impl Network {
539    /// `INITIAL_NSM_VALUE_BALANCE`: the NSM value balance seeded at NU7 activation under the
540    /// [halving-preserving issuance ZIP][zip].
541    ///
542    /// Mainnet and public Testnet use their measured pre-NU6 shortfalls. Configured Testnets
543    /// and Regtest can set their own value, and default to zero.
544    ///
545    /// [zip]: https://zips.z.cash/zip-0237
546    pub fn initial_nsm_value_balance(&self) -> Amount<NonNegative> {
547        match self {
548            Network::Mainnet => Amount::try_from(MAINNET_INITIAL_NSM_VALUE_BALANCE)
549                .expect("hard-coded initial NSM value balance should be valid"),
550            Network::Testnet(params) => params.initial_nsm_value_balance(),
551        }
552    }
553
554    /// The ZIP 237 reissuance height calculated from the scheduled-issuance crossover.
555    ///
556    /// Configured networks may explicitly override it for accelerated testing. An unscheduled
557    /// NU7, or a custom schedule with no crossing before the fourth halving, returns `None`.
558    pub fn nsm_reissuance_height(&self) -> Option<Height> {
559        match self {
560            Network::Mainnet => {
561                static HEIGHT: LazyLock<Option<Height>> = LazyLock::new(|| {
562                    nsm_reissuance_crossing_height(&Network::Mainnet)
563                        .expect("the hard-coded Mainnet subsidy schedule is valid")
564                });
565                *HEIGHT
566            }
567            Network::Testnet(params) => params.nsm_reissuance_height(),
568        }
569    }
570}
571
572/// Finds ZIP 237's first strict reference-subsidy crossing after the third halving.
573///
574/// This depends only on the issuance schedule, never the actual reserve or transaction fees.
575/// Within this halving era the reference reserve decreases and the scheduled subsidy is
576/// constant (or increases during a custom slow start), so the predicate is monotonic.
577pub(super) fn nsm_reissuance_crossing_height(
578    network: &Network,
579) -> Result<Option<Height>, SubsidyError> {
580    let Some(activation) = NetworkUpgrade::Nu7.activation_height(network) else {
581        return Ok(None);
582    };
583    let Some(third_halving) = height_for_halving(3, network) else {
584        return Ok(None);
585    };
586    let mut low = activation.0.max(third_halving.0 + 1);
587    let mut high =
588        height_for_halving(4, network).map_or(Height::MAX.0, |height| height.0.saturating_sub(1));
589    if low > high {
590        return Ok(None);
591    }
592    let crossed = |height| -> Result<bool, SubsidyError> {
593        let issued = cumulative_scheduled_issuance_zatoshis(Height(height - 1), network)?;
594        let reserve = u64::try_from(MAX_MONEY)
595            .expect("MAX_MONEY is positive")
596            .saturating_sub(issued);
597        let reference =
598            (u128::from(reserve) * 1_375).div_ceil(u128::from(BLOCK_SUBSIDY_FRACTION_DENOMINATOR));
599        Ok(reference < u128::from(u64::from(scheduled_block_subsidy(Height(height), network)?)))
600    };
601    if !crossed(high)? {
602        return Ok(None);
603    }
604    while low < high {
605        let middle = low + (high - low) / 2;
606        if crossed(middle)? {
607            high = middle;
608        } else {
609            low = middle + 1;
610        }
611    }
612    Ok(Some(Height(low)))
613}
614
615/// The divisor used for halvings.
616///
617/// `1 << Halving(height)`, as described in [protocol specification §7.8][7.8]
618///
619/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
620///
621/// Returns `None` if the divisor would overflow a `u64`.
622pub fn halving_divisor(height: Height, network: &Network) -> Option<u64> {
623    // Some far-future shifts can be more than 63 bits
624    1u64.checked_shl(halving(height, network))
625}
626
627/// The halving index for a block height and network.
628///
629/// `Halving(height)`, as described in [protocol specification §7.8][7.8]
630///
631/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
632pub fn halving(height: Height, network: &Network) -> u32 {
633    let slow_start_shift = network.slow_start_shift();
634    let blossom_height = NetworkUpgrade::Blossom
635        .activation_height(network)
636        .expect("blossom activation height should be available");
637
638    // `NetworkUpgrade::activation_height()` falls back to the next upgrade's height, so this is
639    // `None` exactly when no upgrade from NU7 onward is scheduled on `network`.
640    let nu7_height = NetworkUpgrade::Nu7.activation_height(network);
641
642    let halving_index = if height < slow_start_shift {
643        0
644    } else if height < blossom_height {
645        let pre_blossom_height = height - slow_start_shift;
646        pre_blossom_height / network.pre_blossom_halving_interval()
647    } else if nu7_height.is_none_or(|nu7_height| height < nu7_height) {
648        let pre_blossom_height = blossom_height - slow_start_shift;
649        let scaled_pre_blossom_height =
650            pre_blossom_height * HeightDiff::from(BLOSSOM_POW_TARGET_SPACING_RATIO);
651
652        let post_blossom_height = height - blossom_height;
653
654        (scaled_pre_blossom_height + post_blossom_height) / network.post_blossom_halving_interval()
655    } else {
656        // ZIP 218 adds a third era to `Halving()`. Each era is scaled into post-NU7 blocks: a
657        // pre-Blossom block is worth `BlossomPoWTargetSpacingRatio * NU7PoWTargetSpacingRatio`
658        // of them, and a post-Blossom pre-NU7 block is worth `NU7PoWTargetSpacingRatio`.
659        let nu7_height = nu7_height.expect("checked by the branch condition above");
660
661        let scaled_pre_blossom_height = (blossom_height - slow_start_shift)
662            * HeightDiff::from(BLOSSOM_POW_TARGET_SPACING_RATIO)
663            * HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO);
664
665        let scaled_post_blossom_height =
666            (nu7_height - blossom_height) * HeightDiff::from(NU7_POW_TARGET_SPACING_RATIO);
667
668        let post_nu7_height = height - nu7_height;
669
670        (scaled_pre_blossom_height + scaled_post_blossom_height + post_nu7_height)
671            / network.post_nu7_halving_interval()
672    };
673
674    halving_index
675        .try_into()
676        .expect("already checked for negatives")
677}
678
679/// `10^10 * ln 2`, rounded so that Mainnet's `PostBlossomHalvingInterval` of 1,680,000 blocks
680/// gives a `BLOCK_SUBSIDY_FRACTION` numerator of exactly 4126.
681///
682/// The [halving-preserving issuance ZIP][zip] states `BLOCK_SUBSIDY_FRACTION` as a function of the
683/// halving schedule, so that the NSM value balance's half-life is one halving period whatever the
684/// target spacing is. With ZIP 218's `PostNU7HalvingInterval` of 5,040,000 blocks the numerator is
685/// 1375, with no separate constant.
686///
687/// [zip]: https://zips.z.cash/zip-0237
688pub const LN2_SCALED: u64 = 6_931_680_000;
689
690/// The denominator of `BLOCK_SUBSIDY_FRACTION` in the [halving-preserving issuance ZIP][zip].
691///
692/// [zip]: https://zips.z.cash/zip-0237
693pub const BLOCK_SUBSIDY_FRACTION_DENOMINATOR: u64 = 10_000_000_000;
694
695/// `HalvingInterval(height)`: the number of blocks in the halving period containing `height`.
696///
697/// The [halving-preserving issuance ZIP][zip] defines this as `PostNU7HalvingInterval` where
698/// ZIP 218's 25-second blocks are active, and `PostBlossomHalvingInterval` otherwise.
699///
700/// [zip]: https://zips.z.cash/zip-0237
701pub fn halving_interval(height: Height, network: &Network) -> HeightDiff {
702    if NetworkUpgrade::current(network, height) >= NetworkUpgrade::Nu7 {
703        network.post_nu7_halving_interval()
704    } else {
705        network.post_blossom_halving_interval()
706    }
707}
708
709/// The numerator of `BLOCK_SUBSIDY_FRACTION(height)` on `network`:
710/// `LN2_SCALED / HalvingInterval(height)`.
711///
712/// Over one halving period this reissues about half the NSM value balance, because
713/// `(1 - ln 2 / n)^n` approaches `1/2` for large `n`.
714///
715/// The result is non-zero for any halving interval up to `Height::MAX`.
716pub fn block_subsidy_fraction_numerator(height: Height, network: &Network) -> u64 {
717    let halving_interval =
718        u64::try_from(halving_interval(height, network)).expect("halving intervals are positive");
719
720    LN2_SCALED / halving_interval
721}
722
723/// `NSMFeeContribution(height)`: the transaction fees the block at `height` removes from
724/// circulation, `floor(block_miner_fees * 6 / 10)` from NU7 activation, and zero before it. This
725/// is the fraction from [ZIP 235], applied the way the [NU7 deployment ZIP][nu7] specifies.
726///
727/// The fraction applies to the total fees in the block, so rounding favors the miner. The
728/// coinbase transaction can only claim the remaining fees, and the contribution needs no
729/// transaction field.
730///
731/// [ZIP 235]: https://zips.z.cash/zip-0235
732/// [nu7]: https://github.com/zcash/zips/pull/1363
733pub fn nsm_fee_contribution(
734    height: Height,
735    network: &Network,
736    block_miner_fees: Amount<NonNegative>,
737) -> Amount<NonNegative> {
738    if !nsm_value_balance_is_tracked(height, network) {
739        return Amount::zero();
740    }
741
742    let fees = u64::from(block_miner_fees);
743
744    // Splitting at the divisor keeps the exact floor without overflowing `fees * 6`.
745    (fees / 10 * 6 + fees % 10 * 6 / 10)
746        .try_into()
747        .expect("the contribution is at most the fees, which are a valid amount")
748}
749
750/// Returns `true` if the NSM value balance is tracked at `height`: from NU7 activation, per the
751/// [halving-preserving issuance ZIP][zip].
752///
753/// [zip]: https://zips.z.cash/zip-0237
754pub fn nsm_value_balance_is_tracked(height: Height, network: &Network) -> bool {
755    NetworkUpgrade::Nu7
756        .activation_height(network)
757        .is_some_and(|activation_height| height >= activation_height)
758}
759
760/// Returns `true` if the [halving-preserving issuance ZIP][zip] reissues the NSM value balance at
761/// `height`: from `DEPLOYMENT_BLOCK_HEIGHT`, which is at or after NU7 activation.
762///
763/// [zip]: https://zips.z.cash/zip-0237
764pub fn nsm_reissuance_is_active(height: Height, network: &Network) -> bool {
765    network
766        .nsm_reissuance_height()
767        .is_some_and(|deployment_height| height >= deployment_height)
768}
769
770/// The value the block at `height` seeds into the NSM value balance: `INITIAL_NSM_VALUE_BALANCE`
771/// at the NU7 activation block, and zero otherwise.
772fn nsm_seed(height: Height, network: &Network) -> Amount<NonNegative> {
773    if Some(height) == NetworkUpgrade::Nu7.activation_height(network) {
774        network.initial_nsm_value_balance()
775    } else {
776        Amount::zero()
777    }
778}
779
780/// `NSMValueBalance(height - 1)`: the Network Sustainability Mechanism value balance the block at
781/// `height` reissues from, where `parent_nsm_value_balance` is the balance after its parent block.
782///
783/// The [halving-preserving issuance ZIP][zip] defines
784/// `NSMValueBalance(NU7ActivationHeight - 1)` as `INITIAL_NSM_VALUE_BALANCE`, the subsidy and fees
785/// left unclaimed before NU6, so the NU7 activation block reissues from that seed.
786///
787/// [zip]: https://zips.z.cash/zip-0237
788pub fn nsm_value_balance_before(
789    height: Height,
790    network: &Network,
791    parent_nsm_value_balance: Amount<NonNegative>,
792) -> Amount<NonNegative> {
793    (parent_nsm_value_balance + nsm_seed(height, network))
794        .expect("the balance is zero before NU7 activation, and the seed is zero after it")
795}
796
797/// The change the block at `height` makes to the Network Sustainability Mechanism value balance,
798/// where `parent_chain_value_pools` are the chain value pools after its parent block.
799///
800/// The balance is credited at the NU7 activation block with `INITIAL_NSM_VALUE_BALANCE`, and
801/// debited by the additional block subsidy, which is zero before `DEPLOYMENT_BLOCK_HEIGHT`. Before
802/// NU7 activation the change is zero.
803///
804/// It is also credited with [`nsm_fee_contribution`], the part of `block_miner_fees` that ZIP 235
805/// removes from circulation.
806pub fn nsm_value_balance_change(
807    height: Height,
808    network: &Network,
809    parent_chain_value_pools: ValueBalance<NonNegative>,
810    block_miner_fees: Amount<NonNegative>,
811) -> Result<Amount<NegativeAllowed>, amount::Error> {
812    if !nsm_value_balance_is_tracked(height, network) {
813        return Ok(Amount::zero());
814    }
815
816    let seed = nsm_seed(height, network).constrain::<NegativeAllowed>()?;
817    let contributed =
818        nsm_fee_contribution(height, network, block_miner_fees).constrain::<NegativeAllowed>()?;
819    let reissued = additional_block_subsidy(
820        height,
821        network,
822        nsm_value_balance_before(height, network, parent_chain_value_pools.nsm_amount()),
823    )
824    .constrain::<NegativeAllowed>()?;
825
826    // The seed and the contribution can each be up to `MAX_MONEY`, so subtract first.
827    (seed - reissued)? + contributed
828}
829
830/// `AdditionalBlockSubsidy(height)`: the block subsidy added to the scheduled block subsidy by the
831/// [halving-preserving issuance ZIP][zip], `ceiling(BLOCK_SUBSIDY_FRACTION * nsm_value_balance)`
832/// from `DEPLOYMENT_BLOCK_HEIGHT`, and zero before it.
833///
834/// [zip]: https://zips.z.cash/zip-0237
835pub fn additional_block_subsidy(
836    height: Height,
837    network: &Network,
838    nsm_value_balance: Amount<NonNegative>,
839) -> Amount<NonNegative> {
840    if !nsm_reissuance_is_active(height, network) {
841        return Amount::zero();
842    }
843
844    let additional_block_subsidy = (u128::from(u64::from(nsm_value_balance))
845        * u128::from(block_subsidy_fraction_numerator(height, network)))
846    .div_ceil(u128::from(BLOCK_SUBSIDY_FRACTION_DENOMINATOR));
847
848    u64::try_from(additional_block_subsidy)
849        .ok()
850        .and_then(|additional_block_subsidy| Amount::try_from(additional_block_subsidy).ok())
851        .expect("BLOCK_SUBSIDY_FRACTION is less than 1, so the result is at most the balance")
852}
853
854/// `BlockSubsidy(height)` for a block whose parent block leaves `parent_chain_value_pools` in the
855/// chain value pools.
856///
857/// From `DEPLOYMENT_BLOCK_HEIGHT`, this is
858/// `ScheduledBlockSubsidy(height) + ceiling(BLOCK_SUBSIDY_FRACTION * NSMValueBalance(height - 1))`.
859/// Before that, `parent_chain_value_pools` is unused and this is [`scheduled_block_subsidy`].
860///
861/// [zip]: https://zips.z.cash/zip-0237
862pub fn block_subsidy_with_parent_pools(
863    height: Height,
864    net: &Network,
865    parent_chain_value_pools: ValueBalance<NonNegative>,
866) -> Result<Amount<NonNegative>, SubsidyError> {
867    block_subsidy_with_parent_nsm_value_balance(height, net, parent_chain_value_pools.nsm_amount())
868}
869
870/// `BlockSubsidy(height)` for a block whose parent block leaves `parent_nsm_value_balance` in the
871/// NSM value balance. See [`block_subsidy_with_parent_pools`].
872pub fn block_subsidy_with_parent_nsm_value_balance(
873    height: Height,
874    net: &Network,
875    parent_nsm_value_balance: Amount<NonNegative>,
876) -> Result<Amount<NonNegative>, SubsidyError> {
877    let scheduled_block_subsidy = scheduled_block_subsidy(height, net)?;
878
879    if !nsm_reissuance_is_active(height, net) {
880        return Ok(scheduled_block_subsidy);
881    }
882
883    let nsm_value_balance = nsm_value_balance_before(height, net, parent_nsm_value_balance);
884
885    Ok((scheduled_block_subsidy + additional_block_subsidy(height, net, nsm_value_balance))?)
886}
887
888/// `BlockSubsidy(height)` as described in [protocol specification §7.8][7.8]
889///
890/// This returns [`SubsidyError::ParentChainValuePoolsRequired`] once the
891/// [halving-preserving issuance ZIP][zip] reissues, because the subsidy then depends on
892/// the parent block's NSM value balance. Use [`block_subsidy_with_parent_pools`] there.
893///
894/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
895/// [zip]: https://zips.z.cash/zip-0237
896pub fn block_subsidy(height: Height, net: &Network) -> Result<Amount<NonNegative>, SubsidyError> {
897    if nsm_reissuance_is_active(height, net) {
898        return Err(SubsidyError::ParentChainValuePoolsRequired(height));
899    }
900
901    scheduled_block_subsidy(height, net)
902}
903
904/// `ScheduledBlockSubsidy(height)`: the block subsidy under the halving schedule, as described in
905/// [protocol specification §7.8][7.8] for `BlockSubsidy(height)`.
906///
907/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
908pub fn scheduled_block_subsidy(
909    height: Height,
910    net: &Network,
911) -> Result<Amount<NonNegative>, SubsidyError> {
912    let Some(halving_div) = halving_divisor(height, net) else {
913        return Ok(Amount::zero());
914    };
915
916    let slow_start_interval = net.slow_start_interval();
917
918    // The `floor` fn used in the spec is implicit in Rust's division of primitive integer types.
919
920    let amount = if height < slow_start_interval {
921        let slow_start_rate = MAX_BLOCK_SUBSIDY / u64::from(slow_start_interval);
922
923        if height < net.slow_start_shift() {
924            slow_start_rate * u64::from(height)
925        } else {
926            slow_start_rate * (u64::from(height) + 1)
927        }
928    } else {
929        // Nested integer divisions by `base_subsidy` then `halving_div` give the same result as
930        // the spec's single `floor()` over their product, because both divisors are positive.
931        let nu = NetworkUpgrade::current(net, height);
932        let base_subsidy = if nu < NetworkUpgrade::Blossom {
933            MAX_BLOCK_SUBSIDY
934        } else if nu < NetworkUpgrade::Nu7 {
935            MAX_BLOCK_SUBSIDY / u64::from(BLOSSOM_POW_TARGET_SPACING_RATIO)
936        } else {
937            // ZIP 218 divides the subsidy by a further `NU7PoWTargetSpacingRatio`, so that the
938            // issuance per unit of wall clock time is unchanged by the faster block spacing.
939            MAX_BLOCK_SUBSIDY
940                / u64::from(BLOSSOM_POW_TARGET_SPACING_RATIO)
941                / u64::from(NU7_POW_TARGET_SPACING_RATIO)
942        };
943
944        base_subsidy / halving_div
945    };
946
947    Ok(Amount::try_from(amount)?)
948}
949
950/// Cumulative scheduled issuance through `height`, including the scheduled genesis subsidy.
951///
952/// Slow start is summed arithmetically; later constant-subsidy ranges are bounded by spacing
953/// changes and halvings. The inverse halving-height calculation is deliberately not required.
954pub fn cumulative_scheduled_issuance(
955    height: Height,
956    network: &Network,
957) -> Result<Amount<NonNegative>, SubsidyError> {
958    Ok(Amount::try_from(cumulative_scheduled_issuance_zatoshis(
959        height, network,
960    )?)?)
961}
962
963/// Sums the schedule before applying the monetary cap, so builder validation can exclude the
964/// unspendable genesis subsidy.
965pub(super) fn cumulative_scheduled_issuance_zatoshis(
966    height: Height,
967    network: &Network,
968) -> Result<u64, SubsidyError> {
969    let end = u64::from(height) + 1;
970    let mut slow_end = u64::from(network.slow_start_interval()).min(end);
971    // The schedule stops after 64 halvings, even during slow start on custom networks.
972    if slow_end > 0
973        && halving_divisor(
974            Height(u32::try_from(slow_end - 1).map_err(|_| SubsidyError::Overflow)?),
975            network,
976        )
977        .is_none()
978    {
979        let mut low = 0;
980        while low < slow_end {
981            let mid = low + (slow_end - low) / 2;
982            if halving_divisor(
983                Height(u32::try_from(mid).map_err(|_| SubsidyError::Overflow)?),
984                network,
985            )
986            .is_some()
987            {
988                low = mid + 1;
989            } else {
990                slow_end = mid;
991            }
992        }
993    }
994    let mut total = 0u64;
995    if slow_end > 0 {
996        let last = slow_end - 1;
997        let shift = u64::from(network.slow_start_shift());
998        total = (MAX_BLOCK_SUBSIDY / u64::from(network.slow_start_interval()))
999            * (last * (last + 1) / 2 + slow_end.saturating_sub(shift));
1000    }
1001
1002    let mut start = slow_end;
1003    while start < end {
1004        let height = Height(u32::try_from(start).map_err(|_| SubsidyError::Overflow)?);
1005        let subsidy = u64::from(scheduled_block_subsidy(height, network)?);
1006        if subsidy == 0 {
1007            break;
1008        }
1009        let era_end = [NetworkUpgrade::Blossom, NetworkUpgrade::Nu7]
1010            .into_iter()
1011            .filter_map(|upgrade| upgrade.activation_height(network))
1012            .map(u64::from)
1013            .filter(|&boundary| boundary > start)
1014            .min()
1015            .unwrap_or(end)
1016            .min(end);
1017        let index = halving(height, network);
1018        let (mut low, mut high) = (start + 1, era_end);
1019        while low < high {
1020            let mid = low + (high - low) / 2;
1021            if halving(
1022                Height(u32::try_from(mid).map_err(|_| SubsidyError::Overflow)?),
1023                network,
1024            ) == index
1025            {
1026                low = mid + 1;
1027            } else {
1028                high = mid;
1029            }
1030        }
1031        total = total
1032            .checked_add(subsidy * (low - start))
1033            .ok_or(SubsidyError::Overflow)?;
1034        start = low;
1035    }
1036    Ok(total)
1037}
1038
1039/// `MinerSubsidy(height)` as described in [protocol specification §7.8][7.8]
1040///
1041/// [7.8]: https://zips.z.cash/protocol/protocol.pdf#subsidies
1042pub fn miner_subsidy(
1043    height: Height,
1044    network: &Network,
1045    expected_block_subsidy: Amount<NonNegative>,
1046) -> Result<Amount<NonNegative>, amount::Error> {
1047    let founders_reward = founders_reward(network, height);
1048
1049    let funding_streams_sum = funding_stream_values(height, network, expected_block_subsidy)?
1050        .values()
1051        .sum::<Result<Amount<NonNegative>, _>>()?;
1052
1053    expected_block_subsidy - founders_reward - funding_streams_sum
1054}
1055
1056/// Returns the founders reward address for a given height and network as described in [§7.9].
1057///
1058/// [§7.9]: <https://zips.z.cash/protocol/protocol.pdf#foundersreward>
1059pub fn founders_reward_address(net: &Network, height: Height) -> Option<transparent::Address> {
1060    let founders_address_list = net.founder_address_list();
1061    let num_founder_addresses = u32::try_from(founders_address_list.len()).ok()?;
1062    let slow_start_shift = u32::from(net.slow_start_shift());
1063    let pre_blossom_halving_interval = u32::try_from(net.pre_blossom_halving_interval()).ok()?;
1064
1065    let founder_address_change_interval = slow_start_shift
1066        .checked_add(pre_blossom_halving_interval)?
1067        .div_ceil(num_founder_addresses);
1068
1069    let founder_address_adjusted_height =
1070        if NetworkUpgrade::current(net, height) < NetworkUpgrade::Blossom {
1071            u32::from(height)
1072        } else {
1073            NetworkUpgrade::Blossom
1074                .activation_height(net)
1075                .and_then(|h| {
1076                    let blossom_activation_height = u32::from(h);
1077                    let height = u32::from(height);
1078
1079                    blossom_activation_height.checked_add(
1080                        height.checked_sub(blossom_activation_height)?
1081                            / BLOSSOM_POW_TARGET_SPACING_RATIO,
1082                    )
1083                })?
1084        };
1085
1086    let founder_address_index =
1087        usize::try_from(founder_address_adjusted_height / founder_address_change_interval).ok()?;
1088
1089    founders_address_list
1090        .get(founder_address_index)
1091        .and_then(|a| a.parse().ok())
1092}
1093
1094/// `FoundersReward(height)` as described in [§7.8].
1095///
1096/// [§7.8]: <https://zips.z.cash/protocol/protocol.pdf#subsidies>
1097pub fn founders_reward(net: &Network, height: Height) -> Amount<NonNegative> {
1098    // The founders reward is 20% of the block subsidy before the first halving, and 0 afterwards.
1099    //
1100    // On custom testnets, the first halving can occur later than Canopy, which causes an
1101    // inconsistency in the definition of the founders reward, which should occur only before
1102    // Canopy, so we check if Canopy is active as well.
1103    if halving(height, net) < 1 && NetworkUpgrade::current(net, height) < NetworkUpgrade::Canopy {
1104        let subsidy = scheduled_block_subsidy(height, net)
1105            .expect("block subsidy must be valid for founders rewards");
1106
1107        // Use truncating integer division to match zcashd's
1108        // `GetBlockSubsidy(nHeight) / 5`. On configured Testnets the slow-start
1109        // subsidy is not always a multiple of 5, so exact division would panic.
1110        (subsidy / 5).expect("dividing by a non-zero constant cannot fail")
1111    } else {
1112        Amount::zero()
1113    }
1114}