zakura-client-backend 0.1.0-rc2

APIs for creating shielded Zcash light clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
use std::{
    convert::Infallible,
    fmt::{self, Debug, Display},
    num::{NonZeroU64, NonZeroUsize},
};

use ::transparent::bundle::OutPoint;
use zcash_primitives::transaction::fees::{
    FeeRule,
    transparent::{self, InputSize},
    zip317 as prim_zip317,
};
use zcash_protocol::{
    PoolType, ShieldedPool,
    consensus::{self, BlockHeight},
    memo::MemoBytes,
    value::{BalanceError, Zatoshis},
};

use crate::data_api::{InputSource, anchor_retention::PoolMigrationParams, wallet::TargetHeight};

pub mod common;
#[cfg(feature = "non-standard-fees")]
pub mod fixed;
#[cfg(feature = "orchard")]
pub mod orchard;
pub mod sapling;
pub mod standard;
pub mod zip317;

/// An enumeration of the standard fee rules supported by the wallet backend.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum StandardFeeRule {
    Zip317,
}

impl FeeRule for StandardFeeRule {
    type Error = prim_zip317::FeeError;

    fn fee_required<P: consensus::Parameters>(
        &self,
        params: &P,
        target_height: BlockHeight,
        transparent_input_sizes: impl IntoIterator<Item = InputSize>,
        transparent_output_sizes: impl IntoIterator<Item = usize>,
        sapling_input_count: usize,
        sapling_output_count: usize,
        orchard_action_count: usize,
        ironwood_action_count: usize,
    ) -> Result<Zatoshis, Self::Error> {
        #[allow(deprecated)]
        match self {
            Self::Zip317 => prim_zip317::FeeRule::standard().fee_required(
                params,
                target_height,
                transparent_input_sizes,
                transparent_output_sizes,
                sapling_input_count,
                sapling_output_count,
                orchard_action_count,
                ironwood_action_count,
            ),
        }
    }
}

/// A policy that determines how change should be returned to the wallet when the net flows of a
/// transaction under construction are fully transparent.
///
/// This policy has no effect on transactions that have any shielded inputs or outputs; change
/// for such transactions is always returned to a shielded pool, irrespective of the policy in
/// use. When the flows of a transaction are fully transparent, shielding change (the default)
/// reveals the change amount as the value of the shielded output(s) in an otherwise-transparent
/// transaction; returning the change to the transparent pool matches the behavior of
/// transparent-only wallets (including `zcashd`) at the cost of the change remaining unshielded.
///
/// Transparent change is currently always sent to a P2PKH address derived under the wallet
/// account's internal scope; returning change to the originating address when spending from a
/// P2SH (e.g. multisig) address is not yet supported. See [zcash/librustzcash#2570] for
/// details.
///
/// [zcash/librustzcash#2570]: https://github.com/zcash/librustzcash/issues/2570
#[cfg(feature = "transparent-inputs")]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TransparentChangePolicy {
    /// Change is always returned to a shielded pool, even when the net flows of the transaction
    /// are fully transparent.
    ///
    /// This is the default policy.
    #[default]
    ShieldChange,
    /// When the net flows of the transaction are fully transparent, change is returned to the
    /// transparent pool at an internal-scope (change) transparent address of the wallet, as
    /// described in [BIP 44].
    ///
    /// [BIP 44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
    TransparentChangeAllowed,
}

/// `ChangeValue` represents either a proposed change output to a shielded pool
/// (with an optional change memo), or if the "transparent-inputs" feature is
/// enabled, an output to the transparent pool: either an ephemeral output as
/// part of a [ZIP 320] transaction pair, or a change output to an
/// internal-scope (change) transparent address of the wallet.
///
/// [ZIP 320]: https://zips.z.cash/zip-0320
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChangeValue(ChangeValueInner);

#[derive(Clone, Debug, PartialEq, Eq)]
enum ChangeValueInner {
    Shielded {
        protocol: ShieldedPool,
        value: Zatoshis,
        memo: Option<MemoBytes>,
    },
    #[cfg(feature = "transparent-inputs")]
    EphemeralTransparent { value: Zatoshis },
    #[cfg(feature = "transparent-inputs")]
    Transparent { value: Zatoshis },
}

impl ChangeValue {
    /// Constructs a new ephemeral transparent output value.
    #[cfg(feature = "transparent-inputs")]
    pub fn ephemeral_transparent(value: Zatoshis) -> Self {
        Self(ChangeValueInner::EphemeralTransparent { value })
    }

    /// Constructs a new change value that will be created as a non-ephemeral transparent output
    /// sent to an internal-scope (change) transparent address of the wallet.
    #[cfg(feature = "transparent-inputs")]
    pub fn transparent(value: Zatoshis) -> Self {
        Self(ChangeValueInner::Transparent { value })
    }

    /// Constructs a new change value that will be created as a shielded output.
    pub fn shielded(protocol: ShieldedPool, value: Zatoshis, memo: Option<MemoBytes>) -> Self {
        Self(ChangeValueInner::Shielded {
            protocol,
            value,
            memo,
        })
    }

    /// Constructs a new change value that will be created as a Sapling output.
    pub fn sapling(value: Zatoshis, memo: Option<MemoBytes>) -> Self {
        Self::shielded(ShieldedPool::Sapling, value, memo)
    }

    /// Constructs a new change value that will be created as an Orchard output.
    #[cfg(feature = "orchard")]
    pub fn orchard(value: Zatoshis, memo: Option<MemoBytes>) -> Self {
        Self::shielded(ShieldedPool::Orchard, value, memo)
    }

    /// Constructs a new change value that will be created as an Ironwood output.
    #[cfg(feature = "orchard")]
    pub fn ironwood(value: Zatoshis, memo: Option<MemoBytes>) -> Self {
        Self::shielded(ShieldedPool::Ironwood, value, memo)
    }

    /// Returns the pool to which the change or ephemeral output should be sent.
    pub fn output_pool(&self) -> PoolType {
        match &self.0 {
            ChangeValueInner::Shielded { protocol, .. } => PoolType::Shielded(*protocol),
            #[cfg(feature = "transparent-inputs")]
            ChangeValueInner::EphemeralTransparent { .. } => PoolType::Transparent,
            #[cfg(feature = "transparent-inputs")]
            ChangeValueInner::Transparent { .. } => PoolType::Transparent,
        }
    }

    /// Returns the value of the change or ephemeral output to be created, in zatoshis.
    pub fn value(&self) -> Zatoshis {
        match &self.0 {
            ChangeValueInner::Shielded { value, .. } => *value,
            #[cfg(feature = "transparent-inputs")]
            ChangeValueInner::EphemeralTransparent { value } => *value,
            #[cfg(feature = "transparent-inputs")]
            ChangeValueInner::Transparent { value } => *value,
        }
    }

    /// Returns the memo to be associated with the output.
    pub fn memo(&self) -> Option<&MemoBytes> {
        match &self.0 {
            ChangeValueInner::Shielded { memo, .. } => memo.as_ref(),
            #[cfg(feature = "transparent-inputs")]
            ChangeValueInner::EphemeralTransparent { .. } => None,
            #[cfg(feature = "transparent-inputs")]
            ChangeValueInner::Transparent { .. } => None,
        }
    }

    /// Whether this is to be an ephemeral output.
    #[cfg_attr(
        not(feature = "transparent-inputs"),
        doc = "This is always false because the `transparent-inputs` feature is
               not enabled."
    )]
    pub fn is_ephemeral(&self) -> bool {
        match &self.0 {
            ChangeValueInner::Shielded { .. } => false,
            #[cfg(feature = "transparent-inputs")]
            ChangeValueInner::EphemeralTransparent { .. } => true,
            #[cfg(feature = "transparent-inputs")]
            ChangeValueInner::Transparent { .. } => false,
        }
    }
}

/// Orchard actions in a canonical ZIP 318 crossing: the spend and its change, or a padding dummy
/// when the note's value exactly covers the crossing and its fee.
#[cfg(feature = "orchard")]
const CANONICAL_CROSSING_ORCHARD_ACTIONS: usize = 2;

/// Ironwood actions in a canonical ZIP 318 crossing: the single unpadded output.
#[cfg(feature = "orchard")]
const CANONICAL_CROSSING_IRONWOOD_ACTIONS: usize = 1;

/// The fee a canonical ZIP 318 crossing pays at `target_height`, obtained by asking the STANDARD
/// ZIP 317 rule what the canonical shape costs.
///
/// ZIP 318 requires this exact fee. Any other value partitions the anonymity set, so a transaction
/// paying a non-standard fee is not a canonical crossing however well its structure matches. The
/// standard rule is used rather than the caller's: a proposal built on a fixed non-standard rule
/// would otherwise be compared against its own fee and always agree.
#[cfg(feature = "orchard")]
pub fn canonical_crossing_fee<P: consensus::Parameters>(
    params: &P,
    target_height: BlockHeight,
) -> Result<Zatoshis, zcash_primitives::transaction::fees::zip317::FeeError> {
    prim_zip317::FeeRule::standard().fee_required(
        params,
        target_height,
        std::iter::empty::<InputSize>(),
        std::iter::empty::<usize>(),
        0,
        0,
        CANONICAL_CROSSING_ORCHARD_ACTIONS,
        CANONICAL_CROSSING_IRONWOOD_ACTIONS,
    )
}

/// The amount of change and fees required to make a transaction's inputs and
/// outputs balance under a specific fee rule, as computed by a particular
/// [`ChangeStrategy`] that is aware of that rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransactionBalance {
    proposed_change: Vec<ChangeValue>,
    fee_required: Zatoshis,

    // A cache for the sum of proposed change and fee; we compute it on construction anyway, so we
    // cache the resulting value.
    total: Zatoshis,

    // The exact number of dummy outputs in each shielded bundle this balance was costed for.
    // `None` is retained for compatibility with callers and serialized proposals that predate
    // explicit transaction-shape modelling.
    dummy_outputs: Option<DummyOutputCounts>,
}

/// The number of dummy outputs in each shielded value pool.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DummyOutputCounts {
    sapling: usize,
    #[cfg(feature = "orchard")]
    orchard: usize,
    #[cfg(feature = "orchard")]
    ironwood: usize,
}

impl DummyOutputCounts {
    /// Constructs per-pool dummy-output counts.
    pub fn new(
        sapling: usize,
        #[cfg(feature = "orchard")] orchard: usize,
        #[cfg(feature = "orchard")] ironwood: usize,
    ) -> Self {
        Self {
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
            #[cfg(feature = "orchard")]
            ironwood,
        }
    }

    /// Returns the number of Sapling dummy outputs.
    pub fn sapling(&self) -> usize {
        self.sapling
    }

    /// Returns the number of Orchard dummy outputs.
    #[cfg(feature = "orchard")]
    pub fn orchard(&self) -> usize {
        self.orchard
    }

    /// Returns the number of Ironwood dummy outputs.
    #[cfg(feature = "orchard")]
    pub fn ironwood(&self) -> usize {
        self.ironwood
    }
}

impl TransactionBalance {
    /// Constructs a new balance from its constituent parts.
    pub fn new(
        proposed_change: Vec<ChangeValue>,
        fee_required: Zatoshis,
    ) -> Result<Self, BalanceError> {
        let total = proposed_change
            .iter()
            .map(|c| c.value())
            .chain(Some(fee_required))
            .sum::<Option<Zatoshis>>()
            .ok_or(BalanceError::Overflow)?;

        Ok(Self {
            proposed_change,
            fee_required,
            total,
            dummy_outputs: None,
        })
    }

    /// Records the exact dummy-output counts this balance was computed for.
    pub fn with_dummy_outputs(mut self, dummy_outputs: DummyOutputCounts) -> Self {
        self.dummy_outputs = Some(dummy_outputs);
        self
    }

    /// Returns the exact dummy-output counts this balance was computed for, when recorded.
    pub fn dummy_outputs(&self) -> Option<DummyOutputCounts> {
        self.dummy_outputs
    }

    /// The change values proposed by the [`ChangeStrategy`] that computed this balance.
    pub fn proposed_change(&self) -> &[ChangeValue] {
        &self.proposed_change
    }

    /// Returns the fee computed for the transaction, assuming that the suggested
    /// change outputs are added to the transaction.
    pub fn fee_required(&self) -> Zatoshis {
        self.fee_required
    }

    /// Returns the sum of the proposed change outputs and the required fee.
    pub fn total(&self) -> Zatoshis {
        self.total
    }
}

/// Errors that can occur in computing suggested change and/or fees.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChangeError<E, NoteRefT> {
    /// Insufficient inputs were provided to change selection to fund the
    /// required outputs and fees.
    InsufficientFunds {
        /// The total of the inputs provided to change selection
        available: Zatoshis,
        /// The total amount of input value required to fund the requested outputs,
        /// including the required fees.
        required: Zatoshis,
    },
    /// Some of the inputs provided to the transaction have value less than the
    /// marginal fee, and could not be determined to have any economic value in
    /// the context of this input selection.
    ///
    /// This determination is potentially conservative in the sense that inputs
    /// with value less than or equal to the marginal fee might be excluded, even
    /// though in practice they would not cause the fee to increase. Inputs with
    /// value greater than the marginal fee will never be excluded.
    ///
    /// The ordering of the inputs in each list is unspecified.
    DustInputs {
        /// The outpoints for transparent inputs that could not be determined to
        /// have economic value in the context of this input selection.
        transparent: Vec<OutPoint>,
        /// The identifiers for Sapling inputs that could not be determined to
        /// have economic value in the context of this input selection.
        sapling: Vec<NoteRefT>,
        /// The identifiers for Orchard inputs that could not be determined to
        /// have economic value in the context of this input selection.
        #[cfg(feature = "orchard")]
        orchard: Vec<NoteRefT>,
        /// The identifiers for Ironwood inputs that could not be determined to
        /// have economic value in the context of this input selection.
        #[cfg(feature = "orchard")]
        ironwood: Vec<NoteRefT>,
    },
    /// An error occurred that was specific to the change selection strategy in use.
    StrategyError(E),
    /// The proposed bundle structure would violate bundle type construction rules.
    BundleError(&'static str),
}

impl<CE: fmt::Display, N: fmt::Display> fmt::Display for ChangeError<CE, N> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self {
            ChangeError::InsufficientFunds {
                available,
                required,
            } => write!(
                f,
                "Insufficient funds: required {} zatoshis, but only {} zatoshis were available.",
                u64::from(*required),
                u64::from(*available)
            ),
            ChangeError::DustInputs {
                transparent,
                sapling,
                #[cfg(feature = "orchard")]
                orchard,
                #[cfg(feature = "orchard")]
                ironwood,
            } => {
                #[cfg(feature = "orchard")]
                let orchard_len = orchard.len() + ironwood.len();
                #[cfg(not(feature = "orchard"))]
                let orchard_len = 0;

                // we can't encode the UA to its string representation because we
                // don't have network parameters here
                write!(
                    f,
                    "Insufficient funds: {} dust inputs were present, but would cost more to spend than they are worth.",
                    transparent.len() + sapling.len() + orchard_len,
                )
            }
            ChangeError::StrategyError(err) => {
                write!(f, "{err}")
            }
            ChangeError::BundleError(err) => {
                write!(
                    f,
                    "The proposed transaction structure violates bundle type constraints: {err}"
                )
            }
        }
    }
}

impl<E, N> std::error::Error for ChangeError<E, N>
where
    E: Debug + Display + std::error::Error + 'static,
    N: Debug + Display + 'static,
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self {
            ChangeError::StrategyError(e) => Some(e),
            _ => None,
        }
    }
}

/// An enumeration of actions to take when a transaction would potentially create dust
/// outputs (outputs that are likely to be without economic value due to fee rules).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DustAction {
    /// Do not allow creation of dust outputs; instead, require that additional inputs be provided.
    Reject,
    /// Explicitly allow the creation of dust change amounts greater than the specified value.
    AllowDustChange,
    /// Allow dust amounts to be added to the transaction fee.
    AddDustToFee,
}

/// A policy describing how a [`ChangeStrategy`] should treat potentially dust-valued change
/// outputs (outputs that are likely to be without economic value due to fee rules).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DustOutputPolicy {
    action: DustAction,
    dust_threshold: Option<Zatoshis>,
}

impl DustOutputPolicy {
    /// Constructs a new dust output policy.
    ///
    /// A dust policy created with `None` as the dust threshold will delegate determination
    /// of the dust threshold to the change strategy that is evaluating the strategy; this
    /// is recommended, but an explicit value (including zero) may be provided to explicitly
    /// override the determination of the change strategy.
    pub fn new(action: DustAction, dust_threshold: Option<Zatoshis>) -> Self {
        Self {
            action,
            dust_threshold,
        }
    }

    /// Returns the action to take in the event that a dust change amount would be produced.
    pub fn action(&self) -> DustAction {
        self.action
    }
    /// Returns a value that will be used to override the dust determination logic of the
    /// change policy, if any.
    pub fn dust_threshold(&self) -> Option<Zatoshis> {
        self.dust_threshold
    }
}

impl Default for DustOutputPolicy {
    fn default() -> Self {
        DustOutputPolicy::new(DustAction::Reject, None)
    }
}

/// A policy that describes how change output should be split into multiple notes for the purpose
/// of note management.
///
/// If an account contains at least [`Self::target_output_count`] notes having at least value
/// [`Self::min_split_output_value`], this policy will recommend a single output; if the account
/// contains fewer such notes, this policy will recommend that multiple outputs be produced in
/// order to achieve the target.
#[derive(Clone, Copy, Debug)]
pub struct SplitPolicy {
    target_output_count: NonZeroUsize,
    min_split_output_value: Option<Zatoshis>,
}

impl SplitPolicy {
    /// In the case that no other conditions provided by the user are available to fall back on,
    /// a default value of [`MARGINAL_FEE`] * 100 will be used as the "minimum usable note value"
    /// when retrieving wallet metadata.
    ///
    /// [`MARGINAL_FEE`]: zcash_primitives::transaction::fees::zip317::MARGINAL_FEE
    pub(crate) const MIN_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(500000);

    /// Constructs a new [`SplitPolicy`] that splits change to ensure the given number of spendable
    /// outputs exists within an account, each having at least the specified minimum note value.
    pub fn with_min_output_value(
        target_output_count: NonZeroUsize,
        min_split_output_value: Zatoshis,
    ) -> Self {
        Self {
            target_output_count,
            min_split_output_value: Some(min_split_output_value),
        }
    }

    /// Constructs a [`SplitPolicy`] that prescribes a single output (no splitting).
    pub fn single_output() -> Self {
        Self {
            target_output_count: NonZeroUsize::MIN,
            min_split_output_value: None,
        }
    }

    /// Returns the number of outputs that this policy will attempt to ensure that the wallet has
    /// available for spending.
    pub fn target_output_count(&self) -> NonZeroUsize {
        self.target_output_count
    }

    /// Returns the minimum value for a note resulting from splitting of change.
    pub fn min_split_output_value(&self) -> Option<Zatoshis> {
        self.min_split_output_value
    }

    /// Returns the number of output notes to produce from the given total change value, given the
    /// total value and number of existing unspent notes in the account and this policy.
    ///
    /// If splitting change to produce [`Self::target_output_count`] would result in notes of value
    /// less than [`Self::min_split_output_value`], then this will suggest a smaller number of
    /// splits so that each resulting change note has sufficient value.
    pub fn split_count(
        &self,
        existing_notes: Option<usize>,
        existing_notes_total: Option<Zatoshis>,
        total_change: Zatoshis,
    ) -> NonZeroUsize {
        fn to_nonzero_u64(value: usize) -> NonZeroU64 {
            NonZeroU64::new(u64::try_from(value).expect("usize fits into u64"))
                .expect("NonZeroU64 input derived from NonZeroUsize")
        }

        let mut split_count = NonZeroUsize::new(
            usize::from(self.target_output_count)
                .saturating_sub(existing_notes.unwrap_or(usize::MAX)),
        )
        .unwrap_or(NonZeroUsize::MIN);

        let min_split_output_value = self.min_split_output_value.or_else(|| {
            // If no minimum split output size is set, we choose the minimum split size to be a
            // quarter of the average value of notes in the wallet after the transaction.
            (existing_notes_total + total_change).map(|total| {
                *total
                    .div_with_remainder(to_nonzero_u64(
                        usize::from(self.target_output_count).saturating_mul(4),
                    ))
                    .quotient()
            })
        });

        if let Some(min_split_output_value) = min_split_output_value {
            loop {
                let per_output_change =
                    total_change.div_with_remainder(to_nonzero_u64(usize::from(split_count)));
                if *per_output_change.quotient() >= min_split_output_value {
                    return split_count;
                } else if let Some(new_count) = NonZeroUsize::new(usize::from(split_count) - 1) {
                    split_count = new_count;
                } else {
                    // We always create at least one change output.
                    return NonZeroUsize::MIN;
                }
            }
        } else {
            NonZeroUsize::MIN
        }
    }
}

/// `EphemeralBalance` describes the ephemeral input or output value for a transaction. It is used
/// in fee computation for series of transactions that use an ephemeral transparent output in an
/// intermediate step, such as when sending from a shielded pool to a [ZIP 320] "TEX" address.
///
/// [ZIP 320]: https://zips.z.cash/zip-0320
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EphemeralBalance {
    Input(Zatoshis),
    Output(Zatoshis),
}

impl EphemeralBalance {
    pub fn is_input(&self) -> bool {
        matches!(self, EphemeralBalance::Input(_))
    }

    pub fn is_output(&self) -> bool {
        matches!(self, EphemeralBalance::Output(_))
    }

    pub fn ephemeral_input_amount(&self) -> Option<Zatoshis> {
        match self {
            EphemeralBalance::Input(v) => Some(*v),
            EphemeralBalance::Output(_) => None,
        }
    }

    pub fn ephemeral_output_amount(&self) -> Option<Zatoshis> {
        match self {
            EphemeralBalance::Input(_) => None,
            EphemeralBalance::Output(v) => Some(*v),
        }
    }
}

/// A trait that defines a set of types used in wallet metadata retrieval. Ordinarily, this will
/// correspond to a type that implements [`InputSource`], and a blanket implementation of this
/// trait is provided for all types that implement [`InputSource`].
///
/// If more capabilities are required of the backend than are exposed in the [`InputSource`] trait,
/// the implementer of this trait should define their own trait that descends from [`InputSource`]
/// and adds the required capabilities there, and then implement that trait for their desired
/// database backend.
pub trait MetaSource {
    type Error;
    type AccountId;
    type NoteRef;
}

impl MetaSource for Infallible {
    type Error = Infallible;
    type AccountId = Infallible;
    type NoteRef = Infallible;
}

impl<I: InputSource> MetaSource for I {
    type Error = I::Error;
    type AccountId = I::AccountId;
    type NoteRef = I::NoteRef;
}

/// A trait that represents the ability to compute the suggested change and fees that must be paid
/// by a transaction having a specified set of inputs and outputs.
pub trait ChangeStrategy {
    type FeeRule: FeeRule + Clone;
    type Error: From<<Self::FeeRule as FeeRule>::Error>;

    /// The type of metadata source that this change strategy requires in order to be able to
    /// retrieve required wallet metadata.
    type MetaSource: MetaSource;

    /// Tye type of wallet metadata that this change strategy relies upon in order to compute
    /// change.
    type AccountMetaT;

    /// Returns the fee rule that this change strategy will respect when performing
    /// balance computations.
    fn fee_rule(&self) -> &Self::FeeRule;

    /// Uses the provided metadata source to obtain the wallet metadata required for change
    /// creation determinations.
    fn fetch_wallet_meta(
        &self,
        meta_source: &Self::MetaSource,
        account: <Self::MetaSource as MetaSource>::AccountId,
        target_height: TargetHeight,
        exclude: &[<Self::MetaSource as MetaSource>::NoteRef],
    ) -> Result<Self::AccountMetaT, <Self::MetaSource as MetaSource>::Error>;

    /// Computes the totals of inputs, suggested change amounts, and fees given the
    /// provided inputs and outputs being used to construct a transaction.
    ///
    /// The fee computed as part of this operation should take into account the prospective
    /// change outputs recommended by this operation. If insufficient funds are available to
    /// supply the requested outputs and required fees, implementations should return
    /// [`ChangeError::InsufficientFunds`].
    ///
    /// If the inputs include notes or UTXOs that are not economic to spend in the context
    /// of this input selection, a [`ChangeError::DustInputs`] error can be returned
    /// indicating inputs that should be removed from the selection (all of which will
    /// have value less than or equal to the marginal fee). The caller should order the
    /// inputs from most to least preferred to spend within each pool, so that the most
    /// preferred ones are less likely to be indicated to remove.
    ///
    /// - `ironwood`: the Ironwood bundle view (behind the `orchard` feature). A V6
    ///   transaction carries a separate Ironwood bundle, distinct from `orchard`,
    ///   with its own action count; pass an empty view when nothing targets the
    ///   Ironwood pool.
    /// - `ephemeral_balance`: if the transaction is to be constructed with either an
    ///   ephemeral transparent input or an ephemeral transparent output this argument
    ///   may be used to provide the value of that input or output. The value of this
    ///   argument should be `None` in the case that there are no such items.
    /// - `wallet_meta`: Additional wallet metadata that the change strategy may use
    ///   in determining how to construct change outputs. This wallet metadata value
    ///   should be computed excluding the inputs provided in the `transparent_inputs`,
    ///   `sapling`, `orchard`, and `ironwood` arguments.
    ///
    /// [ZIP 320]: https://zips.z.cash/zip-0320
    #[allow(clippy::too_many_arguments)]
    fn compute_balance<P: consensus::Parameters, NoteRefT: Clone>(
        &self,
        params: &P,
        target_height: TargetHeight,
        anchor_height: BlockHeight,
        zip318: &PoolMigrationParams,
        transparent_inputs: &[impl transparent::InputView],
        transparent_outputs: &[impl transparent::OutputView],
        sapling: &impl sapling::BundleView<NoteRefT>,
        #[cfg(feature = "orchard")] orchard: &impl orchard::BundleView<NoteRefT>,
        #[cfg(feature = "orchard")] ironwood: &impl orchard::BundleView<NoteRefT>,
        ephemeral_balance: Option<EphemeralBalance>,
        wallet_meta: &Self::AccountMetaT,
    ) -> Result<TransactionBalance, ChangeError<Self::Error, NoteRefT>>;
}

#[cfg(test)]
pub(crate) mod tests {
    #[cfg(feature = "orchard")]
    use {
        zcash_primitives::transaction::fees::zip317::MARGINAL_FEE,
        zcash_protocol::consensus::{BlockHeight, MAIN_NETWORK},
    };

    use ::transparent::bundle::{OutPoint, TxOut};
    use zcash_primitives::transaction::fees::transparent;
    use zcash_protocol::value::Zatoshis;

    /// The canonical crossing fee is three ZIP 317 marginal fees: the Orchard bundle's two actions
    /// plus the single unpadded Ironwood one, which together exceed the grace allowance. Pinning it
    /// means a change to the marginal fee or to the canonical shape surfaces here rather than
    /// silently reclassifying transactions.
    #[test]
    #[cfg(feature = "orchard")]
    fn canonical_crossing_fee_is_three_marginal_fees() {
        let fee = super::canonical_crossing_fee(&MAIN_NETWORK, BlockHeight::from_u32(2_000_000))
            .expect("the canonical shape is a valid input to the ZIP 317 rule");
        assert_eq!(fee, (MARGINAL_FEE * 3u64).expect("a valid amount"));
        assert_eq!(u64::from(fee), 15_000);
    }

    use super::sapling;

    #[derive(Debug)]
    pub(crate) struct TestTransparentInput {
        pub outpoint: OutPoint,
        pub coin: TxOut,
    }

    impl transparent::InputView for TestTransparentInput {
        fn outpoint(&self) -> &OutPoint {
            &self.outpoint
        }
        fn coin(&self) -> &TxOut {
            &self.coin
        }
    }

    pub(crate) struct TestSaplingInput {
        pub note_id: u32,
        pub value: Zatoshis,
    }

    impl sapling::InputView<u32> for TestSaplingInput {
        fn note_id(&self) -> &u32 {
            &self.note_id
        }
        fn value(&self) -> Zatoshis {
            self.value
        }
    }

    #[cfg(feature = "orchard")]
    pub(crate) struct TestOrchardInput {
        pub note_id: u32,
        pub value: Zatoshis,
    }

    #[cfg(feature = "orchard")]
    impl super::orchard::InputView<u32> for TestOrchardInput {
        fn note_id(&self) -> &u32 {
            &self.note_id
        }
        fn value(&self) -> Zatoshis {
            self.value
        }
    }
}