Skip to main content

zcash_client_backend/fees/
zip317.rs

1//! Change strategies designed to implement the ZIP 317 fee rules.
2//!
3//! Change selection in ZIP 317 requires careful handling of low-valued inputs
4//! to ensure that inputs added to a transaction do not cause fees to rise by
5//! an amount greater than their value.
6
7use core::marker::PhantomData;
8
9use zcash_primitives::transaction::fees::{FeeRule, transparent, zip317 as prim_zip317};
10use zcash_protocol::{
11    ShieldedPool,
12    consensus::{self, BlockHeight},
13    memo::MemoBytes,
14    value::{BalanceError, Zatoshis},
15};
16
17use crate::{
18    data_api::{
19        AccountMeta, ChangeReceivers, InputSource, NoteFilter,
20        anchor_retention::PoolMigrationParams,
21        wallet::{
22            TargetHeight,
23            input_selection::{LockFilter, LockedInputPolicy},
24        },
25    },
26    fees::StandardFeeRule,
27};
28
29use super::{
30    ChangeError, ChangeStrategy, DustOutputPolicy, EphemeralBalance, MetaSource, SplitPolicy,
31    TransactionBalance,
32    common::{SinglePoolBalanceConfig, single_pool_output_balance},
33    sapling as sapling_fees,
34};
35
36#[cfg(feature = "transparent-inputs")]
37use super::TransparentChangePolicy;
38#[cfg(feature = "orchard")]
39use {super::orchard as orchard_fees, zcash_primitives::transaction::builder::BundlePadding};
40
41/// An extension to the [`FeeRule`] trait that exposes methods required for
42/// ZIP 317 fee calculation.
43pub trait Zip317FeeRule: FeeRule {
44    /// Returns the ZIP 317 marginal fee in effect for a transaction expected to be mined at
45    /// `target_height`.
46    fn marginal_fee<P: consensus::Parameters>(
47        &self,
48        params: &P,
49        target_height: TargetHeight,
50    ) -> Zatoshis;
51
52    /// Returns the ZIP 317 number of grace actions
53    fn grace_actions(&self) -> usize;
54}
55
56impl Zip317FeeRule for prim_zip317::FeeRule {
57    fn marginal_fee<P: consensus::Parameters>(
58        &self,
59        params: &P,
60        target_height: TargetHeight,
61    ) -> Zatoshis {
62        prim_zip317::FeeRule::marginal_fee(self, params, target_height.into())
63    }
64
65    fn grace_actions(&self) -> usize {
66        self.grace_actions()
67    }
68}
69
70impl Zip317FeeRule for StandardFeeRule {
71    fn marginal_fee<P: consensus::Parameters>(
72        &self,
73        params: &P,
74        target_height: TargetHeight,
75    ) -> Zatoshis {
76        prim_zip317::marginal_fee(params, target_height.into())
77    }
78
79    fn grace_actions(&self) -> usize {
80        prim_zip317::FeeRule::standard().grace_actions()
81    }
82}
83
84/// A change strategy that proposes change as a single output. The output pool is chosen
85/// as the most current pool that avoids unnecessary pool-crossing (with a specified
86/// fallback when the transaction has no shielded inputs). Fee calculation is delegated
87/// to the provided fee rule.
88pub struct SingleOutputChangeStrategy<R, I> {
89    fee_rule: R,
90    change_memo: Option<MemoBytes>,
91    fallback_change_pool: ShieldedPool,
92    dust_output_policy: DustOutputPolicy,
93    #[cfg(feature = "transparent-inputs")]
94    transparent_change_policy: TransparentChangePolicy,
95    meta_source: PhantomData<I>,
96}
97
98impl<R, I> SingleOutputChangeStrategy<R, I> {
99    /// Constructs a new [`SingleOutputChangeStrategy`] with the specified ZIP 317
100    /// fee parameters and change memo.
101    ///
102    /// `fallback_change_pool` is used when more than one shielded pool is enabled via
103    /// feature flags, and the transaction has no shielded inputs.
104    pub fn new(
105        fee_rule: R,
106        change_memo: Option<MemoBytes>,
107        fallback_change_pool: ShieldedPool,
108        dust_output_policy: DustOutputPolicy,
109    ) -> Self {
110        Self {
111            fee_rule,
112            change_memo,
113            fallback_change_pool,
114            dust_output_policy,
115            #[cfg(feature = "transparent-inputs")]
116            transparent_change_policy: TransparentChangePolicy::ShieldChange,
117            meta_source: PhantomData,
118        }
119    }
120
121    /// Sets the [`TransparentChangePolicy`] to be used by this change strategy, determining
122    /// whether change may be returned to the transparent pool when the flows of the transaction
123    /// under construction are fully transparent.
124    ///
125    /// The default is [`TransparentChangePolicy::ShieldChange`]. This policy has no effect on
126    /// transactions that involve any shielded flows.
127    #[cfg(feature = "transparent-inputs")]
128    pub fn with_transparent_change_policy(
129        mut self,
130        transparent_change_policy: TransparentChangePolicy,
131    ) -> Self {
132        self.transparent_change_policy = transparent_change_policy;
133        self
134    }
135}
136
137impl<R, I> ChangeStrategy for SingleOutputChangeStrategy<R, I>
138where
139    R: Zip317FeeRule + Clone,
140    I: MetaSource,
141    <R as FeeRule>::Error: From<BalanceError>,
142{
143    type FeeRule = R;
144    type Error = <R as FeeRule>::Error;
145    type MetaSource = I;
146    type AccountMetaT = ChangeReceivers;
147
148    fn fee_rule(&self) -> &Self::FeeRule {
149        &self.fee_rule
150    }
151
152    fn fetch_wallet_meta<P: consensus::Parameters>(
153        &self,
154        _params: &P,
155        meta_source: &Self::MetaSource,
156        account: <Self::MetaSource as MetaSource>::AccountId,
157        _target_height: TargetHeight,
158        _exclude: &[<Self::MetaSource as MetaSource>::NoteRef],
159    ) -> Result<Self::AccountMetaT, <Self::MetaSource as MetaSource>::Error> {
160        meta_source.change_receivers(account)
161    }
162
163    fn compute_balance<P: consensus::Parameters, NoteRefT: Clone>(
164        &self,
165        params: &P,
166        target_height: TargetHeight,
167        anchor_height: BlockHeight,
168        zip318: &PoolMigrationParams,
169        transparent_inputs: &[impl transparent::InputView],
170        transparent_outputs: &[impl transparent::OutputView],
171        sapling: &impl sapling_fees::BundleView<NoteRefT>,
172        #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
173        #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
174        ephemeral_balance: Option<EphemeralBalance>,
175        wallet_meta: &Self::AccountMetaT,
176    ) -> Result<TransactionBalance, ChangeError<Self::Error, NoteRefT>> {
177        let split_policy = SplitPolicy::single_output();
178        let marginal_fee = self.fee_rule.marginal_fee(params, target_height);
179        let cfg = SinglePoolBalanceConfig::new(
180            params,
181            &self.fee_rule,
182            &self.dust_output_policy,
183            marginal_fee,
184            &split_policy,
185            self.fallback_change_pool,
186            #[cfg(feature = "transparent-inputs")]
187            self.transparent_change_policy,
188            marginal_fee,
189            self.fee_rule.grace_actions(),
190        );
191
192        single_pool_output_balance(
193            cfg,
194            None,
195            wallet_meta,
196            target_height,
197            transparent_inputs,
198            transparent_outputs,
199            sapling,
200            #[cfg(feature = "orchard")]
201            orchard,
202            #[cfg(feature = "orchard")]
203            ironwood,
204            // The Orchard bundle is always padded to the default floor. Only the Ironwood
205            // bundle's padding varies, and it is derived from the transaction's shape rather
206            // than chosen here.
207            #[cfg(feature = "orchard")]
208            BundlePadding::DEFAULT,
209            anchor_height,
210            zip318,
211            self.change_memo.as_ref(),
212            ephemeral_balance,
213        )
214    }
215}
216
217/// A change strategy that attempts to split the change value into some number of equal-sized notes
218/// as dictated by the included [`SplitPolicy`] value.
219pub struct MultiOutputChangeStrategy<R, I> {
220    fee_rule: R,
221    change_memo: Option<MemoBytes>,
222    fallback_change_pool: ShieldedPool,
223    dust_output_policy: DustOutputPolicy,
224    split_policy: SplitPolicy,
225    #[cfg(feature = "transparent-inputs")]
226    transparent_change_policy: TransparentChangePolicy,
227    meta_source: PhantomData<I>,
228}
229
230impl<R, I> MultiOutputChangeStrategy<R, I> {
231    /// Constructs a new [`MultiOutputChangeStrategy`] with the specified ZIP 317
232    /// fee parameters, change memo, and change splitting policy.
233    ///
234    /// This change strategy will fall back to creating a single change output if insufficient
235    /// change value is available to create notes with at least the minimum value dictated by the
236    /// split policy.
237    ///
238    /// - `fallback_change_pool`: the pool to which change will be sent if when more than one
239    ///   shielded pool is enabled via feature flags, and the transaction has no shielded inputs.
240    /// - `split_policy`: A policy value describing how the change value should be returned as
241    ///   multiple notes.
242    pub fn new(
243        fee_rule: R,
244        change_memo: Option<MemoBytes>,
245        fallback_change_pool: ShieldedPool,
246        dust_output_policy: DustOutputPolicy,
247        split_policy: SplitPolicy,
248    ) -> Self {
249        Self {
250            fee_rule,
251            change_memo,
252            fallback_change_pool,
253            dust_output_policy,
254            split_policy,
255            #[cfg(feature = "transparent-inputs")]
256            transparent_change_policy: TransparentChangePolicy::ShieldChange,
257            meta_source: PhantomData,
258        }
259    }
260
261    /// Sets the [`TransparentChangePolicy`] to be used by this change strategy, determining
262    /// whether change may be returned to the transparent pool when the flows of the transaction
263    /// under construction are fully transparent.
264    ///
265    /// The default is [`TransparentChangePolicy::ShieldChange`]. This policy has no effect on
266    /// transactions that involve any shielded flows. When transparent change is produced, it is
267    /// always emitted as a single output; the [`SplitPolicy`] configured for this strategy applies
268    /// only to shielded change.
269    #[cfg(feature = "transparent-inputs")]
270    pub fn with_transparent_change_policy(
271        mut self,
272        transparent_change_policy: TransparentChangePolicy,
273    ) -> Self {
274        self.transparent_change_policy = transparent_change_policy;
275        self
276    }
277}
278
279impl<R, I> ChangeStrategy for MultiOutputChangeStrategy<R, I>
280where
281    R: Zip317FeeRule + Clone,
282    I: InputSource,
283    <R as FeeRule>::Error: From<BalanceError>,
284{
285    type FeeRule = R;
286    type Error = <R as FeeRule>::Error;
287    type MetaSource = I;
288    type AccountMetaT = AccountMeta;
289
290    fn fee_rule(&self) -> &Self::FeeRule {
291        &self.fee_rule
292    }
293
294    fn fetch_wallet_meta<P: consensus::Parameters>(
295        &self,
296        params: &P,
297        meta_source: &Self::MetaSource,
298        account: <Self::MetaSource as InputSource>::AccountId,
299        target_height: TargetHeight,
300        exclude: &[<Self::MetaSource as InputSource>::NoteRef],
301    ) -> Result<Self::AccountMetaT, <Self::MetaSource as InputSource>::Error> {
302        let note_selector = NoteFilter::ExceedsMinValue(
303            self.split_policy
304                .min_split_output_value()
305                .unwrap_or_else(|| SplitPolicy::min_note_value(params, target_height)),
306        );
307
308        // Account metadata feeds change-splitting decisions, which reason about the
309        // notes that selection can actually draw on; locked notes are excluded from
310        // selection, so they are excluded here as well.
311        meta_source.get_account_metadata(
312            account,
313            &note_selector,
314            target_height,
315            exclude,
316            LockFilter::Policy(&LockedInputPolicy::Exclude),
317        )
318    }
319
320    fn compute_balance<P: consensus::Parameters, NoteRefT: Clone>(
321        &self,
322        params: &P,
323        target_height: TargetHeight,
324        anchor_height: BlockHeight,
325        zip318: &PoolMigrationParams,
326        transparent_inputs: &[impl transparent::InputView],
327        transparent_outputs: &[impl transparent::OutputView],
328        sapling: &impl sapling_fees::BundleView<NoteRefT>,
329        #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
330        #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
331        ephemeral_balance: Option<EphemeralBalance>,
332        wallet_meta: &Self::AccountMetaT,
333    ) -> Result<TransactionBalance, ChangeError<Self::Error, NoteRefT>> {
334        let marginal_fee = self.fee_rule.marginal_fee(params, target_height);
335        let cfg = SinglePoolBalanceConfig::new(
336            params,
337            &self.fee_rule,
338            &self.dust_output_policy,
339            marginal_fee,
340            &self.split_policy,
341            self.fallback_change_pool,
342            #[cfg(feature = "transparent-inputs")]
343            self.transparent_change_policy,
344            marginal_fee,
345            self.fee_rule.grace_actions(),
346        );
347
348        single_pool_output_balance(
349            cfg,
350            Some(wallet_meta),
351            wallet_meta.change_receivers(),
352            target_height,
353            transparent_inputs,
354            transparent_outputs,
355            sapling,
356            #[cfg(feature = "orchard")]
357            orchard,
358            #[cfg(feature = "orchard")]
359            ironwood,
360            // The Orchard bundle is always padded to the default floor. Only the Ironwood
361            // bundle's padding varies, and it is derived from the transaction's shape rather
362            // than chosen here.
363            #[cfg(feature = "orchard")]
364            BundlePadding::DEFAULT,
365            anchor_height,
366            zip318,
367            self.change_memo.as_ref(),
368            ephemeral_balance,
369        )
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    // Fixtures are pre-Revision-2 (no NU7 activation), where the fee is the 5000-zatoshi constant.
376    #![allow(deprecated)]
377
378    use crate::fees::tests::all_change_receivers;
379    // `sapling_fees` is named by both the orchard and the transparent-inputs tests.
380    #[cfg(any(feature = "orchard", feature = "transparent-inputs"))]
381    use crate::fees::sapling as sapling_fees;
382
383    #[cfg(feature = "transparent-inputs")]
384    use {
385        crate::{
386            data_api::TransparentChangeKind,
387            fees::{EphemeralBalance, TransparentChangePolicy},
388        },
389        ::transparent::{address::TransparentAddress, bundle::OutPoint},
390        zcash_primitives::transaction::fees::zip317::MINIMUM_FEE,
391    };
392
393    #[cfg(feature = "orchard")]
394    use {
395        crate::{
396            data_api::wallet::{TargetHeight, input_selection::OrchardPayment},
397            fees::{canonical_crossing_fee, orchard as orchard_fees, tests::TestOrchardInput},
398        },
399        zcash_protocol::zip318::{AnchorBucketInterval, MAX_RESIDUAL_VALUE},
400    };
401
402    use crate::{
403        data_api::{
404            AccountMeta, ChangeReceivers, PoolMeta,
405            anchor_retention::{AnchorRetentionInterval, PoolMigrationParams},
406            testing::{MockWalletDb, pool::nu7_activating_network},
407            wallet::input_selection::SaplingPayment,
408        },
409        fees::{
410            ChangeError, ChangeStrategy, ChangeValue, DustAction, DustOutputPolicy, SplitPolicy,
411            TransactionBalance,
412            common::DUST_TO_FEE_CAP_MINIMUM_FEES,
413            tests::{TestSaplingInput, TestTransparentInput},
414            zip317::MultiOutputChangeStrategy,
415        },
416    };
417    use core::{convert::Infallible, num::NonZeroUsize};
418    use zcash_protocol::{
419        PoolType, ShieldedPool,
420        consensus::{BlockHeight, Network, NetworkUpgrade, Parameters},
421        local_consensus::LocalNetwork,
422        value::Zatoshis,
423    };
424
425    use ::transparent::{address::Script, bundle::TxOut};
426    use zcash_primitives::transaction::fees::zip317::{
427        FeeError as Zip317FeeError, FeeRule as Zip317FeeRule, marginal_fee, minimum_fee,
428    };
429
430    use super::SingleOutputChangeStrategy;
431
432    #[test]
433    fn change_without_dust() {
434        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
435            Zip317FeeRule::standard(),
436            None,
437            ShieldedPool::Sapling,
438            DustOutputPolicy::default(),
439        );
440
441        // spend a single Sapling note that is sufficient to pay the fee
442        let result = change_strategy.compute_balance(
443            &Network::TestNetwork,
444            Network::TestNetwork
445                .activation_height(NetworkUpgrade::Nu5)
446                .unwrap()
447                .into(),
448            BlockHeight::from_u32(1),
449            &PoolMigrationParams::new(
450                zcash_protocol::zip318::BlockSpacing::UNIFORM,
451                AnchorRetentionInterval::ZIP_318,
452            ),
453            &[] as &[TestTransparentInput],
454            &[] as &[TxOut<Zatoshis>],
455            &(
456                sapling::builder::BundleType::DEFAULT,
457                &[TestSaplingInput {
458                    note_id: 0,
459                    value: Zatoshis::const_from_u64(55000),
460                }][..],
461                &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..],
462            ),
463            #[cfg(feature = "orchard")]
464            &orchard_fees::EmptyBundleView,
465            #[cfg(feature = "orchard")]
466            &orchard_fees::EmptyBundleView,
467            None,
468            &all_change_receivers(),
469        );
470
471        assert_matches!(
472            result,
473            Ok(balance) if
474                balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(5000), None)] &&
475                balance.fee_required() == Zatoshis::const_from_u64(10000)
476        );
477    }
478
479    #[test]
480    fn change_without_dust_multi() {
481        let change_strategy = MultiOutputChangeStrategy::<_, MockWalletDb>::new(
482            Zip317FeeRule::standard(),
483            None,
484            ShieldedPool::Sapling,
485            DustOutputPolicy::default(),
486            SplitPolicy::with_min_output_value(
487                NonZeroUsize::new(5).unwrap(),
488                Zatoshis::const_from_u64(100_0000),
489            ),
490        );
491
492        {
493            // spend a single Sapling note and produce 5 outputs
494            let balance = |existing_notes, total| {
495                change_strategy.compute_balance(
496                    &Network::TestNetwork,
497                    Network::TestNetwork
498                        .activation_height(NetworkUpgrade::Nu5)
499                        .unwrap()
500                        .into(),
501                    BlockHeight::from_u32(1),
502                    &PoolMigrationParams::new(
503                        zcash_protocol::zip318::BlockSpacing::UNIFORM,
504                        AnchorRetentionInterval::ZIP_318,
505                    ),
506                    &[] as &[TestTransparentInput],
507                    &[] as &[TxOut<Zatoshis>],
508                    &(
509                        sapling::builder::BundleType::DEFAULT,
510                        &[TestSaplingInput {
511                            note_id: 0,
512                            value: Zatoshis::const_from_u64(750_0000),
513                        }][..],
514                        &[SaplingPayment::new(Zatoshis::const_from_u64(100_0000))][..],
515                    ),
516                    #[cfg(feature = "orchard")]
517                    &orchard_fees::EmptyBundleView,
518                    #[cfg(feature = "orchard")]
519                    &orchard_fees::EmptyBundleView,
520                    None,
521                    &AccountMeta::new(
522                        Some(PoolMeta::new(existing_notes, total)),
523                        None,
524                        None,
525                        all_change_receivers(),
526                    ),
527                )
528            };
529
530            assert_matches!(
531                balance(0, Zatoshis::ZERO),
532                Ok(balance) if
533                    balance.proposed_change() == [
534                        ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None),
535                        ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None),
536                        ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None),
537                        ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None),
538                        ChangeValue::sapling(Zatoshis::const_from_u64(129_4000), None),
539                    ] &&
540                    balance.fee_required() == Zatoshis::const_from_u64(30000)
541            );
542
543            assert_matches!(
544                balance(2, Zatoshis::const_from_u64(100_0000)),
545                Ok(balance) if
546                    balance.proposed_change() == [
547                        ChangeValue::sapling(Zatoshis::const_from_u64(216_0000), None),
548                        ChangeValue::sapling(Zatoshis::const_from_u64(216_0000), None),
549                        ChangeValue::sapling(Zatoshis::const_from_u64(216_0000), None),
550                    ] &&
551                    balance.fee_required() == Zatoshis::const_from_u64(20000)
552            );
553        }
554
555        {
556            // spend a single Sapling note and produce 4 outputs, as the value of the note isn't
557            // sufficient to produce 5
558            let result = change_strategy.compute_balance(
559                &Network::TestNetwork,
560                Network::TestNetwork
561                    .activation_height(NetworkUpgrade::Nu5)
562                    .unwrap()
563                    .into(),
564                BlockHeight::from_u32(1),
565                &PoolMigrationParams::new(
566                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
567                    AnchorRetentionInterval::ZIP_318,
568                ),
569                &[] as &[TestTransparentInput],
570                &[] as &[TxOut<Zatoshis>],
571                &(
572                    sapling::builder::BundleType::DEFAULT,
573                    &[TestSaplingInput {
574                        note_id: 0,
575                        value: Zatoshis::const_from_u64(600_0000),
576                    }][..],
577                    &[SaplingPayment::new(Zatoshis::const_from_u64(100_0000))][..],
578                ),
579                #[cfg(feature = "orchard")]
580                &orchard_fees::EmptyBundleView,
581                #[cfg(feature = "orchard")]
582                &orchard_fees::EmptyBundleView,
583                None,
584                &AccountMeta::new(
585                    Some(PoolMeta::new(0, Zatoshis::ZERO)),
586                    Some(PoolMeta::new(0, Zatoshis::ZERO)),
587                    None,
588                    all_change_receivers(),
589                ),
590            );
591
592            assert_matches!(
593                result,
594                Ok(balance) if
595                    balance.proposed_change() == [
596                        ChangeValue::sapling(Zatoshis::const_from_u64(124_3750), None),
597                        ChangeValue::sapling(Zatoshis::const_from_u64(124_3750), None),
598                        ChangeValue::sapling(Zatoshis::const_from_u64(124_3750), None),
599                        ChangeValue::sapling(Zatoshis::const_from_u64(124_3750), None),
600                    ] &&
601                    balance.fee_required() == Zatoshis::const_from_u64(25000)
602            );
603        }
604
605        {
606            // spend a single Sapling note and produce no change outputs, as the value of outputs
607            // has been requested such that it exactly empties the wallet
608            let result = change_strategy.compute_balance(
609                &Network::TestNetwork,
610                Network::TestNetwork
611                    .activation_height(NetworkUpgrade::Nu5)
612                    .unwrap()
613                    .into(),
614                BlockHeight::from_u32(1),
615                &PoolMigrationParams::new(
616                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
617                    AnchorRetentionInterval::ZIP_318,
618                ),
619                &[] as &[TestTransparentInput],
620                &[] as &[TxOut<Zatoshis>],
621                &(
622                    sapling::builder::BundleType::DEFAULT,
623                    &[TestSaplingInput {
624                        note_id: 0,
625                        value: Zatoshis::const_from_u64(50000),
626                    }][..],
627                    &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..],
628                ),
629                #[cfg(feature = "orchard")]
630                &orchard_fees::EmptyBundleView,
631                #[cfg(feature = "orchard")]
632                &orchard_fees::EmptyBundleView,
633                None,
634                // after excluding the inputs we're spending, we have no notes in the wallet
635                &AccountMeta::new(
636                    Some(PoolMeta::new(0, Zatoshis::ZERO)),
637                    Some(PoolMeta::new(0, Zatoshis::ZERO)),
638                    None,
639                    all_change_receivers(),
640                ),
641            );
642
643            assert_matches!(
644                result,
645                Ok(balance) if
646                    balance.proposed_change() == [ChangeValue::sapling(Zatoshis::ZERO, None)] &&
647                    balance.fee_required() == Zatoshis::const_from_u64(10000)
648            );
649        }
650
651        {
652            // spend a single Sapling note, with insufficient funds to cover the minimum fee.
653            let result = change_strategy.compute_balance(
654                &Network::TestNetwork,
655                Network::TestNetwork
656                    .activation_height(NetworkUpgrade::Nu5)
657                    .unwrap()
658                    .into(),
659                BlockHeight::from_u32(1),
660                &PoolMigrationParams::new(
661                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
662                    AnchorRetentionInterval::ZIP_318,
663                ),
664                &[] as &[TestTransparentInput],
665                &[] as &[TxOut<Zatoshis>],
666                &(
667                    sapling::builder::BundleType::DEFAULT,
668                    &[TestSaplingInput {
669                        note_id: 0,
670                        value: Zatoshis::const_from_u64(50000),
671                    }][..],
672                    &[SaplingPayment::new(Zatoshis::const_from_u64(40001))][..],
673                ),
674                #[cfg(feature = "orchard")]
675                &orchard_fees::EmptyBundleView,
676                #[cfg(feature = "orchard")]
677                &orchard_fees::EmptyBundleView,
678                None,
679                // after excluding the inputs we're spending, we have no notes in the wallet
680                &AccountMeta::new(
681                    Some(PoolMeta::new(0, Zatoshis::ZERO)),
682                    Some(PoolMeta::new(0, Zatoshis::ZERO)),
683                    None,
684                    all_change_receivers(),
685                ),
686            );
687
688            assert_matches!(
689                result,
690                Err(ChangeError::InsufficientFunds { available, required })
691                    if available == Zatoshis::const_from_u64(50000)
692                       && required == Zatoshis::const_from_u64(50001)
693            );
694        }
695
696        {
697            // Spend a single Sapling note, creating two output notes that cause the transaction to
698            // balance exactly. This will fail, because even though there are enough funds in the
699            // wallet for the transaction to go through, and the fee is correct for a two-output
700            // transaction, we prohibit this case in order to prevent the transaction recipients
701            // from being able to reason about the value of the input note via knowledge that there
702            // is no change output.
703            let result = change_strategy.compute_balance(
704                &Network::TestNetwork,
705                Network::TestNetwork
706                    .activation_height(NetworkUpgrade::Nu5)
707                    .unwrap()
708                    .into(),
709                BlockHeight::from_u32(1),
710                &PoolMigrationParams::new(
711                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
712                    AnchorRetentionInterval::ZIP_318,
713                ),
714                &[] as &[TestTransparentInput],
715                &[] as &[TxOut<Zatoshis>],
716                &(
717                    sapling::builder::BundleType::DEFAULT,
718                    &[TestSaplingInput {
719                        note_id: 0,
720                        value: Zatoshis::const_from_u64(50000),
721                    }][..],
722                    &[
723                        SaplingPayment::new(Zatoshis::const_from_u64(30000)),
724                        SaplingPayment::new(Zatoshis::const_from_u64(10000)),
725                    ][..],
726                ),
727                #[cfg(feature = "orchard")]
728                &orchard_fees::EmptyBundleView,
729                #[cfg(feature = "orchard")]
730                &orchard_fees::EmptyBundleView,
731                None,
732                // after excluding the inputs we're spending, we have no notes in the wallet
733                &AccountMeta::new(
734                    Some(PoolMeta::new(0, Zatoshis::ZERO)),
735                    Some(PoolMeta::new(0, Zatoshis::ZERO)),
736                    None,
737                    all_change_receivers(),
738                ),
739            );
740
741            assert_matches!(
742                result,
743                Err(ChangeError::InsufficientFunds { available, required })
744                    if available == Zatoshis::const_from_u64(50000)
745                       && required == Zatoshis::const_from_u64(55000)
746            );
747        }
748    }
749
750    #[test]
751    #[cfg(feature = "orchard")]
752    fn cross_pool_change_without_dust() {
753        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
754            Zip317FeeRule::standard(),
755            None,
756            ShieldedPool::Orchard,
757            DustOutputPolicy::default(),
758        );
759
760        // spend a single Sapling note that is sufficient to pay the fee
761        let result = change_strategy.compute_balance(
762            &Network::TestNetwork,
763            Network::TestNetwork
764                .activation_height(NetworkUpgrade::Nu5)
765                .unwrap()
766                .into(),
767            BlockHeight::from_u32(1),
768            &PoolMigrationParams::new(
769                zcash_protocol::zip318::BlockSpacing::UNIFORM,
770                AnchorRetentionInterval::ZIP_318,
771            ),
772            &[] as &[TestTransparentInput],
773            &[] as &[TxOut<Zatoshis>],
774            &(
775                sapling::builder::BundleType::DEFAULT,
776                &[TestSaplingInput {
777                    note_id: 0,
778                    value: Zatoshis::const_from_u64(55000),
779                }][..],
780                &[] as &[Infallible],
781            ),
782            &(
783                ::orchard::bundle::BundleVersion::orchard_v2(),
784                &[] as &[Infallible],
785                &[OrchardPayment::new(Zatoshis::const_from_u64(30000))][..],
786            ),
787            &orchard_fees::EmptyBundleView,
788            None,
789            &all_change_receivers(),
790        );
791
792        assert_matches!(
793            result,
794            Ok(balance) if
795                balance.proposed_change() == [ChangeValue::orchard(Zatoshis::const_from_u64(5000), None)] &&
796                balance.fee_required() == Zatoshis::const_from_u64(20000)
797        );
798    }
799
800    #[test]
801    #[cfg(feature = "orchard")]
802    fn orchard_v3_change_counts_spends_and_outputs_separately() {
803        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
804            Zip317FeeRule::standard(),
805            None,
806            ShieldedPool::Orchard,
807            DustOutputPolicy::default(),
808        );
809
810        // Under the post-NU6.3 Orchard pool restriction (cross-address transfers
811        // disabled), every spend and output occupies its own action: one spend plus a
812        // payment and a change output make three logical actions, where the legacy
813        // policy would count `max(1, 2) == 2`.
814        let result = change_strategy.compute_balance(
815            &Network::TestNetwork,
816            Network::TestNetwork
817                .activation_height(NetworkUpgrade::Nu6_3)
818                .unwrap()
819                .into(),
820            BlockHeight::from_u32(1),
821            &PoolMigrationParams::new(
822                zcash_protocol::zip318::BlockSpacing::UNIFORM,
823                AnchorRetentionInterval::ZIP_318,
824            ),
825            &[] as &[TestTransparentInput],
826            &[] as &[TxOut<Zatoshis>],
827            &sapling_fees::EmptyBundleView,
828            &(
829                ::orchard::bundle::BundleVersion::orchard_v3(),
830                &[TestOrchardInput {
831                    note_id: 0,
832                    value: Zatoshis::const_from_u64(80000),
833                }][..],
834                &[OrchardPayment::new(Zatoshis::const_from_u64(30000))][..],
835            ),
836            &orchard_fees::EmptyBundleView,
837            None,
838            &all_change_receivers(),
839        );
840
841        assert_matches!(
842            result,
843            Ok(balance) if
844                balance.proposed_change() == [ChangeValue::orchard(Zatoshis::const_from_u64(35000), None)] &&
845                balance.fee_required() == Zatoshis::const_from_u64(15000)
846        );
847    }
848
849    #[test]
850    #[cfg(all(feature = "orchard", feature = "transparent-inputs"))]
851    fn orchard_fallback_change_pool_is_promoted_to_ironwood_after_nu6_3() {
852        // A caller that names Orchard as its fallback change pool.
853        let change_strategy = MultiOutputChangeStrategy::<_, MockWalletDb>::new(
854            Zip317FeeRule::standard(),
855            None,
856            ShieldedPool::Orchard,
857            DustOutputPolicy::default(),
858            SplitPolicy::with_min_output_value(
859                NonZeroUsize::new(2).unwrap(),
860                Zatoshis::const_from_u64(100_0000),
861            ),
862        );
863
864        // A single transparent UTXO, shielded to the change pool. The fallback pool only
865        // decides where change goes for a transaction whose flows are fully transparent: one
866        // with shielded flows infers its change pool from the pool it already uses. So this
867        // is the case in which naming Orchard as the fallback can actually direct change
868        // into the Orchard pool.
869        let transparent_inputs = [TestTransparentInput {
870            outpoint: OutPoint::fake(),
871            coin: TxOut::new(
872                Zatoshis::const_from_u64(63000),
873                TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
874            ),
875        }];
876        let transparent_outputs = [TxOut::new(
877            Zatoshis::const_from_u64(40000),
878            Script::default(),
879        )];
880
881        // The shielded views are empty: the transaction has no shielded flows, so the change
882        // output the strategy proposes is the only thing that will populate one of them.
883        let sapling_view = sapling_fees::EmptyBundleView;
884        let ironwood_view = (
885            ::orchard::bundle::BundleVersion::ironwood_v3(),
886            &[] as &[Infallible],
887            &[] as &[Infallible],
888        );
889
890        // This transaction is not one half of a ZIP 320 pair, so it has no ephemeral balance.
891        let ephemeral_balance = None;
892
893        // No note counts are known for the account, so the split policy proposes a single
894        // change output: the assertions below are about the pool it lands in, not the split.
895        let wallet_meta = AccountMeta::new(None, None, None, all_change_receivers());
896
897        // The Orchard bundle version whose action-count policy applies at each height. The
898        // Orchard view is empty in both cases and so contributes no actions, but the version
899        // is what the transaction builder will be configured with.
900        let pre_nu6_3_orchard_view = (
901            ::orchard::bundle::BundleVersion::orchard_v2(),
902            &[] as &[Infallible],
903            &[] as &[Infallible],
904        );
905        let post_nu6_3_orchard_view = (
906            ::orchard::bundle::BundleVersion::orchard_v3(),
907            &[] as &[Infallible],
908            &[] as &[Infallible],
909        );
910
911        let pre_nu6_3_height: TargetHeight = Network::TestNetwork
912            .activation_height(NetworkUpgrade::Nu5)
913            .unwrap()
914            .into();
915        let post_nu6_3_height: TargetHeight = Network::TestNetwork
916            .activation_height(NetworkUpgrade::Nu6_3)
917            .unwrap()
918            .into();
919
920        // Before NU6.3, value may freely enter the Orchard pool, so the fallback is honoured
921        // as given and the change is returned to Orchard.
922        let pre_nu6_3_balance = change_strategy.compute_balance::<_, Infallible>(
923            &Network::TestNetwork,
924            pre_nu6_3_height,
925            BlockHeight::from_u32(1),
926            &PoolMigrationParams::new(
927                zcash_protocol::zip318::BlockSpacing::UNIFORM,
928                AnchorRetentionInterval::ZIP_318,
929            ),
930            &transparent_inputs,
931            &transparent_outputs,
932            &sapling_view,
933            &pre_nu6_3_orchard_view,
934            &ironwood_view,
935            ephemeral_balance,
936            &wallet_meta,
937        );
938
939        assert_matches!(
940            pre_nu6_3_balance,
941            Ok(balance) if
942                balance.proposed_change() == [ChangeValue::orchard(Zatoshis::const_from_u64(8000), None)] &&
943                balance.fee_required() == Zatoshis::const_from_u64(15000)
944        );
945
946        // After NU6.3, the Orchard turnstile forbids value from entering the Orchard pool.
947        // This transaction spends no Orchard notes, so no amount of change may return to
948        // Orchard; the strategy promotes the Orchard fallback to Ironwood rather than
949        // proposing change that consensus would reject. The fee is unchanged: the change
950        // output is charged to the Ironwood bundle instead of the Orchard one, and each pads
951        // to the same two-action floor.
952        let post_nu6_3_balance = change_strategy.compute_balance::<_, Infallible>(
953            &Network::TestNetwork,
954            post_nu6_3_height,
955            BlockHeight::from_u32(1),
956            &PoolMigrationParams::new(
957                zcash_protocol::zip318::BlockSpacing::UNIFORM,
958                AnchorRetentionInterval::ZIP_318,
959            ),
960            &transparent_inputs,
961            &transparent_outputs,
962            &sapling_view,
963            &post_nu6_3_orchard_view,
964            &ironwood_view,
965            ephemeral_balance,
966            &wallet_meta,
967        );
968
969        assert_matches!(
970            post_nu6_3_balance,
971            Ok(balance) if
972                balance.proposed_change() == [ChangeValue::ironwood(Zatoshis::const_from_u64(8000), None)] &&
973                balance.fee_required() == Zatoshis::const_from_u64(15000)
974        );
975    }
976
977    /// The change strategy records the exact dummy outputs it charged the fee against, so the
978    /// builder can reproduce that action count. A canonical crossing has no Ironwood dummy output;
979    /// a payment one zatoshi off the denomination grid has one.
980    #[test]
981    #[cfg(feature = "orchard")]
982    fn the_change_strategy_records_the_dummy_outputs_it_costed() {
983        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
984            Zip317FeeRule::standard(),
985            None,
986            ShieldedPool::Orchard,
987            DustOutputPolicy::default(),
988        );
989        let zip318 = PoolMigrationParams::new(
990            zcash_protocol::zip318::BlockSpacing::UNIFORM,
991            AnchorRetentionInterval::ZIP_318,
992        );
993        let interval = AnchorBucketInterval::ZIP_318;
994
995        // An anchor ON the grid, as a canonical crossing requires.
996        let anchor = zcash_protocol::zip318::AnchorGrid::new(
997            interval,
998            zcash_protocol::zip318::BlockSpacing::UNIFORM,
999        )
1000        .boundary_at_or_below(BlockHeight::from_u32(2_000_000));
1001        let height = TargetHeight::from(BlockHeight::from_u32(u32::from(anchor) + 10));
1002
1003        // One Orchard input, large enough that its change stays in Orchard rather than being
1004        // promoted to Ironwood by the turnstile rule.
1005        let orchard_inputs = [TestOrchardInput {
1006            note_id: 0,
1007            value: Zatoshis::const_from_u64(10_000_000),
1008        }];
1009        let orchard_view = (
1010            ::orchard::bundle::BundleVersion::orchard_v3(),
1011            &orchard_inputs[..],
1012            &[] as &[Infallible],
1013        );
1014        let sapling_view = (
1015            sapling::builder::BundleType::DEFAULT,
1016            &[] as &[Infallible],
1017            &[] as &[Infallible],
1018        );
1019
1020        let recorded_for = |value: Zatoshis| {
1021            let ironwood_outputs = [OrchardPayment::new(value)];
1022            let ironwood_view = (
1023                ::orchard::bundle::BundleVersion::ironwood_v3(),
1024                &[] as &[Infallible],
1025                &ironwood_outputs[..],
1026            );
1027            change_strategy
1028                .compute_balance::<_, u32>(
1029                    &Network::TestNetwork,
1030                    height,
1031                    anchor,
1032                    &zip318,
1033                    &[] as &[TestTransparentInput],
1034                    &[] as &[TxOut<Zatoshis>],
1035                    &sapling_view,
1036                    &orchard_view,
1037                    &ironwood_view,
1038                    None,
1039                    &all_change_receivers(),
1040                )
1041                .expect("the input covers the payment and its fee")
1042                .dummy_outputs()
1043                .expect("the change strategy records dummy outputs")
1044                .ironwood()
1045        };
1046
1047        assert_eq!(recorded_for(MAX_RESIDUAL_VALUE), 0);
1048        assert_eq!(
1049            recorded_for((MAX_RESIDUAL_VALUE + Zatoshis::const_from_u64(1)).unwrap()),
1050            1
1051        );
1052    }
1053
1054    /// A canonical crossing whose note leaves dust over the canonical fee in effect at the target
1055    /// height keeps the canonical shape and fee under `AllowDustChange`, with the dust as its one
1056    /// Orchard change output; the default policy rejects that change.
1057    #[test]
1058    #[cfg(feature = "orchard")]
1059    fn canonical_crossing_keeps_dust_change_under_allow_dust_change() {
1060        /// Change below the marginal fee on both sides of the fee reduction.
1061        const DUST_CHANGE: Zatoshis = Zatoshis::const_from_u64(500);
1062
1063        let net = nu7_activating_network();
1064        let reduction_height = fee_reduction_height(&net);
1065        let zip318 = PoolMigrationParams::new(
1066            zcash_protocol::zip318::BlockSpacing::UNIFORM,
1067            AnchorRetentionInterval::ZIP_318,
1068        );
1069        let sapling_view = (
1070            sapling::builder::BundleType::DEFAULT,
1071            &[] as &[Infallible],
1072            &[] as &[Infallible],
1073        );
1074        let ironwood_outputs = [OrchardPayment::new(MAX_RESIDUAL_VALUE)];
1075        let ironwood_view = (
1076            ::orchard::bundle::BundleVersion::ironwood_v3(),
1077            &[] as &[Infallible],
1078            &ironwood_outputs[..],
1079        );
1080        let strategy = |dust_output_policy| {
1081            SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1082                Zip317FeeRule::standard(),
1083                None,
1084                ShieldedPool::Orchard,
1085                dust_output_policy,
1086            )
1087        };
1088
1089        for target_height in [reduction_height - 1, reduction_height] {
1090            assert!(DUST_CHANGE < marginal_fee(&net, target_height));
1091            let canonical_fee = canonical_crossing_fee(&net, target_height)
1092                .expect("the canonical shape is a valid input to the ZIP 317 rule");
1093            let anchor = zcash_protocol::zip318::AnchorGrid::new(
1094                AnchorBucketInterval::ZIP_318,
1095                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1096            )
1097            .boundary_at_or_below(target_height - 1);
1098            let orchard_inputs = [TestOrchardInput {
1099                note_id: 0,
1100                value: (MAX_RESIDUAL_VALUE + canonical_fee)
1101                    .and_then(|v| v + DUST_CHANGE)
1102                    .unwrap(),
1103            }];
1104            let orchard_view = (
1105                ::orchard::bundle::BundleVersion::orchard_v3(),
1106                &orchard_inputs[..],
1107                &[] as &[Infallible],
1108            );
1109            let balance_under = |dust_output_policy| {
1110                strategy(dust_output_policy).compute_balance::<_, u32>(
1111                    &net,
1112                    target_height.into(),
1113                    anchor,
1114                    &zip318,
1115                    &[] as &[TestTransparentInput],
1116                    &[] as &[TxOut<Zatoshis>],
1117                    &sapling_view,
1118                    &orchard_view,
1119                    &ironwood_view,
1120                    None,
1121                    &all_change_receivers(),
1122                )
1123            };
1124
1125            assert_matches!(
1126                balance_under(DustOutputPolicy::default()),
1127                Err(ChangeError::InsufficientFunds { .. }),
1128                "change of {DUST_CHANGE:?} at {target_height:?} should be dust",
1129            );
1130            assert_matches!(
1131                balance_under(DustOutputPolicy::new(DustAction::AllowDustChange, None)),
1132                Ok(balance) if
1133                    balance.proposed_change() == [ChangeValue::orchard(DUST_CHANGE, None)] &&
1134                    balance.fee_required() == canonical_fee &&
1135                    balance.dummy_outputs().is_some_and(|d| d.ironwood() == 0),
1136                "at {target_height:?} the crossing should stay canonical with dust change",
1137            );
1138        }
1139    }
1140
1141    #[test]
1142    #[cfg(feature = "orchard")]
1143    fn ironwood_outputs_are_charged_actions() {
1144        // V6 transactions carry a separate Ironwood bundle, so a populated
1145        // Ironwood view must contribute its own actions to the fee rather than
1146        // being treated as zero. Compare two otherwise-identical balances that
1147        // differ only by the presence of an Ironwood output.
1148        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1149            Zip317FeeRule::standard(),
1150            None,
1151            ShieldedPool::Orchard,
1152            DustOutputPolicy::default(),
1153        );
1154
1155        let height = Network::TestNetwork
1156            .activation_height(NetworkUpgrade::Nu5)
1157            .unwrap()
1158            .into();
1159        let sapling_inputs = [TestSaplingInput {
1160            note_id: 0,
1161            value: Zatoshis::const_from_u64(100000),
1162        }];
1163        let orchard_outputs = [OrchardPayment::new(Zatoshis::const_from_u64(30000))];
1164        let sapling_view = (
1165            sapling::builder::BundleType::DEFAULT,
1166            &sapling_inputs[..],
1167            &[] as &[Infallible],
1168        );
1169        let orchard_view = (
1170            ::orchard::bundle::BundleVersion::orchard_v2(),
1171            &[] as &[Infallible],
1172            &orchard_outputs[..],
1173        );
1174
1175        let without_ironwood = change_strategy
1176            .compute_balance(
1177                &Network::TestNetwork,
1178                height,
1179                BlockHeight::from_u32(1),
1180                &PoolMigrationParams::new(
1181                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
1182                    AnchorRetentionInterval::ZIP_318,
1183                ),
1184                &[] as &[TestTransparentInput],
1185                &[] as &[TxOut<Zatoshis>],
1186                &sapling_view,
1187                &orchard_view,
1188                &orchard_fees::EmptyBundleView,
1189                None,
1190                &all_change_receivers(),
1191            )
1192            .unwrap();
1193
1194        let with_ironwood = change_strategy
1195            .compute_balance(
1196                &Network::TestNetwork,
1197                height,
1198                BlockHeight::from_u32(1),
1199                &PoolMigrationParams::new(
1200                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
1201                    AnchorRetentionInterval::ZIP_318,
1202                ),
1203                &[] as &[TestTransparentInput],
1204                &[] as &[TxOut<Zatoshis>],
1205                &sapling_view,
1206                &orchard_view,
1207                &(
1208                    ::orchard::bundle::BundleVersion::ironwood_v3(),
1209                    &[] as &[Infallible],
1210                    &orchard_outputs[..],
1211                ),
1212                None,
1213                &all_change_receivers(),
1214            )
1215            .unwrap();
1216
1217        // ZIP 317 floors each shielded bundle that is used at 2 actions. Without
1218        // an Ironwood bundle: sapling (2) + orchard (2 outputs) = 4 actions; with
1219        // an Ironwood output: + ironwood (2) = 6 actions. At 5000 zat/action that
1220        // is 20000 vs 30000.
1221        assert_eq!(
1222            without_ironwood.fee_required(),
1223            Zatoshis::const_from_u64(20000)
1224        );
1225        assert_eq!(
1226            with_ironwood.fee_required(),
1227            Zatoshis::const_from_u64(30000)
1228        );
1229    }
1230
1231    #[test]
1232    fn change_with_transparent_payments_implicitly_allowing_zero_change() {
1233        change_with_transparent_payments(DustOutputPolicy::default())
1234    }
1235
1236    #[test]
1237    fn change_with_transparent_payments_explicitly_allowing_zero_change() {
1238        change_with_transparent_payments(DustOutputPolicy::new(
1239            DustAction::AllowDustChange,
1240            Some(Zatoshis::ZERO),
1241        ))
1242    }
1243
1244    fn change_with_transparent_payments(dust_output_policy: DustOutputPolicy) {
1245        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1246            Zip317FeeRule::standard(),
1247            None,
1248            ShieldedPool::Sapling,
1249            dust_output_policy,
1250        );
1251
1252        // spend a single Sapling note that is sufficient to pay the fee
1253        let result = change_strategy.compute_balance(
1254            &Network::TestNetwork,
1255            Network::TestNetwork
1256                .activation_height(NetworkUpgrade::Nu5)
1257                .unwrap()
1258                .into(),
1259            BlockHeight::from_u32(1),
1260            &PoolMigrationParams::new(
1261                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1262                AnchorRetentionInterval::ZIP_318,
1263            ),
1264            &[] as &[TestTransparentInput],
1265            &[TxOut::new(
1266                Zatoshis::const_from_u64(40000),
1267                Script::default(),
1268            )],
1269            &(
1270                sapling::builder::BundleType::DEFAULT,
1271                &[TestSaplingInput {
1272                    note_id: 0,
1273                    value: Zatoshis::const_from_u64(55000),
1274                }][..],
1275                &[] as &[Infallible],
1276            ),
1277            #[cfg(feature = "orchard")]
1278            &orchard_fees::EmptyBundleView,
1279            #[cfg(feature = "orchard")]
1280            &orchard_fees::EmptyBundleView,
1281            None,
1282            &all_change_receivers(),
1283        );
1284
1285        assert_matches!(
1286            result,
1287            Ok(balance) if
1288                balance.proposed_change() == [ChangeValue::sapling(Zatoshis::ZERO, None)]
1289                && balance.fee_required() == Zatoshis::const_from_u64(15000)
1290        );
1291    }
1292
1293    #[test]
1294    #[cfg(feature = "transparent-inputs")]
1295    fn change_fully_transparent_no_change() {
1296        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1297            Zip317FeeRule::standard(),
1298            None,
1299            ShieldedPool::Sapling,
1300            DustOutputPolicy::default(),
1301        );
1302
1303        // Spend a single transparent UTXO that is exactly sufficient to pay the fee.
1304        let result = change_strategy.compute_balance::<_, Infallible>(
1305            &Network::TestNetwork,
1306            Network::TestNetwork
1307                .activation_height(NetworkUpgrade::Nu5)
1308                .unwrap()
1309                .into(),
1310            BlockHeight::from_u32(1),
1311            &PoolMigrationParams::new(
1312                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1313                AnchorRetentionInterval::ZIP_318,
1314            ),
1315            &[TestTransparentInput {
1316                outpoint: OutPoint::fake(),
1317                coin: TxOut::new(
1318                    Zatoshis::const_from_u64(50000),
1319                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1320                ),
1321            }],
1322            &[TxOut::new(
1323                Zatoshis::const_from_u64(40000),
1324                Script::default(),
1325            )],
1326            &sapling_fees::EmptyBundleView,
1327            #[cfg(feature = "orchard")]
1328            &orchard_fees::EmptyBundleView,
1329            #[cfg(feature = "orchard")]
1330            &orchard_fees::EmptyBundleView,
1331            None,
1332            &all_change_receivers(),
1333        );
1334
1335        assert_matches!(
1336            result,
1337            Ok(balance) if
1338                balance.proposed_change().is_empty() &&
1339                balance.fee_required() == Zatoshis::const_from_u64(10000)
1340        );
1341    }
1342
1343    #[test]
1344    #[cfg(feature = "transparent-inputs")]
1345    fn change_transparent_flows_with_shielded_change() {
1346        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1347            Zip317FeeRule::standard(),
1348            None,
1349            ShieldedPool::Sapling,
1350            DustOutputPolicy::default(),
1351        );
1352
1353        // Spend a single transparent UTXO that is sufficient to pay the fee.
1354        let result = change_strategy.compute_balance::<_, Infallible>(
1355            &Network::TestNetwork,
1356            Network::TestNetwork
1357                .activation_height(NetworkUpgrade::Nu5)
1358                .unwrap()
1359                .into(),
1360            BlockHeight::from_u32(1),
1361            &PoolMigrationParams::new(
1362                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1363                AnchorRetentionInterval::ZIP_318,
1364            ),
1365            &[TestTransparentInput {
1366                outpoint: OutPoint::fake(),
1367                coin: TxOut::new(
1368                    Zatoshis::const_from_u64(63000),
1369                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1370                ),
1371            }],
1372            &[TxOut::new(
1373                Zatoshis::const_from_u64(40000),
1374                Script::default(),
1375            )],
1376            &sapling_fees::EmptyBundleView,
1377            #[cfg(feature = "orchard")]
1378            &orchard_fees::EmptyBundleView,
1379            #[cfg(feature = "orchard")]
1380            &orchard_fees::EmptyBundleView,
1381            None,
1382            &all_change_receivers(),
1383        );
1384
1385        assert_matches!(
1386            result,
1387            Ok(balance) if
1388                balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(8000), None)] &&
1389                balance.fee_required() == Zatoshis::const_from_u64(15000)
1390        );
1391    }
1392
1393    #[test]
1394    #[cfg(feature = "transparent-inputs")]
1395    fn change_transparent_flows_with_shielded_dust_change() {
1396        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1397            Zip317FeeRule::standard(),
1398            None,
1399            ShieldedPool::Sapling,
1400            DustOutputPolicy::new(
1401                DustAction::AllowDustChange,
1402                Some(Zatoshis::const_from_u64(1000)),
1403            ),
1404        );
1405
1406        // Spend a single transparent UTXO that is sufficient to pay the fee.
1407        // The change will go to the fallback shielded change pool even though all inputs
1408        // and payments are transparent, and even though the change amount (1000) would
1409        // normally be considered dust, because we set the dust policy to allow that.
1410        let result = change_strategy.compute_balance::<_, Infallible>(
1411            &Network::TestNetwork,
1412            Network::TestNetwork
1413                .activation_height(NetworkUpgrade::Nu5)
1414                .unwrap()
1415                .into(),
1416            BlockHeight::from_u32(1),
1417            &PoolMigrationParams::new(
1418                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1419                AnchorRetentionInterval::ZIP_318,
1420            ),
1421            &[TestTransparentInput {
1422                outpoint: OutPoint::fake(),
1423                coin: TxOut::new(
1424                    Zatoshis::const_from_u64(56000),
1425                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1426                ),
1427            }],
1428            &[TxOut::new(
1429                Zatoshis::const_from_u64(40000),
1430                Script::default(),
1431            )],
1432            &sapling_fees::EmptyBundleView,
1433            #[cfg(feature = "orchard")]
1434            &orchard_fees::EmptyBundleView,
1435            #[cfg(feature = "orchard")]
1436            &orchard_fees::EmptyBundleView,
1437            None,
1438            &all_change_receivers(),
1439        );
1440
1441        assert_matches!(
1442            result,
1443            Ok(balance) if
1444                balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(1000), None)] &&
1445                balance.fee_required() == Zatoshis::const_from_u64(15000)
1446        );
1447    }
1448
1449    #[test]
1450    #[cfg(feature = "transparent-inputs")]
1451    fn change_fully_transparent_with_transparent_change() {
1452        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1453            Zip317FeeRule::standard(),
1454            None,
1455            ShieldedPool::Sapling,
1456            DustOutputPolicy::default(),
1457        )
1458        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
1459
1460        // Spend a single transparent UTXO that is sufficient to pay the fee. The change is
1461        // returned to the transparent pool: one P2PKH input and two P2PKH outputs (the
1462        // payment plus the change output) require `5000 * max(1, 2) = 10000` zats in fees,
1463        // rather than the 15000 zats required when the change is shielded.
1464        let result = change_strategy.compute_balance::<_, Infallible>(
1465            &Network::TestNetwork,
1466            Network::TestNetwork
1467                .activation_height(NetworkUpgrade::Nu5)
1468                .unwrap()
1469                .into(),
1470            BlockHeight::from_u32(1),
1471            &PoolMigrationParams::new(
1472                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1473                AnchorRetentionInterval::ZIP_318,
1474            ),
1475            &[TestTransparentInput {
1476                outpoint: OutPoint::fake(),
1477                coin: TxOut::new(
1478                    Zatoshis::const_from_u64(63000),
1479                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1480                ),
1481            }],
1482            &[TxOut::new(
1483                Zatoshis::const_from_u64(40000),
1484                Script::default(),
1485            )],
1486            &sapling_fees::EmptyBundleView,
1487            #[cfg(feature = "orchard")]
1488            &orchard_fees::EmptyBundleView,
1489            #[cfg(feature = "orchard")]
1490            &orchard_fees::EmptyBundleView,
1491            None,
1492            &all_change_receivers(),
1493        );
1494
1495        assert_matches!(
1496            result,
1497            Ok(balance) if
1498                balance.proposed_change() == [ChangeValue::transparent(Zatoshis::const_from_u64(13000))] &&
1499                balance.fee_required() == Zatoshis::const_from_u64(10000)
1500        );
1501    }
1502
1503    #[test]
1504    #[cfg(feature = "transparent-inputs")]
1505    fn change_fully_transparent_exact_match_with_transparent_change() {
1506        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1507            Zip317FeeRule::standard(),
1508            None,
1509            ShieldedPool::Sapling,
1510            DustOutputPolicy::default(),
1511        )
1512        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
1513
1514        // Spend a single transparent UTXO that exactly covers the payment plus the minimum
1515        // fee; no change output should be produced.
1516        let result = change_strategy.compute_balance::<_, Infallible>(
1517            &Network::TestNetwork,
1518            Network::TestNetwork
1519                .activation_height(NetworkUpgrade::Nu5)
1520                .unwrap()
1521                .into(),
1522            BlockHeight::from_u32(1),
1523            &PoolMigrationParams::new(
1524                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1525                AnchorRetentionInterval::ZIP_318,
1526            ),
1527            &[TestTransparentInput {
1528                outpoint: OutPoint::fake(),
1529                coin: TxOut::new(
1530                    Zatoshis::const_from_u64(50000),
1531                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1532                ),
1533            }],
1534            &[TxOut::new(
1535                Zatoshis::const_from_u64(40000),
1536                Script::default(),
1537            )],
1538            &sapling_fees::EmptyBundleView,
1539            #[cfg(feature = "orchard")]
1540            &orchard_fees::EmptyBundleView,
1541            #[cfg(feature = "orchard")]
1542            &orchard_fees::EmptyBundleView,
1543            None,
1544            &all_change_receivers(),
1545        );
1546
1547        assert_matches!(
1548            result,
1549            Ok(balance) if
1550                balance.proposed_change().is_empty() &&
1551                balance.fee_required() == Zatoshis::const_from_u64(10000)
1552        );
1553    }
1554
1555    #[test]
1556    #[cfg(feature = "transparent-inputs")]
1557    fn transparent_change_policy_has_no_effect_on_shielded_flows() {
1558        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1559            Zip317FeeRule::standard(),
1560            None,
1561            ShieldedPool::Sapling,
1562            DustOutputPolicy::default(),
1563        )
1564        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
1565
1566        // Spend a single Sapling note; because the transaction involves shielded flows, the
1567        // change must be shielded even though transparent change is allowed by the policy.
1568        let result = change_strategy.compute_balance(
1569            &Network::TestNetwork,
1570            Network::TestNetwork
1571                .activation_height(NetworkUpgrade::Nu5)
1572                .unwrap()
1573                .into(),
1574            BlockHeight::from_u32(1),
1575            &PoolMigrationParams::new(
1576                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1577                AnchorRetentionInterval::ZIP_318,
1578            ),
1579            &[] as &[TestTransparentInput],
1580            &[] as &[TxOut<Zatoshis>],
1581            &(
1582                sapling::builder::BundleType::DEFAULT,
1583                &[TestSaplingInput {
1584                    note_id: 0,
1585                    value: Zatoshis::const_from_u64(55000),
1586                }][..],
1587                &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..],
1588            ),
1589            #[cfg(feature = "orchard")]
1590            &orchard_fees::EmptyBundleView,
1591            #[cfg(feature = "orchard")]
1592            &orchard_fees::EmptyBundleView,
1593            None,
1594            &all_change_receivers(),
1595        );
1596
1597        assert_matches!(
1598            result,
1599            Ok(balance) if
1600                balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(5000), None)] &&
1601                balance.fee_required() == Zatoshis::const_from_u64(10000)
1602        );
1603    }
1604
1605    #[test]
1606    #[cfg(feature = "transparent-inputs")]
1607    fn transparent_change_is_not_split() {
1608        let change_strategy = MultiOutputChangeStrategy::<_, MockWalletDb>::new(
1609            Zip317FeeRule::standard(),
1610            None,
1611            ShieldedPool::Sapling,
1612            DustOutputPolicy::default(),
1613            SplitPolicy::with_min_output_value(
1614                NonZeroUsize::new(5).unwrap(),
1615                Zatoshis::const_from_u64(100_0000),
1616            ),
1617        )
1618        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
1619
1620        // Spend a single transparent UTXO with change value sufficient to produce five
1621        // split outputs under the split policy; because the change is returned to the
1622        // transparent pool, it must nevertheless be emitted as a single output.
1623        let result = change_strategy.compute_balance::<_, Infallible>(
1624            &Network::TestNetwork,
1625            Network::TestNetwork
1626                .activation_height(NetworkUpgrade::Nu5)
1627                .unwrap()
1628                .into(),
1629            BlockHeight::from_u32(1),
1630            &PoolMigrationParams::new(
1631                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1632                AnchorRetentionInterval::ZIP_318,
1633            ),
1634            &[TestTransparentInput {
1635                outpoint: OutPoint::fake(),
1636                coin: TxOut::new(
1637                    Zatoshis::const_from_u64(750_0000),
1638                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1639                ),
1640            }],
1641            &[TxOut::new(
1642                Zatoshis::const_from_u64(100_0000),
1643                Script::default(),
1644            )],
1645            &sapling_fees::EmptyBundleView,
1646            #[cfg(feature = "orchard")]
1647            &orchard_fees::EmptyBundleView,
1648            #[cfg(feature = "orchard")]
1649            &orchard_fees::EmptyBundleView,
1650            None,
1651            &AccountMeta::new(
1652                Some(PoolMeta::new(0, Zatoshis::ZERO)),
1653                None,
1654                None,
1655                all_change_receivers(),
1656            ),
1657        );
1658
1659        assert_matches!(
1660            result,
1661            Ok(balance) if
1662                balance.proposed_change() == [ChangeValue::transparent(Zatoshis::const_from_u64(649_0000))] &&
1663                balance.fee_required() == Zatoshis::const_from_u64(10000)
1664        );
1665    }
1666
1667    #[test]
1668    #[cfg(feature = "transparent-inputs")]
1669    fn transparent_change_rejects_dust() {
1670        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1671            Zip317FeeRule::standard(),
1672            None,
1673            ShieldedPool::Sapling,
1674            DustOutputPolicy::default(),
1675        )
1676        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
1677
1678        // Spend a single transparent UTXO that would result in a 100-zat transparent change
1679        // output; under the default dust policy this must be rejected. The 55000-zat
1680        // requirement reflects the 5000-zat default dust threshold: adding 4900 zats to the
1681        // input value would produce change exactly at the threshold.
1682        let result = change_strategy.compute_balance::<_, Infallible>(
1683            &Network::TestNetwork,
1684            Network::TestNetwork
1685                .activation_height(NetworkUpgrade::Nu5)
1686                .unwrap()
1687                .into(),
1688            BlockHeight::from_u32(1),
1689            &PoolMigrationParams::new(
1690                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1691                AnchorRetentionInterval::ZIP_318,
1692            ),
1693            &[TestTransparentInput {
1694                outpoint: OutPoint::fake(),
1695                coin: TxOut::new(
1696                    Zatoshis::const_from_u64(50100),
1697                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1698                ),
1699            }],
1700            &[TxOut::new(
1701                Zatoshis::const_from_u64(40000),
1702                Script::default(),
1703            )],
1704            &sapling_fees::EmptyBundleView,
1705            #[cfg(feature = "orchard")]
1706            &orchard_fees::EmptyBundleView,
1707            #[cfg(feature = "orchard")]
1708            &orchard_fees::EmptyBundleView,
1709            None,
1710            &all_change_receivers(),
1711        );
1712
1713        assert_matches!(
1714            result,
1715            Err(ChangeError::InsufficientFunds { available, required })
1716                if available == Zatoshis::const_from_u64(50100)
1717                   && required == Zatoshis::const_from_u64(55000)
1718        );
1719    }
1720
1721    #[test]
1722    #[cfg(feature = "transparent-inputs")]
1723    fn transparent_change_allows_dust() {
1724        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1725            Zip317FeeRule::standard(),
1726            None,
1727            ShieldedPool::Sapling,
1728            DustOutputPolicy::new(
1729                DustAction::AllowDustChange,
1730                Some(Zatoshis::const_from_u64(1000)),
1731            ),
1732        )
1733        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
1734
1735        // Spend a single transparent UTXO that results in a 100-zat transparent change
1736        // output; the `AllowDustChange` policy permits emitting it even though it is below
1737        // the 1000-zat dust threshold.
1738        let result = change_strategy.compute_balance::<_, Infallible>(
1739            &Network::TestNetwork,
1740            Network::TestNetwork
1741                .activation_height(NetworkUpgrade::Nu5)
1742                .unwrap()
1743                .into(),
1744            BlockHeight::from_u32(1),
1745            &PoolMigrationParams::new(
1746                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1747                AnchorRetentionInterval::ZIP_318,
1748            ),
1749            &[TestTransparentInput {
1750                outpoint: OutPoint::fake(),
1751                coin: TxOut::new(
1752                    Zatoshis::const_from_u64(50100),
1753                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1754                ),
1755            }],
1756            &[TxOut::new(
1757                Zatoshis::const_from_u64(40000),
1758                Script::default(),
1759            )],
1760            &sapling_fees::EmptyBundleView,
1761            #[cfg(feature = "orchard")]
1762            &orchard_fees::EmptyBundleView,
1763            #[cfg(feature = "orchard")]
1764            &orchard_fees::EmptyBundleView,
1765            None,
1766            &all_change_receivers(),
1767        );
1768
1769        assert_matches!(
1770            result,
1771            Ok(balance) if
1772                balance.proposed_change() == [ChangeValue::transparent(Zatoshis::const_from_u64(100))] &&
1773                balance.fee_required() == Zatoshis::const_from_u64(10000)
1774        );
1775    }
1776
1777    #[test]
1778    #[cfg(feature = "transparent-inputs")]
1779    fn transparent_change_dust_added_to_fee() {
1780        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1781            Zip317FeeRule::standard(),
1782            None,
1783            ShieldedPool::Sapling,
1784            DustOutputPolicy::new(DustAction::AddDustToFee, None),
1785        )
1786        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
1787
1788        // Spend a single transparent UTXO that would result in a 100-zat transparent change
1789        // output; under the `AddDustToFee` policy the dust value is instead added to the
1790        // fee and no change output is produced.
1791        let result = change_strategy.compute_balance::<_, Infallible>(
1792            &Network::TestNetwork,
1793            Network::TestNetwork
1794                .activation_height(NetworkUpgrade::Nu5)
1795                .unwrap()
1796                .into(),
1797            BlockHeight::from_u32(1),
1798            &PoolMigrationParams::new(
1799                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1800                AnchorRetentionInterval::ZIP_318,
1801            ),
1802            &[TestTransparentInput {
1803                outpoint: OutPoint::fake(),
1804                coin: TxOut::new(
1805                    Zatoshis::const_from_u64(50100),
1806                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
1807                ),
1808            }],
1809            &[TxOut::new(
1810                Zatoshis::const_from_u64(40000),
1811                Script::default(),
1812            )],
1813            &sapling_fees::EmptyBundleView,
1814            #[cfg(feature = "orchard")]
1815            &orchard_fees::EmptyBundleView,
1816            #[cfg(feature = "orchard")]
1817            &orchard_fees::EmptyBundleView,
1818            None,
1819            &all_change_receivers(),
1820        );
1821
1822        assert_matches!(
1823            result,
1824            Ok(balance) if
1825                balance.proposed_change().is_empty() &&
1826                balance.fee_required() == Zatoshis::const_from_u64(10100)
1827        );
1828    }
1829
1830    #[test]
1831    fn change_with_allowable_dust_implicitly_allowing_zero_change() {
1832        change_with_allowable_dust(DustOutputPolicy::default())
1833    }
1834
1835    #[test]
1836    fn change_with_allowable_dust_explicitly_allowing_zero_change() {
1837        change_with_allowable_dust(DustOutputPolicy::new(
1838            DustAction::AllowDustChange,
1839            Some(Zatoshis::ZERO),
1840        ))
1841    }
1842
1843    fn change_with_allowable_dust(dust_output_policy: DustOutputPolicy) {
1844        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1845            Zip317FeeRule::standard(),
1846            None,
1847            ShieldedPool::Sapling,
1848            dust_output_policy,
1849        );
1850
1851        // Spend two Sapling notes, one of them dust. There is sufficient to
1852        // pay the fee: if only one note is spent then we are 1000 short, but
1853        // if both notes are spent then the fee stays at 10000 (even with a
1854        // zero-valued change output), so we have just enough.
1855        let result = change_strategy.compute_balance(
1856            &Network::TestNetwork,
1857            Network::TestNetwork
1858                .activation_height(NetworkUpgrade::Nu5)
1859                .unwrap()
1860                .into(),
1861            BlockHeight::from_u32(1),
1862            &PoolMigrationParams::new(
1863                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1864                AnchorRetentionInterval::ZIP_318,
1865            ),
1866            &[] as &[TestTransparentInput],
1867            &[] as &[TxOut<Zatoshis>],
1868            &(
1869                sapling::builder::BundleType::DEFAULT,
1870                &[
1871                    TestSaplingInput {
1872                        note_id: 0,
1873                        value: Zatoshis::const_from_u64(49000),
1874                    },
1875                    TestSaplingInput {
1876                        note_id: 1,
1877                        value: Zatoshis::const_from_u64(1000),
1878                    },
1879                ][..],
1880                &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..],
1881            ),
1882            #[cfg(feature = "orchard")]
1883            &orchard_fees::EmptyBundleView,
1884            #[cfg(feature = "orchard")]
1885            &orchard_fees::EmptyBundleView,
1886            None,
1887            &all_change_receivers(),
1888        );
1889
1890        assert_matches!(
1891            result,
1892            Ok(balance) if
1893                balance.proposed_change() == [ChangeValue::sapling(Zatoshis::ZERO, None)] &&
1894                balance.fee_required() == Zatoshis::const_from_u64(10000)
1895        );
1896    }
1897
1898    #[test]
1899    fn change_with_disallowed_dust() {
1900        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
1901            Zip317FeeRule::standard(),
1902            None,
1903            ShieldedPool::Sapling,
1904            DustOutputPolicy::default(),
1905        );
1906
1907        // Attempt to spend three Sapling notes, one of them dust. Adding the third
1908        // note increases the number of actions, and so it is uneconomic to spend it.
1909        let result = change_strategy.compute_balance(
1910            &Network::TestNetwork,
1911            Network::TestNetwork
1912                .activation_height(NetworkUpgrade::Nu5)
1913                .unwrap()
1914                .into(),
1915            BlockHeight::from_u32(1),
1916            &PoolMigrationParams::new(
1917                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1918                AnchorRetentionInterval::ZIP_318,
1919            ),
1920            &[] as &[TestTransparentInput],
1921            &[] as &[TxOut<Zatoshis>],
1922            &(
1923                sapling::builder::BundleType::DEFAULT,
1924                &[
1925                    TestSaplingInput {
1926                        note_id: 0,
1927                        value: Zatoshis::const_from_u64(29000),
1928                    },
1929                    TestSaplingInput {
1930                        note_id: 1,
1931                        value: Zatoshis::const_from_u64(20000),
1932                    },
1933                    TestSaplingInput {
1934                        note_id: 2,
1935                        value: Zatoshis::const_from_u64(1000),
1936                    },
1937                ][..],
1938                &[SaplingPayment::new(Zatoshis::const_from_u64(30000))][..],
1939            ),
1940            #[cfg(feature = "orchard")]
1941            &orchard_fees::EmptyBundleView,
1942            #[cfg(feature = "orchard")]
1943            &orchard_fees::EmptyBundleView,
1944            None,
1945            &all_change_receivers(),
1946        );
1947
1948        // We will get an error here, because the dust input isn't free to add
1949        // to the transaction.
1950        assert_matches!(
1951            result,
1952            Err(ChangeError::DustInputs { sapling, .. }) if sapling == vec![2]
1953        );
1954    }
1955
1956    /// Returns the height at which the fee reduction of ZIP 2009 takes effect on `network`: on
1957    /// a regtest network, the NU7 activation height.
1958    fn fee_reduction_height(network: &LocalNetwork) -> BlockHeight {
1959        network
1960            .activation_height(NetworkUpgrade::Nu7)
1961            .expect("the test network activates NU7")
1962    }
1963
1964    /// Computes the balance of a Sapling-only transaction under `change_strategy` at
1965    /// `target_height` on `network`: `inputs` are the values of the notes spent, numbered in
1966    /// order, and `payment` the single Sapling payment.
1967    fn sapling_balance_at(
1968        change_strategy: &SingleOutputChangeStrategy<Zip317FeeRule, MockWalletDb>,
1969        network: &LocalNetwork,
1970        target_height: BlockHeight,
1971        inputs: &[Zatoshis],
1972        payment: Zatoshis,
1973    ) -> Result<TransactionBalance, ChangeError<Zip317FeeError, u32>> {
1974        /// Sapling-only flows do not consult the anchor, so any height serves.
1975        const ANCHOR_HEIGHT: BlockHeight = BlockHeight::from_u32(1);
1976
1977        let inputs: Vec<_> = inputs
1978            .iter()
1979            .enumerate()
1980            .map(|(note_id, value)| TestSaplingInput {
1981                note_id: u32::try_from(note_id).expect("a handful of notes"),
1982                value: *value,
1983            })
1984            .collect();
1985        change_strategy.compute_balance(
1986            network,
1987            target_height.into(),
1988            ANCHOR_HEIGHT,
1989            &PoolMigrationParams::new(
1990                zcash_protocol::zip318::BlockSpacing::UNIFORM,
1991                AnchorRetentionInterval::ZIP_318,
1992            ),
1993            &[] as &[TestTransparentInput],
1994            &[] as &[TxOut<Zatoshis>],
1995            &(
1996                sapling::builder::BundleType::DEFAULT,
1997                &inputs[..],
1998                &[SaplingPayment::new(payment)][..],
1999            ),
2000            #[cfg(feature = "orchard")]
2001            &orchard_fees::EmptyBundleView,
2002            #[cfg(feature = "orchard")]
2003            &orchard_fees::EmptyBundleView,
2004            None,
2005            &all_change_receivers(),
2006        )
2007    }
2008
2009    /// An input is uneconomic if and only if its value is at most the marginal fee in effect at the target
2010    /// height, and change is dust if and only if it is below that fee; both boundaries follow the ZIP 317
2011    /// schedule across the fee reduction of ZIP 2009.
2012    #[test]
2013    fn uneconomic_inputs_and_dust_follow_marginal_fee_at_target_height() {
2014        /// Two notes that are never dust and together cover `FUNDED_PAYMENT`, so a third note
2015        /// is spent only if it is free to add.
2016        const FUNDING_NOTES: [Zatoshis; 2] = [
2017            Zatoshis::const_from_u64(29_000),
2018            Zatoshis::const_from_u64(20_000),
2019        ];
2020        /// The payment made from `FUNDING_NOTES` plus a candidate note.
2021        const FUNDED_PAYMENT: Zatoshis = Zatoshis::const_from_u64(30_000);
2022        /// The payment made from a single note when probing the change dust boundary.
2023        const SINGLE_NOTE_PAYMENT: Zatoshis = Zatoshis::const_from_u64(40_000);
2024        /// The index of the candidate note in `FUNDING_NOTES ++ [candidate]`.
2025        const CANDIDATE_NOTE_ID: u32 = 2;
2026        /// Logical actions in the single-note case: one spend, and a payment plus a change
2027        /// output; equal to the grace allowance, so the fee is the minimum fee.
2028        const SINGLE_NOTE_ACTIONS: usize = 2;
2029        /// Logical actions when the candidate note is spent alongside `FUNDING_NOTES`: three
2030        /// spends against two outputs.
2031        const THREE_NOTE_ACTIONS: usize = 3;
2032
2033        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2034            Zip317FeeRule::standard(),
2035            None,
2036            ShieldedPool::Sapling,
2037            DustOutputPolicy::default(),
2038        );
2039        let net = nu7_activating_network();
2040        let reduction_height = fee_reduction_height(&net);
2041
2042        // The schedule itself is pinned by `zip317_rule_charges_fee_in_effect_at_target_height`.
2043        for target_height in [reduction_height - 1, reduction_height] {
2044            let marginal = marginal_fee(&net, target_height);
2045            let one_above = (marginal + Zatoshis::const_from_u64(1)).unwrap();
2046            let one_below = (marginal - Zatoshis::const_from_u64(1)).unwrap();
2047
2048            // A third note worth exactly the marginal fee is uneconomic: spending it adds a
2049            // logical action that costs more than the note is worth.
2050            let funding_plus = |candidate| [FUNDING_NOTES[0], FUNDING_NOTES[1], candidate];
2051            assert_matches!(
2052                sapling_balance_at(
2053                    &change_strategy,
2054                    &net,
2055                    target_height,
2056                    &funding_plus(marginal),
2057                    FUNDED_PAYMENT,
2058                ),
2059                Err(ChangeError::DustInputs { sapling, .. }) if sapling == vec![CANDIDATE_NOTE_ID],
2060                "input of {marginal:?} at {target_height:?} should be uneconomic",
2061            );
2062
2063            // One zatoshi more and it is spent, paying the marginal fee for its action.
2064            let three_note_fee = (marginal * THREE_NOTE_ACTIONS).unwrap();
2065            let three_note_in = (FUNDING_NOTES[0] + FUNDING_NOTES[1])
2066                .and_then(|v| v + one_above)
2067                .unwrap();
2068            let three_note_change = (three_note_in - FUNDED_PAYMENT)
2069                .and_then(|v| v - three_note_fee)
2070                .unwrap();
2071            assert_matches!(
2072                sapling_balance_at(
2073                    &change_strategy,
2074                    &net,
2075                    target_height,
2076                    &funding_plus(one_above),
2077                    FUNDED_PAYMENT,
2078                ),
2079                Ok(balance) if
2080                    balance.proposed_change() == [ChangeValue::sapling(three_note_change, None)] &&
2081                    balance.fee_required() == three_note_fee,
2082                "input of {one_above:?} at {target_height:?} should be economic",
2083            );
2084
2085            // Change one zatoshi below the marginal fee is dust and rejected under the default
2086            // policy; change of exactly the marginal fee is kept.
2087            let single_note_fee = (marginal * SINGLE_NOTE_ACTIONS).unwrap();
2088            assert_eq!(single_note_fee, minimum_fee(&net, target_height));
2089            let note_leaving = |change| {
2090                (SINGLE_NOTE_PAYMENT + single_note_fee)
2091                    .and_then(|v| v + change)
2092                    .unwrap()
2093            };
2094            assert_matches!(
2095                sapling_balance_at(
2096                    &change_strategy,
2097                    &net,
2098                    target_height,
2099                    &[note_leaving(one_below)],
2100                    SINGLE_NOTE_PAYMENT,
2101                ),
2102                Err(ChangeError::InsufficientFunds { available, required })
2103                    if available == note_leaving(one_below) && required == note_leaving(marginal),
2104                "change of {one_below:?} at {target_height:?} should be dust",
2105            );
2106            assert_matches!(
2107                sapling_balance_at(
2108                    &change_strategy,
2109                    &net,
2110                    target_height,
2111                    &[note_leaving(marginal)],
2112                    SINGLE_NOTE_PAYMENT,
2113                ),
2114                Ok(balance) if
2115                    balance.proposed_change() == [ChangeValue::sapling(marginal, None)] &&
2116                    balance.fee_required() == single_note_fee,
2117                "change of {marginal:?} at {target_height:?} should be kept",
2118            );
2119        }
2120    }
2121
2122    /// Under `DustAction::AddDustToFee`, dust is folded into the fee only up to ten times the
2123    /// minimum fee in effect at the target height; above that it is kept as a change output.
2124    #[test]
2125    fn add_dust_to_fee_cap_follows_minimum_fee() {
2126        /// The payment made from a single note.
2127        const PAYMENT: Zatoshis = Zatoshis::const_from_u64(40_000);
2128        /// A dust threshold above every change value probed, so that the cap alone decides.
2129        const DUST_THRESHOLD: Zatoshis = Zatoshis::const_from_u64(30_000);
2130
2131        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2132            Zip317FeeRule::standard(),
2133            None,
2134            ShieldedPool::Sapling,
2135            DustOutputPolicy::new(DustAction::AddDustToFee, Some(DUST_THRESHOLD)),
2136        );
2137        let net = nu7_activating_network();
2138        let target_height = fee_reduction_height(&net);
2139        // One spend, a payment and a change output: the grace allowance, so the minimum fee.
2140        let fee = minimum_fee(&net, target_height);
2141        let cap = (fee * DUST_TO_FEE_CAP_MINIMUM_FEES).unwrap();
2142        assert_eq!(u64::from(cap), 20_000);
2143        let one_above_cap = (cap + Zatoshis::const_from_u64(1)).unwrap();
2144        let note_leaving = |change| (PAYMENT + fee).and_then(|v| v + change).unwrap();
2145
2146        // Dust of exactly the cap is folded into the fee.
2147        assert_matches!(
2148            sapling_balance_at(
2149                &change_strategy,
2150                &net,
2151                target_height,
2152                &[note_leaving(cap)],
2153                PAYMENT,
2154            ),
2155            Ok(balance) if
2156                balance.proposed_change().is_empty() &&
2157                balance.fee_required() == (fee + cap).unwrap()
2158        );
2159
2160        // One zatoshi more and it is returned as change instead.
2161        assert_matches!(
2162            sapling_balance_at(
2163                &change_strategy,
2164                &net,
2165                target_height,
2166                &[note_leaving(one_above_cap)],
2167                PAYMENT,
2168            ),
2169            Ok(balance) if
2170                balance.proposed_change() == [ChangeValue::sapling(one_above_cap, None)] &&
2171                balance.fee_required() == fee
2172        );
2173
2174        // Before the fee reduction the cap is 100 000, so the same dust is still folded.
2175        let before = target_height - 1;
2176        let fee_before = minimum_fee(&net, before);
2177        assert_eq!(
2178            u64::from((fee_before * DUST_TO_FEE_CAP_MINIMUM_FEES).unwrap()),
2179            100_000
2180        );
2181        assert_matches!(
2182            sapling_balance_at(
2183                &change_strategy,
2184                &net,
2185                before,
2186                &[(PAYMENT + fee_before).and_then(|v| v + one_above_cap).unwrap()],
2187                PAYMENT,
2188            ),
2189            Ok(balance) if
2190                balance.proposed_change().is_empty() &&
2191                balance.fee_required() == (fee_before + one_above_cap).unwrap()
2192        );
2193    }
2194
2195    #[test]
2196    #[cfg(feature = "orchard")]
2197    fn sapling_only_account_paying_orchard_gets_sapling_change() {
2198        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2199            Zip317FeeRule::standard(),
2200            None,
2201            ShieldedPool::Orchard,
2202            DustOutputPolicy::default(),
2203        );
2204
2205        // The account has no Orchard key, so the change from paying an Orchard recipient
2206        // goes to the Sapling pool that the transaction spends from.
2207        let result = change_strategy.compute_balance(
2208            &Network::TestNetwork,
2209            Network::TestNetwork
2210                .activation_height(NetworkUpgrade::Nu5)
2211                .unwrap()
2212                .into(),
2213            BlockHeight::from_u32(1),
2214            &PoolMigrationParams::new(
2215                zcash_protocol::zip318::BlockSpacing::UNIFORM,
2216                AnchorRetentionInterval::ZIP_318,
2217            ),
2218            &[] as &[TestTransparentInput],
2219            &[] as &[TxOut<Zatoshis>],
2220            &(
2221                sapling::builder::BundleType::DEFAULT,
2222                &[TestSaplingInput {
2223                    note_id: 0,
2224                    value: Zatoshis::const_from_u64(55000),
2225                }][..],
2226                &[] as &[Infallible],
2227            ),
2228            &(
2229                ::orchard::bundle::BundleVersion::orchard_v2(),
2230                &[] as &[Infallible],
2231                &[OrchardPayment::new(Zatoshis::const_from_u64(30000))][..],
2232            ),
2233            &orchard_fees::EmptyBundleView,
2234            None,
2235            &ChangeReceivers::new(
2236                true,
2237                false,
2238                #[cfg(feature = "transparent-inputs")]
2239                None,
2240            ),
2241        );
2242
2243        assert_matches!(
2244            result,
2245            Ok(balance) if
2246                balance.proposed_change() == [ChangeValue::sapling(Zatoshis::const_from_u64(5000), None)] &&
2247                balance.fee_required() == Zatoshis::const_from_u64(20000)
2248        );
2249    }
2250
2251    #[test]
2252    fn shielded_change_requires_a_shielded_receiver() {
2253        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2254            Zip317FeeRule::standard(),
2255            None,
2256            ShieldedPool::Sapling,
2257            DustOutputPolicy::default(),
2258        );
2259
2260        // An account with no shielded key cannot receive the change of a shielded spend.
2261        let result = change_strategy.compute_balance(
2262            &Network::TestNetwork,
2263            Network::TestNetwork
2264                .activation_height(NetworkUpgrade::Nu5)
2265                .unwrap()
2266                .into(),
2267            BlockHeight::from_u32(1),
2268            &PoolMigrationParams::new(
2269                zcash_protocol::zip318::BlockSpacing::UNIFORM,
2270                AnchorRetentionInterval::ZIP_318,
2271            ),
2272            &[] as &[TestTransparentInput],
2273            &[] as &[TxOut<Zatoshis>],
2274            &(
2275                sapling::builder::BundleType::DEFAULT,
2276                &[TestSaplingInput {
2277                    note_id: 0,
2278                    value: Zatoshis::const_from_u64(55000),
2279                }][..],
2280                &[SaplingPayment::new(Zatoshis::const_from_u64(40000))][..],
2281            ),
2282            #[cfg(feature = "orchard")]
2283            &orchard_fees::EmptyBundleView,
2284            #[cfg(feature = "orchard")]
2285            &orchard_fees::EmptyBundleView,
2286            None,
2287            &ChangeReceivers::new(
2288                false,
2289                false,
2290                #[cfg(feature = "transparent-inputs")]
2291                Some(TransparentChangeKind::P2pkh),
2292            ),
2293        );
2294
2295        assert_matches!(
2296            result,
2297            Err(ChangeError::UnsupportedChangePool(pool)) if pool == PoolType::SAPLING
2298        );
2299    }
2300
2301    #[test]
2302    #[cfg(feature = "transparent-inputs")]
2303    fn transparent_change_requires_a_transparent_receiver() {
2304        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2305            Zip317FeeRule::standard(),
2306            None,
2307            ShieldedPool::Sapling,
2308            DustOutputPolicy::default(),
2309        )
2310        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
2311
2312        // Transparent change is allowed, but the account has no transparent key.
2313        let result = change_strategy.compute_balance::<_, Infallible>(
2314            &Network::TestNetwork,
2315            Network::TestNetwork
2316                .activation_height(NetworkUpgrade::Nu5)
2317                .unwrap()
2318                .into(),
2319            BlockHeight::from_u32(1),
2320            &PoolMigrationParams::new(
2321                zcash_protocol::zip318::BlockSpacing::UNIFORM,
2322                AnchorRetentionInterval::ZIP_318,
2323            ),
2324            &[TestTransparentInput {
2325                outpoint: OutPoint::fake(),
2326                coin: TxOut::new(
2327                    Zatoshis::const_from_u64(63000),
2328                    TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
2329                ),
2330            }],
2331            &[TxOut::new(
2332                Zatoshis::const_from_u64(40000),
2333                Script::default(),
2334            )],
2335            &sapling_fees::EmptyBundleView,
2336            #[cfg(feature = "orchard")]
2337            &orchard_fees::EmptyBundleView,
2338            #[cfg(feature = "orchard")]
2339            &orchard_fees::EmptyBundleView,
2340            None,
2341            &ChangeReceivers::new(true, true, None),
2342        );
2343
2344        assert_matches!(
2345            result,
2346            Err(ChangeError::UnsupportedChangePool(pool)) if pool == PoolType::TRANSPARENT
2347        );
2348    }
2349
2350    #[test]
2351    #[cfg(feature = "transparent-inputs")]
2352    fn missing_transparent_receiver_does_not_hide_insufficient_funds() {
2353        /// The value of the transparent payment.
2354        const PAYMENT_VALUE: Zatoshis = Zatoshis::const_from_u64(40000);
2355
2356        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2357            Zip317FeeRule::standard(),
2358            None,
2359            ShieldedPool::Sapling,
2360            DustOutputPolicy::default(),
2361        )
2362        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
2363
2364        // Input selection starts with no inputs. A shielded-only account that pays a
2365        // transparent address must learn that it needs more funds, so that shielded notes
2366        // can be selected.
2367        let result = change_strategy.compute_balance::<_, Infallible>(
2368            &Network::TestNetwork,
2369            Network::TestNetwork
2370                .activation_height(NetworkUpgrade::Nu5)
2371                .unwrap()
2372                .into(),
2373            BlockHeight::from_u32(1),
2374            &PoolMigrationParams::new(
2375                zcash_protocol::zip318::BlockSpacing::UNIFORM,
2376                AnchorRetentionInterval::ZIP_318,
2377            ),
2378            &[] as &[TestTransparentInput],
2379            &[TxOut::new(PAYMENT_VALUE, Script::default())],
2380            &sapling_fees::EmptyBundleView,
2381            #[cfg(feature = "orchard")]
2382            &orchard_fees::EmptyBundleView,
2383            #[cfg(feature = "orchard")]
2384            &orchard_fees::EmptyBundleView,
2385            None,
2386            &ChangeReceivers::new(true, true, None),
2387        );
2388
2389        assert_matches!(
2390            result,
2391            Err(ChangeError::InsufficientFunds { available, required })
2392                if available == Zatoshis::ZERO && required == (PAYMENT_VALUE + MINIMUM_FEE).unwrap()
2393        );
2394    }
2395
2396    #[test]
2397    #[cfg(feature = "transparent-inputs")]
2398    fn changeless_transparent_transaction_needs_no_transparent_receiver() {
2399        /// The value of the transparent payment.
2400        const PAYMENT_VALUE: Zatoshis = Zatoshis::const_from_u64(40000);
2401
2402        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2403            Zip317FeeRule::standard(),
2404            None,
2405            ShieldedPool::Sapling,
2406            DustOutputPolicy::default(),
2407        )
2408        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
2409
2410        // The second transaction of a ZIP 320 pair spends the ephemeral output exactly, so it
2411        // has no change output. The account needs no transparent receiver for it.
2412        let result = change_strategy.compute_balance::<_, Infallible>(
2413            &Network::TestNetwork,
2414            Network::TestNetwork
2415                .activation_height(NetworkUpgrade::Nu5)
2416                .unwrap()
2417                .into(),
2418            BlockHeight::from_u32(1),
2419            &PoolMigrationParams::new(
2420                zcash_protocol::zip318::BlockSpacing::UNIFORM,
2421                AnchorRetentionInterval::ZIP_318,
2422            ),
2423            &[] as &[TestTransparentInput],
2424            &[TxOut::new(PAYMENT_VALUE, Script::default())],
2425            &sapling_fees::EmptyBundleView,
2426            #[cfg(feature = "orchard")]
2427            &orchard_fees::EmptyBundleView,
2428            #[cfg(feature = "orchard")]
2429            &orchard_fees::EmptyBundleView,
2430            Some(EphemeralBalance::Input(
2431                (PAYMENT_VALUE + MINIMUM_FEE).unwrap(),
2432            )),
2433            &ChangeReceivers::new(true, true, None),
2434        );
2435
2436        assert_matches!(
2437            result,
2438            Ok(balance) if balance.proposed_change().is_empty() && balance.fee_required() == MINIMUM_FEE
2439        );
2440    }
2441
2442    #[test]
2443    #[cfg(feature = "transparent-inputs")]
2444    fn transparent_change_is_sized_by_its_kind() {
2445        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2446            Zip317FeeRule::standard(),
2447            None,
2448            ShieldedPool::Sapling,
2449            DustOutputPolicy::default(),
2450        )
2451        .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
2452
2453        // Sixteen 32-byte P2SH payments make 512 bytes of outputs. A 32-byte P2SH change
2454        // output brings this to 544 bytes, which is 16 logical actions of 34 bytes. A
2455        // 34-byte P2PKH change output brings it to 546 bytes, which is 17 logical actions.
2456        let payments = vec![
2457            TxOut::new(
2458                Zatoshis::const_from_u64(5000),
2459                TransparentAddress::ScriptHash([0u8; 20]).script().into(),
2460            );
2461            16
2462        ];
2463        let balance = |kind| {
2464            change_strategy.compute_balance::<_, Infallible>(
2465                &Network::TestNetwork,
2466                Network::TestNetwork
2467                    .activation_height(NetworkUpgrade::Nu5)
2468                    .unwrap()
2469                    .into(),
2470                BlockHeight::from_u32(1),
2471                &PoolMigrationParams::new(
2472                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
2473                    AnchorRetentionInterval::ZIP_318,
2474                ),
2475                &[TestTransparentInput {
2476                    outpoint: OutPoint::fake(),
2477                    coin: TxOut::new(
2478                        Zatoshis::const_from_u64(200000),
2479                        TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
2480                    ),
2481                }],
2482                &payments[..],
2483                &sapling_fees::EmptyBundleView,
2484                #[cfg(feature = "orchard")]
2485                &orchard_fees::EmptyBundleView,
2486                #[cfg(feature = "orchard")]
2487                &orchard_fees::EmptyBundleView,
2488                None,
2489                &ChangeReceivers::new(false, false, Some(kind)),
2490            )
2491        };
2492
2493        assert_matches!(
2494            balance(TransparentChangeKind::P2sh),
2495            Ok(balance) if
2496                balance.proposed_change() == [ChangeValue::transparent(Zatoshis::const_from_u64(40000))] &&
2497                balance.fee_required() == Zatoshis::const_from_u64(80000)
2498        );
2499        assert_matches!(
2500            balance(TransparentChangeKind::P2pkh),
2501            Ok(balance) if
2502                balance.proposed_change() == [ChangeValue::transparent(Zatoshis::const_from_u64(35000))] &&
2503                balance.fee_required() == Zatoshis::const_from_u64(85000)
2504        );
2505    }
2506
2507    #[test]
2508    #[cfg(feature = "transparent-inputs")]
2509    fn ephemeral_output_requires_a_p2pkh_receiver() {
2510        let change_strategy = SingleOutputChangeStrategy::<_, MockWalletDb>::new(
2511            Zip317FeeRule::standard(),
2512            None,
2513            ShieldedPool::Sapling,
2514            DustOutputPolicy::default(),
2515        );
2516
2517        // The first transaction of a ZIP 320 pair sends value to an ephemeral P2PKH
2518        // address of the account. An account whose transparent key is a P2SH key has no
2519        // such address.
2520        let balance = |kind| {
2521            change_strategy.compute_balance::<_, Infallible>(
2522                &Network::TestNetwork,
2523                Network::TestNetwork
2524                    .activation_height(NetworkUpgrade::Nu5)
2525                    .unwrap()
2526                    .into(),
2527                BlockHeight::from_u32(1),
2528                &PoolMigrationParams::new(
2529                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
2530                    AnchorRetentionInterval::ZIP_318,
2531                ),
2532                &[TestTransparentInput {
2533                    outpoint: OutPoint::fake(),
2534                    coin: TxOut::new(
2535                        Zatoshis::const_from_u64(100000),
2536                        TransparentAddress::PublicKeyHash([0u8; 20]).script().into(),
2537                    ),
2538                }],
2539                &[] as &[TxOut<Zatoshis>],
2540                &sapling_fees::EmptyBundleView,
2541                #[cfg(feature = "orchard")]
2542                &orchard_fees::EmptyBundleView,
2543                #[cfg(feature = "orchard")]
2544                &orchard_fees::EmptyBundleView,
2545                Some(EphemeralBalance::Output(Zatoshis::const_from_u64(50000))),
2546                &ChangeReceivers::new(true, false, Some(kind)),
2547            )
2548        };
2549
2550        assert_matches!(
2551            balance(TransparentChangeKind::P2sh),
2552            Err(ChangeError::UnsupportedChangePool(pool)) if pool == PoolType::TRANSPARENT
2553        );
2554        assert_matches!(
2555            balance(TransparentChangeKind::P2pkh),
2556            Ok(balance) if balance.proposed_change().iter().any(|c| c.is_ephemeral())
2557        );
2558    }
2559}