Skip to main content

zcash_client_backend/fees/
common.rs

1use core::cmp::{Ordering, max, min};
2use std::num::{NonZeroU64, NonZeroUsize};
3
4#[cfg(feature = "orchard")]
5use zcash_primitives::transaction::builder::BundlePadding;
6use zcash_primitives::transaction::fees::{
7    FeeRule, transparent,
8    zip317::{P2PKH_STANDARD_OUTPUT_SIZE, minimum_fee},
9};
10#[cfg(feature = "orchard")]
11use zcash_protocol::zip318::PoolMigrationConstants;
12
13use crate::data_api::anchor_retention::PoolMigrationParams;
14use zcash_protocol::{
15    PoolType, ShieldedPool,
16    consensus::{self, BlockHeight, NetworkUpgrade},
17    memo::MemoBytes,
18    value::{BalanceError, Zatoshis},
19};
20
21use crate::data_api::{AccountMeta, ChangeReceivers, wallet::TargetHeight};
22
23use super::{
24    ChangeError, ChangeValue, DummyOutputCounts, DustAction, DustOutputPolicy, EphemeralBalance,
25    SplitPolicy, TransactionBalance, sapling as sapling_fees,
26};
27
28#[cfg(feature = "orchard")]
29use super::orchard::{self as orchard_fees, OutputView as _};
30#[cfg(feature = "transparent-inputs")]
31use {super::TransparentChangePolicy, crate::data_api::TransparentChangeKind};
32
33/// The most dust [`DustAction::AddDustToFee`] folds into the fee, as a multiple of the ZIP 317
34/// minimum fee in effect at the target height; change above this cap is kept as a change output
35/// so that a mis-set dust threshold cannot burn more than this as fee.
36pub(crate) const DUST_TO_FEE_CAP_MINIMUM_FEES: u64 = 10;
37
38pub(crate) struct NetFlows {
39    t_in: Zatoshis,
40    t_out: Zatoshis,
41    sapling_in: Zatoshis,
42    sapling_out: Zatoshis,
43    orchard_in: Zatoshis,
44    orchard_out: Zatoshis,
45    // Value flowing through the Ironwood bundle, accounted separately from
46    // Orchard because V6 transactions carry distinct Orchard and Ironwood
47    // bundles. Splitting output value between the Orchard and Ironwood views
48    // leaves `total_in`/`total_out` unchanged; the separate fields exist so each
49    // bundle's action count can be derived from its own inputs and outputs.
50    ironwood_in: Zatoshis,
51    ironwood_out: Zatoshis,
52}
53
54impl NetFlows {
55    fn total_in(&self) -> Result<Zatoshis, BalanceError> {
56        (self.t_in + self.sapling_in + self.orchard_in + self.ironwood_in)
57            .ok_or(BalanceError::Overflow)
58    }
59    fn total_out(&self) -> Result<Zatoshis, BalanceError> {
60        (self.t_out + self.sapling_out + self.orchard_out + self.ironwood_out)
61            .ok_or(BalanceError::Overflow)
62    }
63    /// Returns true iff the flows excluding change are fully transparent.
64    fn is_transparent(&self) -> bool {
65        !(self.sapling_in.is_positive()
66            || self.sapling_out.is_positive()
67            || self.orchard_in.is_positive()
68            || self.orchard_out.is_positive()
69            || self.ironwood_in.is_positive()
70            || self.ironwood_out.is_positive())
71    }
72}
73
74#[allow(clippy::too_many_arguments)]
75pub(crate) fn calculate_net_flows<NoteRefT: Clone, F: FeeRule, E>(
76    transparent_inputs: &[impl transparent::InputView],
77    transparent_outputs: &[impl transparent::OutputView],
78    sapling: &impl sapling_fees::BundleView<NoteRefT>,
79    #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
80    #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
81    ephemeral_balance: Option<EphemeralBalance>,
82) -> Result<NetFlows, ChangeError<E, NoteRefT>>
83where
84    E: From<F::Error> + From<BalanceError>,
85{
86    let overflow = || ChangeError::StrategyError(E::from(BalanceError::Overflow));
87
88    let t_in = transparent_inputs
89        .iter()
90        .map(|t_in| t_in.coin().value())
91        .chain(ephemeral_balance.and_then(|b| b.ephemeral_input_amount()))
92        .sum::<Option<_>>()
93        .ok_or_else(overflow)?;
94    let t_out = transparent_outputs
95        .iter()
96        .map(|t_out| t_out.value())
97        .chain(ephemeral_balance.and_then(|b| b.ephemeral_output_amount()))
98        .sum::<Option<_>>()
99        .ok_or_else(overflow)?;
100    let sapling_in = sapling
101        .inputs()
102        .iter()
103        .map(sapling_fees::InputView::<NoteRefT>::value)
104        .sum::<Option<_>>()
105        .ok_or_else(overflow)?;
106    let sapling_out = sapling
107        .outputs()
108        .iter()
109        .map(sapling_fees::OutputView::value)
110        .sum::<Option<_>>()
111        .ok_or_else(overflow)?;
112
113    #[cfg(feature = "orchard")]
114    let orchard_in = orchard
115        .inputs()
116        .iter()
117        .map(orchard_fees::InputView::<NoteRefT>::value)
118        .sum::<Option<_>>()
119        .ok_or_else(overflow)?;
120    #[cfg(not(feature = "orchard"))]
121    let orchard_in = Zatoshis::ZERO;
122
123    #[cfg(feature = "orchard")]
124    let orchard_out = orchard
125        .outputs()
126        .iter()
127        .map(orchard_fees::OutputView::value)
128        .sum::<Option<_>>()
129        .ok_or_else(overflow)?;
130    #[cfg(not(feature = "orchard"))]
131    let orchard_out = Zatoshis::ZERO;
132
133    #[cfg(feature = "orchard")]
134    let ironwood_in = ironwood
135        .inputs()
136        .iter()
137        .map(orchard_fees::InputView::<NoteRefT>::value)
138        .sum::<Option<_>>()
139        .ok_or_else(overflow)?;
140    #[cfg(not(feature = "orchard"))]
141    let ironwood_in = Zatoshis::ZERO;
142
143    #[cfg(feature = "orchard")]
144    let ironwood_out = ironwood
145        .outputs()
146        .iter()
147        .map(orchard_fees::OutputView::value)
148        .sum::<Option<_>>()
149        .ok_or_else(overflow)?;
150    #[cfg(not(feature = "orchard"))]
151    let ironwood_out = Zatoshis::ZERO;
152
153    Ok(NetFlows {
154        t_in,
155        t_out,
156        sapling_in,
157        sapling_out,
158        orchard_in,
159        orchard_out,
160        ironwood_in,
161        ironwood_out,
162    })
163}
164
165/// Decide which shielded pool change should go to if there is any.
166///
167/// Change goes to a pool in which the account can receive it, as given by
168/// `change_receivers`. Among those pools, the pools that the transaction already uses
169/// come first, so that change does not cross into another pool when this can be
170/// avoided. The fallback pool comes next, and then any other pool. If the account cannot
171/// receive change in any shielded pool, the result is the pool that the transaction's
172/// flows indicate, and the caller rejects any change that it would place there.
173///
174/// `max_change_value` is an upper bound on the value of the change the transaction will
175/// produce: the value that would remain if it paid only the minimum (changeless) fee.
176/// After Ironwood activation it determines whether change may be returned to the Orchard
177/// pool without violating the turnstile requirement that the pool's balance strictly
178/// decrease.
179pub(crate) fn select_change_pool(
180    _net_flows: &NetFlows,
181    _fallback_change_pool: ShieldedPool,
182    _change_receivers: &ChangeReceivers,
183    _ironwood_active: bool,
184    _max_change_value: Zatoshis,
185) -> ShieldedPool {
186    // TODO: implement a less naive strategy for selecting the pool to which change will be sent.
187    #[cfg(feature = "orchard")]
188    {
189        // The pools with flows in this transaction, in order of preference. Orchard comes
190        // first. Ironwood comes before Sapling, so that change from an Ironwood spend stays
191        // in the Ironwood pool rather than crossing the turnstile back into Orchard.
192        let flow_pools = [
193            (
194                ShieldedPool::Orchard,
195                _net_flows.orchard_in.is_positive() || _net_flows.orchard_out.is_positive(),
196            ),
197            (
198                ShieldedPool::Ironwood,
199                _net_flows.ironwood_in.is_positive() || _net_flows.ironwood_out.is_positive(),
200            ),
201            (
202                ShieldedPool::Sapling,
203                _net_flows.sapling_in.is_positive() || _net_flows.sapling_out.is_positive(),
204            ),
205        ]
206        .into_iter()
207        .filter_map(|(pool, has_flows)| has_flows.then_some(pool));
208
209        // If the flows are transparent, there may not be change. If there is, the caller
210        // gets to decide where to shield it.
211        let flow_preferred = flow_pools.clone().next().unwrap_or(_fallback_change_pool);
212
213        let preferred = flow_pools
214            .chain([
215                _fallback_change_pool,
216                ShieldedPool::Orchard,
217                ShieldedPool::Sapling,
218            ])
219            .find(|pool| _change_receivers.can_receive(PoolType::Shielded(*pool)))
220            .unwrap_or(flow_preferred);
221
222        // After Ironwood activation, the turnstile forbids value from entering the
223        // Orchard pool: change may return to Orchard only when the transaction spends
224        // Orchard notes, and only if strictly less value returns to the pool than the
225        // notes remove from it. Change that cannot go to Orchard flows onward to the
226        // Ironwood pool. An account that can receive change in one of these pools can
227        // receive change in the other, as both use the account's Orchard key.
228        if _ironwood_active
229            && preferred == ShieldedPool::Orchard
230            && (!_net_flows.orchard_in.is_positive() || _max_change_value >= _net_flows.orchard_in)
231        {
232            ShieldedPool::Ironwood
233        } else {
234            preferred
235        }
236    }
237    #[cfg(not(feature = "orchard"))]
238    ShieldedPool::Sapling
239}
240
241#[derive(Clone, Copy, Debug)]
242pub(crate) struct OutputManifest {
243    transparent: usize,
244    sapling: usize,
245    orchard: usize,
246    ironwood: usize,
247}
248
249impl OutputManifest {
250    const ZERO: OutputManifest = OutputManifest {
251        transparent: 0,
252        sapling: 0,
253        orchard: 0,
254        ironwood: 0,
255    };
256
257    pub(crate) fn sapling(&self) -> usize {
258        self.sapling
259    }
260
261    pub(crate) fn orchard(&self) -> usize {
262        self.orchard
263    }
264
265    pub(crate) fn ironwood(&self) -> usize {
266        self.ironwood
267    }
268
269    #[cfg(feature = "orchard")]
270    pub(crate) fn transparent(&self) -> usize {
271        self.transparent
272    }
273
274    pub(crate) fn total_shielded(&self) -> usize {
275        self.sapling + self.orchard + self.ironwood
276    }
277
278    /// A manifest placing `count` change outputs in `pool` and none elsewhere.
279    fn for_pool(pool: ShieldedPool, count: usize) -> Self {
280        Self {
281            transparent: 0,
282            sapling: if pool == ShieldedPool::Sapling {
283                count
284            } else {
285                0
286            },
287            orchard: if pool == ShieldedPool::Orchard {
288                count
289            } else {
290                0
291            },
292            ironwood: if pool == ShieldedPool::Ironwood {
293                count
294            } else {
295                0
296            },
297        }
298    }
299}
300
301pub(crate) struct SinglePoolBalanceConfig<'a, P, F> {
302    params: &'a P,
303    fee_rule: &'a F,
304    dust_output_policy: &'a DustOutputPolicy,
305    default_dust_threshold: Zatoshis,
306    split_policy: &'a SplitPolicy,
307    fallback_change_pool: ShieldedPool,
308    #[cfg(feature = "transparent-inputs")]
309    transparent_change_policy: TransparentChangePolicy,
310    marginal_fee: Zatoshis,
311    grace_actions: usize,
312}
313
314impl<'a, P, F> SinglePoolBalanceConfig<'a, P, F> {
315    #[allow(clippy::too_many_arguments)]
316    pub(crate) fn new(
317        params: &'a P,
318        fee_rule: &'a F,
319        dust_output_policy: &'a DustOutputPolicy,
320        default_dust_threshold: Zatoshis,
321        split_policy: &'a SplitPolicy,
322        fallback_change_pool: ShieldedPool,
323        #[cfg(feature = "transparent-inputs")] transparent_change_policy: TransparentChangePolicy,
324        marginal_fee: Zatoshis,
325        grace_actions: usize,
326    ) -> Self {
327        Self {
328            params,
329            fee_rule,
330            dust_output_policy,
331            default_dust_threshold,
332            split_policy,
333            fallback_change_pool,
334            #[cfg(feature = "transparent-inputs")]
335            transparent_change_policy,
336            marginal_fee,
337            grace_actions,
338        }
339    }
340}
341
342#[allow(clippy::too_many_arguments)]
343pub(crate) fn single_pool_output_balance<P: consensus::Parameters, NoteRefT: Clone, F: FeeRule, E>(
344    cfg: SinglePoolBalanceConfig<P, F>,
345    wallet_meta: Option<&AccountMeta>,
346    change_receivers: &ChangeReceivers,
347    target_height: TargetHeight,
348    transparent_inputs: &[impl transparent::InputView],
349    transparent_outputs: &[impl transparent::OutputView],
350    sapling: &impl sapling_fees::BundleView<NoteRefT>,
351    #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
352    #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
353    // The transactional bundle padding the transaction builder will use for the Orchard and
354    // Ironwood bundles respectively; the action counts computed here must match them so the
355    // builder's exact-balance check succeeds (see `orchard_fees::transactional_action_count`).
356    //
357    // This is `BundlePadding` rather than `BundleType` deliberately: coinbase construction is a
358    // property of the whole transaction, never of one pool, and a fee is never computed for a
359    // coinbase transaction at all. Carrying padding keeps a per-pool coinbase unrepresentable, as
360    // `BuildConfig::Standard` does for the builder.
361    //
362    // There is no matching Ironwood parameter. That bundle's padding is DERIVED from the
363    // transaction's shape (see `ironwood_is_canonical_crossing` below), not chosen by the caller.
364    #[cfg(feature = "orchard")] orchard_padding: BundlePadding,
365    // The anchor the shielded bundles will be proved against, and the ZIP 318 parameters in force
366    // for the wallet proposing the transaction. A canonical crossing must be anchored to a
367    // boundary of the bucket grid, so the padding decision depends on both. The grid comes from
368    // the wallet rather than the network defaults: the wallet is the side that retains the
369    // checkpoints, so its grid is the only one a crossing can actually be proved against.
370    _anchor_height: BlockHeight,
371    _zip318: &PoolMigrationParams,
372    change_memo: Option<&MemoBytes>,
373    ephemeral_balance: Option<EphemeralBalance>,
374) -> Result<TransactionBalance, ChangeError<E, NoteRefT>>
375where
376    E: From<F::Error> + From<BalanceError>,
377{
378    // The change memo, if any, must be attached to the change in the intermediate step that
379    // produces the ephemeral output, and so it should be discarded in the ultimate step; this is
380    // distinguished by identifying that this transaction has ephemeral inputs.
381    let change_memo = change_memo.filter(|_| ephemeral_balance.is_none_or(|b| !b.is_input()));
382
383    let overflow = || ChangeError::StrategyError(E::from(BalanceError::Overflow));
384    let underflow = || ChangeError::StrategyError(E::from(BalanceError::Underflow));
385
386    let net_flows = calculate_net_flows::<NoteRefT, F, E>(
387        transparent_inputs,
388        transparent_outputs,
389        sapling,
390        #[cfg(feature = "orchard")]
391        orchard,
392        #[cfg(feature = "orchard")]
393        ironwood,
394        ephemeral_balance,
395    )?;
396
397    // We don't create a fully-transparent transaction if a change memo is used.
398    let fully_transparent = net_flows.is_transparent() && change_memo.is_none();
399
400    // Whether change should be returned to the transparent pool instead of being shielded.
401    // Transparent change is only ever produced when the flows of the transaction are fully
402    // transparent, so that shielded flows never leak change information to the transparent
403    // pool.
404    #[cfg(feature = "transparent-inputs")]
405    let wants_transparent_change = fully_transparent
406        && cfg.transparent_change_policy == TransparentChangePolicy::TransparentChangeAllowed;
407    #[cfg(not(feature = "transparent-inputs"))]
408    let wants_transparent_change = false;
409
410    // The size of the transparent change output, which depends on the kind of address the
411    // account receives it at. An account with no transparent receiver has no size here. Any
412    // transparent change proposed for such an account is rejected below, when the change is
413    // known. An earlier rejection would hide insufficient funds and changeless transactions.
414    #[cfg(feature = "transparent-inputs")]
415    let transparent_change_size = change_receivers
416        .transparent()
417        .filter(|_| wants_transparent_change)
418        .map(|kind| kind.output_size());
419    #[cfg(not(feature = "transparent-inputs"))]
420    let transparent_change_size = None;
421
422    let total_in = net_flows
423        .total_in()
424        .map_err(|e| ChangeError::StrategyError(E::from(e)))?;
425    let subtotal_out = net_flows
426        .total_out()
427        .map_err(|e| ChangeError::StrategyError(E::from(e)))?;
428
429    let sapling_input_count = sapling
430        .bundle_type()
431        .num_spends(sapling.inputs().len())
432        .map_err(ChangeError::BundleError)?;
433    let sapling_output_count = |change_count| {
434        sapling
435            .bundle_type()
436            .num_outputs(
437                sapling.inputs().len(),
438                sapling.outputs().len() + change_count,
439            )
440            .map_err(ChangeError::BundleError)
441    };
442
443    #[cfg(feature = "orchard")]
444    let orchard_action_count = |change_count| {
445        orchard_fees::transactional_action_count(
446            orchard_padding.bundle_type(),
447            orchard.bundle_version(),
448            orchard.inputs().len(),
449            orchard.outputs().len() + change_count,
450        )
451        .map_err(ChangeError::BundleError)
452    };
453    #[cfg(not(feature = "orchard"))]
454    let orchard_action_count = |change_count: usize| -> Result<usize, ChangeError<E, NoteRefT>> {
455        if change_count != 0 {
456            Err(ChangeError::BundleError(
457                "Nonzero Orchard change requested but the `orchard` feature is not enabled.",
458            ))
459        } else {
460            Ok(0)
461        }
462    };
463
464    // The Ironwood bundle is accounted separately from Orchard: a V6 transaction
465    // carries distinct Orchard and Ironwood bundles, each padded to its own
466    // action floor. Callers route Ironwood inputs/outputs into the `ironwood`
467    // view; it is empty (contributing no actions) when nothing targets the
468    // Ironwood pool.
469    //
470    // A CANONICAL CROSSING drops the default padding: no Ironwood spends and a single Ironwood
471    // output whose value is a canonical ZIP 318 denomination, which is exactly the shape of a
472    // ZIP 318 migration transfer. Building it unpadded puts an ordinary turnstile-crossing
473    // payment into that anonymity set rather than leaving it distinguishable by action count.
474    // The resulting dummy-output count is recorded below. `Step::ironwood_bundle_padding`
475    // reconstructs the builder's action target from that finished transaction shape.
476    //
477    // The value is only known here when the sole output is a PAYMENT, i.e. `change_count == 0`;
478    // an Ironwood change value is what this function is in the middle of solving for. That costs
479    // nothing: with a change output there are two real Ironwood outputs, so the bundle is at or
480    // above the default floor and the padding is irrelevant.
481    #[cfg(feature = "orchard")]
482    let ironwood_is_canonical_crossing = |change: OutputManifest| {
483        let constants = _zip318;
484        orchard.inputs().len() == 1
485            && ironwood.inputs().is_empty()
486            && change.ironwood() == 0
487            // The Orchard bundle must be exactly two actions, and from NU6.3 a spend and an output
488            // no longer share one; a second Orchard change output would make three. Change in any
489            // other pool adds a bundle no migration transfer carries. `Step::is_canonical_crossing`
490            // applies the identical bounds, and the two must agree or the builder's exact-balance
491            // check rejects the transaction.
492            && change.orchard() <= 1
493            && change.sapling() == 0
494            && change.transparent() == 0
495            && match ironwood.outputs() {
496                [output] => constants.is_canonical_denomination(output.value()),
497                _ => false,
498            }
499            && constants
500                .anchor_grid().is_boundary(_anchor_height)
501    };
502    #[cfg(feature = "orchard")]
503    let ironwood_action_count = |change: OutputManifest| {
504        // The Ironwood bundle drops its padding exactly when doing so makes the transaction look
505        // like a migration transfer, and is padded otherwise. This is not the caller's to choose.
506        let padding = if ironwood_is_canonical_crossing(change) {
507            BundlePadding::UNPADDED
508        } else {
509            BundlePadding::DEFAULT
510        };
511        orchard_fees::transactional_action_count(
512            padding.bundle_type(),
513            ironwood.bundle_version(),
514            ironwood.inputs().len(),
515            ironwood.outputs().len() + change.ironwood(),
516        )
517        .map_err(ChangeError::BundleError)
518    };
519    #[cfg(not(feature = "orchard"))]
520    let ironwood_action_count =
521        |change: OutputManifest| -> Result<usize, ChangeError<E, NoteRefT>> {
522            if change.ironwood() != 0 {
523                Err(ChangeError::BundleError(
524                    "Nonzero Ironwood change requested but the `orchard` feature is not enabled.",
525                ))
526            } else {
527                Ok(0)
528            }
529        };
530
531    let transparent_input_sizes = transparent_inputs
532        .iter()
533        .map(|i| i.serialized_size())
534        .chain(
535            ephemeral_balance
536                .and_then(|b| b.ephemeral_input_amount())
537                .map(|_| transparent::InputSize::STANDARD_P2PKH),
538        );
539    let transparent_output_sizes = transparent_outputs
540        .iter()
541        .map(|i| i.serialized_size())
542        .chain(
543            ephemeral_balance
544                .and_then(|b| b.ephemeral_output_amount())
545                .map(|_| P2PKH_STANDARD_OUTPUT_SIZE),
546        );
547
548    // Once we calculate the balance with minimum fee (i.e. with no change),
549    // there are three cases:
550    //
551    // 1. Insufficient funds even with minimum fee.
552    // 2. The minimum fee exactly cancels out the net flow balance.
553    // 3. The minimum fee is smaller than the change.
554    //
555    // If case 2 happens for a transaction with any shielded flows, we want there
556    // to be a zero-value shielded change output anyway (i.e. treat this like case 3),
557    // because:
558    // * being able to distinguish these cases potentially leaks too much
559    //   information (an adversary that knows the number of external recipients
560    //   and the sum of their outputs learns the sum of the inputs if no change
561    //   output is present); and
562    // * we will then always have an shielded output in which to put change_memo,
563    //   if one is used.
564    //
565    // Note that using the `DustAction::AddDustToFee` policy inherently leaks
566    // more information.
567
568    let min_fee = cfg
569        .fee_rule
570        .fee_required(
571            cfg.params,
572            BlockHeight::from(target_height),
573            transparent_input_sizes.clone(),
574            transparent_output_sizes.clone(),
575            sapling_input_count,
576            sapling_output_count(0)?,
577            orchard_action_count(0)?,
578            ironwood_action_count(OutputManifest::ZERO)?,
579        )
580        .map_err(|fee_error| ChangeError::StrategyError(E::from(fee_error)))?;
581
582    let total_out_with_min_fee = (subtotal_out + min_fee).ok_or_else(overflow)?;
583
584    // The value that would remain if the transaction paid only the minimum (changeless)
585    // fee is an upper bound on the change value: the fee never falls below `min_fee`.
586    let change_pool = select_change_pool(
587        &net_flows,
588        cfg.fallback_change_pool,
589        change_receivers,
590        cfg.params
591            .is_nu_active(NetworkUpgrade::Nu6_3, target_height.into()),
592        (total_in - total_out_with_min_fee).unwrap_or(Zatoshis::ZERO),
593    );
594
595    let (target_change_count, target_change_counts) = if wants_transparent_change {
596        // Transparent change is always emitted as a single output; the note-splitting policy
597        // exists to improve the spendability of shielded notes and does not apply to
598        // transparent outputs.
599        (
600            1,
601            OutputManifest {
602                transparent: 1,
603                sapling: 0,
604                orchard: 0,
605                ironwood: 0,
606            },
607        )
608    } else {
609        let target_change_count = wallet_meta.map_or(1, |m| {
610            usize::from(cfg.split_policy.target_output_count)
611                // If we cannot determine a total note count, fall back to a single output
612                .saturating_sub(m.total_note_count().unwrap_or(usize::MAX))
613                .max(1)
614        });
615        let target_change_counts = OutputManifest {
616            transparent: 0,
617            sapling: if change_pool == ShieldedPool::Sapling {
618                target_change_count
619            } else {
620                0
621            },
622            orchard: if change_pool == ShieldedPool::Orchard {
623                target_change_count
624            } else {
625                0
626            },
627            ironwood: if change_pool == ShieldedPool::Ironwood {
628                target_change_count
629            } else {
630                0
631            },
632        };
633        assert!(target_change_counts.total_shielded() == target_change_count);
634        (target_change_count, target_change_counts)
635    };
636
637    // If we have a non-zero marginal fee, we need to check for uneconomic inputs.
638    // This is basically assuming that fee rules with non-zero marginal fee are
639    // "ZIP 317-like", but we can generalize later if needed.
640    if cfg.marginal_fee.is_positive() {
641        // Is it certain that there will be a change output? If it is not certain,
642        // we should call `check_for_uneconomic_inputs` with `possible_change`
643        // including both possibilities.
644        let possible_change = {
645            // These are the situations where we might not have a change output.
646            if fully_transparent
647                || (cfg.dust_output_policy.action() == DustAction::AddDustToFee
648                    && change_memo.is_none())
649            {
650                vec![OutputManifest::ZERO, target_change_counts]
651            } else {
652                vec![target_change_counts]
653            }
654        };
655
656        check_for_uneconomic_inputs(
657            transparent_inputs,
658            transparent_outputs,
659            sapling,
660            #[cfg(feature = "orchard")]
661            orchard,
662            #[cfg(feature = "orchard")]
663            ironwood,
664            #[cfg(feature = "orchard")]
665            orchard_padding,
666            #[cfg(feature = "orchard")]
667            _anchor_height,
668            #[cfg(feature = "orchard")]
669            _zip318,
670            cfg.marginal_fee,
671            cfg.grace_actions,
672            &possible_change[..],
673            ephemeral_balance,
674        )?;
675    }
676
677    #[allow(unused_mut)]
678    let (mut change, fee) = match total_in.cmp(&total_out_with_min_fee) {
679        Ordering::Less => {
680            // Case 1. Insufficient input value exists to pay the minimum fee; there's no way
681            // we can construct the transaction.
682            return Err(ChangeError::InsufficientFunds {
683                available: total_in,
684                required: total_out_with_min_fee,
685            });
686        }
687        Ordering::Equal if fully_transparent => {
688            // Case 2 for a tx with all transparent flows and no change memo
689            // (e.g. the second transaction of a ZIP 320 pair).
690            (vec![], min_fee)
691        }
692        _ => {
693            let max_fee = max(
694                min_fee,
695                cfg.fee_rule
696                    .fee_required(
697                        cfg.params,
698                        BlockHeight::from(target_height),
699                        transparent_input_sizes.clone(),
700                        transparent_output_sizes
701                            .clone()
702                            // Count the change output when change is to be returned to the
703                            // transparent pool.
704                            .chain(transparent_change_size),
705                        sapling_input_count,
706                        sapling_output_count(target_change_counts.sapling())?,
707                        orchard_action_count(target_change_counts.orchard())?,
708                        ironwood_action_count(target_change_counts)?,
709                    )
710                    .map_err(|fee_error| ChangeError::StrategyError(E::from(fee_error)))?,
711            );
712
713            let total_out_with_max_fee = (subtotal_out + max_fee).ok_or_else(overflow)?;
714
715            // We obtain a split count based on the total number of notes of sufficient size
716            // available in the wallet, irrespective of pool. If we don't have any wallet metadata
717            // available, we fall back to generating a single change output. Transparent change is
718            // always emitted as a single output.
719            let split_count = if wants_transparent_change {
720                1
721            } else {
722                usize::from(wallet_meta.map_or(NonZeroUsize::MIN, |wm| {
723                    cfg.split_policy.split_count(
724                        wm.total_note_count(),
725                        wm.total_value(),
726                        // We use a saturating subtraction here because there may be insufficient funds to pay
727                        // the fee, *if* the requested number of split outputs are created. If there is no
728                        // proposed change, the split policy should recommend only a single change output.
729                        (total_in - total_out_with_max_fee).unwrap_or(Zatoshis::ZERO),
730                    )
731                }))
732            };
733
734            // If we don't have as many change outputs as we expected, recompute the fee.
735            let total_fee = if split_count < target_change_count {
736                cfg.fee_rule
737                    .fee_required(
738                        cfg.params,
739                        BlockHeight::from(target_height),
740                        transparent_input_sizes,
741                        transparent_output_sizes,
742                        sapling_input_count,
743                        sapling_output_count(if change_pool == ShieldedPool::Sapling {
744                            split_count
745                        } else {
746                            0
747                        })?,
748                        orchard_action_count(if change_pool == ShieldedPool::Orchard {
749                            split_count
750                        } else {
751                            0
752                        })?,
753                        ironwood_action_count(OutputManifest::for_pool(change_pool, split_count))?,
754                    )
755                    .map_err(|fee_error| ChangeError::StrategyError(E::from(fee_error)))?
756            } else {
757                max_fee
758            };
759
760            let total_out = (subtotal_out + total_fee).ok_or_else(overflow)?;
761            let total_change =
762                (total_in - total_out).ok_or_else(|| ChangeError::InsufficientFunds {
763                    available: total_in,
764                    required: total_out,
765                })?;
766
767            let per_output_change = total_change.div_with_remainder(
768                NonZeroU64::new(u64::try_from(split_count).expect("usize fits into u64")).unwrap(),
769            );
770            let simple_case = || {
771                #[cfg(feature = "transparent-inputs")]
772                if wants_transparent_change {
773                    return (
774                        if total_change.is_zero() {
775                            // A zero-valued transparent output would be unspendable, so we omit
776                            // it. Unlike the shielded change case, omitting the output does not
777                            // reveal additional information, because transparent output values
778                            // are already publicly visible.
779                            vec![]
780                        } else {
781                            vec![ChangeValue::transparent(total_change)]
782                        },
783                        total_fee,
784                    );
785                }
786
787                (
788                    (0usize..split_count)
789                        .map(|i| {
790                            ChangeValue::shielded(
791                                change_pool,
792                                if i == 0 {
793                                    // Add any remainder to the first output only
794                                    (*per_output_change.quotient() + *per_output_change.remainder())
795                                        .unwrap()
796                                } else {
797                                    // For any other output, the change value will just be the
798                                    // quotient.
799                                    *per_output_change.quotient()
800                                },
801                                change_memo.cloned(),
802                            )
803                        })
804                        .collect(),
805                    total_fee,
806                )
807            };
808
809            let change_dust_threshold = cfg
810                .dust_output_policy
811                .dust_threshold()
812                .unwrap_or(cfg.default_dust_threshold);
813
814            if total_change < change_dust_threshold {
815                match cfg.dust_output_policy.action() {
816                    DustAction::Reject => {
817                        // Always allow zero-valued change even for the `Reject` policy:
818                        // * it should be allowed in order to record change memos and to improve
819                        //   indistinguishability;
820                        // * this case occurs in practice when sending all funds from an account;
821                        // * zero-valued notes do not require witness tracking;
822                        // * the effect on trial decryption overhead is small.
823                        if total_change.is_zero() {
824                            simple_case()
825                        } else {
826                            let shortfall =
827                                (change_dust_threshold - total_change).ok_or_else(underflow)?;
828
829                            return Err(ChangeError::InsufficientFunds {
830                                available: total_in,
831                                required: (total_in + shortfall).ok_or_else(overflow)?,
832                            });
833                        }
834                    }
835                    DustAction::AllowDustChange => simple_case(),
836                    DustAction::AddDustToFee => {
837                        // Zero-valued change is also always allowed for this policy, but when
838                        // no change memo is given, we might omit the change output instead.
839                        let fee_with_dust = (total_change + total_fee).ok_or_else(overflow)?;
840
841                        let dust_cap = (minimum_fee(cfg.params, target_height.into())
842                            * DUST_TO_FEE_CAP_MINIMUM_FEES)
843                            .ok_or_else(overflow)?;
844                        let reasonable_fee = (total_fee + dust_cap).ok_or_else(overflow)?;
845
846                        if fee_with_dust > reasonable_fee {
847                            // Defend against losing money by using AddDustToFee with a too-high
848                            // dust threshold.
849                            simple_case()
850                        } else if change_memo.is_some() {
851                            (
852                                vec![ChangeValue::shielded(
853                                    change_pool,
854                                    Zatoshis::ZERO,
855                                    change_memo.cloned(),
856                                )],
857                                fee_with_dust,
858                            )
859                        } else {
860                            (vec![], fee_with_dust)
861                        }
862                    }
863                }
864            } else {
865                simple_case()
866            }
867        }
868    };
869
870    #[cfg(feature = "transparent-inputs")]
871    change.extend(
872        ephemeral_balance
873            .and_then(|b| b.ephemeral_output_amount())
874            .map(ChangeValue::ephemeral_transparent),
875    );
876
877    for change_value in &change {
878        if !can_receive_change(change_receivers, change_value) {
879            return Err(ChangeError::UnsupportedChangePool(
880                change_value.output_pool(),
881            ));
882        }
883    }
884
885    // Record the exact number of dummy outputs in each shielded bundle. This is transaction
886    // shape, rather than a builder policy; it can therefore be serialized in a proposal and
887    // reproduced by every construction path without re-running the fee model.
888    let final_change = OutputManifest {
889        transparent: change
890            .iter()
891            .filter(|c| c.output_pool() == PoolType::TRANSPARENT)
892            .count(),
893        sapling: change
894            .iter()
895            .filter(|c| c.output_pool() == PoolType::SAPLING)
896            .count(),
897        orchard: change
898            .iter()
899            .filter(|c| c.output_pool() == PoolType::ORCHARD)
900            .count(),
901        ironwood: change
902            .iter()
903            .filter(|c| c.output_pool() == PoolType::IRONWOOD)
904            .count(),
905    };
906    let sapling_real_outputs = sapling.outputs().len() + final_change.sapling();
907    let sapling_dummy_outputs = sapling_output_count(final_change.sapling())?
908        .checked_sub(sapling_real_outputs)
909        .expect("the Sapling action count includes every real output");
910    #[cfg(feature = "orchard")]
911    let orchard_dummy_outputs = orchard_action_count(final_change.orchard())?
912        .checked_sub(orchard.outputs().len() + final_change.orchard())
913        .expect("the Orchard action count includes every real output");
914    #[cfg(feature = "orchard")]
915    let ironwood_dummy_outputs = ironwood_action_count(final_change)?
916        .checked_sub(ironwood.outputs().len() + final_change.ironwood())
917        .expect("the Ironwood action count includes every real output");
918
919    TransactionBalance::new(change, fee)
920        .map(|balance| {
921            balance.with_dummy_outputs(DummyOutputCounts::new(
922                sapling_dummy_outputs,
923                #[cfg(feature = "orchard")]
924                orchard_dummy_outputs,
925                #[cfg(feature = "orchard")]
926                ironwood_dummy_outputs,
927            ))
928        })
929        .map_err(|_| overflow())
930}
931
932/// Returns whether an account that can receive change in `change_receivers` can receive
933/// `change`. Ephemeral outputs are sent to P2PKH addresses.
934fn can_receive_change(change_receivers: &ChangeReceivers, change: &ChangeValue) -> bool {
935    #[cfg(feature = "transparent-inputs")]
936    if change.is_ephemeral() {
937        return matches!(
938            change_receivers.transparent(),
939            Some(TransparentChangeKind::P2pkh)
940        );
941    }
942    change_receivers.can_receive(change.output_pool())
943}
944
945/// Returns a `[ChangeStrategy::DustInputs]` error if some of the inputs provided
946/// to the transaction have value less than or equal to the marginal fee, and could not be
947/// determined to have any economic value in the context of this input selection.
948///
949/// This determination is potentially conservative in the sense that outputs
950/// with value less than or equal to the marginal fee might be excluded, even though in
951/// practice they would not cause the fee to increase. Outputs with value
952/// greater than the marginal fee will never be excluded.
953///
954/// `possible_change` is a slice of [`OutputManifest`] values indicating possible
955/// combinations of how many change outputs (0 or 1) might be included in the
956/// transaction for each pool. The shape of the manifest does not depend on which
957/// protocol features are enabled.
958#[allow(clippy::too_many_arguments)]
959pub(crate) fn check_for_uneconomic_inputs<NoteRefT: Clone, E>(
960    transparent_inputs: &[impl transparent::InputView],
961    transparent_outputs: &[impl transparent::OutputView],
962    sapling: &impl sapling_fees::BundleView<NoteRefT>,
963    #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
964    #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
965    // The Orchard-pool bundle type the builder will use; the action counts computed
966    // for the grace-input check must match it (see `single_pool_output_balance`).
967    #[cfg(feature = "orchard")] orchard_padding: BundlePadding,
968    #[cfg(feature = "orchard")] anchor_height: BlockHeight,
969    #[cfg(feature = "orchard")] zip318: &PoolMigrationParams,
970    marginal_fee: Zatoshis,
971    grace_actions: usize,
972    possible_change: &[OutputManifest],
973    ephemeral_balance: Option<EphemeralBalance>,
974) -> Result<(), ChangeError<E, NoteRefT>> {
975    let mut t_dust: Vec<_> = transparent_inputs
976        .iter()
977        .filter_map(|i| {
978            // For now, we're just assuming P2PKH inputs, so we don't check the
979            // size of the input script.
980            if i.coin().value() <= marginal_fee {
981                Some(i.outpoint().clone())
982            } else {
983                None
984            }
985        })
986        .collect();
987
988    let mut s_dust: Vec<_> = sapling
989        .inputs()
990        .iter()
991        .filter_map(|i| {
992            if sapling_fees::InputView::<NoteRefT>::value(i) <= marginal_fee {
993                Some(sapling_fees::InputView::<NoteRefT>::note_id(i).clone())
994            } else {
995                None
996            }
997        })
998        .collect();
999
1000    #[cfg(feature = "orchard")]
1001    let mut o_dust: Vec<NoteRefT> = orchard
1002        .inputs()
1003        .iter()
1004        .filter_map(|i| {
1005            if orchard_fees::InputView::<NoteRefT>::value(i) <= marginal_fee {
1006                Some(orchard_fees::InputView::<NoteRefT>::note_id(i).clone())
1007            } else {
1008                None
1009            }
1010        })
1011        .collect();
1012    #[cfg(not(feature = "orchard"))]
1013    let mut o_dust: Vec<NoteRefT> = vec![];
1014
1015    #[cfg(feature = "orchard")]
1016    let mut i_dust: Vec<NoteRefT> = ironwood
1017        .inputs()
1018        .iter()
1019        .filter_map(|i| {
1020            if orchard_fees::InputView::<NoteRefT>::value(i) <= marginal_fee {
1021                Some(orchard_fees::InputView::<NoteRefT>::note_id(i).clone())
1022            } else {
1023                None
1024            }
1025        })
1026        .collect();
1027    #[cfg(not(feature = "orchard"))]
1028    let mut i_dust: Vec<NoteRefT> = vec![];
1029
1030    // If we don't have any dust inputs, there is nothing to check.
1031    if t_dust.is_empty() && s_dust.is_empty() && o_dust.is_empty() && i_dust.is_empty() {
1032        return Ok(());
1033    }
1034
1035    let (t_inputs_len, t_outputs_len) = (
1036        transparent_inputs.len() + usize::from(ephemeral_balance.is_some_and(|b| b.is_input())),
1037        transparent_outputs.len() + usize::from(ephemeral_balance.is_some_and(|b| b.is_output())),
1038    );
1039    let (s_inputs_len, s_outputs_len) = (sapling.inputs().len(), sapling.outputs().len());
1040    #[cfg(feature = "orchard")]
1041    let (o_inputs_len, o_outputs_len) = (orchard.inputs().len(), orchard.outputs().len());
1042    #[cfg(not(feature = "orchard"))]
1043    let (o_inputs_len, o_outputs_len) = (0usize, 0usize);
1044    #[cfg(feature = "orchard")]
1045    let (i_inputs_len, i_outputs_len) = (ironwood.inputs().len(), ironwood.outputs().len());
1046    #[cfg(not(feature = "orchard"))]
1047    let (i_inputs_len, i_outputs_len) = (0usize, 0usize);
1048
1049    let t_non_dust = t_inputs_len.checked_sub(t_dust.len()).unwrap();
1050    let s_non_dust = s_inputs_len.checked_sub(s_dust.len()).unwrap();
1051    let o_non_dust = o_inputs_len.checked_sub(o_dust.len()).unwrap();
1052    let i_non_dust = i_inputs_len.checked_sub(i_dust.len()).unwrap();
1053
1054    // Return the number of allowed dust inputs from each pool.
1055    let allowed_dust = |change: &OutputManifest| {
1056        // Here we assume a "ZIP 317-like" fee model in which the existence of an output
1057        // to a given pool implies that a corresponding input from that pool can be
1058        // provided without increasing the fee. (This is also likely to be true for
1059        // future fee models if we do not want to penalize use of Orchard relative to
1060        // other pools.)
1061        //
1062        // Under that assumption, we want to calculate the maximum number of dust inputs
1063        // from each pool, out of the ones we actually have, that can be economically
1064        // spent along with the non-dust inputs. Get an initial estimate by calculating
1065        // the number of dust inputs in each pool that will be allowed regardless of
1066        // padding or grace.
1067
1068        let t_allowed = min(
1069            t_dust.len(),
1070            (t_outputs_len + change.transparent).saturating_sub(t_non_dust),
1071        );
1072        let s_allowed = min(
1073            s_dust.len(),
1074            (s_outputs_len + change.sapling).saturating_sub(s_non_dust),
1075        );
1076        let o_allowed = min(
1077            o_dust.len(),
1078            (o_outputs_len + change.orchard).saturating_sub(o_non_dust),
1079        );
1080        let i_allowed = min(
1081            i_dust.len(),
1082            (i_outputs_len + change.ironwood).saturating_sub(i_non_dust),
1083        );
1084
1085        // We'll be spending the non-dust and allowed dust in each pool.
1086        let t_req_inputs = t_non_dust + t_allowed;
1087        let s_req_inputs = s_non_dust + s_allowed;
1088        #[cfg(feature = "orchard")]
1089        let o_req_inputs = o_non_dust + o_allowed;
1090        #[cfg(feature = "orchard")]
1091        let i_req_inputs = i_non_dust + i_allowed;
1092
1093        // This calculates the hypothetical number of actions with given extra inputs,
1094        // for ZIP 317 and the padding rules in effect. The padding rules for each
1095        // pool are subtle (they also depend on `bundle_required` for example), so we
1096        // must actually call them rather than try to predict their effect. To tell
1097        // whether we can freely add an extra input from a given pool, we need to call
1098        // them both with and without that input; if the number of actions does not
1099        // increase, then the input is free to add.
1100        let hypothetical_actions = |t_extra, s_extra, _o_extra, _i_extra| {
1101            let s_spend_count = sapling
1102                .bundle_type()
1103                .num_spends(s_req_inputs + s_extra)
1104                .map_err(ChangeError::BundleError)?;
1105
1106            let s_output_count = sapling
1107                .bundle_type()
1108                .num_outputs(s_req_inputs + s_extra, s_outputs_len + change.sapling)
1109                .map_err(ChangeError::BundleError)?;
1110
1111            #[cfg(feature = "orchard")]
1112            let o_action_count = orchard_fees::transactional_action_count(
1113                orchard_padding.bundle_type(),
1114                orchard.bundle_version(),
1115                o_req_inputs + _o_extra,
1116                o_outputs_len + change.orchard,
1117            )
1118            .map_err(ChangeError::BundleError)?;
1119            #[cfg(not(feature = "orchard"))]
1120            let o_action_count = 0;
1121
1122            // The Ironwood padding is derived here on the same rule as in
1123            // `single_pool_output_balance`, over this hypothetical change manifest rather than the
1124            // chosen one, so that the two agree about what each candidate would cost.
1125            #[cfg(feature = "orchard")]
1126            let i_padding = {
1127                let constants = zip318;
1128                let canonical = o_req_inputs + _o_extra == 1
1129                    && i_req_inputs + _i_extra == 0
1130                    && change.ironwood == 0
1131                    && match ironwood.outputs() {
1132                        [output] => constants.is_canonical_denomination(output.value()),
1133                        _ => false,
1134                    }
1135                    && constants.anchor_grid().is_boundary(anchor_height);
1136                if canonical {
1137                    BundlePadding::UNPADDED
1138                } else {
1139                    BundlePadding::DEFAULT
1140                }
1141            };
1142            #[cfg(feature = "orchard")]
1143            let i_action_count = orchard_fees::transactional_action_count(
1144                i_padding.bundle_type(),
1145                ironwood.bundle_version(),
1146                i_req_inputs + _i_extra,
1147                i_outputs_len + change.ironwood,
1148            )
1149            .map_err(ChangeError::BundleError)?;
1150            #[cfg(not(feature = "orchard"))]
1151            let i_action_count = 0;
1152
1153            // To calculate the number of unused actions, we assume that transparent inputs
1154            // and outputs are P2PKH.
1155            Ok(
1156                max(t_req_inputs + t_extra, t_outputs_len + change.transparent)
1157                    + max(s_spend_count, s_output_count)
1158                    + o_action_count
1159                    + i_action_count,
1160            )
1161        };
1162
1163        // First calculate the baseline number of logical actions with only the definitely
1164        // allowed inputs estimated above. If it is less than `grace_actions`, try to allocate
1165        // a grace input first to transparent dust, then to Sapling dust, then to Orchard
1166        // dust, then to Ironwood dust. If the number of actions increases, it was not
1167        // possible to allocate that input for free. This approach is sufficient because at
1168        // most one such input can be allocated, since `grace_actions` is at most 2 for
1169        // ZIP 317 and there must be at least one logical action. (If `grace_actions` were
1170        // greater than 2 then the code would still be correct, it would just not find all
1171        // potential extra inputs.)
1172
1173        let baseline = hypothetical_actions(0, 0, 0, 0)?;
1174
1175        let (t_extra, s_extra, o_extra, i_extra) = if baseline >= grace_actions {
1176            (0, 0, 0, 0)
1177        } else if t_dust.len() > t_allowed && hypothetical_actions(1, 0, 0, 0)? <= baseline {
1178            (1, 0, 0, 0)
1179        } else if s_dust.len() > s_allowed && hypothetical_actions(0, 1, 0, 0)? <= baseline {
1180            (0, 1, 0, 0)
1181        } else if o_dust.len() > o_allowed && hypothetical_actions(0, 0, 1, 0)? <= baseline {
1182            (0, 0, 1, 0)
1183        } else if i_dust.len() > i_allowed && hypothetical_actions(0, 0, 0, 1)? <= baseline {
1184            (0, 0, 0, 1)
1185        } else {
1186            (0, 0, 0, 0)
1187        };
1188        Ok(OutputManifest {
1189            transparent: t_allowed + t_extra,
1190            sapling: s_allowed + s_extra,
1191            orchard: o_allowed + o_extra,
1192            ironwood: i_allowed + i_extra,
1193        })
1194    };
1195
1196    // Find the least number of allowed dust inputs for each pool for any `possible_change`.
1197    let allowed = possible_change
1198        .iter()
1199        .map(allowed_dust)
1200        .collect::<Result<Vec<_>, _>>()?
1201        .into_iter()
1202        .reduce(|l, r| OutputManifest {
1203            transparent: min(l.transparent, r.transparent),
1204            sapling: min(l.sapling, r.sapling),
1205            orchard: min(l.orchard, r.orchard),
1206            ironwood: min(l.ironwood, r.ironwood),
1207        })
1208        .expect("possible_change is nonempty");
1209
1210    // The inputs in the tail of each list after the first `*_allowed` are returned as uneconomic.
1211    // The caller should order the inputs from most to least preferred to spend.
1212    let t_dust = t_dust.split_off(allowed.transparent);
1213    let s_dust = s_dust.split_off(allowed.sapling);
1214    let o_dust = o_dust.split_off(allowed.orchard);
1215    let i_dust = i_dust.split_off(allowed.ironwood);
1216
1217    if t_dust.is_empty() && s_dust.is_empty() && o_dust.is_empty() && i_dust.is_empty() {
1218        Ok(())
1219    } else {
1220        Err(ChangeError::DustInputs {
1221            transparent: t_dust,
1222            sapling: s_dust,
1223            #[cfg(feature = "orchard")]
1224            orchard: o_dust,
1225            #[cfg(feature = "orchard")]
1226            ironwood: i_dust,
1227        })
1228    }
1229}
1230
1231#[cfg(all(test, feature = "orchard"))]
1232mod tests {
1233    use super::{NetFlows, select_change_pool};
1234    use crate::data_api::ChangeReceivers;
1235    use zcash_protocol::{ShieldedPool, value::Zatoshis};
1236
1237    /// Returns the change receivers of an account with the given shielded keys and no
1238    /// transparent key.
1239    fn receivers(sapling: bool, orchard: bool) -> ChangeReceivers {
1240        ChangeReceivers::new(
1241            sapling,
1242            orchard,
1243            #[cfg(feature = "transparent-inputs")]
1244            None,
1245        )
1246    }
1247
1248    /// Returns the change receivers of an account with a key in each shielded pool.
1249    fn all_receivers() -> ChangeReceivers {
1250        receivers(true, true)
1251    }
1252
1253    fn flows(orchard_in: u64, ironwood_in: u64, sapling_in: u64) -> NetFlows {
1254        NetFlows {
1255            t_in: Zatoshis::ZERO,
1256            t_out: Zatoshis::ZERO,
1257            sapling_in: Zatoshis::const_from_u64(sapling_in),
1258            sapling_out: Zatoshis::ZERO,
1259            orchard_in: Zatoshis::const_from_u64(orchard_in),
1260            orchard_out: Zatoshis::ZERO,
1261            ironwood_in: Zatoshis::const_from_u64(ironwood_in),
1262            ironwood_out: Zatoshis::ZERO,
1263        }
1264    }
1265
1266    #[test]
1267    fn select_change_pool_routes_ironwood_spend_to_ironwood() {
1268        // Spending Ironwood funds (no Orchard or Sapling flows) sends change to Ironwood,
1269        // keeping it in the pool being spent rather than crossing back into Orchard.
1270        assert_eq!(
1271            select_change_pool(
1272                &flows(0, 10_000, 0),
1273                ShieldedPool::Sapling,
1274                &all_receivers(),
1275                true,
1276                Zatoshis::const_from_u64(5_000)
1277            ),
1278            ShieldedPool::Ironwood
1279        );
1280
1281        // Spending Orchard funds keeps change in Orchard even when Ironwood funds are also
1282        // spent, so that Ironwood-routed change cannot reveal the spent Orchard notes' balances.
1283        assert_eq!(
1284            select_change_pool(
1285                &flows(10_000, 10_000, 0),
1286                ShieldedPool::Sapling,
1287                &all_receivers(),
1288                true,
1289                Zatoshis::const_from_u64(5_000)
1290            ),
1291            ShieldedPool::Orchard
1292        );
1293
1294        // A combined Sapling + Ironwood spend routes change to Ironwood (Ironwood is preferred
1295        // over Sapling).
1296        assert_eq!(
1297            select_change_pool(
1298                &flows(0, 10_000, 10_000),
1299                ShieldedPool::Sapling,
1300                &all_receivers(),
1301                true,
1302                Zatoshis::const_from_u64(5_000)
1303            ),
1304            ShieldedPool::Ironwood
1305        );
1306
1307        // A Sapling-only spend keeps change in Sapling.
1308        assert_eq!(
1309            select_change_pool(
1310                &flows(0, 0, 10_000),
1311                ShieldedPool::Orchard,
1312                &all_receivers(),
1313                true,
1314                Zatoshis::const_from_u64(5_000)
1315            ),
1316            ShieldedPool::Sapling
1317        );
1318    }
1319
1320    #[test]
1321    fn select_change_pool_enforces_orchard_turnstile() {
1322        // Before Ironwood activation, Orchard-spend change stays in Orchard regardless of
1323        // the change bound: value may freely enter the pool.
1324        assert_eq!(
1325            select_change_pool(
1326                &flows(10_000, 0, 10_000),
1327                ShieldedPool::Sapling,
1328                &all_receivers(),
1329                false,
1330                Zatoshis::const_from_u64(15_000)
1331            ),
1332            ShieldedPool::Orchard
1333        );
1334
1335        // After activation, change may return to Orchard while the pool balance strictly
1336        // decreases: the change bound is below the Orchard input value.
1337        assert_eq!(
1338            select_change_pool(
1339                &flows(10_000, 0, 10_000),
1340                ShieldedPool::Sapling,
1341                &all_receivers(),
1342                true,
1343                Zatoshis::const_from_u64(9_999)
1344            ),
1345            ShieldedPool::Orchard
1346        );
1347
1348        // After activation, change that could equal or exceed the Orchard input value would
1349        // grow the pool, so it flows onward to Ironwood instead.
1350        assert_eq!(
1351            select_change_pool(
1352                &flows(10_000, 0, 10_000),
1353                ShieldedPool::Sapling,
1354                &all_receivers(),
1355                true,
1356                Zatoshis::const_from_u64(10_000)
1357            ),
1358            ShieldedPool::Ironwood
1359        );
1360
1361        // A post-activation Orchard fallback for transparent-only flows is corrected to
1362        // Ironwood: with no Orchard inputs, no value may enter the Orchard pool.
1363        assert_eq!(
1364            select_change_pool(
1365                &NetFlows {
1366                    t_in: Zatoshis::const_from_u64(10_000),
1367                    t_out: Zatoshis::ZERO,
1368                    sapling_in: Zatoshis::ZERO,
1369                    sapling_out: Zatoshis::ZERO,
1370                    orchard_in: Zatoshis::ZERO,
1371                    orchard_out: Zatoshis::ZERO,
1372                    ironwood_in: Zatoshis::ZERO,
1373                    ironwood_out: Zatoshis::ZERO,
1374                },
1375                ShieldedPool::Orchard,
1376                &all_receivers(),
1377                true,
1378                Zatoshis::const_from_u64(10_000)
1379            ),
1380            ShieldedPool::Ironwood
1381        );
1382    }
1383
1384    #[test]
1385    fn select_change_pool_uses_a_pool_the_account_can_receive() {
1386        let orchard_out = |sapling_in: u64, orchard_out: u64| NetFlows {
1387            sapling_in: Zatoshis::const_from_u64(sapling_in),
1388            orchard_out: Zatoshis::const_from_u64(orchard_out),
1389            ..flows(0, 0, 0)
1390        };
1391
1392        // A Sapling-only account that pays an Orchard recipient from Sapling notes gets
1393        // Sapling change, not Orchard change.
1394        assert_eq!(
1395            select_change_pool(
1396                &orchard_out(10_000, 5_000),
1397                ShieldedPool::Orchard,
1398                &receivers(true, false),
1399                false,
1400                Zatoshis::const_from_u64(4_000)
1401            ),
1402            ShieldedPool::Sapling
1403        );
1404
1405        // An Orchard-only account that spends Sapling notes gets Orchard change before
1406        // Ironwood activation.
1407        assert_eq!(
1408            select_change_pool(
1409                &flows(0, 0, 10_000),
1410                ShieldedPool::Sapling,
1411                &receivers(false, true),
1412                false,
1413                Zatoshis::const_from_u64(5_000)
1414            ),
1415            ShieldedPool::Orchard
1416        );
1417
1418        // After activation, that change cannot enter the Orchard pool, so it goes to the
1419        // Ironwood pool, which uses the same key.
1420        assert_eq!(
1421            select_change_pool(
1422                &flows(0, 0, 10_000),
1423                ShieldedPool::Sapling,
1424                &receivers(false, true),
1425                true,
1426                Zatoshis::const_from_u64(5_000)
1427            ),
1428            ShieldedPool::Ironwood
1429        );
1430
1431        // For transparent flows, a fallback pool that the account cannot receive in is
1432        // replaced by one that it can receive in.
1433        let transparent_flows = NetFlows {
1434            t_in: Zatoshis::const_from_u64(10_000),
1435            ..flows(0, 0, 0)
1436        };
1437        assert_eq!(
1438            select_change_pool(
1439                &transparent_flows,
1440                ShieldedPool::Orchard,
1441                &receivers(true, false),
1442                true,
1443                Zatoshis::const_from_u64(5_000)
1444            ),
1445            ShieldedPool::Sapling
1446        );
1447
1448        // An account that can receive in no shielded pool gets the pool that the flows
1449        // indicate. The caller rejects change that would go there.
1450        assert_eq!(
1451            select_change_pool(
1452                &orchard_out(10_000, 5_000),
1453                ShieldedPool::Sapling,
1454                &receivers(false, false),
1455                false,
1456                Zatoshis::const_from_u64(4_000)
1457            ),
1458            ShieldedPool::Orchard
1459        );
1460    }
1461}