Skip to main content

zebra_chain/parameters/network/subsidy/
check.rs

1//! Block subsidy, funding stream, and miner fee consensus checks.
2
3use mset::MultiSet;
4
5use crate::{
6    amount::{
7        Amount, DeferredPoolBalanceChange, Error as AmountError, NegativeAllowed, NonNegative,
8    },
9    block::{Block, Height},
10    parameters::{Network, NetworkUpgrade},
11    transaction::Transaction,
12    transparent::{Address, Output},
13};
14
15use super::{
16    founders_reward, founders_reward_address, funding_stream_address, funding_stream_values,
17    nsm_fee_contribution, FundingStreamReceiver, ParameterSubsidy, SubsidyError,
18};
19
20/// An error from the block subsidy or miner fee checks on a block's coinbase transaction.
21#[derive(thiserror::Error, Clone, Debug, PartialEq, Eq)]
22#[allow(missing_docs)]
23#[non_exhaustive]
24pub enum CoinbaseTransactionError {
25    #[error(transparent)]
26    Subsidy(#[from] SubsidyError),
27
28    #[error("founders reward address must be defined for height: {0:?}")]
29    FoundersRewardAddressNotFound(Height),
30
31    #[error("missing lockbox disbursements for NU6.1 activation block")]
32    MissingLockboxDisbursements,
33
34    #[error("A funding stream other than the deferred pool must have an address")]
35    FundingStreamAddressNotFound,
36
37    #[error("invalid transparent value balance: {0}")]
38    InvalidTransparentValueBalance(AmountError),
39}
40
41impl From<AmountError> for CoinbaseTransactionError {
42    fn from(error: AmountError) -> Self {
43        Self::Subsidy(error.into())
44    }
45}
46
47/// Returns `Ok()` with the deferred pool balance change of the coinbase transaction if the block
48/// subsidy in `block` is valid for `network`
49///
50/// [3.9]: https://zips.z.cash/protocol/protocol.pdf#subsidyconcepts
51pub fn subsidy_is_valid(
52    block: &Block,
53    net: &Network,
54    expected_block_subsidy: Amount<NonNegative>,
55) -> Result<DeferredPoolBalanceChange, CoinbaseTransactionError> {
56    let height = block.coinbase_height().ok_or(SubsidyError::NoCoinbase)?;
57
58    // A zero subsidy removes proportional payouts, but not fixed lockbox disbursements.
59    if expected_block_subsidy.is_zero()
60        && Some(height) != NetworkUpgrade::Nu6_1.activation_height(net)
61    {
62        return Ok(DeferredPoolBalanceChange::zero());
63    }
64
65    let mut coinbase_outputs: MultiSet<Output> = block
66        .transactions
67        .first()
68        .ok_or(SubsidyError::NoCoinbase)?
69        .outputs()
70        .iter()
71        .cloned()
72        .collect();
73
74    let mut has_amount =
75        |addr: &Address, amount| coinbase_outputs.remove(&Output::new(amount, addr.script()));
76
77    // # Note
78    //
79    // Canopy activation is at the first halving on Mainnet, but not on Testnet. [ZIP-1014] only
80    // applies to Mainnet; [ZIP-214] contains the specific rules for Testnet funding stream amount
81    // values.
82    //
83    // [ZIP-1014]: <https://zips.z.cash/zip-1014>
84    // [ZIP-214]: <https://zips.z.cash/zip-0214
85    if NetworkUpgrade::current(net, height) < NetworkUpgrade::Canopy {
86        // # Consensus
87        //
88        // > [Pre-Canopy] A coinbase transaction at `height ∈ {1 .. FoundersRewardLastBlockHeight}`
89        // > MUST include at least one output that pays exactly `FoundersReward(height)` zatoshi
90        // > with a standard P2SH script of the form `OP_HASH160 FounderRedeemScriptHash(height)
91        // > OP_EQUAL` as its `scriptPubKey`.
92        //
93        // ## Notes
94        //
95        // - `FoundersRewardLastBlockHeight := max({height : N | Halving(height) < 1})`
96        //
97        // <https://zips.z.cash/protocol/protocol.pdf#foundersreward>
98
99        if Height::MIN < height && height < net.height_for_first_halving() {
100            let addr = founders_reward_address(net, height).ok_or(
101                CoinbaseTransactionError::FoundersRewardAddressNotFound(height),
102            )?;
103
104            if !has_amount(&addr, founders_reward(net, height)) {
105                Err(SubsidyError::FoundersRewardNotFound)?;
106            }
107        }
108
109        Ok(DeferredPoolBalanceChange::zero())
110    } else {
111        // # Consensus
112        //
113        // > [Canopy onward] In each block with coinbase transaction `cb` at block height `height`,
114        // > `cb` MUST contain at least the given number of distinct outputs for each of the
115        // > following:
116        //
117        // > • for each funding stream `fs` active at that block height with a recipient identifier
118        // > other than `DEFERRED_POOL` given by `fs.Recipient(height)`, one output that pays
119        // > `fs.Value(height)` zatoshi in the prescribed way to the address represented by that
120        // > recipient identifier;
121        //
122        // > • [NU6.1 onward] if the block height is `ZIP271ActivationHeight`,
123        // > `ZIP271DisbursementChunks` equal outputs paying a total of `ZIP271DisbursementAmount`
124        // > zatoshi in the prescribed way to the Key-Holder Organizations’ P2SH multisig address
125        // > represented by `ZIP271DisbursementAddress`, as specified by [ZIP-271].
126        //
127        // > The term “prescribed way” is defined as follows:
128        //
129        // > The prescribed way to pay a transparent P2SH address is to use a standard P2SH script
130        // > of the form `OP_HASH160 fs.RedeemScriptHash(height) OP_EQUAL` as the `scriptPubKey`.
131        // > Here `fs.RedeemScriptHash(height)` is the standard redeem script hash for the recipient
132        // > address for `fs.Recipient(height)` in _Base58Check_ form. Standard redeem script hashes
133        // > are defined in [ZIP-48] for P2SH multisig addresses, or [Bitcoin-P2SH] for other P2SH
134        // > addresses.
135        //
136        // <https://zips.z.cash/protocol/protocol.pdf#fundingstreams>
137        //
138        // ZIP 2008 assigns a P2PKH recipient. Match the standard script of the assigned address
139        // exactly, retaining the prescribed P2SH scripts for all historical recipients.
140        // <https://zips.z.cash/zip-2008>
141        //
142        // [ZIP-271]: <https://zips.z.cash/zip-0271>
143        // [ZIP-48]: <https://zips.z.cash/zip-0048>
144        // [Bitcoin-P2SH]: <https://developer.bitcoin.org/devguide/transactions.html#pay-to-script-hash-p2sh>
145
146        let mut funding_streams = funding_stream_values(height, net, expected_block_subsidy)?;
147
148        // The deferred pool contribution is checked in `miner_fees_are_valid()` according to
149        // [ZIP-1015](https://zips.z.cash/zip-1015).
150        let mut deferred_pool_balance_change = funding_streams
151            .remove(&FundingStreamReceiver::Deferred)
152            .unwrap_or_default()
153            .constrain::<NegativeAllowed>()?;
154
155        // Check the one-time lockbox disbursements in the NU6.1 activation block's coinbase tx
156        // according to [ZIP-271] and [ZIP-1016].
157        //
158        // [ZIP-271]: <https://zips.z.cash/zip-0271>
159        // [ZIP-1016]: <https://zips.z.cash/zip-101>
160        if Some(height) == NetworkUpgrade::Nu6_1.activation_height(net) {
161            let lockbox_disbursements = net.lockbox_disbursements(height);
162
163            // The Mainnet and default Testnet disbursement lists are hardcoded and must be
164            // non-empty. Custom testnets and Regtest may configure no disbursements, in which
165            // case the NU6.1 activation block is not required to contain any disbursement
166            // outputs.
167            let must_have_disbursements =
168                matches!(net, Network::Mainnet) || net.is_default_testnet();
169            if lockbox_disbursements.is_empty() && must_have_disbursements {
170                Err(CoinbaseTransactionError::MissingLockboxDisbursements)?;
171            }
172
173            deferred_pool_balance_change = lockbox_disbursements.into_iter().try_fold(
174                deferred_pool_balance_change,
175                |balance, (addr, expected_amount)| {
176                    if !has_amount(&addr, expected_amount) {
177                        Err(SubsidyError::OneTimeLockboxDisbursementNotFound)?;
178                    }
179
180                    balance
181                        .checked_sub(expected_amount)
182                        .ok_or(SubsidyError::Underflow)
183                },
184            )?;
185        };
186
187        // Check each funding stream output.
188        funding_streams.into_iter().try_for_each(
189            |(receiver, expected_amount)| -> Result<(), CoinbaseTransactionError> {
190                let addr = funding_stream_address(height, net, receiver)
191                    .ok_or(CoinbaseTransactionError::FundingStreamAddressNotFound)?;
192
193                if !has_amount(addr, expected_amount) {
194                    Err(SubsidyError::FundingStreamNotFound)?;
195                }
196
197                Ok(())
198            },
199        )?;
200
201        Ok(DeferredPoolBalanceChange::new(deferred_pool_balance_change))
202    }
203}
204
205/// Returns `Ok(())` if the miner fees consensus rule is valid.
206///
207/// [7.1.2]: https://zips.z.cash/protocol/protocol.pdf#txnconsensus
208pub fn miner_fees_are_valid(
209    coinbase_tx: &Transaction,
210    height: Height,
211    block_miner_fees: Amount<NonNegative>,
212    expected_block_subsidy: Amount<NonNegative>,
213    expected_deferred_pool_balance_change: DeferredPoolBalanceChange,
214    network: &Network,
215) -> Result<(), CoinbaseTransactionError> {
216    let transparent_value_balance = coinbase_tx
217        .outputs()
218        .iter()
219        .map(|output| output.value())
220        .sum::<Result<Amount<NonNegative>, AmountError>>()
221        .map_err(|_| SubsidyError::Overflow)?
222        .constrain()
223        .map_err(CoinbaseTransactionError::InvalidTransparentValueBalance)?;
224    let sapling_value_balance = coinbase_tx.sapling_value_balance().sapling_amount();
225    let orchard_value_balance = coinbase_tx.orchard_value_balance().orchard_amount();
226    // [NU6.3 onward] The Ironwood pool is shielded too, so its value balance affects the coinbase
227    // output value exactly like Sapling and Orchard. This is zero for pre-v6 coinbase transactions
228    // (no Ironwood bundle), so it is a no-op before NU6.3.
229    let ironwood_value_balance = coinbase_tx.ironwood_value_balance().ironwood_amount();
230
231    // # Consensus
232    //
233    // > - define the total output value of its coinbase transaction to be the total value in zatoshi of its transparent
234    // >   outputs, minus vbalanceSapling, minus vbalanceOrchard, minus vbalanceIronwood, plus totalDeferredOutput(height);
235    // > – define the total input value of its coinbase transaction to be the value in zatoshi of the block subsidy,
236    // >   plus the transaction fees paid by transactions in the block.
237    //
238    // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
239    //
240    // The expected lockbox funding stream output of the coinbase transaction is also subtracted
241    // from the block subsidy value plus the transaction fees paid by transactions in this block.
242    let total_output_value = (transparent_value_balance
243        - sapling_value_balance
244        - orchard_value_balance
245        - ironwood_value_balance
246        + expected_deferred_pool_balance_change.value())
247    .map_err(|_| SubsidyError::Overflow)?;
248
249    // # Consensus
250    //
251    // > For every block from NU7 activation onward, the coinbase transaction MUST be balanced using
252    // > MinerFees in place of TransactionFees
253    //
254    // where `MinerFees(height) := TransactionFees(height) - NSMFeeContribution(height)`.
255    //
256    // https://github.com/zcash/zips/pull/1363
257    let claimable_miner_fees = (block_miner_fees
258        - nsm_fee_contribution(height, network, block_miner_fees))
259    .map_err(|_| SubsidyError::Overflow)?;
260
261    let total_input_value =
262        (expected_block_subsidy + claimable_miner_fees).map_err(|_| SubsidyError::Overflow)?;
263
264    // # Consensus
265    //
266    // > [Pre-NU6] The total output of a coinbase transaction MUST NOT be greater than its total
267    // input.
268    //
269    // > [NU6 onward] The total output of a coinbase transaction MUST be equal to its total input.
270    if if NetworkUpgrade::current(network, height) < NetworkUpgrade::Nu6 {
271        total_output_value > total_input_value
272    } else {
273        total_output_value != total_input_value
274    } {
275        Err(SubsidyError::InvalidMinerFees)?
276    };
277
278    Ok(())
279}