Skip to main content

zcash_primitives/transaction/fees/
zip317.rs

1//! Types related to implementing a [`FeeRule`] provides [ZIP 317] fee calculation.
2//!
3//! [`FeeRule`]: crate::transaction::fees::FeeRule
4//! [ZIP 317]: https://zips.z.cash/zip-0317
5use alloc::vec::Vec;
6use core::cmp::max;
7
8use ::transparent::bundle::OutPoint;
9use zcash_protocol::{
10    consensus::{self, BlockHeight, NetworkType, NetworkUpgrade},
11    value::{BalanceError, Zatoshis},
12};
13
14use crate::transaction::fees::transparent;
15
16/// The [ZIP 317] marginal fee before Revision 2 ([ZIP 2009]).
17///
18/// [ZIP 317]: https://zips.z.cash/zip-0317
19/// [ZIP 2009]: https://zips.z.cash/zip-2009
20#[deprecated(
21    since = "0.32.0",
22    note = "Use `zip317::marginal_fee(params, target_height)` for the marginal fee in effect at the height a transaction is expected to be mined."
23)]
24pub const MARGINAL_FEE: Zatoshis = Zatoshis::const_from_u64(5_000);
25
26/// The [ZIP 317] marginal fee from Revision 2 ([ZIP 2009]), in zatoshis per logical action.
27///
28/// [ZIP 317]: https://zips.z.cash/zip-0317
29/// [ZIP 2009]: https://zips.z.cash/zip-2009
30const REVISION_2_MARGINAL_FEE: Zatoshis = Zatoshis::const_from_u64(1_000);
31
32/// The Mainnet height from which Revision 2 applies (`FEE_REDUCTION_HEIGHT` in [ZIP 2009]).
33///
34/// [ZIP 2009]: https://zips.z.cash/zip-2009
35const MAINNET_FEE_REDUCTION_HEIGHT: BlockHeight = BlockHeight::from_u32(3_590_000);
36
37/// The Testnet height from which Revision 2 applies; equal to the Testnet NU7 activation height.
38const TESTNET_FEE_REDUCTION_HEIGHT: BlockHeight = BlockHeight::from_u32(4_465_026);
39
40/// Returns the height from which Revision 2 applies on the network `params` describes, or `None`
41/// if it never applies there.
42fn revision_2_height<P: consensus::Parameters>(params: &P) -> Option<BlockHeight> {
43    match params.network_type() {
44        NetworkType::Main => Some(MAINNET_FEE_REDUCTION_HEIGHT),
45        NetworkType::Test => Some(TESTNET_FEE_REDUCTION_HEIGHT),
46        NetworkType::Regtest => params.activation_height(NetworkUpgrade::Nu7),
47    }
48}
49
50/// Returns the [ZIP 317] marginal fee, in zatoshis per logical action, for a transaction
51/// expected to be mined at `target_height` on the network `params` describes.
52///
53/// The fee is 5000 zatoshis for a `target_height` before the fee reduction of [ZIP 2009] takes
54/// effect, and 1000 from then on. The reduction takes effect at height 3590000 on Mainnet,
55/// 4465026 on Testnet, and the NU7 activation height on a regtest network (never, if NU7 does
56/// not activate there).
57///
58/// [ZIP 317]: https://zips.z.cash/zip-0317
59/// [ZIP 2009]: https://zips.z.cash/zip-2009
60pub fn marginal_fee<P: consensus::Parameters>(params: &P, target_height: BlockHeight) -> Zatoshis {
61    // The pre-Revision-2 constant is deprecated for external callers; this is its only reader.
62    #[allow(deprecated)]
63    let pre_revision_2 = MARGINAL_FEE;
64    if revision_2_height(params).is_some_and(|h| h <= target_height) {
65        REVISION_2_MARGINAL_FEE
66    } else {
67        pre_revision_2
68    }
69}
70
71/// Returns the [ZIP 317] minimum conventional fee at `target_height`: [`marginal_fee`] times
72/// [`GRACE_ACTIONS`].
73///
74/// [ZIP 317]: https://zips.z.cash/zip-0317
75pub fn minimum_fee<P: consensus::Parameters>(params: &P, target_height: BlockHeight) -> Zatoshis {
76    // Cannot overflow: the product is at most `MARGINAL_FEE * GRACE_ACTIONS` (the value of
77    // `MINIMUM_FEE`), which is far below `MAX_MONEY`.
78    (marginal_fee(params, target_height) * GRACE_ACTIONS)
79        .expect("MARGINAL_FEE * GRACE_ACTIONS is below MAX_MONEY")
80}
81
82/// The minimum number of logical actions that must be paid according to [ZIP 317].
83///
84/// [ZIP 317]: https://zips.z.cash/zip-0317
85pub const GRACE_ACTIONS: usize = 2;
86
87/// The standard size of a P2PKH input, in bytes, according to [ZIP 317].
88///
89/// [ZIP 317]: https://zips.z.cash/zip-0317
90pub const P2PKH_STANDARD_INPUT_SIZE: usize = 150;
91
92/// The standard size of a P2PKH output, in bytes, according to [ZIP 317].
93///
94/// [ZIP 317]: https://zips.z.cash/zip-0317
95pub const P2PKH_STANDARD_OUTPUT_SIZE: usize = 34;
96
97/// The consensus maximum size of a serialized transparent input: outpoint (36) +
98/// CompactSize prefix for the scriptSig (at most 9) + scriptSig (at most
99/// `MAX_SCRIPT_SIZE = 10_000`) + sequence (4). This is the safe upper bound for a
100/// transparent input whose script size is unknown.
101pub const MAX_TRANSPARENT_INPUT_SIZE: usize = 36 + 9 + 10_000 + 4;
102
103/// The per-bundle overhead of a transparent bundle: two CompactSize vector-length
104/// prefixes (one for `vin`, one for `vout`), at most 9 bytes each.
105pub const TRANSPARENT_BUNDLE_OVERHEAD: usize = 18;
106
107/// The fixed size of a Zcash transaction header: version (4) +
108/// `consensus_branch_id` (4) + `lock_time` (4) + `expiry_height` (4). The constant
109/// leaves room for future header fields.
110pub const TX_HEADER_SIZE: usize = 32;
111
112/// The [ZIP 317] minimum conventional fee before Revision 2 ([ZIP 2009]). Equivalent to
113/// `MARGINAL_FEE * GRACE_ACTIONS`.
114///
115/// [ZIP 317]: https://zips.z.cash/zip-0317
116/// [ZIP 2009]: https://zips.z.cash/zip-2009
117#[deprecated(
118    since = "0.32.0",
119    note = "Use `zip317::minimum_fee(params, target_height)` for the minimum conventional fee in effect at the height a transaction is expected to be mined."
120)]
121pub const MINIMUM_FEE: Zatoshis = Zatoshis::const_from_u64(10_000);
122
123/// A [`FeeRule`] implementation that implements the [ZIP 317] fee rule.
124///
125/// This fee rule supports Ironwood, Orchard, Sapling, and (P2PKH only) transparent
126/// inputs. Returns an error if a coin containing a non-P2PKH script is provided as an input.
127///
128/// This fee rule may slightly overestimate fees in case where the user is attempting
129/// to spend a large number of transparent inputs. This is intentional and is relied
130/// on for the correctness of transaction construction algorithms in the
131/// `zcash_client_backend` crate.
132///
133/// [`FeeRule`]: crate::transaction::fees::FeeRule
134/// [ZIP 317]: https://zips.z.cash/zip-0317
135#[derive(Clone, Debug)]
136pub struct FeeRule {
137    marginal_fee: MarginalFee,
138    grace_actions: usize,
139    p2pkh_standard_input_size: usize,
140    p2pkh_standard_output_size: usize,
141}
142
143/// The marginal fee a [`FeeRule`] charges.
144#[derive(Clone, Debug)]
145enum MarginalFee {
146    /// The ZIP 317 schedule ([`marginal_fee`]).
147    Standard,
148    /// A fixed value, from [`FeeRule::non_standard`].
149    #[cfg(feature = "non-standard-fees")]
150    Fixed(Zatoshis),
151}
152
153impl FeeRule {
154    /// The standard [ZIP 317] rule: the marginal fee in effect at the height a transaction is
155    /// expected to be mined ([`marginal_fee`]), with the standard grace actions and P2PKH sizes.
156    ///
157    /// [ZIP 317]: https://zips.z.cash/zip-0317
158    pub fn standard() -> Self {
159        Self {
160            marginal_fee: MarginalFee::Standard,
161            grace_actions: GRACE_ACTIONS,
162            p2pkh_standard_input_size: P2PKH_STANDARD_INPUT_SIZE,
163            p2pkh_standard_output_size: P2PKH_STANDARD_OUTPUT_SIZE,
164        }
165    }
166
167    /// Construct a new FeeRule instance with the specified parameter values.
168    ///
169    /// Using this fee rule with
170    /// ```text
171    /// marginal_fee < marginal_fee(params, target_height) || grace_actions < 2
172    ///     || p2pkh_standard_input_size > P2PKH_STANDARD_INPUT_SIZE
173    ///     || p2pkh_standard_output_size > P2PKH_STANDARD_OUTPUT_SIZE
174    /// ```
175    /// violates ZIP 317, and might cause transactions built with it to fail.
176    ///
177    /// Returns `None` if either `p2pkh_standard_input_size` or `p2pkh_standard_output_size` are
178    /// zero.
179    #[cfg(feature = "non-standard-fees")]
180    pub fn non_standard(
181        marginal_fee: Zatoshis,
182        grace_actions: usize,
183        p2pkh_standard_input_size: usize,
184        p2pkh_standard_output_size: usize,
185    ) -> Option<Self> {
186        if p2pkh_standard_input_size == 0 || p2pkh_standard_output_size == 0 {
187            None
188        } else {
189            Some(Self {
190                marginal_fee: MarginalFee::Fixed(marginal_fee),
191                grace_actions,
192                p2pkh_standard_input_size,
193                p2pkh_standard_output_size,
194            })
195        }
196    }
197
198    /// Returns the marginal fee this rule charges a transaction expected to be mined at
199    /// `target_height`.
200    pub fn marginal_fee<P: consensus::Parameters>(
201        &self,
202        params: &P,
203        target_height: BlockHeight,
204    ) -> Zatoshis {
205        match self.marginal_fee {
206            MarginalFee::Standard => marginal_fee(params, target_height),
207            #[cfg(feature = "non-standard-fees")]
208            MarginalFee::Fixed(fee) => fee,
209        }
210    }
211    /// Returns the ZIP 317 number of grace actions
212    pub fn grace_actions(&self) -> usize {
213        self.grace_actions
214    }
215    /// Returns the ZIP 317 standard P2PKH input size
216    pub fn p2pkh_standard_input_size(&self) -> usize {
217        self.p2pkh_standard_input_size
218    }
219    /// Returns the ZIP 317 standard P2PKH output size
220    pub fn p2pkh_standard_output_size(&self) -> usize {
221        self.p2pkh_standard_output_size
222    }
223}
224
225/// Errors that can occur in ZIP 317 fee computation
226#[derive(Clone, Debug, PartialEq, Eq)]
227pub enum FeeError {
228    /// An overflow or underflow of amount computation occurred.
229    Balance(BalanceError),
230    /// Transparent inputs provided to the fee calculation included coins that pay to
231    /// unknown P2SH redeem scripts.
232    UnknownP2shInputs(Vec<OutPoint>),
233}
234
235impl From<BalanceError> for FeeError {
236    fn from(err: BalanceError) -> Self {
237        FeeError::Balance(err)
238    }
239}
240
241impl core::fmt::Display for FeeError {
242    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
243        match &self {
244            FeeError::Balance(e) => write!(
245                f,
246                "A balance calculation violated amount validity bounds: {e}."
247            ),
248            FeeError::UnknownP2shInputs(_) => {
249                write!(f, "Only P2PKH or known-P2SH inputs are supported.")
250            }
251        }
252    }
253}
254
255impl super::FeeRule for FeeRule {
256    type Error = FeeError;
257
258    fn fee_required<P: consensus::Parameters>(
259        &self,
260        params: &P,
261        target_height: BlockHeight,
262        transparent_input_sizes: impl IntoIterator<Item = transparent::InputSize>,
263        transparent_output_sizes: impl IntoIterator<Item = usize>,
264        sapling_input_count: usize,
265        sapling_output_count: usize,
266        orchard_action_count: usize,
267        ironwood_action_count: usize,
268    ) -> Result<Zatoshis, Self::Error> {
269        let mut t_in_total_size: usize = 0;
270        let mut unknown_p2sh_outpoints = vec![];
271        for sz in transparent_input_sizes.into_iter() {
272            match sz {
273                transparent::InputSize::Known(s) => {
274                    t_in_total_size += s;
275                }
276                transparent::InputSize::Unknown(outpoint) => {
277                    unknown_p2sh_outpoints.push(outpoint.clone());
278                }
279            }
280        }
281
282        if !unknown_p2sh_outpoints.is_empty() {
283            return Err(FeeError::UnknownP2shInputs(unknown_p2sh_outpoints));
284        }
285
286        let t_out_total_size = transparent_output_sizes.into_iter().sum();
287
288        let ceildiv = |num: usize, den: usize| num.div_ceil(den);
289
290        let logical_actions = max(
291            ceildiv(t_in_total_size, self.p2pkh_standard_input_size),
292            ceildiv(t_out_total_size, self.p2pkh_standard_output_size),
293        ) + max(sapling_input_count, sapling_output_count)
294            + orchard_action_count
295            + ironwood_action_count;
296
297        (self.marginal_fee(params, target_height) * max(self.grace_actions, logical_actions))
298            .ok_or_else(|| BalanceError::Overflow.into())
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    // The tests pin the deprecated pre-Revision-2 constants themselves.
305    #![allow(deprecated)]
306
307    use core::iter;
308
309    use zcash_protocol::{
310        consensus::{BlockHeight, MAIN_NETWORK, NetworkUpgrade, Parameters, TEST_NETWORK},
311        local_consensus::LocalNetwork,
312        value::Zatoshis,
313    };
314
315    use super::{
316        FeeRule, GRACE_ACTIONS, MAINNET_FEE_REDUCTION_HEIGHT, MARGINAL_FEE, MINIMUM_FEE,
317        REVISION_2_MARGINAL_FEE, TESTNET_FEE_REDUCTION_HEIGHT, marginal_fee, minimum_fee,
318        revision_2_height,
319    };
320    use crate::transaction::fees::{FeeRule as _, transparent::InputSize};
321
322    #[cfg(feature = "non-standard-fees")]
323    use super::{P2PKH_STANDARD_INPUT_SIZE, P2PKH_STANDARD_OUTPUT_SIZE};
324
325    /// The regtest NU7 activation height used by the schedule tests.
326    const REGTEST_NU7_HEIGHT: BlockHeight = BlockHeight::from_u32(10);
327
328    fn regtest(nu7: Option<BlockHeight>) -> LocalNetwork {
329        LocalNetwork {
330            overwinter: None,
331            sapling: None,
332            blossom: None,
333            heartwood: None,
334            canopy: None,
335            nu5: None,
336            nu6: None,
337            nu6_1: None,
338            nu6_2: None,
339            nu6_3: None,
340            nu7,
341            #[cfg(zcash_unstable = "nutachyon")]
342            nu_tachyon: None,
343        }
344    }
345
346    fn fee_for(orchard_action_count: usize, ironwood_action_count: usize) -> Zatoshis {
347        FeeRule::standard()
348            .fee_required(
349                &MAIN_NETWORK,
350                BlockHeight::from_u32(1_000_000),
351                iter::empty::<InputSize>(),
352                iter::empty::<usize>(),
353                0,
354                0,
355                orchard_action_count,
356                ironwood_action_count,
357            )
358            .unwrap()
359    }
360
361    /// The fee `rule` charges a transaction of `orchard_action_count` Orchard actions and nothing
362    /// else, expected to be mined at `height`.
363    fn fee_at<P: Parameters>(
364        rule: &FeeRule,
365        params: &P,
366        height: BlockHeight,
367        orchard_action_count: usize,
368    ) -> Zatoshis {
369        rule.fee_required(
370            params,
371            height,
372            iter::empty::<InputSize>(),
373            iter::empty::<usize>(),
374            0,
375            0,
376            orchard_action_count,
377            0,
378        )
379        .unwrap()
380    }
381
382    /// Asserts the marginal fee at `height`, and that the minimum fee follows it.
383    fn assert_fees_at<P: Parameters>(params: &P, height: BlockHeight, expected: Zatoshis) {
384        assert_eq!(marginal_fee(params, height), expected);
385        assert_eq!(
386            minimum_fee(params, height),
387            (expected * GRACE_ACTIONS).unwrap()
388        );
389    }
390
391    #[test]
392    fn ironwood_actions_charged_marginal_fee() {
393        // Five Ironwood actions exceed the grace allowance, so each is charged the
394        // marginal fee.
395        assert_eq!(fee_for(0, 5), (MARGINAL_FEE * 5usize).unwrap());
396    }
397
398    #[test]
399    fn ironwood_actions_combine_with_orchard() {
400        // Orchard and Ironwood actions are summed into the logical action count.
401        assert_eq!(fee_for(2, 3), (MARGINAL_FEE * 5usize).unwrap());
402    }
403
404    #[test]
405    fn marginal_fee_per_network() {
406        let below = |h: BlockHeight| h - 1;
407
408        assert_eq!(
409            revision_2_height(&MAIN_NETWORK),
410            Some(MAINNET_FEE_REDUCTION_HEIGHT)
411        );
412        assert_fees_at(
413            &MAIN_NETWORK,
414            below(MAINNET_FEE_REDUCTION_HEIGHT),
415            MARGINAL_FEE,
416        );
417        assert_fees_at(
418            &MAIN_NETWORK,
419            MAINNET_FEE_REDUCTION_HEIGHT,
420            REVISION_2_MARGINAL_FEE,
421        );
422
423        assert_eq!(
424            revision_2_height(&TEST_NETWORK),
425            Some(TESTNET_FEE_REDUCTION_HEIGHT)
426        );
427        assert_eq!(
428            TEST_NETWORK.activation_height(NetworkUpgrade::Nu7),
429            Some(TESTNET_FEE_REDUCTION_HEIGHT)
430        );
431        assert_fees_at(
432            &TEST_NETWORK,
433            below(TESTNET_FEE_REDUCTION_HEIGHT),
434            MARGINAL_FEE,
435        );
436        assert_fees_at(
437            &TEST_NETWORK,
438            TESTNET_FEE_REDUCTION_HEIGHT,
439            REVISION_2_MARGINAL_FEE,
440        );
441
442        let with_nu7 = regtest(Some(REGTEST_NU7_HEIGHT));
443        assert_eq!(revision_2_height(&with_nu7), Some(REGTEST_NU7_HEIGHT));
444        assert_fees_at(&with_nu7, below(REGTEST_NU7_HEIGHT), MARGINAL_FEE);
445        assert_fees_at(&with_nu7, REGTEST_NU7_HEIGHT, REVISION_2_MARGINAL_FEE);
446
447        let without_nu7 = regtest(None);
448        assert_eq!(revision_2_height(&without_nu7), None);
449        assert_fees_at(&without_nu7, BlockHeight::from_u32(u32::MAX), MARGINAL_FEE);
450
451        // The pre-Revision 2 constants keep their values.
452        assert_eq!(MARGINAL_FEE, Zatoshis::const_from_u64(5_000));
453        assert_eq!(MINIMUM_FEE, Zatoshis::const_from_u64(10_000));
454    }
455
456    #[test]
457    fn standard_rule_follows_schedule_and_fixed_rule_does_not() {
458        let rule = FeeRule::standard();
459        let before = MAINNET_FEE_REDUCTION_HEIGHT - 1;
460        let from = MAINNET_FEE_REDUCTION_HEIGHT;
461
462        // A transaction of exactly `GRACE_ACTIONS` logical actions pays the minimum fee.
463        assert_eq!(
464            fee_at(&rule, &MAIN_NETWORK, before, GRACE_ACTIONS),
465            minimum_fee(&MAIN_NETWORK, before)
466        );
467        assert_eq!(
468            fee_at(&rule, &MAIN_NETWORK, from, GRACE_ACTIONS),
469            minimum_fee(&MAIN_NETWORK, from)
470        );
471        assert_eq!(
472            rule.marginal_fee(&MAIN_NETWORK, from),
473            REVISION_2_MARGINAL_FEE
474        );
475
476        #[cfg(feature = "non-standard-fees")]
477        {
478            let fixed = FeeRule::non_standard(
479                MARGINAL_FEE,
480                GRACE_ACTIONS,
481                P2PKH_STANDARD_INPUT_SIZE,
482                P2PKH_STANDARD_OUTPUT_SIZE,
483            )
484            .unwrap();
485            assert_eq!(fixed.marginal_fee(&MAIN_NETWORK, from), MARGINAL_FEE);
486            assert_eq!(
487                fee_at(&fixed, &MAIN_NETWORK, from, GRACE_ACTIONS),
488                (MARGINAL_FEE * GRACE_ACTIONS).unwrap()
489            );
490        }
491    }
492}