Skip to main content

zcash_client_backend/
fees.rs

1use std::{
2    convert::Infallible,
3    fmt::{self, Debug, Display},
4    num::{NonZeroU64, NonZeroUsize},
5};
6
7use ::transparent::bundle::OutPoint;
8use zcash_primitives::transaction::fees::{
9    FeeRule,
10    transparent::{self, InputSize},
11    zip317 as prim_zip317,
12};
13use zcash_protocol::{
14    PoolType, ShieldedPool,
15    consensus::{self, BlockHeight},
16    memo::MemoBytes,
17    value::{BalanceError, Zatoshis},
18};
19
20use crate::data_api::{
21    ChangeReceivers, InputSource, anchor_retention::PoolMigrationParams, wallet::TargetHeight,
22};
23
24pub mod common;
25#[cfg(feature = "non-standard-fees")]
26pub mod fixed;
27#[cfg(feature = "orchard")]
28pub mod orchard;
29pub mod sapling;
30pub mod standard;
31pub mod zip317;
32
33/// An enumeration of the standard fee rules supported by the wallet backend.
34#[derive(Debug, Copy, Clone, PartialEq, Eq)]
35pub enum StandardFeeRule {
36    /// The [ZIP 317] fee rule: the marginal fee in effect at the target height
37    /// ([`zip317::marginal_fee`]).
38    ///
39    /// [ZIP 317]: https://zips.z.cash/zip-0317
40    /// [`zip317::marginal_fee`]: zcash_primitives::transaction::fees::zip317::marginal_fee
41    Zip317,
42}
43
44impl FeeRule for StandardFeeRule {
45    type Error = prim_zip317::FeeError;
46
47    fn fee_required<P: consensus::Parameters>(
48        &self,
49        params: &P,
50        target_height: BlockHeight,
51        transparent_input_sizes: impl IntoIterator<Item = InputSize>,
52        transparent_output_sizes: impl IntoIterator<Item = usize>,
53        sapling_input_count: usize,
54        sapling_output_count: usize,
55        orchard_action_count: usize,
56        ironwood_action_count: usize,
57    ) -> Result<Zatoshis, Self::Error> {
58        match self {
59            Self::Zip317 => prim_zip317::FeeRule::standard().fee_required(
60                params,
61                target_height,
62                transparent_input_sizes,
63                transparent_output_sizes,
64                sapling_input_count,
65                sapling_output_count,
66                orchard_action_count,
67                ironwood_action_count,
68            ),
69        }
70    }
71}
72
73/// A policy that determines how change should be returned to the wallet when the net flows of a
74/// transaction under construction are fully transparent.
75///
76/// This policy has no effect on transactions that have any shielded inputs or outputs; change
77/// for such transactions is always returned to a shielded pool, irrespective of the policy in
78/// use. When the flows of a transaction are fully transparent, shielding change (the default)
79/// reveals the change amount as the value of the shielded output(s) in an otherwise-transparent
80/// transaction; returning the change to the transparent pool matches the behavior of
81/// transparent-only wallets (including `zcashd`) at the cost of the change remaining unshielded.
82///
83/// Transparent change is currently always sent to a P2PKH address derived under the wallet
84/// account's internal scope; returning change to the originating address when spending from a
85/// P2SH (e.g. multisig) address is not yet supported. See [zcash/librustzcash#2570] for
86/// details.
87///
88/// [zcash/librustzcash#2570]: https://github.com/zcash/librustzcash/issues/2570
89#[cfg(feature = "transparent-inputs")]
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
91pub enum TransparentChangePolicy {
92    /// Change is always returned to a shielded pool, even when the net flows of the transaction
93    /// are fully transparent.
94    ///
95    /// This is the default policy.
96    #[default]
97    ShieldChange,
98    /// When the net flows of the transaction are fully transparent, change is returned to the
99    /// transparent pool at an internal-scope (change) transparent address of the wallet, as
100    /// described in [BIP 44].
101    ///
102    /// [BIP 44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
103    TransparentChangeAllowed,
104}
105
106/// `ChangeValue` represents either a proposed change output to a shielded pool
107/// (with an optional change memo), or if the "transparent-inputs" feature is
108/// enabled, an output to the transparent pool: either an ephemeral output as
109/// part of a [ZIP 320] transaction pair, or a change output to an
110/// internal-scope (change) transparent address of the wallet.
111///
112/// [ZIP 320]: https://zips.z.cash/zip-0320
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct ChangeValue(ChangeValueInner);
115
116#[derive(Clone, Debug, PartialEq, Eq)]
117enum ChangeValueInner {
118    Shielded {
119        protocol: ShieldedPool,
120        value: Zatoshis,
121        memo: Option<MemoBytes>,
122    },
123    #[cfg(feature = "transparent-inputs")]
124    EphemeralTransparent { value: Zatoshis },
125    #[cfg(feature = "transparent-inputs")]
126    Transparent { value: Zatoshis },
127}
128
129impl ChangeValue {
130    /// Constructs a new ephemeral transparent output value.
131    #[cfg(feature = "transparent-inputs")]
132    pub fn ephemeral_transparent(value: Zatoshis) -> Self {
133        Self(ChangeValueInner::EphemeralTransparent { value })
134    }
135
136    /// Constructs a new change value that will be created as a non-ephemeral transparent output
137    /// sent to an internal-scope (change) transparent address of the wallet.
138    #[cfg(feature = "transparent-inputs")]
139    pub fn transparent(value: Zatoshis) -> Self {
140        Self(ChangeValueInner::Transparent { value })
141    }
142
143    /// Constructs a new change value that will be created as a shielded output.
144    pub fn shielded(protocol: ShieldedPool, value: Zatoshis, memo: Option<MemoBytes>) -> Self {
145        Self(ChangeValueInner::Shielded {
146            protocol,
147            value,
148            memo,
149        })
150    }
151
152    /// Constructs a new change value that will be created as a Sapling output.
153    pub fn sapling(value: Zatoshis, memo: Option<MemoBytes>) -> Self {
154        Self::shielded(ShieldedPool::Sapling, value, memo)
155    }
156
157    /// Constructs a new change value that will be created as an Orchard output.
158    #[cfg(feature = "orchard")]
159    pub fn orchard(value: Zatoshis, memo: Option<MemoBytes>) -> Self {
160        Self::shielded(ShieldedPool::Orchard, value, memo)
161    }
162
163    /// Constructs a new change value that will be created as an Ironwood output.
164    #[cfg(feature = "orchard")]
165    pub fn ironwood(value: Zatoshis, memo: Option<MemoBytes>) -> Self {
166        Self::shielded(ShieldedPool::Ironwood, value, memo)
167    }
168
169    /// Returns the pool to which the change or ephemeral output should be sent.
170    pub fn output_pool(&self) -> PoolType {
171        match &self.0 {
172            ChangeValueInner::Shielded { protocol, .. } => PoolType::Shielded(*protocol),
173            #[cfg(feature = "transparent-inputs")]
174            ChangeValueInner::EphemeralTransparent { .. } => PoolType::Transparent,
175            #[cfg(feature = "transparent-inputs")]
176            ChangeValueInner::Transparent { .. } => PoolType::Transparent,
177        }
178    }
179
180    /// Returns the value of the change or ephemeral output to be created, in zatoshis.
181    pub fn value(&self) -> Zatoshis {
182        match &self.0 {
183            ChangeValueInner::Shielded { value, .. } => *value,
184            #[cfg(feature = "transparent-inputs")]
185            ChangeValueInner::EphemeralTransparent { value } => *value,
186            #[cfg(feature = "transparent-inputs")]
187            ChangeValueInner::Transparent { value } => *value,
188        }
189    }
190
191    /// Returns the memo to be associated with the output.
192    pub fn memo(&self) -> Option<&MemoBytes> {
193        match &self.0 {
194            ChangeValueInner::Shielded { memo, .. } => memo.as_ref(),
195            #[cfg(feature = "transparent-inputs")]
196            ChangeValueInner::EphemeralTransparent { .. } => None,
197            #[cfg(feature = "transparent-inputs")]
198            ChangeValueInner::Transparent { .. } => None,
199        }
200    }
201
202    /// Whether this is to be an ephemeral output.
203    #[cfg_attr(
204        not(feature = "transparent-inputs"),
205        doc = "This is always false because the `transparent-inputs` feature is
206               not enabled."
207    )]
208    pub fn is_ephemeral(&self) -> bool {
209        match &self.0 {
210            ChangeValueInner::Shielded { .. } => false,
211            #[cfg(feature = "transparent-inputs")]
212            ChangeValueInner::EphemeralTransparent { .. } => true,
213            #[cfg(feature = "transparent-inputs")]
214            ChangeValueInner::Transparent { .. } => false,
215        }
216    }
217}
218
219/// Orchard actions in a canonical ZIP 318 crossing: the spend and its change, or a padding dummy
220/// when the note's value exactly covers the crossing and its fee.
221#[cfg(feature = "orchard")]
222const CANONICAL_CROSSING_ORCHARD_ACTIONS: usize = 2;
223
224/// Ironwood actions in a canonical ZIP 318 crossing: the single unpadded output.
225#[cfg(feature = "orchard")]
226const CANONICAL_CROSSING_IRONWOOD_ACTIONS: usize = 1;
227
228/// The canonical ZIP 318 crossing's fee under the ZIP 317 marginal fee in effect at
229/// `target_height` ([`zip317::marginal_fee`]): what the STANDARD ZIP 317 rule charges the
230/// canonical shape, 15 000 zatoshis before the fee reduction of ZIP 2009 takes effect and 3 000
231/// from then on.
232///
233/// ZIP 318 requires this exact fee. Any other value partitions the anonymity set, so a transaction
234/// paying a non-standard fee is not a canonical crossing however well its structure matches. The
235/// standard rule is used rather than the caller's: a proposal built on a fixed non-standard rule
236/// would otherwise be compared against its own fee and always agree.
237///
238/// [`zip317::marginal_fee`]: zcash_primitives::transaction::fees::zip317::marginal_fee
239#[cfg(feature = "orchard")]
240pub fn canonical_crossing_fee<P: consensus::Parameters>(
241    params: &P,
242    target_height: BlockHeight,
243) -> Result<Zatoshis, zcash_primitives::transaction::fees::zip317::FeeError> {
244    prim_zip317::FeeRule::standard().fee_required(
245        params,
246        target_height,
247        std::iter::empty::<InputSize>(),
248        std::iter::empty::<usize>(),
249        0,
250        0,
251        CANONICAL_CROSSING_ORCHARD_ACTIONS,
252        CANONICAL_CROSSING_IRONWOOD_ACTIONS,
253    )
254}
255
256/// The amount of change and fees required to make a transaction's inputs and
257/// outputs balance under a specific fee rule, as computed by a particular
258/// [`ChangeStrategy`] that is aware of that rule.
259#[derive(Clone, Debug, PartialEq, Eq)]
260pub struct TransactionBalance {
261    proposed_change: Vec<ChangeValue>,
262    fee_required: Zatoshis,
263
264    // A cache for the sum of proposed change and fee; we compute it on construction anyway, so we
265    // cache the resulting value.
266    total: Zatoshis,
267
268    // The exact number of dummy outputs in each shielded bundle this balance was costed for.
269    // `None` is retained for compatibility with callers and serialized proposals that predate
270    // explicit transaction-shape modelling.
271    dummy_outputs: Option<DummyOutputCounts>,
272}
273
274/// The number of dummy outputs in each shielded value pool.
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276pub struct DummyOutputCounts {
277    sapling: usize,
278    #[cfg(feature = "orchard")]
279    orchard: usize,
280    #[cfg(feature = "orchard")]
281    ironwood: usize,
282}
283
284impl DummyOutputCounts {
285    /// Constructs per-pool dummy-output counts.
286    pub fn new(
287        sapling: usize,
288        #[cfg(feature = "orchard")] orchard: usize,
289        #[cfg(feature = "orchard")] ironwood: usize,
290    ) -> Self {
291        Self {
292            sapling,
293            #[cfg(feature = "orchard")]
294            orchard,
295            #[cfg(feature = "orchard")]
296            ironwood,
297        }
298    }
299
300    /// Returns the number of Sapling dummy outputs.
301    pub fn sapling(&self) -> usize {
302        self.sapling
303    }
304
305    /// Returns the number of Orchard dummy outputs.
306    #[cfg(feature = "orchard")]
307    pub fn orchard(&self) -> usize {
308        self.orchard
309    }
310
311    /// Returns the number of Ironwood dummy outputs.
312    #[cfg(feature = "orchard")]
313    pub fn ironwood(&self) -> usize {
314        self.ironwood
315    }
316}
317
318impl TransactionBalance {
319    /// Constructs a new balance from its constituent parts.
320    pub fn new(
321        proposed_change: Vec<ChangeValue>,
322        fee_required: Zatoshis,
323    ) -> Result<Self, BalanceError> {
324        let total = proposed_change
325            .iter()
326            .map(|c| c.value())
327            .chain(Some(fee_required))
328            .sum::<Option<Zatoshis>>()
329            .ok_or(BalanceError::Overflow)?;
330
331        Ok(Self {
332            proposed_change,
333            fee_required,
334            total,
335            dummy_outputs: None,
336        })
337    }
338
339    /// Records the exact dummy-output counts this balance was computed for.
340    pub fn with_dummy_outputs(mut self, dummy_outputs: DummyOutputCounts) -> Self {
341        self.dummy_outputs = Some(dummy_outputs);
342        self
343    }
344
345    /// Returns the exact dummy-output counts this balance was computed for, when recorded.
346    pub fn dummy_outputs(&self) -> Option<DummyOutputCounts> {
347        self.dummy_outputs
348    }
349
350    /// The change values proposed by the [`ChangeStrategy`] that computed this balance.
351    pub fn proposed_change(&self) -> &[ChangeValue] {
352        &self.proposed_change
353    }
354
355    /// Returns the fee computed for the transaction, assuming that the suggested
356    /// change outputs are added to the transaction.
357    pub fn fee_required(&self) -> Zatoshis {
358        self.fee_required
359    }
360
361    /// Returns the sum of the proposed change outputs and the required fee.
362    pub fn total(&self) -> Zatoshis {
363        self.total
364    }
365}
366
367/// Errors that can occur in computing suggested change and/or fees.
368#[derive(Clone, Debug, PartialEq, Eq)]
369#[non_exhaustive]
370pub enum ChangeError<E, NoteRefT> {
371    /// Insufficient inputs were provided to change selection to fund the
372    /// required outputs and fees.
373    InsufficientFunds {
374        /// The total of the inputs provided to change selection
375        available: Zatoshis,
376        /// The total amount of input value required to fund the requested outputs,
377        /// including the required fees.
378        required: Zatoshis,
379    },
380    /// Some of the inputs provided to the transaction have value less than the
381    /// marginal fee, and could not be determined to have any economic value in
382    /// the context of this input selection.
383    ///
384    /// This determination is potentially conservative in the sense that inputs
385    /// with value less than or equal to the marginal fee might be excluded, even
386    /// though in practice they would not cause the fee to increase. Inputs with
387    /// value greater than the marginal fee will never be excluded.
388    ///
389    /// The ordering of the inputs in each list is unspecified.
390    DustInputs {
391        /// The outpoints for transparent inputs that could not be determined to
392        /// have economic value in the context of this input selection.
393        transparent: Vec<OutPoint>,
394        /// The identifiers for Sapling inputs that could not be determined to
395        /// have economic value in the context of this input selection.
396        sapling: Vec<NoteRefT>,
397        /// The identifiers for Orchard inputs that could not be determined to
398        /// have economic value in the context of this input selection.
399        #[cfg(feature = "orchard")]
400        orchard: Vec<NoteRefT>,
401        /// The identifiers for Ironwood inputs that could not be determined to
402        /// have economic value in the context of this input selection.
403        #[cfg(feature = "orchard")]
404        ironwood: Vec<NoteRefT>,
405    },
406    /// The change strategy would send change to a pool in which the account cannot receive
407    /// it: the account's viewing key cannot derive an address in that pool (for an ephemeral
408    /// transparent output, a P2PKH address).
409    UnsupportedChangePool(PoolType),
410    /// An error occurred that was specific to the change selection strategy in use.
411    StrategyError(E),
412    /// The proposed bundle structure would violate bundle type construction rules.
413    BundleError(&'static str),
414}
415
416impl<CE: fmt::Display, N: fmt::Display> fmt::Display for ChangeError<CE, N> {
417    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
418        match &self {
419            ChangeError::InsufficientFunds {
420                available,
421                required,
422            } => write!(
423                f,
424                "Insufficient funds: required {} zatoshis, but only {} zatoshis were available.",
425                u64::from(*required),
426                u64::from(*available)
427            ),
428            ChangeError::DustInputs {
429                transparent,
430                sapling,
431                #[cfg(feature = "orchard")]
432                orchard,
433                #[cfg(feature = "orchard")]
434                ironwood,
435            } => {
436                #[cfg(feature = "orchard")]
437                let orchard_len = orchard.len() + ironwood.len();
438                #[cfg(not(feature = "orchard"))]
439                let orchard_len = 0;
440
441                // we can't encode the UA to its string representation because we
442                // don't have network parameters here
443                write!(
444                    f,
445                    "Insufficient funds: {} dust inputs were present, but would cost more to spend than they are worth.",
446                    transparent.len() + sapling.len() + orchard_len,
447                )
448            }
449            ChangeError::UnsupportedChangePool(pool) => {
450                write!(f, "The account cannot receive change in the {pool} pool.")
451            }
452            ChangeError::StrategyError(err) => {
453                write!(f, "{err}")
454            }
455            ChangeError::BundleError(err) => {
456                write!(
457                    f,
458                    "The proposed transaction structure violates bundle type constraints: {err}"
459                )
460            }
461        }
462    }
463}
464
465impl<E, N> std::error::Error for ChangeError<E, N>
466where
467    E: Debug + Display + std::error::Error + 'static,
468    N: Debug + Display + 'static,
469{
470    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
471        match &self {
472            ChangeError::StrategyError(e) => Some(e),
473            _ => None,
474        }
475    }
476}
477
478/// An enumeration of actions to take when a transaction would potentially create dust
479/// outputs (outputs that are likely to be without economic value due to fee rules).
480#[derive(Clone, Copy, Debug, PartialEq, Eq)]
481pub enum DustAction {
482    /// Do not allow creation of dust outputs; instead, require that additional inputs be provided.
483    Reject,
484    /// Explicitly allow the creation of dust change amounts greater than the specified value.
485    AllowDustChange,
486    /// Allow dust amounts to be added to the transaction fee.
487    AddDustToFee,
488}
489
490/// A policy describing how a [`ChangeStrategy`] should treat potentially dust-valued change
491/// outputs (outputs that are likely to be without economic value due to fee rules).
492#[derive(Clone, Copy, Debug, PartialEq, Eq)]
493pub struct DustOutputPolicy {
494    action: DustAction,
495    dust_threshold: Option<Zatoshis>,
496}
497
498impl DustOutputPolicy {
499    /// Constructs a new dust output policy.
500    ///
501    /// A dust policy created with `None` as the dust threshold will delegate determination
502    /// of the dust threshold to the change strategy that is evaluating the strategy; this
503    /// is recommended, but an explicit value (including zero) may be provided to explicitly
504    /// override the determination of the change strategy.
505    pub fn new(action: DustAction, dust_threshold: Option<Zatoshis>) -> Self {
506        Self {
507            action,
508            dust_threshold,
509        }
510    }
511
512    /// Returns the action to take in the event that a dust change amount would be produced.
513    pub fn action(&self) -> DustAction {
514        self.action
515    }
516    /// Returns a value that will be used to override the dust determination logic of the
517    /// change policy, if any.
518    pub fn dust_threshold(&self) -> Option<Zatoshis> {
519        self.dust_threshold
520    }
521}
522
523impl Default for DustOutputPolicy {
524    fn default() -> Self {
525        DustOutputPolicy::new(DustAction::Reject, None)
526    }
527}
528
529/// A policy that describes how change output should be split into multiple notes for the purpose
530/// of note management.
531///
532/// If an account contains at least [`Self::target_output_count`] notes having at least value
533/// [`Self::min_split_output_value`], this policy will recommend a single output; if the account
534/// contains fewer such notes, this policy will recommend that multiple outputs be produced in
535/// order to achieve the target.
536#[derive(Clone, Copy, Debug)]
537pub struct SplitPolicy {
538    target_output_count: NonZeroUsize,
539    min_split_output_value: Option<Zatoshis>,
540}
541
542impl SplitPolicy {
543    /// The number of ZIP 317 marginal fees in the default "minimum usable note value".
544    const MIN_NOTE_VALUE_MARGINAL_FEES: u64 = 100;
545
546    /// In the case that no other conditions provided by the user are available to fall back on,
547    /// [`MIN_NOTE_VALUE_MARGINAL_FEES`] times the ZIP 317 marginal fee in effect at
548    /// `target_height` will be used as the "minimum usable note value" when retrieving wallet
549    /// metadata.
550    ///
551    /// [`MIN_NOTE_VALUE_MARGINAL_FEES`]: Self::MIN_NOTE_VALUE_MARGINAL_FEES
552    pub(crate) fn min_note_value<P: consensus::Parameters>(
553        params: &P,
554        target_height: TargetHeight,
555    ) -> Zatoshis {
556        (prim_zip317::marginal_fee(params, target_height.into())
557            * Self::MIN_NOTE_VALUE_MARGINAL_FEES)
558            .expect("a hundred marginal fees cannot overflow")
559    }
560
561    /// Constructs a new [`SplitPolicy`] that splits change to ensure the given number of spendable
562    /// outputs exists within an account, each having at least the specified minimum note value.
563    pub fn with_min_output_value(
564        target_output_count: NonZeroUsize,
565        min_split_output_value: Zatoshis,
566    ) -> Self {
567        Self {
568            target_output_count,
569            min_split_output_value: Some(min_split_output_value),
570        }
571    }
572
573    /// Constructs a [`SplitPolicy`] that prescribes a single output (no splitting).
574    pub fn single_output() -> Self {
575        Self {
576            target_output_count: NonZeroUsize::MIN,
577            min_split_output_value: None,
578        }
579    }
580
581    /// Returns the number of outputs that this policy will attempt to ensure that the wallet has
582    /// available for spending.
583    pub fn target_output_count(&self) -> NonZeroUsize {
584        self.target_output_count
585    }
586
587    /// Returns the minimum value for a note resulting from splitting of change.
588    pub fn min_split_output_value(&self) -> Option<Zatoshis> {
589        self.min_split_output_value
590    }
591
592    /// Returns the number of output notes to produce from the given total change value, given the
593    /// total value and number of existing unspent notes in the account and this policy.
594    ///
595    /// If splitting change to produce [`Self::target_output_count`] would result in notes of value
596    /// less than [`Self::min_split_output_value`], then this will suggest a smaller number of
597    /// splits so that each resulting change note has sufficient value.
598    pub fn split_count(
599        &self,
600        existing_notes: Option<usize>,
601        existing_notes_total: Option<Zatoshis>,
602        total_change: Zatoshis,
603    ) -> NonZeroUsize {
604        fn to_nonzero_u64(value: usize) -> NonZeroU64 {
605            NonZeroU64::new(u64::try_from(value).expect("usize fits into u64"))
606                .expect("NonZeroU64 input derived from NonZeroUsize")
607        }
608
609        let mut split_count = NonZeroUsize::new(
610            usize::from(self.target_output_count)
611                .saturating_sub(existing_notes.unwrap_or(usize::MAX)),
612        )
613        .unwrap_or(NonZeroUsize::MIN);
614
615        let min_split_output_value = self.min_split_output_value.or_else(|| {
616            // If no minimum split output size is set, we choose the minimum split size to be a
617            // quarter of the average value of notes in the wallet after the transaction.
618            (existing_notes_total + total_change).map(|total| {
619                *total
620                    .div_with_remainder(to_nonzero_u64(
621                        usize::from(self.target_output_count).saturating_mul(4),
622                    ))
623                    .quotient()
624            })
625        });
626
627        if let Some(min_split_output_value) = min_split_output_value {
628            loop {
629                let per_output_change =
630                    total_change.div_with_remainder(to_nonzero_u64(usize::from(split_count)));
631                if *per_output_change.quotient() >= min_split_output_value {
632                    return split_count;
633                } else if let Some(new_count) = NonZeroUsize::new(usize::from(split_count) - 1) {
634                    split_count = new_count;
635                } else {
636                    // We always create at least one change output.
637                    return NonZeroUsize::MIN;
638                }
639            }
640        } else {
641            NonZeroUsize::MIN
642        }
643    }
644}
645
646/// `EphemeralBalance` describes the ephemeral input or output value for a transaction. It is used
647/// in fee computation for series of transactions that use an ephemeral transparent output in an
648/// intermediate step, such as when sending from a shielded pool to a [ZIP 320] "TEX" address.
649///
650/// [ZIP 320]: https://zips.z.cash/zip-0320
651#[derive(Clone, Copy, Debug, PartialEq, Eq)]
652pub enum EphemeralBalance {
653    Input(Zatoshis),
654    Output(Zatoshis),
655}
656
657impl EphemeralBalance {
658    pub fn is_input(&self) -> bool {
659        matches!(self, EphemeralBalance::Input(_))
660    }
661
662    pub fn is_output(&self) -> bool {
663        matches!(self, EphemeralBalance::Output(_))
664    }
665
666    pub fn ephemeral_input_amount(&self) -> Option<Zatoshis> {
667        match self {
668            EphemeralBalance::Input(v) => Some(*v),
669            EphemeralBalance::Output(_) => None,
670        }
671    }
672
673    pub fn ephemeral_output_amount(&self) -> Option<Zatoshis> {
674        match self {
675            EphemeralBalance::Input(_) => None,
676            EphemeralBalance::Output(v) => Some(*v),
677        }
678    }
679}
680
681/// A trait that defines a set of types used in wallet metadata retrieval. Ordinarily, this will
682/// correspond to a type that implements [`InputSource`], and a blanket implementation of this
683/// trait is provided for all types that implement [`InputSource`].
684///
685/// If more capabilities are required of the backend than are exposed in the [`InputSource`] trait,
686/// the implementer of this trait should define their own trait that descends from [`InputSource`]
687/// and adds the required capabilities there, and then implement that trait for their desired
688/// database backend.
689pub trait MetaSource {
690    type Error;
691    type AccountId;
692    type NoteRef;
693
694    /// Returns the outputs in which the given account can receive change.
695    fn change_receivers(&self, account: Self::AccountId) -> Result<ChangeReceivers, Self::Error>;
696}
697
698impl MetaSource for Infallible {
699    type Error = Infallible;
700    type AccountId = Infallible;
701    type NoteRef = Infallible;
702
703    fn change_receivers(&self, account: Infallible) -> Result<ChangeReceivers, Infallible> {
704        match account {}
705    }
706}
707
708impl<I: InputSource> MetaSource for I {
709    type Error = I::Error;
710    type AccountId = I::AccountId;
711    type NoteRef = I::NoteRef;
712
713    fn change_receivers(&self, account: I::AccountId) -> Result<ChangeReceivers, I::Error> {
714        self.get_change_receivers(account)
715    }
716}
717
718/// A trait that represents the ability to compute the suggested change and fees that must be paid
719/// by a transaction having a specified set of inputs and outputs.
720pub trait ChangeStrategy {
721    type FeeRule: FeeRule + Clone;
722    type Error: From<<Self::FeeRule as FeeRule>::Error>;
723
724    /// The type of metadata source that this change strategy requires in order to be able to
725    /// retrieve required wallet metadata.
726    type MetaSource: MetaSource;
727
728    /// Tye type of wallet metadata that this change strategy relies upon in order to compute
729    /// change.
730    type AccountMetaT;
731
732    /// Returns the fee rule that this change strategy will respect when performing
733    /// balance computations.
734    fn fee_rule(&self) -> &Self::FeeRule;
735
736    /// Uses the provided metadata source to obtain the wallet metadata required for change
737    /// creation determinations, for a transaction on the network `params` expected to be mined
738    /// at `target_height`.
739    fn fetch_wallet_meta<P: consensus::Parameters>(
740        &self,
741        params: &P,
742        meta_source: &Self::MetaSource,
743        account: <Self::MetaSource as MetaSource>::AccountId,
744        target_height: TargetHeight,
745        exclude: &[<Self::MetaSource as MetaSource>::NoteRef],
746    ) -> Result<Self::AccountMetaT, <Self::MetaSource as MetaSource>::Error>;
747
748    /// Computes the totals of inputs, suggested change amounts, and fees given the
749    /// provided inputs and outputs being used to construct a transaction.
750    ///
751    /// The fee computed as part of this operation should take into account the prospective
752    /// change outputs recommended by this operation. If insufficient funds are available to
753    /// supply the requested outputs and required fees, implementations should return
754    /// [`ChangeError::InsufficientFunds`], with a `required` value that exceeds the total
755    /// value of the inputs provided.
756    ///
757    /// If the inputs include notes or UTXOs that are not economic to spend in the context
758    /// of this input selection, a [`ChangeError::DustInputs`] error can be returned
759    /// indicating inputs that should be removed from the selection (all of which will
760    /// have value less than or equal to the marginal fee). Every input it names must be
761    /// one of the inputs provided, and it must name at least one. The caller should order
762    /// the inputs from most to least preferred to spend within each pool, so that the most
763    /// preferred ones are less likely to be indicated to remove.
764    ///
765    /// - `ironwood`: the Ironwood bundle view (behind the `orchard` feature). A V6
766    ///   transaction carries a separate Ironwood bundle, distinct from `orchard`,
767    ///   with its own action count; pass an empty view when nothing targets the
768    ///   Ironwood pool.
769    /// - `ephemeral_balance`: if the transaction is to be constructed with either an
770    ///   ephemeral transparent input or an ephemeral transparent output this argument
771    ///   may be used to provide the value of that input or output. The value of this
772    ///   argument should be `None` in the case that there are no such items.
773    /// - `wallet_meta`: Additional wallet metadata that the change strategy may use
774    ///   in determining how to construct change outputs. This wallet metadata value
775    ///   should be computed excluding the inputs provided in the `transparent_inputs`,
776    ///   `sapling`, `orchard`, and `ironwood` arguments.
777    ///
778    /// [ZIP 320]: https://zips.z.cash/zip-0320
779    #[allow(clippy::too_many_arguments)]
780    fn compute_balance<P: consensus::Parameters, NoteRefT: Clone>(
781        &self,
782        params: &P,
783        target_height: TargetHeight,
784        anchor_height: BlockHeight,
785        zip318: &PoolMigrationParams,
786        transparent_inputs: &[impl transparent::InputView],
787        transparent_outputs: &[impl transparent::OutputView],
788        sapling: &impl sapling::BundleView<NoteRefT>,
789        #[cfg(feature = "orchard")] orchard: &impl orchard::BundleView<NoteRefT>,
790        #[cfg(feature = "orchard")] ironwood: &impl orchard::BundleView<NoteRefT>,
791        ephemeral_balance: Option<EphemeralBalance>,
792        wallet_meta: &Self::AccountMetaT,
793    ) -> Result<TransactionBalance, ChangeError<Self::Error, NoteRefT>>;
794}
795
796#[cfg(test)]
797pub(crate) mod tests {
798    use core::iter;
799
800    use ::transparent::bundle::{OutPoint, TxOut};
801    use zcash_keys::keys::UnifiedSpendingKey;
802    use zcash_primitives::transaction::fees::{
803        FeeRule as _,
804        transparent::{self, InputSize},
805        zip317::{GRACE_ACTIONS, minimum_fee},
806    };
807    use zcash_protocol::{
808        consensus::{Network, NetworkUpgrade, Parameters},
809        value::Zatoshis,
810    };
811
812    use crate::{
813        data_api::{ChangeReceivers, testing::pool::nu7_activating_network},
814        fees::{SplitPolicy, StandardFeeRule, zip317::Zip317FeeRule as _},
815    };
816
817    #[cfg(feature = "orchard")]
818    use zcash_primitives::transaction::fees::zip317::marginal_fee;
819
820    /// The seed of the account of [`all_change_receivers`].
821    const ALL_RECEIVERS_SEED: [u8; 32] = [0; 32];
822
823    /// Returns the change receivers of an account that has a key in every pool.
824    pub(crate) fn all_change_receivers() -> ChangeReceivers {
825        ChangeReceivers::from_uivk(
826            &UnifiedSpendingKey::from_seed(
827                &Network::TestNetwork,
828                &ALL_RECEIVERS_SEED,
829                zip32::AccountId::ZERO,
830            )
831            .unwrap()
832            .to_unified_full_viewing_key()
833            .to_unified_incoming_viewing_key(),
834        )
835    }
836
837    /// The standard rule, the marginal fee it exposes, and the canonical ZIP 318 crossing fee all
838    /// follow the ZIP 317 schedule at the target height. The literal values are deliberate pins:
839    /// a change to the marginal fee or to the canonical shape surfaces here rather than silently
840    /// reclassifying transactions.
841    #[test]
842    fn zip317_rule_charges_fee_in_effect_at_target_height() {
843        /// The marginal fee before the fee reduction of ZIP 2009 takes effect.
844        const PRE_REDUCTION_MARGINAL_FEE: Zatoshis = Zatoshis::const_from_u64(5_000);
845        /// The marginal fee from the fee reduction onward.
846        const REDUCED_MARGINAL_FEE: Zatoshis = Zatoshis::const_from_u64(1_000);
847
848        // On a regtest network the fee reduction takes effect at NU7 activation.
849        let network = nu7_activating_network();
850        let from = network
851            .activation_height(NetworkUpgrade::Nu7)
852            .expect("the test network activates NU7");
853        let before = from - 1;
854
855        // A transaction of exactly `GRACE_ACTIONS` Orchard actions pays the minimum fee at
856        // either side of the boundary.
857        let fee_at = |height| {
858            StandardFeeRule::Zip317
859                .fee_required(
860                    &network,
861                    height,
862                    iter::empty::<InputSize>(),
863                    iter::empty::<usize>(),
864                    0,
865                    0,
866                    GRACE_ACTIONS,
867                    0,
868                )
869                .expect("a valid input to the ZIP 317 rule")
870        };
871        assert_eq!(fee_at(before), minimum_fee(&network, before));
872        assert_eq!(u64::from(fee_at(before)), 10_000);
873        assert_eq!(fee_at(from), minimum_fee(&network, from));
874        assert_eq!(u64::from(fee_at(from)), 2_000);
875
876        assert_eq!(
877            StandardFeeRule::Zip317.marginal_fee(&network, before.into()),
878            PRE_REDUCTION_MARGINAL_FEE
879        );
880        assert_eq!(
881            StandardFeeRule::Zip317.marginal_fee(&network, from.into()),
882            REDUCED_MARGINAL_FEE
883        );
884
885        // The default minimum usable note value is a hundred marginal fees.
886        assert_eq!(
887            u64::from(SplitPolicy::min_note_value(&network, before.into())),
888            500_000
889        );
890        assert_eq!(
891            u64::from(SplitPolicy::min_note_value(&network, from.into())),
892            100_000
893        );
894
895        #[cfg(feature = "orchard")]
896        {
897            /// The number of logical actions in a canonical ZIP 318 crossing: two Orchard
898            /// actions plus one unpadded Ironwood action, which together exceed the grace
899            /// allowance.
900            const CANONICAL_CROSSING_ACTIONS: u64 = 3;
901
902            let crossing_fee = |height| {
903                super::canonical_crossing_fee(&network, height)
904                    .expect("the canonical shape is a valid input to the ZIP 317 rule")
905            };
906            assert_eq!(
907                crossing_fee(before),
908                (marginal_fee(&network, before) * CANONICAL_CROSSING_ACTIONS).unwrap()
909            );
910            assert_eq!(u64::from(crossing_fee(before)), 15_000);
911            assert_eq!(
912                crossing_fee(from),
913                (marginal_fee(&network, from) * CANONICAL_CROSSING_ACTIONS).unwrap()
914            );
915            assert_eq!(u64::from(crossing_fee(from)), 3_000);
916        }
917    }
918
919    use super::sapling;
920
921    #[derive(Debug)]
922    pub(crate) struct TestTransparentInput {
923        pub outpoint: OutPoint,
924        pub coin: TxOut<Zatoshis>,
925    }
926
927    impl transparent::InputView for TestTransparentInput {
928        fn outpoint(&self) -> &OutPoint {
929            &self.outpoint
930        }
931        fn coin(&self) -> &TxOut<Zatoshis> {
932            &self.coin
933        }
934    }
935
936    pub(crate) struct TestSaplingInput {
937        pub note_id: u32,
938        pub value: Zatoshis,
939    }
940
941    impl sapling::InputView<u32> for TestSaplingInput {
942        fn note_id(&self) -> &u32 {
943            &self.note_id
944        }
945        fn value(&self) -> Zatoshis {
946            self.value
947        }
948    }
949
950    #[cfg(feature = "orchard")]
951    pub(crate) struct TestOrchardInput {
952        pub note_id: u32,
953        pub value: Zatoshis,
954    }
955
956    #[cfg(feature = "orchard")]
957    impl super::orchard::InputView<u32> for TestOrchardInput {
958        fn note_id(&self) -> &u32 {
959            &self.note_id
960        }
961        fn value(&self) -> Zatoshis {
962            self.value
963        }
964    }
965}