Skip to main content

zcash_client_backend/data_api/wallet/
input_selection.rs

1//! Types related to the process of selecting inputs to be spent given a transaction request.
2#[cfg(feature = "transparent-inputs")]
3use {
4    crate::{
5        data_api::CoinbaseFilter,
6        fees::{ChangeValue, StandardFeeRule},
7        proposal::{Step, StepOutput, StepOutputIndex},
8    },
9    std::convert::Infallible,
10    transparent::{address::TransparentAddress, bundle::OutPoint},
11    zcash_keys::keys::transparent::TransparentKeyScope,
12    zcash_primitives::transaction::fees::{
13        transparent as transparent_fees, transparent::InputSize, zip317::P2PKH_STANDARD_INPUT_SIZE,
14    },
15    zcash_protocol::constants::MAX_BLOCK_BYTES,
16    zip321::Payment,
17};
18
19use core::marker::PhantomData;
20use nonempty::NonEmpty;
21use std::{
22    collections::{BTreeMap, BTreeSet},
23    error,
24    fmt::{self, Debug, Display},
25};
26
27use transparent::bundle::TxOut;
28use zcash_address::{ConversionError, ZcashAddress};
29use zcash_keys::address::{Address, UnifiedAddress};
30use zcash_primitives::transaction::{
31    TxVersion,
32    fees::{FeeRule, zip317::P2PKH_STANDARD_OUTPUT_SIZE},
33};
34use zcash_protocol::{
35    PoolType, ShieldedPool,
36    consensus::{self, BlockHeight},
37    memo::MemoBytes,
38    value::{BalanceError, MAX_MONEY, Zatoshis},
39};
40use zip321::TransactionRequest;
41
42use crate::{
43    data_api::{
44        InputSource, MaxSpendMode, ReceivedNotes, SimpleNoteRetention, TargetValue,
45        anchor_retention::PoolMigrationParams, wallet::TargetHeight,
46    },
47    fees::{ChangeError, ChangeStrategy, EphemeralBalance, TransactionBalance, sapling},
48    proposal::{Proposal, ProposalError, ShieldedInputs},
49    wallet::{ReceivedNote, WalletTransparentOutput},
50};
51
52pub use crate::data_api::locking::{LockFilter, LockedInputPolicy};
53
54use super::ConfirmationsPolicy;
55
56#[cfg(feature = "orchard")]
57use crate::{data_api::wallet::ironwood_active_at, fees::orchard as orchard_fees};
58
59/// The type of errors that may be produced in input selection.
60#[derive(Debug)]
61#[non_exhaustive]
62pub enum InputSelectorError<DbErrT, SelectorErrT, ChangeErrT, N> {
63    /// An error occurred accessing the underlying data store.
64    DataSource(DbErrT),
65    /// An error occurred specific to the provided input selector's selection rules.
66    Selection(SelectorErrT),
67    /// An error occurred in computing the change or fee for the proposed transfer.
68    Change(ChangeError<ChangeErrT, N>),
69    /// Input selection attempted to generate an invalid transaction proposal.
70    Proposal(ProposalError),
71    /// An error occurred parsing the address from a payment request.
72    Address(ConversionError<&'static str>),
73    /// Insufficient funds were available to satisfy the payment request that inputs were being
74    /// selected to attempt to satisfy.
75    InsufficientFunds {
76        available: Zatoshis,
77        required: Zatoshis,
78    },
79    /// The data source has no target height or no anchor height for the transaction:
80    /// [`WalletRead::get_target_and_anchor_heights`] returned `None`.
81    ///
82    /// [`WalletRead::get_target_and_anchor_heights`]: crate::data_api::WalletRead::get_target_and_anchor_heights
83    SyncRequired,
84}
85
86impl<DE: fmt::Display, SE: fmt::Display, CE: fmt::Display, N: fmt::Display> fmt::Display
87    for InputSelectorError<DE, SE, CE, N>
88{
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        match &self {
91            InputSelectorError::DataSource(e) => {
92                write!(
93                    f,
94                    "The underlying datasource produced the following error: {e}"
95                )
96            }
97            InputSelectorError::Selection(e) => {
98                write!(f, "Note selection encountered the following error: {e}")
99            }
100            InputSelectorError::Change(e) => write!(
101                f,
102                "Proposal generation failed due to an error in computing change or transaction fees: {e}"
103            ),
104            InputSelectorError::Proposal(e) => {
105                write!(
106                    f,
107                    "Input selection attempted to generate an invalid proposal: {e}"
108                )
109            }
110            InputSelectorError::Address(e) => {
111                write!(
112                    f,
113                    "An error occurred decoding the address from a payment request: {e}."
114                )
115            }
116            InputSelectorError::InsufficientFunds {
117                available,
118                required,
119            } => write!(
120                f,
121                "Insufficient balance (have {}, need {} including fee)",
122                u64::from(*available),
123                u64::from(*required)
124            ),
125            InputSelectorError::SyncRequired => {
126                write!(f, "Insufficient chain data is available, sync required.")
127            }
128        }
129    }
130}
131
132impl<DE, SE, CE, N> error::Error for InputSelectorError<DE, SE, CE, N>
133where
134    DE: Debug + Display + error::Error + 'static,
135    SE: Debug + Display + error::Error + 'static,
136    CE: Debug + Display + error::Error + 'static,
137    N: Debug + Display + 'static,
138{
139    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
140        match &self {
141            Self::DataSource(e) => Some(e),
142            Self::Selection(e) => Some(e),
143            Self::Change(e) => Some(e),
144            Self::Proposal(e) => Some(e),
145            _ => None,
146        }
147    }
148}
149
150impl<E, S, F, N> From<ConversionError<&'static str>> for InputSelectorError<E, S, F, N> {
151    fn from(value: ConversionError<&'static str>) -> Self {
152        InputSelectorError::Address(value)
153    }
154}
155
156impl<E, S, C, N> From<ChangeError<C, N>> for InputSelectorError<E, S, C, N> {
157    fn from(err: ChangeError<C, N>) -> Self {
158        InputSelectorError::Change(err)
159    }
160}
161
162impl<E, S, C, N> From<ProposalError> for InputSelectorError<E, S, C, N> {
163    fn from(err: ProposalError) -> Self {
164        InputSelectorError::Proposal(err)
165    }
166}
167
168/// A strategy for selecting transaction inputs and proposing transaction outputs.
169///
170/// Proposals should include only economically useful inputs, as determined by `Self::FeeRule`;
171/// that is, do not return inputs that cause fees to increase by an amount greater than the value
172/// of the input.
173pub trait InputSelector {
174    /// The type of errors that may be generated in input selection
175    type Error;
176
177    /// The type of data source that the input selector expects to access to obtain input notes.
178    /// This associated type permits input selectors that may use specialized knowledge of the
179    /// internals of a particular backing data store, if the generic API of `InputSource` does not
180    /// provide sufficiently fine-grained operations for a particular backing store to optimally
181    /// perform input selection.
182    type InputSource: InputSource;
183
184    /// Performs input selection and returns a proposal for transaction construction including
185    /// change and fee outputs.
186    ///
187    /// Implementations of this method should return inputs sufficient to satisfy the given
188    /// transaction request using a best-effort strategy to preserve user privacy, as follows:
189    /// * If it is possible to satisfy the specified transaction request by creating
190    ///   a fully-shielded transaction without requiring value to cross pool boundaries,
191    ///   return the inputs necessary to construct such a transaction; otherwise
192    /// * If it is possible to satisfy the transaction request by creating a fully-shielded
193    ///   transaction with some amounts crossing between shielded pools, return the inputs
194    ///   necessary.
195    ///
196    /// If insufficient funds are available to satisfy the required outputs for the shielding
197    /// request, this operation must fail and return [`InputSelectorError::InsufficientFunds`].
198    ///
199    /// `spend_policy` controls which sources of funds the implementation may draw upon. It names
200    /// the shielded pools from which notes may be selected — the implementation must not select
201    /// notes from a pool the policy does not permit, returning
202    /// [`InputSelectorError::InsufficientFunds`] rather than crossing into a non-permitted pool —
203    /// and, behind the `transparent-inputs` feature flag, whether and from which addresses the
204    /// account's transparent UTXOs may additionally be spent. Spending transparent funds, or
205    /// combining notes across shielded pools, reduces privacy, so the caller must opt in
206    /// explicitly by naming the permitted sources.
207    #[allow(clippy::type_complexity)]
208    #[allow(clippy::too_many_arguments)]
209    fn propose_transaction<ParamsT, ChangeT>(
210        &self,
211        params: &ParamsT,
212        wallet_db: &Self::InputSource,
213        target_height: TargetHeight,
214        anchor_height: BlockHeight,
215        zip318: &PoolMigrationParams,
216        confirmations_policy: ConfirmationsPolicy,
217        account: <Self::InputSource as InputSource>::AccountId,
218        transaction_request: TransactionRequest,
219        change_strategy: &ChangeT,
220        spend_policy: &SpendPolicy,
221        proposed_version: Option<TxVersion>,
222    ) -> Result<
223        Proposal<<ChangeT as ChangeStrategy>::FeeRule, <Self::InputSource as InputSource>::NoteRef>,
224        InputSelectorError<
225            <Self::InputSource as InputSource>::Error,
226            Self::Error,
227            ChangeT::Error,
228            <Self::InputSource as InputSource>::NoteRef,
229        >,
230    >
231    where
232        ParamsT: consensus::Parameters,
233        ChangeT: ChangeStrategy<MetaSource = Self::InputSource>;
234}
235
236/// A strategy for selecting transaction inputs and proposing transaction outputs
237/// for shielding-only transactions (transactions which spend transparent UTXOs and
238/// send all transaction outputs to the wallet's shielded internal address(es)).
239#[cfg(feature = "transparent-inputs")]
240pub trait ShieldingSelector {
241    /// The type of errors that may be generated in input selection
242    type Error;
243    /// The type of data source that the input selector expects to access to obtain input
244    /// transparent UTXOs. This associated type permits input selectors that may use specialized
245    /// knowledge of the internals of a particular backing data store, if the generic API of
246    /// [`InputSource`] does not provide sufficiently fine-grained operations for a
247    /// particular backing store to optimally perform input selection.
248    type InputSource: InputSource;
249
250    /// Performs input selection and returns a proposal for the construction of a shielding
251    /// transaction.
252    ///
253    /// Implementations should return the maximum possible number of economically useful inputs
254    /// required to supply at least the requested value, choosing only inputs received at the
255    /// specified source addresses. If insufficient funds are available to satisfy the required
256    /// outputs for the shielding request, this operation must fail and return
257    /// [`InputSelectorError::InsufficientFunds`].
258    ///
259    /// The `output_filter` parameter controls which transparent outputs are eligible for
260    /// inclusion in the proposal. See [`CoinbaseFilter`] for details.
261    #[allow(clippy::type_complexity)]
262    #[allow(clippy::too_many_arguments)]
263    fn propose_shielding<ParamsT, ChangeT>(
264        &self,
265        params: &ParamsT,
266        wallet_db: &Self::InputSource,
267        change_strategy: &ChangeT,
268        shielding_threshold: Zatoshis,
269        source_addrs: &[TransparentAddress],
270        to_account: <Self::InputSource as InputSource>::AccountId,
271        target_height: TargetHeight,
272        anchor_height: BlockHeight,
273        zip318: &PoolMigrationParams,
274        confirmations_policy: ConfirmationsPolicy,
275        output_filter: CoinbaseFilter,
276    ) -> Result<
277        Proposal<<ChangeT as ChangeStrategy>::FeeRule, Infallible>,
278        InputSelectorError<
279            <Self::InputSource as InputSource>::Error,
280            Self::Error,
281            ChangeT::Error,
282            Infallible,
283        >,
284    >
285    where
286        ParamsT: consensus::Parameters,
287        ChangeT: ChangeStrategy<MetaSource = Self::InputSource>;
288
289    /// Performs input selection and returns a proposal for the construction of a transaction
290    /// that shields coinbase transparent outputs to an arbitrary shielded recipient.
291    ///
292    /// This method differs from [`Self::propose_shielding`] in the following ways:
293    ///
294    /// - Only coinbase transparent outputs are eligible for inclusion in the proposal. This
295    ///   restriction is hard-coded; callers cannot opt in to selecting non-coinbase outputs
296    ///   via this method. Coinbase outputs are uniquely suited to being sent to arbitrary
297    ///   shielded recipients because they have no prior transparent transaction graph that
298    ///   could be exposed to the recipient.
299    /// - The `to_address` argument specifies the destination of the shielded value. It must
300    ///   be a shielded address (Sapling, or a Unified Address with a shielded receiver). It
301    ///   may be an external address not belonging to any account we control.
302    /// - The resulting proposal carries an explicit ZIP-321 payment to `to_address` for the
303    ///   full available value (input total minus fee). **No change is produced**, in either
304    ///   the transparent or any shielded pool. This is a privacy invariant: producing a
305    ///   shielded change output would allow the recipient (or any chain observer) to learn
306    ///   the sender's total selected-coinbase value by summing the public transparent input
307    ///   values and subtracting the visible payment amount. Since this method targets the
308    ///   `z_shieldcoinbase`-style "sweep coinbase to a recipient" workflow, where the
309    ///   recipient may not belong to the sender's wallet, change is forbidden by design.
310    ///
311    /// Because no change is produced, this method takes a `fee_rule` directly rather than a
312    /// [`ChangeStrategy`]: there is no change to compute, and no per-account metadata is
313    /// required.
314    ///
315    /// The `memo` parameter is stored in the shielded output's memo field; it is always
316    /// permitted because a shielded payment is always present.
317    ///
318    /// The `limit` parameter, when `Some(n)`, caps the number of transparent inputs to at
319    /// most `n`, keeping the highest-value UTXOs (with a stable tiebreaker by outpoint).
320    /// `Some(0)` selects no inputs and will therefore return
321    /// [`InputSelectorError::InsufficientFunds`].
322    ///
323    /// If the total value of selected inputs (after any cap imposed by `limit`), minus the
324    /// fee, is less than `shielding_threshold`, this method returns
325    /// [`InputSelectorError::InsufficientFunds`].
326    #[allow(clippy::type_complexity)]
327    #[allow(clippy::too_many_arguments)]
328    fn propose_shielding_coinbase<ParamsT, FeeRuleT>(
329        &self,
330        params: &ParamsT,
331        wallet_db: &Self::InputSource,
332        fee_rule: &FeeRuleT,
333        shielding_threshold: Zatoshis,
334        source_addrs: &[TransparentAddress],
335        to_address: ZcashAddress,
336        memo: Option<MemoBytes>,
337        limit: Option<usize>,
338        target_height: TargetHeight,
339        anchor_height: BlockHeight,
340    ) -> Result<
341        Proposal<FeeRuleT, Infallible>,
342        InputSelectorError<
343            <Self::InputSource as InputSource>::Error,
344            Self::Error,
345            FeeRuleT::Error,
346            Infallible,
347        >,
348    >
349    where
350        ParamsT: consensus::Parameters,
351        FeeRuleT: FeeRule + Clone;
352}
353
354/// Errors that can occur as a consequence of greedy input selection.
355#[derive(Debug, Clone, PartialEq, Eq)]
356#[non_exhaustive]
357pub enum GreedyInputSelectorError {
358    /// An intermediate value overflowed or underflowed the valid monetary range.
359    Balance(BalanceError),
360    /// A unified address did not contain a supported receiver.
361    UnsupportedAddress(Box<UnifiedAddress>),
362    /// Support for transparent-source-only (TEX) addresses requires the transparent-inputs feature.
363    UnsupportedTexAddress,
364    /// The change strategy reported insufficient funds with a requirement that the inputs it
365    /// was given already cover, breaking the contract of [`ChangeStrategy::compute_balance`].
366    RequirementCovered {
367        /// The requirement the change strategy reported.
368        required: Zatoshis,
369        /// The value of the inputs it was given.
370        available: Zatoshis,
371    },
372    /// The change strategy reported as dust an input it was not given, or no input at all,
373    /// breaking the contract of [`ChangeStrategy::compute_balance`].
374    DustInputsNotGiven,
375    /// The data source returned a note it was asked to exclude, breaking the contract of
376    /// [`InputSource::select_spendable_notes`] or
377    /// [`InputSource::select_single_spendable_note`].
378    ExcludedNoteSelected,
379    /// The data source returned a note from a pool it was not asked to select from, breaking
380    /// the contract of [`InputSource::select_spendable_notes`] or
381    /// [`InputSource::select_single_spendable_note`].
382    UnrequestedPoolSelected,
383}
384
385impl fmt::Display for GreedyInputSelectorError {
386    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
387        match &self {
388            GreedyInputSelectorError::Balance(e) => write!(
389                f,
390                "A balance calculation violated amount validity bounds: {e:?}."
391            ),
392            GreedyInputSelectorError::UnsupportedAddress(_) => {
393                // we can't encode the UA to its string representation because we
394                // don't have network parameters here
395                write!(f, "Unified address contains no supported receivers.")
396            }
397            GreedyInputSelectorError::UnsupportedTexAddress => {
398                write!(
399                    f,
400                    "Support for transparent-source-only (TEX) addresses requires the transparent-inputs feature."
401                )
402            }
403            GreedyInputSelectorError::RequirementCovered {
404                required,
405                available,
406            } => write!(
407                f,
408                "The change strategy required {} of inputs worth {}, which already cover it.",
409                u64::from(*required),
410                u64::from(*available)
411            ),
412            GreedyInputSelectorError::DustInputsNotGiven => {
413                write!(
414                    f,
415                    "The change strategy reported as dust an input it was not given, or none at all."
416                )
417            }
418            GreedyInputSelectorError::ExcludedNoteSelected => {
419                write!(
420                    f,
421                    "The data source returned a note that input selection asked it to exclude."
422                )
423            }
424            GreedyInputSelectorError::UnrequestedPoolSelected => {
425                write!(
426                    f,
427                    "The data source returned a note from a pool that input selection did not ask for."
428                )
429            }
430        }
431    }
432}
433
434impl<DbErrT, ChangeErrT, N> From<GreedyInputSelectorError>
435    for InputSelectorError<DbErrT, GreedyInputSelectorError, ChangeErrT, N>
436{
437    fn from(err: GreedyInputSelectorError) -> Self {
438        InputSelectorError::Selection(err)
439    }
440}
441
442impl<DbErrT, ChangeErrT, N> From<BalanceError>
443    for InputSelectorError<DbErrT, GreedyInputSelectorError, ChangeErrT, N>
444{
445    fn from(err: BalanceError) -> Self {
446        InputSelectorError::Selection(GreedyInputSelectorError::Balance(err))
447    }
448}
449
450pub(crate) struct SaplingPayment(Zatoshis);
451
452#[cfg(test)]
453impl SaplingPayment {
454    pub(crate) fn new(amount: Zatoshis) -> Self {
455        SaplingPayment(amount)
456    }
457}
458
459impl sapling::OutputView for SaplingPayment {
460    fn value(&self) -> Zatoshis {
461        self.0
462    }
463}
464
465#[cfg(feature = "orchard")]
466pub(crate) struct OrchardPayment(Zatoshis);
467
468#[cfg(test)]
469#[cfg(feature = "orchard")]
470impl OrchardPayment {
471    pub(crate) fn new(amount: Zatoshis) -> Self {
472        OrchardPayment(amount)
473    }
474}
475
476#[cfg(feature = "orchard")]
477impl orchard_fees::OutputView for OrchardPayment {
478    fn value(&self) -> Zatoshis {
479        self.0
480    }
481}
482
483/// The default maximum fraction of a block's space, as an integer percentage, that a single
484/// shielding transaction's transparent inputs may occupy.
485#[cfg(feature = "transparent-inputs")]
486const DEFAULT_SHIELDING_BLOCK_SPACE_PERCENT: u32 = 10;
487
488/// A `BTreeSet` that is guaranteed to contain at least one element.
489///
490/// Non-emptiness is maintained by construction: every constructor requires at least one
491/// element, and no mutating operations are exposed.
492#[derive(Clone, Debug, PartialEq, Eq)]
493pub struct NonEmptyBTreeSet<T>(BTreeSet<T>);
494
495impl<T: Ord> NonEmptyBTreeSet<T> {
496    /// Constructs a set containing only the given element.
497    pub fn singleton(value: T) -> Self {
498        Self(BTreeSet::from_iter([value]))
499    }
500
501    /// Constructs a set containing the elements of the given non-empty list, collapsing
502    /// duplicates.
503    pub fn from_nonempty(values: NonEmpty<T>) -> Self {
504        Self(values.into_iter().collect())
505    }
506
507    /// Constructs a set from the given `BTreeSet`, or returns `None` if the set is empty.
508    pub fn from_set(values: BTreeSet<T>) -> Option<Self> {
509        (!values.is_empty()).then_some(Self(values))
510    }
511}
512
513impl<T> NonEmptyBTreeSet<T> {
514    /// Returns a reference to the wrapped set.
515    pub fn as_set(&self) -> &BTreeSet<T> {
516        &self.0
517    }
518
519    /// Returns an iterator over the elements of the set, in ascending order.
520    pub fn iter(&self) -> std::collections::btree_set::Iter<'_, T> {
521        self.0.iter()
522    }
523}
524
525/// The sources of funds an [`InputSelector`] is permitted to draw upon when satisfying a
526/// transaction request.
527///
528/// Crossing a shielded pool boundary reduces privacy, so it must be an explicit choice of the
529/// caller: the selector only spends notes from the shielded pools named in [`Self::shielded`], and
530/// only spends transparent UTXOs when a [`TransparentSpendPolicy`] is provided. When a single
531/// permitted pool cannot cover the request, the selector may combine the permitted pools (drawing
532/// on the legacy Orchard pool last); if no combination of permitted sources suffices it returns
533/// [`InputSelectorError::InsufficientFunds`] rather than reaching into a pool the caller did not
534/// permit.
535///
536/// The default permits every shielded pool present in the build and no transparent spending,
537/// preserving the historical fully-shielded behavior while letting a caller restrict the set to,
538/// for example, `{Orchard}` to forbid pool crossing.
539#[derive(Clone, Debug)]
540pub struct SpendPolicy {
541    shielded: BTreeSet<ShieldedPool>,
542    #[cfg(feature = "transparent-inputs")]
543    transparent: Option<TransparentSpendPolicy>,
544    locked_input_policy: LockedInputPolicy,
545    note_selection: NoteSelection,
546}
547
548/// How an [`InputSelector`] chooses among eligible notes when funding a payment.
549#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
550pub enum NoteSelection {
551    /// Accumulate the oldest eligible notes until the target value is covered.
552    #[default]
553    Accumulate,
554    /// Prefer funding from a SINGLE note — the oldest eligible note whose value alone covers the
555    /// target — falling back to accumulation when no such note exists.
556    ///
557    /// A ZIP 318 migration transfer spends exactly one note, so a canonical pool crossing is
558    /// achievable only under single-note funding; multi-note funding is not an error, but the
559    /// resulting proposal does not have the canonical shape.
560    PreferSingle,
561}
562
563impl Default for SpendPolicy {
564    fn default() -> Self {
565        Self::shielded_pools([
566            ShieldedPool::Sapling,
567            #[cfg(feature = "orchard")]
568            ShieldedPool::Orchard,
569            #[cfg(feature = "orchard")]
570            ShieldedPool::Ironwood,
571        ])
572    }
573}
574
575impl SpendPolicy {
576    /// Constructs a policy permitting selection from exactly the given shielded pools, with no
577    /// transparent spending.
578    pub fn shielded_pools(pools: impl IntoIterator<Item = ShieldedPool>) -> Self {
579        Self {
580            shielded: pools.into_iter().collect(),
581            #[cfg(feature = "transparent-inputs")]
582            transparent: None,
583            locked_input_policy: LockedInputPolicy::Exclude,
584            note_selection: NoteSelection::Accumulate,
585        }
586    }
587
588    /// Returns whether notes may be selected from the given shielded pool.
589    pub fn permits_shielded(&self, pool: ShieldedPool) -> bool {
590        self.shielded.contains(&pool)
591    }
592
593    /// Returns the set of shielded pools from which notes may be selected.
594    pub fn shielded(&self) -> &BTreeSet<ShieldedPool> {
595        &self.shielded
596    }
597
598    /// Adds a transparent spend policy, permitting transparent UTXOs to be spent as described.
599    #[cfg(feature = "transparent-inputs")]
600    pub fn with_transparent(mut self, transparent: TransparentSpendPolicy) -> Self {
601        self.transparent = Some(transparent);
602        self
603    }
604
605    /// Returns the transparent spend policy, or `None` if transparent UTXOs may not be spent.
606    #[cfg(feature = "transparent-inputs")]
607    pub fn transparent(&self) -> Option<&TransparentSpendPolicy> {
608        self.transparent.as_ref()
609    }
610
611    /// Sets how input selection treats locked outputs (default: `LockedInputPolicy::Exclude`).
612    pub fn with_locked_input_policy(mut self, policy: LockedInputPolicy) -> Self {
613        self.locked_input_policy = policy;
614        self
615    }
616
617    /// Returns the policy governing selection of locked outputs.
618    pub fn locked_input_policy(&self) -> &LockedInputPolicy {
619        &self.locked_input_policy
620    }
621
622    /// Sets how the selector chooses among eligible notes (default:
623    /// [`NoteSelection::Accumulate`]).
624    pub fn with_note_selection(mut self, note_selection: NoteSelection) -> Self {
625        self.note_selection = note_selection;
626        self
627    }
628
629    /// Returns how the selector chooses among eligible notes.
630    pub fn note_selection(&self) -> NoteSelection {
631        self.note_selection
632    }
633}
634
635/// The caller's choice of which coinbase transparent outputs a transparent spend may draw upon.
636///
637/// Consensus requires coinbase funds to be spent to a single shielded output with no change and
638/// without being mixed with non-coinbase inputs, so a transparent spend commits to one or the
639/// other rather than combining them.
640#[derive(Clone, Copy, Debug, PartialEq, Eq)]
641pub enum CoinbasePolicy {
642    /// Spend only coinbase transparent outputs.
643    OnlyCoinbase,
644    /// Spend only non-coinbase transparent outputs.
645    NonCoinbase,
646}
647
648#[cfg(feature = "transparent-inputs")]
649impl From<CoinbasePolicy> for CoinbaseFilter {
650    fn from(policy: CoinbasePolicy) -> Self {
651        match policy {
652            CoinbasePolicy::OnlyCoinbase => CoinbaseFilter::CoinbaseOnly,
653            CoinbasePolicy::NonCoinbase => CoinbaseFilter::NonCoinbaseOnly,
654        }
655    }
656}
657
658/// Specifies how transparent UTXOs may be spent in a transfer, when a [`SpendPolicy`] permits
659/// transparent spending.
660///
661/// Spending transparent funds links the chosen transparent addresses on-chain, reducing privacy,
662/// so a caller opts in by attaching this to a [`SpendPolicy`] via [`SpendPolicy::with_transparent`]
663/// (the absence of a policy — the default — spends no transparent UTXOs). The policy names the
664/// [`TransparentSource`] the UTXOs may be drawn from and, via [`CoinbasePolicy`], whether coinbase
665/// or non-coinbase outputs are spent.
666#[cfg(feature = "transparent-inputs")]
667#[derive(Clone, Debug)]
668pub struct TransparentSpendPolicy {
669    source: TransparentSource,
670    coinbase: CoinbasePolicy,
671}
672
673#[cfg(feature = "transparent-inputs")]
674impl TransparentSpendPolicy {
675    /// Spends non-coinbase UTXOs from arbitrary transparent receivers belonging to the account,
676    /// as needed to satisfy the request. The proposer chooses the addresses, potentially linking
677    /// them. (The legacy `ANY_TADDR` behavior.)
678    pub fn any_account_addr() -> Self {
679        Self {
680            source: TransparentSource::AnyAccountAddr,
681            coinbase: CoinbasePolicy::NonCoinbase,
682        }
683    }
684
685    /// Spends non-coinbase UTXOs only from the specified transparent addresses, intentionally
686    /// linking them.
687    pub fn from_addresses(taddrs: NonEmpty<TransparentAddress>) -> Self {
688        Self {
689            source: TransparentSource::FromAddresses(NonEmptyBTreeSet::from_nonempty(taddrs)),
690            coinbase: CoinbasePolicy::NonCoinbase,
691        }
692    }
693
694    /// Spends non-coinbase UTXOs only from a single transparent address.
695    pub fn from_one_address(taddr: TransparentAddress) -> Self {
696        Self {
697            source: TransparentSource::FromAddresses(NonEmptyBTreeSet::singleton(taddr)),
698            coinbase: CoinbasePolicy::NonCoinbase,
699        }
700    }
701
702    /// Returns a copy of this policy with the given coinbase policy in effect.
703    pub fn with_coinbase(mut self, coinbase: CoinbasePolicy) -> Self {
704        self.coinbase = coinbase;
705        self
706    }
707
708    /// Returns the transparent source from which UTXOs may be drawn.
709    pub fn source(&self) -> &TransparentSource {
710        &self.source
711    }
712
713    /// Returns the coinbase policy in effect for this transparent spend.
714    pub fn coinbase(&self) -> CoinbasePolicy {
715        self.coinbase
716    }
717
718    /// Returns the explicit list of transparent addresses UTXOs may be drawn from, or `None` if
719    /// any of the account's transparent receivers are permitted.
720    fn address_allow_list(&self) -> Option<Vec<TransparentAddress>> {
721        match &self.source {
722            TransparentSource::FromAddresses(addrs) => Some(addrs.iter().copied().collect()),
723            TransparentSource::AnyAccountAddr => None,
724        }
725    }
726}
727
728/// The transparent receivers a [`TransparentSpendPolicy`] may draw UTXOs from.
729#[cfg(feature = "transparent-inputs")]
730#[derive(Clone, Debug)]
731pub enum TransparentSource {
732    /// Any transparent receiver belonging to the account. The proposer chooses which, potentially
733    /// linking them.
734    AnyAccountAddr,
735    /// Only the specified transparent addresses.
736    FromAddresses(NonEmptyBTreeSet<TransparentAddress>),
737}
738
739/// An [`InputSelector`] implementation that uses a greedy strategy to select between available
740/// notes.
741///
742/// This implementation performs input selection using methods available via the
743/// [`InputSource`] interface.
744pub struct GreedyInputSelector<DbT> {
745    /// The maximum fraction of a block's space, as an integer percentage (0–100), that a
746    /// single transaction's transparent inputs may occupy. Bounds both shielding
747    /// transactions and the transparent gather performed for general (non-shielding)
748    /// transfers when the active [`TransparentSpendPolicy`] requires it.
749    #[cfg(feature = "transparent-inputs")]
750    shielding_block_space_percent: u32,
751    /// The policy governing whether the transparent UTXOs gathered by
752    /// [`ShieldingSelector::propose_shielding`] and
753    /// [`ShieldingSelector::propose_shielding_coinbase`] may be drawn from locked outputs.
754    /// Defaults to [`LockedInputPolicy::Exclude`]. Unlike [`SpendPolicy::locked_input_policy`],
755    /// which a caller supplies per call to [`InputSelector::propose_transaction`], shielding has
756    /// no per-call policy argument, so this is configured once on the selector instance via
757    /// [`Self::with_locked_input_policy`].
758    #[cfg(feature = "transparent-inputs")]
759    locked_input_policy: LockedInputPolicy,
760    _ds_type: PhantomData<DbT>,
761}
762
763impl<DbT> GreedyInputSelector<DbT> {
764    /// Constructs a new greedy input selector that uses the provided change strategy to determine
765    /// change values and fee amounts.
766    ///
767    /// The [`ChangeStrategy`] provided must produce exactly one ephemeral change value when
768    /// computing a transaction balance if an [`EphemeralBalance::Output`] value is provided for
769    /// its ephemeral balance, or the resulting [`GreedyInputSelector`] will return an error when
770    /// attempting to construct a transaction proposal that requires such an output.
771    ///
772    /// [`EphemeralBalance::Output`]: crate::fees::EphemeralBalance::Output
773    pub fn new() -> Self {
774        GreedyInputSelector {
775            #[cfg(feature = "transparent-inputs")]
776            shielding_block_space_percent: DEFAULT_SHIELDING_BLOCK_SPACE_PERCENT,
777            #[cfg(feature = "transparent-inputs")]
778            locked_input_policy: LockedInputPolicy::Exclude,
779            _ds_type: PhantomData,
780        }
781    }
782
783    /// Sets the maximum fraction of a block's space, as an integer percentage (0–100), that a
784    /// single transaction's transparent inputs may occupy.
785    ///
786    /// When shielding gathers more spendable transparent outputs than will fit within this
787    /// bound, the highest-value outputs are selected first and the remainder are left unspent,
788    /// to be consolidated by a subsequent shielding transaction. When a general (non-shielding)
789    /// transfer's transparent gather would otherwise require more inputs than fit within this
790    /// bound, the gather stops at the cap even if the requested value has not yet been
791    /// reached; the caller's input-selection loop surfaces this as an `InsufficientFunds`
792    /// error, the same as for any other value shortfall. Values above 100 are clamped to 100.
793    /// Defaults to 10.
794    #[cfg(feature = "transparent-inputs")]
795    pub fn with_shielding_block_space_percent(mut self, percent: u32) -> Self {
796        self.shielding_block_space_percent = percent.min(100);
797        self
798    }
799
800    /// Sets the policy governing whether shielding (via
801    /// [`ShieldingSelector::propose_shielding`] and
802    /// [`ShieldingSelector::propose_shielding_coinbase`]) may draw on transparent UTXOs locked
803    /// by one of the given policy's owners (default: [`LockedInputPolicy::Exclude`], which never
804    /// selects a locked output). This overrides a lock only for the purpose of *selecting through*
805    /// it during shielding; it does not release the lock.
806    #[cfg(feature = "transparent-inputs")]
807    pub fn with_locked_input_policy(mut self, policy: LockedInputPolicy) -> Self {
808        self.locked_input_policy = policy;
809        self
810    }
811
812    #[cfg(feature = "transparent-inputs")]
813    #[allow(clippy::too_many_arguments)]
814    #[allow(clippy::type_complexity)]
815    fn gather_transparent<ChangeT>(
816        &self,
817        wallet_db: &DbT,
818        target_height: TargetHeight,
819        confirmations_policy: ConfirmationsPolicy,
820        account: <DbT as InputSource>::AccountId,
821        // The list used to filter addresses.
822        // If `None`, any address is allowed.
823        address_allow_list: Option<&[TransparentAddress]>,
824        // Which coinbase outputs are eligible for selection.
825        coinbase: CoinbaseFilter,
826        transaction_request: &TransactionRequest,
827        amount_at_transparent_gather: &mut Zatoshis,
828        locked_input_policy: &LockedInputPolicy,
829    ) -> Result<
830        Vec<WalletTransparentOutput<()>>,
831        InputSelectorError<
832            <DbT as InputSource>::Error,
833            <GreedyInputSelector<DbT> as InputSelector>::Error,
834            <ChangeT as ChangeStrategy>::Error,
835            <DbT as InputSource>::NoteRef,
836        >,
837    >
838    where
839        DbT: InputSource,
840        ChangeT: ChangeStrategy<MetaSource = DbT>,
841    {
842        let max_money = Zatoshis::const_from_u64(zcash_protocol::value::MAX_MONEY);
843        let mut total_opt: Option<Zatoshis> = Some(Zatoshis::ZERO);
844        for payment in transaction_request.payments().values() {
845            let Some(payment_amount) = payment.amount() else {
846                total_opt = None;
847                break;
848            };
849            if let Some(t) = total_opt {
850                match t + payment_amount {
851                    Some(sum) => total_opt = Some(sum),
852                    None => {
853                        return Err(InputSelectorError::InsufficientFunds {
854                            available: Zatoshis::ZERO,
855                            required: max_money,
856                        });
857                    }
858                }
859            }
860        }
861        let (target_value, amount_at_gather) = match total_opt {
862            Some(z) => (TargetValue::AtLeast(z), z),
863            None => (
864                TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
865                Zatoshis::ZERO,
866            ),
867        };
868        *amount_at_transparent_gather = amount_at_gather;
869        // Input selection honors the caller's `SpendPolicy::locked_input_policy`: by default
870        // (`Exclude`) a locked output is never drawn upon, since it belongs to another in-flight
871        // proposal and spending it would recreate the conflict that locking exists to prevent; the
872        // `PreferUnlocked`/`PreferLocked` overrides let a caller draw through a lock it recognizes
873        // (e.g. its own pool-migration PCZTs).
874        Ok(wallet_db
875            .select_spendable_transparent_outputs(
876                account,
877                target_height,
878                confirmations_policy,
879                coinbase,
880                address_allow_list,
881                target_value,
882                shielding_max_inputs(self.shielding_block_space_percent),
883                &StandardFeeRule::Zip317,
884                LockFilter::Policy(locked_input_policy),
885            )
886            .map_err(InputSelectorError::DataSource)?
887            .into_iter()
888            .map(|utxo| utxo.redact_account_data())
889            .collect::<Vec<_>>())
890    }
891}
892
893/// Returns the maximum number of transparent inputs that a single transaction may select,
894/// given the configured fraction of a block's space (as an integer percentage) that its
895/// inputs may occupy. Used to bound both shielding transactions and the transparent gather
896/// for general (non-shielding) transfers.
897#[cfg(feature = "transparent-inputs")]
898fn shielding_max_inputs(block_space_percent: u32) -> usize {
899    (MAX_BLOCK_BYTES.saturating_mul(block_space_percent as usize) / 100) / P2PKH_STANDARD_INPUT_SIZE
900}
901
902impl<DbT> Default for GreedyInputSelector<DbT> {
903    fn default() -> Self {
904        Self::new()
905    }
906}
907
908impl<DbT: InputSource> InputSelector for GreedyInputSelector<DbT> {
909    type Error = GreedyInputSelectorError;
910    type InputSource = DbT;
911
912    #[allow(clippy::type_complexity)]
913    fn propose_transaction<ParamsT, ChangeT>(
914        &self,
915        params: &ParamsT,
916        wallet_db: &Self::InputSource,
917        target_height: TargetHeight,
918        anchor_height: BlockHeight,
919        zip318: &PoolMigrationParams,
920        confirmations_policy: ConfirmationsPolicy,
921        account: <DbT as InputSource>::AccountId,
922        transaction_request: TransactionRequest,
923        change_strategy: &ChangeT,
924        spend_policy: &SpendPolicy,
925        proposed_version: Option<TxVersion>,
926    ) -> Result<
927        Proposal<<ChangeT as ChangeStrategy>::FeeRule, DbT::NoteRef>,
928        InputSelectorError<<DbT as InputSource>::Error, Self::Error, ChangeT::Error, DbT::NoteRef>,
929    >
930    where
931        ParamsT: consensus::Parameters,
932        Self::InputSource: InputSource,
933        ChangeT: ChangeStrategy<MetaSource = DbT>,
934    {
935        let (sapling_supported, orchard_supported) =
936            proposed_version.map_or(Ok((true, true)), |v| {
937                let branch_id =
938                    consensus::BranchId::for_height(params, BlockHeight::from(target_height));
939                if v.valid_in_branch(branch_id) {
940                    Ok((
941                        v.has_sapling(),
942                        cfg!(feature = "orchard") && v.has_orchard(),
943                    ))
944                } else {
945                    Err(ProposalError::IncompatibleTxVersion(branch_id))
946                }
947            })?;
948        // Without the `orchard` feature there are no Orchard-family pools to select from, so
949        // `orchard_supported` (always false) is only referenced by Orchard-gated code.
950        #[cfg(not(feature = "orchard"))]
951        let _ = orchard_supported;
952
953        let mut transparent_outputs = vec![];
954        let mut sapling_outputs = vec![];
955        #[cfg(feature = "orchard")]
956        let mut orchard_outputs = vec![];
957        let mut payment_pools = BTreeMap::new();
958
959        // In a ZIP 320 pair, tr0 refers to the first transaction request that
960        // collects shielded value and sends it to an ephemeral address, and tr1
961        // refers to the second transaction request that pays the TEX addresses.
962        #[cfg(feature = "transparent-inputs")]
963        let mut tr1_transparent_outputs = vec![];
964        #[cfg(feature = "transparent-inputs")]
965        let mut tr1_payments = vec![];
966        #[cfg(feature = "transparent-inputs")]
967        let mut tr1_payment_pools = BTreeMap::new();
968        // This balance value is just used for overflow checking; the actual value of ephemeral
969        // outputs will be computed from the constructed `tr1_transparent_outputs` value
970        // constructed below.
971        #[cfg(feature = "transparent-inputs")]
972        let mut total_ephemeral = Zatoshis::ZERO;
973
974        for (idx, payment) in transaction_request.payments() {
975            let payment_amount = payment
976                .amount()
977                .ok_or(ProposalError::PaymentAmountMissing(*idx))?;
978            let recipient_address: Address = payment
979                .recipient_address()
980                .clone()
981                .convert_if_network(params.network_type())?;
982
983            match recipient_address {
984                Address::Transparent(addr) => {
985                    payment_pools.insert(*idx, PoolType::TRANSPARENT);
986                    transparent_outputs.push(TxOut::new(payment_amount, addr.script().into()));
987                }
988                #[cfg(feature = "transparent-inputs")]
989                Address::Tex(data) => {
990                    let p2pkh_addr = TransparentAddress::PublicKeyHash(data);
991
992                    tr1_payment_pools.insert(*idx, PoolType::TRANSPARENT);
993                    tr1_transparent_outputs
994                        .push(TxOut::new(payment_amount, p2pkh_addr.script().into()));
995                    tr1_payments.push(
996                        Payment::new(
997                            payment.recipient_address().clone(),
998                            payment.amount(),
999                            None,
1000                            payment.label().cloned(),
1001                            payment.message().cloned(),
1002                            payment.other_params().to_vec(),
1003                        )
1004                        .expect("cannot fail because memo is None and amount is nonzero"),
1005                    );
1006                    total_ephemeral = (total_ephemeral + payment_amount)
1007                        .ok_or(GreedyInputSelectorError::Balance(BalanceError::Overflow))?;
1008                }
1009                #[cfg(not(feature = "transparent-inputs"))]
1010                Address::Tex(_) => {
1011                    return Err(InputSelectorError::Selection(
1012                        GreedyInputSelectorError::UnsupportedTexAddress,
1013                    ));
1014                }
1015                Address::Sapling(_) => {
1016                    payment_pools.insert(*idx, PoolType::SAPLING);
1017                    sapling_outputs.push(SaplingPayment(payment_amount));
1018                }
1019                Address::Unified(addr) => {
1020                    #[cfg(feature = "orchard")]
1021                    if addr.has_orchard() && orchard_supported {
1022                        // Represent an Orchard-receiver payment as an Ironwood-pool output once
1023                        // Ironwood is active (its value is accounted to the Ironwood bundle
1024                        // below), and as an Orchard-pool output otherwise.
1025                        let pool = if ironwood_active_at(params, target_height) {
1026                            // After NU6.3 the Orchard turnstile (a consensus rule) forbids adding
1027                            // value to the Orchard pool, so the payment must be delivered through
1028                            // the Ironwood bundle, which only a version 6 transaction carries. If a
1029                            // transaction version was explicitly requested that cannot carry an
1030                            // Ironwood bundle, reject the proposal here rather than constructing one
1031                            // that could only fail at build time.
1032                            if let Some(v) = proposed_version
1033                                && !v.has_ironwood()
1034                            {
1035                                return Err(
1036                                    ProposalError::OrchardReceiverRequiresIronwood(v).into()
1037                                );
1038                            }
1039                            PoolType::IRONWOOD
1040                        } else {
1041                            PoolType::ORCHARD
1042                        };
1043                        payment_pools.insert(*idx, pool);
1044                        orchard_outputs.push(OrchardPayment(payment_amount));
1045                        continue;
1046                    }
1047
1048                    if addr.has_sapling() && sapling_supported {
1049                        payment_pools.insert(*idx, PoolType::SAPLING);
1050                        sapling_outputs.push(SaplingPayment(payment_amount));
1051                        continue;
1052                    }
1053
1054                    if let Some(addr) = addr.transparent() {
1055                        payment_pools.insert(*idx, PoolType::TRANSPARENT);
1056                        transparent_outputs.push(TxOut::new(payment_amount, addr.script().into()));
1057                        continue;
1058                    }
1059
1060                    return Err(InputSelectorError::Selection(
1061                        GreedyInputSelectorError::UnsupportedAddress(addr),
1062                    ));
1063                }
1064            }
1065        }
1066
1067        #[cfg(not(feature = "transparent-inputs"))]
1068        let transparent_inputs = vec![];
1069        #[cfg(feature = "transparent-inputs")]
1070        let mut amount_at_transparent_gather = Zatoshis::ZERO;
1071        #[cfg(feature = "transparent-inputs")]
1072        let mut transparent_inputs = match spend_policy.transparent() {
1073            None => {
1074                // No transparent spending is permitted; skip the gather entirely.
1075                Vec::new()
1076            }
1077            Some(transparent) => {
1078                let address_allow_list = transparent.address_allow_list();
1079                self.gather_transparent::<ChangeT>(
1080                    wallet_db,
1081                    target_height,
1082                    confirmations_policy,
1083                    account,
1084                    address_allow_list.as_deref(),
1085                    transparent.coinbase().into(),
1086                    &transaction_request,
1087                    &mut amount_at_transparent_gather,
1088                    spend_policy.locked_input_policy(),
1089                )?
1090            }
1091        };
1092        // Outpoints of gathered transparent inputs that the change strategy has identified as
1093        // dust. Accumulated across loop iterations so that a re-gather (triggered by
1094        // `ChangeError::InsufficientFunds`, below) does not re-introduce previously pruned
1095        // outputs.
1096        #[cfg(feature = "transparent-inputs")]
1097        let mut transparent_dust: BTreeSet<OutPoint> = BTreeSet::new();
1098
1099        let mut shielded_inputs = ReceivedNotes::empty();
1100        let mut amount_required = Zatoshis::ZERO;
1101        let mut exclude: Vec<DbT::NoteRef> = vec![];
1102
1103        // The single pool-preference order that governs both which pools notes are
1104        // selected from and which of the selected notes are spent: the pool matching
1105        // the payment's outputs comes first, and later pools are drawn upon only when
1106        // the earlier ones cannot cover the required amount, so that pool crossing is
1107        // minimized. For a payment to an Orchard receiver the Orchard-family pools
1108        // lead: once NU6.3 is active such payments are constructed in the Ironwood
1109        // bundle — moving their value into the Ironwood pool — so Ironwood is
1110        // preferred, with the legacy Orchard pool last within the family.
1111        #[cfg(feature = "orchard")]
1112        let mut pool_preference = selectable_pool_preference(
1113            params,
1114            target_height,
1115            sapling_supported,
1116            orchard_supported,
1117            !orchard_outputs.is_empty(),
1118        );
1119        #[cfg(not(feature = "orchard"))]
1120        let mut pool_preference = {
1121            let mut pools = vec![];
1122            if sapling_supported {
1123                pools.push(ShieldedPool::Sapling);
1124            }
1125            pools
1126        };
1127
1128        // Restrict selection to the shielded pools the caller's spend policy permits. Crossing a
1129        // pool boundary is privacy-breaking, so a pool the policy does not name is never drawn
1130        // upon — not even as a fallback when the permitted pools cannot cover the request, in
1131        // which case input selection reports `InsufficientFunds`.
1132        pool_preference.retain(|pool| spend_policy.permits_shielded(*pool));
1133
1134        // Every pass that continues advances a bounded measure. After `InsufficientFunds` the
1135        // requirement exceeds the value the balance was computed over, so the next selection,
1136        // trimmed to the pools in use, is worth more. After `DustInputs` a note the change
1137        // strategy was given is excluded, which happens at most once per note since the data
1138        // source never returns an excluded note, or a transparent input is pruned. Transparent
1139        // inputs are re-gathered only at a higher bound. The arms return an error when the
1140        // change strategy reports none of these, since the next pass would repeat this one,
1141        // and the check at the bottom returns `InsufficientFunds` when the data source offers
1142        // no more value toward the requirement.
1143        loop {
1144            // `balance_input_value` is the value of the selected notes in the pools in use: the
1145            // value the balance below is computed over, and the one the check at the bottom
1146            // measures the next selection against.
1147            #[cfg(not(feature = "orchard"))]
1148            let sapling_bundle_required = true;
1149            #[cfg(not(feature = "orchard"))]
1150            let balance_input_value = shielded_inputs.total_value()?;
1151            #[cfg(feature = "orchard")]
1152            let (
1153                sapling_bundle_required,
1154                orchard_bundle_required,
1155                ironwood_bundle_required,
1156                balance_input_value,
1157            ) = {
1158                // Trim the selected notes to the pools that are actually needed: the first
1159                // pool (in `pool_preference` order) whose selected notes cover the required
1160                // amount is spent alone; otherwise pools are accumulated in preference order
1161                // until the running total covers the amount, or all pools are in use.
1162                let pool_values = [
1163                    (ShieldedPool::Sapling, shielded_inputs.sapling_value()?),
1164                    (ShieldedPool::Orchard, shielded_inputs.orchard_value()?),
1165                    (ShieldedPool::Ironwood, shielded_inputs.ironwood_value()?),
1166                ];
1167                let value_of = |pool: ShieldedPool| {
1168                    pool_values
1169                        .iter()
1170                        .find(|(p, _)| *p == pool)
1171                        .map(|(_, v)| *v)
1172                        .expect("all shielded pools are present in pool_values")
1173                };
1174
1175                let (use_pools, trimmed_value) = if let Some(single) = pool_preference
1176                    .iter()
1177                    .find(|p| value_of(**p) >= amount_required)
1178                {
1179                    (vec![*single], value_of(*single))
1180                } else {
1181                    let mut running = Zatoshis::ZERO;
1182                    let mut used = vec![];
1183                    for pool in &pool_preference {
1184                        if running >= amount_required {
1185                            break;
1186                        }
1187                        running = (running + value_of(*pool))
1188                            .ok_or(GreedyInputSelectorError::Balance(BalanceError::Overflow))?;
1189                        used.push(*pool);
1190                    }
1191                    (used, running)
1192                };
1193
1194                (
1195                    use_pools.contains(&ShieldedPool::Sapling),
1196                    use_pools.contains(&ShieldedPool::Orchard),
1197                    use_pools.contains(&ShieldedPool::Ironwood),
1198                    trimmed_value,
1199                )
1200            };
1201
1202            let sapling_inputs = if sapling_bundle_required {
1203                shielded_inputs
1204                    .sapling()
1205                    .iter()
1206                    .map(|i| (*i.internal_note_id(), i.note().value()))
1207                    .collect()
1208            } else {
1209                vec![]
1210            };
1211
1212            #[cfg(feature = "orchard")]
1213            let orchard_inputs = if orchard_bundle_required {
1214                shielded_inputs
1215                    .orchard()
1216                    .iter()
1217                    .map(|i| (*i.internal_note_id(), i.note().value()))
1218                    .collect()
1219            } else {
1220                vec![]
1221            };
1222
1223            // Ironwood inputs are attributed to the Ironwood bundle for action-count and fee
1224            // purposes.
1225            #[cfg(feature = "orchard")]
1226            let ironwood_inputs = if ironwood_bundle_required {
1227                shielded_inputs
1228                    .ironwood()
1229                    .iter()
1230                    .map(|i| (*i.internal_note_id(), i.note().value()))
1231                    .collect()
1232            } else {
1233                vec![]
1234            };
1235
1236            let selected_input_ids = sapling_inputs.iter().map(|(id, _)| id);
1237            #[cfg(feature = "orchard")]
1238            let selected_input_ids =
1239                selected_input_ids.chain(orchard_inputs.iter().map(|(id, _)| id));
1240            #[cfg(feature = "orchard")]
1241            let selected_input_ids =
1242                selected_input_ids.chain(ironwood_inputs.iter().map(|(id, _)| id));
1243
1244            let selected_input_ids = selected_input_ids.cloned().collect::<Vec<_>>();
1245
1246            let wallet_meta = change_strategy
1247                .fetch_wallet_meta(
1248                    params,
1249                    wallet_db,
1250                    account,
1251                    target_height,
1252                    &selected_input_ids,
1253                )
1254                .map_err(InputSelectorError::DataSource)?;
1255
1256            #[cfg(not(feature = "transparent-inputs"))]
1257            let ephemeral_output_value = None;
1258
1259            #[cfg(feature = "transparent-inputs")]
1260            let (ephemeral_output_value, tr1_balance_opt) = {
1261                if tr1_transparent_outputs.is_empty() {
1262                    (None, None)
1263                } else {
1264                    // The ephemeral input going into transaction 1 must be able to pay that
1265                    // transaction's fee, as well as the TEX address payments.
1266
1267                    // Transaction 1 carries no shielded spends or outputs, but the change
1268                    // strategy may still model hypothetical shielded change against these
1269                    // views, so they carry the bundle versions in effect at the target
1270                    // height rather than a fixed default.
1271                    #[cfg(feature = "orchard")]
1272                    let empty_orchard_view = (
1273                        orchard_bundle_version_for_height(params, target_height),
1274                        &[] as &[Infallible],
1275                        &[] as &[Infallible],
1276                    );
1277                    #[cfg(feature = "orchard")]
1278                    let empty_ironwood_view = (
1279                        ironwood_bundle_version_for_height(params, target_height),
1280                        &[] as &[Infallible],
1281                        &[] as &[Infallible],
1282                    );
1283
1284                    // First compute the required total with an additional zero input,
1285                    // catching the `InsufficientFunds` error to obtain the required amount
1286                    // given the provided change strategy. Ignore the change memo in order
1287                    // to avoid adding a change output.
1288                    let tr1_required_input_value = match change_strategy
1289                        .compute_balance::<_, DbT::NoteRef>(
1290                            params,
1291                            target_height,
1292                            anchor_height,
1293                            zip318,
1294                            &[] as &[WalletTransparentOutput<<DbT as InputSource>::AccountId>],
1295                            &tr1_transparent_outputs,
1296                            &sapling::EmptyBundleView,
1297                            #[cfg(feature = "orchard")]
1298                            &empty_orchard_view,
1299                            #[cfg(feature = "orchard")]
1300                            &empty_ironwood_view,
1301                            Some(EphemeralBalance::Input(Zatoshis::ZERO)),
1302                            &wallet_meta,
1303                        ) {
1304                        Err(ChangeError::InsufficientFunds { required, .. })
1305                            if required.is_positive() =>
1306                        {
1307                            required
1308                        }
1309                        // The zero-valued input covers no requirement but zero.
1310                        Err(ChangeError::InsufficientFunds { required, .. }) => {
1311                            return Err(InputSelectorError::Selection(
1312                                GreedyInputSelectorError::RequirementCovered {
1313                                    required,
1314                                    available: Zatoshis::ZERO,
1315                                },
1316                            ));
1317                        }
1318                        // No input was supplied, so none can be named as dust.
1319                        Err(ChangeError::DustInputs { .. }) => {
1320                            return Err(InputSelectorError::Selection(
1321                                GreedyInputSelectorError::DustInputsNotGiven,
1322                            ));
1323                        }
1324                        Err(other) => return Err(InputSelectorError::Change(other)),
1325                        Ok(_) => Zatoshis::ZERO, // shouldn't happen
1326                    };
1327
1328                    // Now recompute to obtain the `TransactionBalance` and verify that it
1329                    // fully accounts for the required fees.
1330                    let tr1_balance = change_strategy.compute_balance::<_, DbT::NoteRef>(
1331                        params,
1332                        target_height,
1333                        anchor_height,
1334                        zip318,
1335                        &[] as &[WalletTransparentOutput<<DbT as InputSource>::AccountId>],
1336                        &tr1_transparent_outputs,
1337                        &sapling::EmptyBundleView,
1338                        #[cfg(feature = "orchard")]
1339                        &empty_orchard_view,
1340                        #[cfg(feature = "orchard")]
1341                        &empty_ironwood_view,
1342                        Some(EphemeralBalance::Input(tr1_required_input_value)),
1343                        &wallet_meta,
1344                    )?;
1345                    assert_eq!(tr1_balance.total(), tr1_balance.fee_required());
1346
1347                    (Some(tr1_required_input_value), Some(tr1_balance))
1348                }
1349            };
1350
1351            // The Orchard bundle keeps the Orchard (version 2) spends; its outputs move to the
1352            // Ironwood bundle when routing is active. The Ironwood bundle takes the Ironwood
1353            // (version 3) spends, and its outputs when routing is active. Attributing each pool's
1354            // spends to its own bundle keeps the action counts (and hence the fee) matching the
1355            // transaction the builder produces.
1356            #[cfg(feature = "orchard")]
1357            let orchard_view = (
1358                orchard_bundle_version_for_height(params, target_height),
1359                &orchard_inputs[..],
1360                if ironwood_active_at(params, target_height) {
1361                    &[]
1362                } else {
1363                    &orchard_outputs[..]
1364                },
1365            );
1366            #[cfg(feature = "orchard")]
1367            let ironwood_view = (
1368                ironwood_bundle_version_for_height(params, target_height),
1369                &ironwood_inputs[..],
1370                if ironwood_active_at(params, target_height) {
1371                    &orchard_outputs[..]
1372                } else {
1373                    &[]
1374                },
1375            );
1376
1377            // Tracks whether this iteration's error handling changed the transparent input
1378            // set, either by re-gathering with a corrected value bound (`InsufficientFunds`)
1379            // or by pruning dust (`DustInputs`). A changed transparent input set is a valid
1380            // form of progress in its own right (distinct from the shielded-note progress
1381            // tracked by `balance_input_value`/`new_available` below): without this, an account
1382            // with no spendable shielded notes at all (or none beyond what's already
1383            // excluded) would spuriously report `InsufficientFunds` on the very next check
1384            // below, even though the changed transparent input set might already be
1385            // sufficient to satisfy the request on the next iteration. Termination is
1386            // preserved: `amount_at_transparent_gather` increases strictly across
1387            // re-gathers, and each outpoint can be pruned as dust at most once (pruned
1388            // outpoints accumulate in `transparent_dust` and are never re-gathered).
1389            #[cfg(not(feature = "transparent-inputs"))]
1390            let transparent_inputs_changed = false;
1391            #[cfg(feature = "transparent-inputs")]
1392            let mut transparent_inputs_changed = false;
1393            // Set when the change strategy names as dust a shielded note it was given. The next
1394            // selection lacks that note and may be worth less than this one, yet it has not
1395            // been balanced, so this too is progress.
1396            let mut shielded_dust_excluded = false;
1397
1398            // In the ZIP 320 case, this is the balance for transaction 0, taking into account
1399            // the ephemeral output.
1400            let tr0_balance = change_strategy.compute_balance(
1401                params,
1402                target_height,
1403                anchor_height,
1404                zip318,
1405                &transparent_inputs,
1406                &transparent_outputs,
1407                &(
1408                    ::sapling::builder::BundleType::DEFAULT,
1409                    &sapling_inputs[..],
1410                    &sapling_outputs[..],
1411                ),
1412                #[cfg(feature = "orchard")]
1413                &orchard_view,
1414                #[cfg(feature = "orchard")]
1415                &ironwood_view,
1416                ephemeral_output_value.map(EphemeralBalance::Output),
1417                &wallet_meta,
1418            );
1419
1420            match tr0_balance {
1421                Ok(tr0_balance) => {
1422                    // At this point, we have enough input value to pay for everything, so we
1423                    // return here.
1424                    let shielded_inputs =
1425                        NonEmpty::from_vec(shielded_inputs.into_vec(&SimpleNoteRetention {
1426                            sapling: sapling_bundle_required,
1427                            #[cfg(feature = "orchard")]
1428                            orchard: orchard_bundle_required,
1429                            #[cfg(feature = "orchard")]
1430                            ironwood: ironwood_bundle_required,
1431                        }))
1432                        .map(ShieldedInputs::from_parts);
1433
1434                    return build_proposal(
1435                        change_strategy.fee_rule(),
1436                        tr0_balance,
1437                        target_height,
1438                        anchor_height,
1439                        confirmations_policy,
1440                        shielded_inputs,
1441                        transparent_inputs,
1442                        transaction_request,
1443                        payment_pools,
1444                        #[cfg(feature = "orchard")]
1445                        ironwood_active_at(params, target_height),
1446                        #[cfg(feature = "transparent-inputs")]
1447                        ephemeral_output_value.zip(tr1_balance_opt).map(
1448                            |(ephemeral_output_value, tr1_balance)| EphemeralStepConfig {
1449                                ephemeral_output_value,
1450                                tr1_balance,
1451                                tr1_payments,
1452                                tr1_payment_pools,
1453                            },
1454                        ),
1455                    )
1456                    .map_err(InputSelectorError::Proposal);
1457                }
1458                Err(ChangeError::DustInputs {
1459                    #[cfg(feature = "transparent-inputs")]
1460                    transparent,
1461                    mut sapling,
1462                    #[cfg(feature = "orchard")]
1463                    mut orchard,
1464                    #[cfg(feature = "orchard")]
1465                    mut ironwood,
1466                    ..
1467                }) => {
1468                    // A named note the change strategy was given leaves the next selection once
1469                    // excluded; one it was not given breaks the strategy's contract.
1470                    let named = sapling.iter();
1471                    #[cfg(feature = "orchard")]
1472                    let named = named.chain(orchard.iter()).chain(ironwood.iter());
1473                    let mut other_named = false;
1474                    for note in named {
1475                        if selected_input_ids.contains(note) {
1476                            shielded_dust_excluded = true;
1477                        } else {
1478                            other_named = true;
1479                        }
1480                    }
1481                    exclude.append(&mut sapling);
1482                    #[cfg(feature = "orchard")]
1483                    exclude.append(&mut orchard);
1484                    #[cfg(feature = "orchard")]
1485                    exclude.append(&mut ironwood);
1486                    #[cfg(feature = "transparent-inputs")]
1487                    {
1488                        let len_before = transparent_inputs.len();
1489                        other_named |= transparent.iter().any(|outpoint| {
1490                            !transparent_inputs
1491                                .iter()
1492                                .any(|input| input.outpoint() == outpoint)
1493                        });
1494                        transparent_dust.extend(transparent);
1495                        transparent_inputs.retain(|i| !transparent_dust.contains(i.outpoint()));
1496                        // Pruning dust changes the balance computation, so give the loop a
1497                        // chance to re-evaluate the pruned set before concluding that funds
1498                        // are insufficient.
1499                        if transparent_inputs.len() != len_before {
1500                            transparent_inputs_changed = true;
1501                        }
1502                    }
1503                    // With no given input named, the next selection would be the one just
1504                    // balanced.
1505                    if other_named || (!shielded_dust_excluded && !transparent_inputs_changed) {
1506                        return Err(InputSelectorError::Selection(
1507                            GreedyInputSelectorError::DustInputsNotGiven,
1508                        ));
1509                    }
1510                }
1511                Err(ChangeError::InsufficientFunds { required, .. }) => {
1512                    // A requirement the inputs already cover cannot be met by selecting more.
1513                    let available = available_value(balance_input_value, &transparent_inputs)?;
1514                    if required <= available {
1515                        return Err(InputSelectorError::Selection(
1516                            GreedyInputSelectorError::RequirementCovered {
1517                                required,
1518                                available,
1519                            },
1520                        ));
1521                    }
1522                    amount_required = required;
1523                    // The initial transparent-input gather was bounded by the payouts
1524                    // alone, but `required` includes the fee. If the bound was too
1525                    // low, re-gather transparents with the corrected value as a
1526                    // defensive fallback. The common case (fee estimate was close) is
1527                    // a no-op.
1528                    #[cfg(feature = "transparent-inputs")]
1529                    if let Some(transparent) = spend_policy.transparent()
1530                        && required > amount_at_transparent_gather
1531                    {
1532                        let address_allow_list = transparent.address_allow_list();
1533                        // Honor the caller's `SpendPolicy::locked_input_policy`, as at the
1534                        // initial gather above.
1535                        transparent_inputs = wallet_db
1536                            .select_spendable_transparent_outputs(
1537                                account,
1538                                target_height,
1539                                confirmations_policy,
1540                                transparent.coinbase().into(),
1541                                address_allow_list.as_deref(),
1542                                TargetValue::AtLeast(required),
1543                                shielding_max_inputs(self.shielding_block_space_percent),
1544                                &StandardFeeRule::Zip317,
1545                                LockFilter::Policy(spend_policy.locked_input_policy()),
1546                            )
1547                            .map_err(InputSelectorError::DataSource)?
1548                            .into_iter()
1549                            // Do not re-introduce outputs previously pruned as dust; the
1550                            // value they would contribute is (approximately) consumed by
1551                            // their own fee cost, so their absence does not meaningfully
1552                            // reduce the gathered value.
1553                            .filter(|utxo| !transparent_dust.contains(utxo.outpoint()))
1554                            .map(|utxo| utxo.redact_account_data())
1555                            .collect::<Vec<_>>();
1556                        amount_at_transparent_gather = required;
1557                        transparent_inputs_changed = true;
1558                    }
1559                }
1560                Err(other) => return Err(InputSelectorError::Change(other)),
1561            }
1562
1563            // Candidate notes are selected from the pools of `pool_preference` — the
1564            // same order the pool-usage trimming at the top of the loop applies — so
1565            // the notes offered for spending and the notes actually spent are governed
1566            // by one policy: pool crossing is minimized, and a payment to an Orchard
1567            // receiver draws on the pool its output is constructed in (the Ironwood
1568            // pool once NU6.3 is active).
1569            // Input selection honors the caller's `SpendPolicy::locked_input_policy`: by default
1570            // (`Exclude`) a locked output is never drawn upon, since it belongs to another
1571            // in-flight proposal and spending it would recreate the conflict that locking exists
1572            // to prevent; the `PreferUnlocked`/`PreferLocked` overrides let a caller draw through
1573            // a lock it recognizes (e.g. its own pool-migration PCZTs).
1574            //
1575            // Under `NoteSelection::PreferSingle`, the single oldest note covering the required
1576            // amount alone is tried first; when no pool holds one, selection falls back to
1577            // ordinary accumulation, which still funds the payment but cannot produce the
1578            // single-input shape the caller preferred.
1579            let single_note = match spend_policy.note_selection() {
1580                NoteSelection::PreferSingle => Some(
1581                    wallet_db
1582                        .select_single_spendable_note(
1583                            account,
1584                            amount_required,
1585                            &pool_preference,
1586                            target_height,
1587                            confirmations_policy,
1588                            &exclude,
1589                            LockFilter::Policy(spend_policy.locked_input_policy()),
1590                        )
1591                        .map_err(InputSelectorError::DataSource)?,
1592                )
1593                .filter(|notes| !notes.is_empty()),
1594                NoteSelection::Accumulate => None,
1595            };
1596            shielded_inputs = match single_note {
1597                Some(single) => single,
1598                None => wallet_db
1599                    .select_spendable_notes(
1600                        account,
1601                        TargetValue::AtLeast(amount_required),
1602                        &pool_preference,
1603                        target_height,
1604                        confirmations_policy,
1605                        &exclude,
1606                        LockFilter::Policy(spend_policy.locked_input_policy()),
1607                    )
1608                    .map_err(InputSelectorError::DataSource)?,
1609            };
1610
1611            // The loop rests on the data source selecting from the pools asked for and
1612            // withholding excluded notes: a note outside those pools is never balanced yet
1613            // counts below, and a note named as dust and returned again would be named again.
1614            check_selection(&shielded_inputs, &pool_preference, &exclude)?;
1615
1616            // Loop again only when selection offers more value than the balance above was
1617            // computed over, a given shielded note was excluded, or the transparent input set
1618            // changed this iteration.
1619            let new_available = shielded_inputs.total_value()?;
1620            if new_available <= balance_input_value
1621                && !transparent_inputs_changed
1622                && !shielded_dust_excluded
1623            {
1624                return Err(InputSelectorError::InsufficientFunds {
1625                    required: amount_required,
1626                    available: available_value(balance_input_value, &transparent_inputs)?,
1627                });
1628            }
1629        }
1630    }
1631}
1632
1633/// Returns the value input selection reports as available: the shielded value a balance was
1634/// computed over plus the transparent inputs it was given.
1635fn available_value<AccountId>(
1636    shielded: Zatoshis,
1637    transparent_inputs: &[WalletTransparentOutput<AccountId>],
1638) -> Result<Zatoshis, BalanceError> {
1639    let transparent = transparent_inputs
1640        .iter()
1641        .map(|input| input.value())
1642        .sum::<Option<Zatoshis>>()
1643        .ok_or(BalanceError::Overflow)?;
1644    (shielded + transparent).ok_or(BalanceError::Overflow)
1645}
1646
1647/// Checks a selection against the contract of [`InputSource`]: it holds no note from a pool
1648/// outside `sources` and no note in `exclude`.
1649fn check_selection<NoteRef: PartialEq>(
1650    notes: &ReceivedNotes<NoteRef>,
1651    sources: &[ShieldedPool],
1652    exclude: &[NoteRef],
1653) -> Result<(), GreedyInputSelectorError> {
1654    fn check_pool<NoteRef: PartialEq, NoteT>(
1655        notes: &[ReceivedNote<NoteRef, NoteT>],
1656        pool: ShieldedPool,
1657        sources: &[ShieldedPool],
1658        exclude: &[NoteRef],
1659    ) -> Result<(), GreedyInputSelectorError> {
1660        if !notes.is_empty() && !sources.contains(&pool) {
1661            return Err(GreedyInputSelectorError::UnrequestedPoolSelected);
1662        }
1663        if notes
1664            .iter()
1665            .any(|note| exclude.contains(note.internal_note_id()))
1666        {
1667            return Err(GreedyInputSelectorError::ExcludedNoteSelected);
1668        }
1669        Ok(())
1670    }
1671    check_pool(notes.sapling(), ShieldedPool::Sapling, sources, exclude)?;
1672    #[cfg(feature = "orchard")]
1673    {
1674        check_pool(notes.orchard(), ShieldedPool::Orchard, sources, exclude)?;
1675        check_pool(notes.ironwood(), ShieldedPool::Ironwood, sources, exclude)?;
1676    }
1677    Ok(())
1678}
1679
1680/// Returns the shielded pools from which the greedy input selector may spend at the
1681/// given target height, in preference order.
1682///
1683/// The pool family matching the payment's outputs comes first, so that single-pool
1684/// coverage avoids unnecessary pool crossings: for an Orchard-family payment this is
1685/// Ironwood (when active) and then Orchard — an Orchard-receiver payment is delivered
1686/// via the Ironwood bundle once Ironwood is active — and for other payments it is
1687/// Sapling. The legacy Orchard pool comes last otherwise, so that it is drawn upon
1688/// only when the more current pools cannot cover the required amount.
1689#[cfg(feature = "orchard")]
1690fn selectable_pool_preference<ParamsT: consensus::Parameters>(
1691    params: &ParamsT,
1692    target_height: TargetHeight,
1693    sapling_supported: bool,
1694    orchard_supported: bool,
1695    prefer_orchard_family: bool,
1696) -> Vec<ShieldedPool> {
1697    let ironwood_selectable = orchard_supported && ironwood_active_at(params, target_height);
1698    let mut preference = Vec::with_capacity(3);
1699    if prefer_orchard_family {
1700        if ironwood_selectable {
1701            preference.push(ShieldedPool::Ironwood);
1702        }
1703        if orchard_supported {
1704            preference.push(ShieldedPool::Orchard);
1705        }
1706        if sapling_supported {
1707            preference.push(ShieldedPool::Sapling);
1708        }
1709    } else {
1710        if sapling_supported {
1711            preference.push(ShieldedPool::Sapling);
1712        }
1713        if ironwood_selectable {
1714            preference.push(ShieldedPool::Ironwood);
1715        }
1716        if orchard_supported {
1717            preference.push(ShieldedPool::Orchard);
1718        }
1719    }
1720    preference
1721}
1722
1723/// Returns the Orchard bundle version whose action-count policy applies to
1724/// transactions constructed for the given target height.
1725#[cfg(feature = "orchard")]
1726fn orchard_bundle_version_for_height<ParamsT: consensus::Parameters, H: Into<BlockHeight>>(
1727    params: &ParamsT,
1728    target_height: H,
1729) -> ::orchard::bundle::BundleVersion {
1730    zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
1731        consensus::BranchId::for_height(params, target_height.into()),
1732        ::orchard::ValuePool::Orchard,
1733    )
1734    // Orchard did not exist prior to NU5, so no Orchard bundle (and no Orchard
1735    // action) can be produced for a pre-NU5 target height; every bundle version
1736    // yields the correct action count (zero) for an empty bundle.
1737    .unwrap_or(::orchard::bundle::BundleVersion::orchard_insecure_v1())
1738}
1739
1740/// Returns the Ironwood bundle version whose action-count policy applies to
1741/// transactions constructed for the given target height.
1742#[cfg(feature = "orchard")]
1743fn ironwood_bundle_version_for_height<ParamsT: consensus::Parameters, H: Into<BlockHeight>>(
1744    params: &ParamsT,
1745    target_height: H,
1746) -> ::orchard::bundle::BundleVersion {
1747    zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
1748        consensus::BranchId::for_height(params, target_height.into()),
1749        ::orchard::ValuePool::Ironwood,
1750    )
1751    // The Ironwood pool did not exist prior to NU6.3, so no Ironwood bundle (and
1752    // no Ironwood action) can be produced for an earlier target height; every
1753    // bundle version yields the correct action count (zero) for an empty bundle.
1754    .unwrap_or(::orchard::bundle::BundleVersion::ironwood_v3())
1755}
1756
1757#[allow(clippy::type_complexity, clippy::too_many_arguments)]
1758pub(crate) fn propose_send_max<ParamsT, InputSourceT, FeeRuleT>(
1759    params: &ParamsT,
1760    wallet_db: &InputSourceT,
1761    fee_rule: &FeeRuleT,
1762    source_account: InputSourceT::AccountId,
1763    spend_pools: &[ShieldedPool],
1764    target_height: TargetHeight,
1765    anchor_height: BlockHeight,
1766    mode: MaxSpendMode,
1767    confirmations_policy: ConfirmationsPolicy,
1768    recipient: ZcashAddress,
1769    memo: Option<MemoBytes>,
1770    locked_input_policy: &LockedInputPolicy,
1771) -> Result<
1772    Proposal<FeeRuleT, InputSourceT::NoteRef>,
1773    InputSelectorError<
1774        InputSourceT::Error,
1775        GreedyInputSelectorError,
1776        FeeRuleT::Error,
1777        InputSourceT::NoteRef,
1778    >,
1779>
1780where
1781    ParamsT: consensus::Parameters,
1782    InputSourceT: InputSource,
1783    FeeRuleT: FeeRule + Clone,
1784{
1785    // Input selection honors the caller's `locked_input_policy`: by default (`Exclude`) a
1786    // locked output is never drawn upon, since it belongs to another in-flight proposal and
1787    // spending it would recreate the conflict that locking exists to prevent; the
1788    // `PreferUnlocked`/`PreferLocked` overrides let a caller draw through a lock it recognizes
1789    // (e.g. its own pool-migration PCZTs).
1790    let spendable_notes = wallet_db
1791        .select_spendable_notes(
1792            source_account,
1793            TargetValue::AllFunds(mode),
1794            spend_pools,
1795            target_height,
1796            confirmations_policy,
1797            &[],
1798            LockFilter::Policy(locked_input_policy),
1799        )
1800        .map_err(InputSelectorError::DataSource)?;
1801
1802    let input_total = spendable_notes
1803        .total_value()
1804        .map_err(|e| InputSelectorError::Selection(GreedyInputSelectorError::Balance(e)))?;
1805
1806    let mut payment_pools = BTreeMap::new();
1807
1808    // An Orchard receiver takes delivery precedence over a Sapling receiver only when
1809    // this build is able to produce Orchard-family outputs; without the `orchard`
1810    // feature, a payment to a recipient having both receivers is delivered via the
1811    // Sapling receiver.
1812    #[cfg(feature = "orchard")]
1813    let orchard_receiver_payable = recipient.can_receive_as(PoolType::ORCHARD);
1814    #[cfg(not(feature = "orchard"))]
1815    let orchard_receiver_payable = false;
1816
1817    let sapling_output_count = {
1818        // we require a sapling output if the recipient has a Sapling receiver and its
1819        // payment is not deliverable via an Orchard receiver.
1820        let requested_sapling_outputs: usize =
1821            if recipient.can_receive_as(PoolType::SAPLING) && !orchard_receiver_payable {
1822                payment_pools.insert(0, PoolType::SAPLING);
1823                1
1824            } else {
1825                0
1826            };
1827
1828        ::sapling::builder::BundleType::DEFAULT
1829            .num_outputs(spendable_notes.sapling.len(), requested_sapling_outputs)
1830            .map_err(|s| InputSelectorError::Change(ChangeError::BundleError(s)))?
1831    };
1832
1833    let sapling_bundle_required = !spendable_notes.sapling().is_empty() || sapling_output_count > 0;
1834
1835    // A payment to an Orchard receiver is represented in the proposal as an Ironwood-pool output
1836    // once Ironwood is active (delivered to the Orchard receiver via the Ironwood bundle), and as
1837    // an Orchard-pool output otherwise. The per-bundle action counts below reflect that split.
1838    #[cfg(feature = "orchard")]
1839    let orchard_receivers_fill_ironwood = ironwood_active_at(params, target_height);
1840    #[cfg(feature = "orchard")]
1841    if orchard_receiver_payable {
1842        payment_pools.insert(
1843            0,
1844            if orchard_receivers_fill_ironwood {
1845                PoolType::IRONWOOD
1846            } else {
1847                PoolType::ORCHARD
1848            },
1849        );
1850    }
1851
1852    #[cfg(feature = "orchard")]
1853    let orchard_action_count = orchard_fees::transactional_action_count(
1854        // Input selection estimates fees with the padded default bundle type; the
1855        // unpadded opt-in is applied later by the change strategy.
1856        ::orchard::builder::BundleType::DEFAULT,
1857        orchard_bundle_version_for_height(params, target_height),
1858        spendable_notes.orchard.len(),
1859        usize::from(orchard_receiver_payable && !orchard_receivers_fill_ironwood),
1860    )
1861    .map_err(|e| InputSelectorError::Change(ChangeError::BundleError(e)))?;
1862    #[cfg(not(feature = "orchard"))]
1863    let orchard_action_count: usize = 0;
1864
1865    #[cfg(feature = "orchard")]
1866    let orchard_bundle_required = orchard_action_count > 0;
1867
1868    #[cfg(feature = "orchard")]
1869    let ironwood_action_count = orchard_fees::transactional_action_count(
1870        ::orchard::builder::BundleType::DEFAULT,
1871        ironwood_bundle_version_for_height(params, target_height),
1872        spendable_notes.ironwood.len(),
1873        usize::from(orchard_receiver_payable && orchard_receivers_fill_ironwood),
1874    )
1875    .map_err(|s| InputSelectorError::Change(ChangeError::BundleError(s)))?;
1876    #[cfg(not(feature = "orchard"))]
1877    let ironwood_action_count: usize = 0;
1878
1879    #[cfg(feature = "orchard")]
1880    let ironwood_bundle_required = ironwood_action_count > 0;
1881
1882    let recipient_address: Address = recipient
1883        .clone()
1884        .convert_if_network(params.network_type())?;
1885
1886    // A recipient that can only receive funds via a transparent output — a bare
1887    // transparent address, or a unified address with no shielded receiver — is paid
1888    // directly from the proposed transaction. TEX recipients are excluded: their
1889    // payment is delivered by the ephemeral second step, which carries its own
1890    // payment pool assignment.
1891    let pays_transparent_directly = match &recipient_address {
1892        Address::Transparent(_) => true,
1893        Address::Unified(addr) => {
1894            addr.has_transparent() && !(addr.has_sapling() || addr.has_orchard())
1895        }
1896        _ => false,
1897    };
1898    if pays_transparent_directly {
1899        payment_pools.insert(0, PoolType::Transparent);
1900    }
1901
1902    // A unified address that has been assigned no payment pool by this point contains
1903    // no receiver that this build is able to pay (for example, an address containing
1904    // only an Orchard receiver, in a build made without the `orchard` feature). Other
1905    // recipient kinds always receive an assignment above, except for TEX addresses,
1906    // whose payment is delivered by the ephemeral second step.
1907    if payment_pools.is_empty()
1908        && let Address::Unified(addr) = &recipient_address
1909    {
1910        return Err(InputSelectorError::Selection(
1911            GreedyInputSelectorError::UnsupportedAddress(addr.clone()),
1912        ));
1913    }
1914
1915    let (tr0_fee, tr1_fee) = match recipient_address {
1916        Address::Sapling(_) => fee_rule
1917            .fee_required(
1918                params,
1919                BlockHeight::from(target_height),
1920                [],
1921                [],
1922                spendable_notes.sapling().len(),
1923                sapling_output_count,
1924                orchard_action_count,
1925                ironwood_action_count,
1926            )
1927            .map(|fee| (fee, None)),
1928        Address::Transparent(_) => fee_rule
1929            .fee_required(
1930                params,
1931                BlockHeight::from(target_height),
1932                [],
1933                [P2PKH_STANDARD_OUTPUT_SIZE],
1934                spendable_notes.sapling().len(),
1935                sapling_output_count,
1936                orchard_action_count,
1937                ironwood_action_count,
1938            )
1939            .map(|fee| (fee, None)),
1940        Address::Unified(_) => fee_rule
1941            .fee_required(
1942                params,
1943                BlockHeight::from(target_height),
1944                [],
1945                if pays_transparent_directly {
1946                    vec![P2PKH_STANDARD_OUTPUT_SIZE]
1947                } else {
1948                    vec![]
1949                },
1950                spendable_notes.sapling().len(),
1951                sapling_output_count,
1952                orchard_action_count,
1953                ironwood_action_count,
1954            )
1955            .map(|fee| (fee, None)),
1956        // Paying a TEX recipient requires a second, purely transparent transaction that
1957        // spends an ephemeral output of the first; constructing that ZIP 320 pair is
1958        // only supported when the `transparent-inputs` feature is enabled.
1959        #[cfg(not(feature = "transparent-inputs"))]
1960        Address::Tex(_) => {
1961            return Err(InputSelectorError::Selection(
1962                GreedyInputSelectorError::UnsupportedTexAddress,
1963            ));
1964        }
1965        #[cfg(feature = "transparent-inputs")]
1966        Address::Tex(_) => fee_rule
1967            .fee_required(
1968                params,
1969                BlockHeight::from(target_height),
1970                [],
1971                [P2PKH_STANDARD_OUTPUT_SIZE],
1972                spendable_notes.sapling().len(),
1973                sapling_output_count,
1974                orchard_action_count,
1975                ironwood_action_count,
1976            )
1977            .and_then(|tr0_fee| {
1978                let tr1_fee = fee_rule.fee_required(
1979                    params,
1980                    BlockHeight::from(target_height),
1981                    [InputSize::Known(P2PKH_STANDARD_INPUT_SIZE)],
1982                    [P2PKH_STANDARD_OUTPUT_SIZE],
1983                    0,
1984                    0,
1985                    0,
1986                    0,
1987                )?;
1988
1989                Ok((tr0_fee, Some(tr1_fee)))
1990            }),
1991    }
1992    .map_err(|fee_error| InputSelectorError::Change(ChangeError::StrategyError(fee_error)))?;
1993
1994    // the total fee required for the all the involved transactions. For the case
1995    // of TEX it means the fee requied to send the max value to the ephemeral
1996    // address + the fee to send the value in that ephemeral change address to
1997    // the TEX address. The sum can only exceed the maximum monetary amount for a
1998    // fee rule that produces fees outside that amount's intended bounds.
1999    let total_fee_required = (tr0_fee + tr1_fee.unwrap_or(Zatoshis::ZERO)).ok_or(
2000        InputSelectorError::Selection(GreedyInputSelectorError::Balance(BalanceError::Overflow)),
2001    )?;
2002
2003    // the total amount involved in the "send max" operation. This is the total
2004    // spendable value present in the wallet minus the fees required to perform
2005    // the send max operation. The proposal must deliver a nonzero amount to the
2006    // recipient: a send-max operation on a wallet whose entire balance would be
2007    // consumed by fees is reported as insufficient funds rather than proposed as
2008    // a fee-only transaction.
2009    let total_to_recipient = (input_total - total_fee_required)
2010        .filter(|amount| *amount > Zatoshis::ZERO)
2011        .ok_or(InputSelectorError::InsufficientFunds {
2012            available: input_total,
2013            required: (total_fee_required + Zatoshis::const_from_u64(1))
2014                .unwrap_or(Zatoshis::const_from_u64(MAX_MONEY)),
2015        })?;
2016
2017    // when the recipient of the send max operation is a TEX address this is the
2018    // amount that will be needed to send the max available amount accounting the
2019    // fees needed to propose a transaction involving one transparent input and
2020    // one transparent output (the TEX address recipient.)
2021    #[cfg(feature = "transparent-inputs")]
2022    let ephemeral_output_value =
2023        tr1_fee.map(|fee| (total_to_recipient + fee).expect("overflow already checked"));
2024
2025    #[cfg(feature = "transparent-inputs")]
2026    let tr0_change = ephemeral_output_value
2027        .into_iter()
2028        .map(ChangeValue::ephemeral_transparent)
2029        .collect();
2030    #[cfg(not(feature = "transparent-inputs"))]
2031    let tr0_change = vec![];
2032
2033    // The transaction produces no change, unless this is a transaction to a TEX address; in this
2034    // case, the first transaction produces a single ephemeral change output.
2035    let tr0_balance = TransactionBalance::new(tr0_change, tr0_fee)
2036        .expect("the sum of an single-element vector of fee values cannot overflow");
2037
2038    let payment = zip321::Payment::new(
2039        recipient,
2040        Some(total_to_recipient),
2041        memo,
2042        None,
2043        None,
2044        vec![],
2045    )
2046    .map_err(|e| InputSelectorError::Proposal(ProposalError::Zip321(e.with_index(0))))?;
2047
2048    let transaction_request =
2049        TransactionRequest::new(vec![payment.clone()]).map_err(|payment_error| {
2050            InputSelectorError::Proposal(ProposalError::Zip321(payment_error))
2051        })?;
2052
2053    let shielded_inputs = NonEmpty::from_vec(spendable_notes.into_vec(&SimpleNoteRetention {
2054        sapling: sapling_bundle_required,
2055        #[cfg(feature = "orchard")]
2056        orchard: orchard_bundle_required,
2057        #[cfg(feature = "orchard")]
2058        ironwood: ironwood_bundle_required,
2059    }))
2060    .map(ShieldedInputs::from_parts);
2061
2062    build_proposal(
2063        fee_rule,
2064        tr0_balance,
2065        target_height,
2066        anchor_height,
2067        confirmations_policy,
2068        shielded_inputs,
2069        vec![],
2070        transaction_request,
2071        payment_pools,
2072        #[cfg(feature = "orchard")]
2073        ironwood_active_at(params, target_height),
2074        #[cfg(feature = "transparent-inputs")]
2075        ephemeral_output_value
2076            .zip(tr1_fee)
2077            .map(|(ephemeral_output_value, tr1_fee)| EphemeralStepConfig {
2078                ephemeral_output_value,
2079                tr1_balance: TransactionBalance::new(vec![], tr1_fee)
2080                    .expect("the sum of an empty vector of fee values cannot overflow"),
2081                tr1_payments: vec![payment],
2082                tr1_payment_pools: BTreeMap::from_iter([(0, PoolType::Transparent)]),
2083            }),
2084    )
2085    .map_err(InputSelectorError::Proposal)
2086}
2087
2088#[cfg(feature = "transparent-inputs")]
2089struct EphemeralStepConfig {
2090    ephemeral_output_value: Zatoshis,
2091    tr1_balance: TransactionBalance,
2092    tr1_payments: Vec<Payment>,
2093    tr1_payment_pools: BTreeMap<usize, PoolType>,
2094}
2095
2096#[allow(clippy::too_many_arguments)]
2097fn build_proposal<FeeRuleT: FeeRule + Clone, NoteRef>(
2098    fee_rule: &FeeRuleT,
2099    tr0_balance: TransactionBalance,
2100    target_height: TargetHeight,
2101    anchor_height: BlockHeight,
2102    confirmations_policy: ConfirmationsPolicy,
2103    shielded_inputs: Option<ShieldedInputs<NoteRef>>,
2104    transparent_inputs: Vec<WalletTransparentOutput<()>>,
2105    transaction_request: TransactionRequest,
2106    payment_pools: BTreeMap<usize, PoolType>,
2107    #[cfg(feature = "orchard")] ironwood_active: bool,
2108    #[cfg(feature = "transparent-inputs")] ephemeral_step_opt: Option<EphemeralStepConfig>,
2109) -> Result<Proposal<FeeRuleT, NoteRef>, ProposalError> {
2110    #[cfg(feature = "transparent-inputs")]
2111    if let Some(ephemeral_step) = ephemeral_step_opt {
2112        let tr1_balance = ephemeral_step.tr1_balance;
2113        // Construct two new `TransactionRequest`s:
2114        // * `tr0` excludes the TEX outputs, and in their place includes
2115        //   a single additional ephemeral output to the transparent pool.
2116        // * `tr1` spends from that ephemeral output to each TEX output.
2117
2118        // Find exactly one ephemeral change output.
2119        let ephemeral_outputs = tr0_balance
2120            .proposed_change()
2121            .iter()
2122            .enumerate()
2123            .filter(|(_, c)| c.is_ephemeral())
2124            .collect::<Vec<_>>();
2125
2126        let ephemeral_output_index = match &ephemeral_outputs[..] {
2127            [(i, change_value)]
2128                if change_value.value() == ephemeral_step.ephemeral_output_value =>
2129            {
2130                Ok(*i)
2131            }
2132            _ => Err(ProposalError::EphemeralOutputsInvalid),
2133        }?;
2134
2135        let ephemeral_stepoutput =
2136            StepOutput::new(0, StepOutputIndex::Change(ephemeral_output_index));
2137
2138        let tr0 = TransactionRequest::from_indexed(
2139            transaction_request
2140                .payments()
2141                .iter()
2142                .filter(|(idx, _payment)| !ephemeral_step.tr1_payment_pools.contains_key(idx))
2143                .map(|(k, v)| (*k, v.clone()))
2144                .collect(),
2145        )
2146        .expect("removing payments from a TransactionRequest preserves validity");
2147
2148        let mut steps = vec![];
2149        let step0 = Step::from_parts(
2150            &[],
2151            tr0,
2152            payment_pools,
2153            transparent_inputs,
2154            shielded_inputs,
2155            Some(anchor_height),
2156            vec![],
2157            tr0_balance,
2158            false,
2159            #[cfg(feature = "orchard")]
2160            ironwood_active,
2161        )?;
2162        steps.push(step0);
2163
2164        let tr1 =
2165            TransactionRequest::new(ephemeral_step.tr1_payments).expect("valid by construction");
2166        let step1 = Step::from_parts(
2167            &steps,
2168            tr1,
2169            ephemeral_step.tr1_payment_pools,
2170            vec![],
2171            None,
2172            Some(anchor_height),
2173            vec![ephemeral_stepoutput],
2174            tr1_balance,
2175            false,
2176            #[cfg(feature = "orchard")]
2177            ironwood_active,
2178        )?;
2179        steps.push(step1);
2180
2181        return Proposal::multi_step(
2182            fee_rule.clone(),
2183            target_height,
2184            confirmations_policy,
2185            NonEmpty::from_vec(steps).expect("steps is known to be nonempty"),
2186        );
2187    }
2188
2189    Proposal::single_step(
2190        transaction_request,
2191        payment_pools,
2192        transparent_inputs,
2193        shielded_inputs,
2194        anchor_height,
2195        tr0_balance,
2196        fee_rule.clone(),
2197        target_height,
2198        confirmations_policy,
2199        false,
2200        #[cfg(feature = "orchard")]
2201        ironwood_active,
2202    )
2203}
2204
2205#[cfg(feature = "transparent-inputs")]
2206impl<DbT: InputSource> ShieldingSelector for GreedyInputSelector<DbT> {
2207    type Error = GreedyInputSelectorError;
2208    type InputSource = DbT;
2209
2210    #[allow(clippy::type_complexity)]
2211    fn propose_shielding<ParamsT, ChangeT>(
2212        &self,
2213        params: &ParamsT,
2214        wallet_db: &Self::InputSource,
2215        change_strategy: &ChangeT,
2216        shielding_threshold: Zatoshis,
2217        source_addrs: &[TransparentAddress],
2218        to_account: <Self::InputSource as InputSource>::AccountId,
2219        target_height: TargetHeight,
2220        anchor_height: BlockHeight,
2221        zip318: &PoolMigrationParams,
2222        confirmations_policy: ConfirmationsPolicy,
2223        output_filter: CoinbaseFilter,
2224    ) -> Result<
2225        Proposal<<ChangeT as ChangeStrategy>::FeeRule, Infallible>,
2226        InputSelectorError<<DbT as InputSource>::Error, Self::Error, ChangeT::Error, Infallible>,
2227    >
2228    where
2229        ParamsT: consensus::Parameters,
2230        ChangeT: ChangeStrategy<MetaSource = Self::InputSource>,
2231    {
2232        let mut transparent_inputs = gather_shielding_inputs::<DbT, ChangeT::Error>(
2233            wallet_db,
2234            source_addrs,
2235            target_height,
2236            confirmations_policy,
2237            output_filter,
2238            shielding_max_inputs(self.shielding_block_space_percent),
2239            &self.locked_input_policy,
2240        )?;
2241
2242        let wallet_meta = change_strategy
2243            .fetch_wallet_meta(params, wallet_db, to_account, target_height, &[])
2244            .map_err(InputSelectorError::DataSource)?;
2245
2246        let balance = compute_shielding_balance_with_dust_retry::<DbT, ChangeT, ParamsT>(
2247            change_strategy,
2248            params,
2249            target_height,
2250            anchor_height,
2251            zip318,
2252            &mut transparent_inputs,
2253            &wallet_meta,
2254        )?;
2255
2256        if balance.total() >= shielding_threshold {
2257            Proposal::single_step(
2258                TransactionRequest::empty(),
2259                BTreeMap::new(),
2260                transparent_inputs,
2261                None,
2262                anchor_height,
2263                balance,
2264                (*change_strategy.fee_rule()).clone(),
2265                target_height,
2266                confirmations_policy,
2267                true,
2268                #[cfg(feature = "orchard")]
2269                ironwood_active_at(params, target_height),
2270            )
2271            .map_err(InputSelectorError::Proposal)
2272        } else {
2273            Err(InputSelectorError::InsufficientFunds {
2274                available: balance.total(),
2275                required: shielding_threshold,
2276            })
2277        }
2278    }
2279
2280    #[allow(clippy::type_complexity)]
2281    fn propose_shielding_coinbase<ParamsT, FeeRuleT>(
2282        &self,
2283        params: &ParamsT,
2284        wallet_db: &Self::InputSource,
2285        fee_rule: &FeeRuleT,
2286        shielding_threshold: Zatoshis,
2287        source_addrs: &[TransparentAddress],
2288        to_address: ZcashAddress,
2289        memo: Option<MemoBytes>,
2290        limit: Option<usize>,
2291        target_height: TargetHeight,
2292        anchor_height: BlockHeight,
2293    ) -> Result<
2294        Proposal<FeeRuleT, Infallible>,
2295        InputSelectorError<<DbT as InputSource>::Error, Self::Error, FeeRuleT::Error, Infallible>,
2296    >
2297    where
2298        ParamsT: consensus::Parameters,
2299        FeeRuleT: FeeRule + Clone,
2300    {
2301        // Coinbase-only is enforced here at the API boundary: callers cannot bypass
2302        // it. This is the privacy property that motivates having a dedicated method
2303        // rather than a more general "shield to address" path; only coinbase
2304        // outputs are eligible because they have no prior transparent transaction
2305        // graph that could be exposed to the shielded recipient.
2306        // The block-space cap and the caller-supplied `limit` (when present) both bound the number
2307        // of transparent inputs; `gather_shielding_inputs` applies the more restrictive of the two,
2308        // keeping the highest-value UTXOs first. When `limit` is `Some(0)` this empties the set, and
2309        // the subsequent `InsufficientFunds` check fires; this is the documented behavior.
2310        let transparent_inputs = gather_shielding_inputs::<DbT, FeeRuleT::Error>(
2311            wallet_db,
2312            source_addrs,
2313            target_height,
2314            // It doesn't matter here if we pass a 100 confirmations or 1 confirmations policy,
2315            // as coinbase txs require 100, which will be enforced by note selection.
2316            ConfirmationsPolicy::MIN,
2317            CoinbaseFilter::CoinbaseOnly,
2318            limit
2319                .unwrap_or(usize::MAX)
2320                .min(shielding_max_inputs(self.shielding_block_space_percent)),
2321            &self.locked_input_policy,
2322        )?;
2323
2324        let destination_pool = resolve_shielded_destination::<DbT, FeeRuleT::Error, ParamsT>(
2325            &to_address,
2326            params,
2327            target_height,
2328        )?;
2329
2330        let (sapling_output_count, orchard_action_count, ironwood_action_count) =
2331            match destination_pool {
2332                PoolType::SAPLING => {
2333                    let count = ::sapling::builder::BundleType::DEFAULT
2334                        .num_outputs(0, 1)
2335                        .expect("sapling DEFAULT bundle type permits any (spends, outputs) count");
2336                    (count, 0usize, 0usize)
2337                }
2338                // A pre-NU6.3 payment to an Orchard receiver; after Ironwood activation,
2339                // `resolve_shielded_destination` assigns such payments to the Ironwood pool.
2340                #[cfg(feature = "orchard")]
2341                PoolType::ORCHARD => {
2342                    let count = orchard_fees::transactional_action_count(
2343                        ::orchard::builder::BundleType::DEFAULT,
2344                        orchard_bundle_version_for_height(params, target_height),
2345                        0,
2346                        1,
2347                    )
2348                    .expect("every Orchard bundle version permits spending and output creation");
2349                    (0usize, count, 0usize)
2350                }
2351                // A post-NU6.3 payment to an Orchard receiver, delivered via the Ironwood
2352                // bundle and charged to its action count.
2353                #[cfg(feature = "orchard")]
2354                PoolType::IRONWOOD => {
2355                    let count = orchard_fees::transactional_action_count(
2356                        ::orchard::builder::BundleType::DEFAULT,
2357                        ironwood_bundle_version_for_height(params, target_height),
2358                        0,
2359                        1,
2360                    )
2361                    .expect("the Ironwood bundle version permits spending and output creation");
2362                    (0usize, 0usize, count)
2363                }
2364                // Unreachable: `resolve_shielded_destination` rejects transparent
2365                // destinations earlier with `ShieldingRequiresShieldedRecipient`.
2366                _ => {
2367                    return Err(InputSelectorError::Proposal(
2368                        ProposalError::ShieldingRequiresShieldedRecipient,
2369                    ));
2370                }
2371            };
2372
2373        let fee = fee_rule
2374            .fee_required(
2375                params,
2376                BlockHeight::from(target_height),
2377                transparent_inputs
2378                    .iter()
2379                    .map(transparent_fees::InputView::serialized_size),
2380                std::iter::empty::<usize>(),
2381                0,
2382                sapling_output_count,
2383                orchard_action_count,
2384                ironwood_action_count,
2385            )
2386            // The `InputSelectorError::Change` variant is the only existing
2387            // carrier capable of holding an arbitrary fee-rule error
2388            // (`ChangeError::StrategyError` wraps `FeeRuleT::Error` in the
2389            // generic position). We reuse it here rather than introduce a new
2390            // top-level variant.
2391            .map_err(|e| InputSelectorError::Change(ChangeError::StrategyError(e)))?;
2392
2393        // Route the full available value (input_total - fee) as an explicit
2394        // payment to the supplied destination. No change is produced.
2395        let input_total = transparent_inputs
2396            .iter()
2397            .map(|utxo| utxo.value())
2398            .try_fold(Zatoshis::ZERO, |acc, v| acc + v)
2399            .ok_or(InputSelectorError::Selection(
2400                GreedyInputSelectorError::Balance(BalanceError::Overflow),
2401            ))?;
2402        let payment_amount =
2403            (input_total - fee).ok_or_else(|| InputSelectorError::InsufficientFunds {
2404                available: input_total,
2405                required: fee,
2406            })?;
2407
2408        if payment_amount < shielding_threshold {
2409            return Err(InputSelectorError::InsufficientFunds {
2410                available: payment_amount,
2411                required: shielding_threshold,
2412            });
2413        }
2414
2415        let payment = Payment::new(to_address, Some(payment_amount), memo, None, None, vec![])
2416            .map_err(|payment_error| {
2417                InputSelectorError::Proposal(ProposalError::Zip321(payment_error.with_index(0)))
2418            })?;
2419        let request = TransactionRequest::new(vec![payment]).map_err(|payment_error| {
2420            InputSelectorError::Proposal(ProposalError::Zip321(payment_error))
2421        })?;
2422        let mut payment_pools = BTreeMap::new();
2423        payment_pools.insert(0usize, destination_pool);
2424        let final_balance = TransactionBalance::new(vec![], fee).map_err(|_| {
2425            InputSelectorError::Selection(GreedyInputSelectorError::Balance(BalanceError::Overflow))
2426        })?;
2427
2428        // `is_shielding` is `false` because the proposal layer reserves
2429        // `is_shielding = true` for the legacy "no payment, all value in change"
2430        // shape produced by `propose_shielding`. From the wallet's perspective
2431        // this is still a transparent -> shielded transfer of coinbase value.
2432        Proposal::single_step(
2433            request,
2434            payment_pools,
2435            transparent_inputs,
2436            None,
2437            anchor_height,
2438            final_balance,
2439            fee_rule.clone(),
2440            target_height,
2441            // Coinbase shielding spends no shielded notes, so the anchor the resulting step defers
2442            // to is resolved from this policy at interpretation; the exact confirmation depth does
2443            // not matter for an input-less step.
2444            ConfirmationsPolicy::default(),
2445            false,
2446            #[cfg(feature = "orchard")]
2447            ironwood_active_at(params, target_height),
2448        )
2449        .map_err(InputSelectorError::Proposal)
2450    }
2451}
2452
2453/// Gathers spendable transparent UTXOs from each source address, applying the
2454/// supplied [`CoinbaseFilter`] and rejecting input sets that would
2455/// link activity on an ephemeral address to other wallet activity.
2456///
2457/// Shared between `propose_shielding` and `propose_shielding_coinbase`.
2458#[cfg(feature = "transparent-inputs")]
2459#[allow(clippy::type_complexity)]
2460fn gather_shielding_inputs<DbT, ChangeErrT>(
2461    wallet_db: &DbT,
2462    source_addrs: &[TransparentAddress],
2463    target_height: TargetHeight,
2464    confirmations_policy: ConfirmationsPolicy,
2465    output_filter: CoinbaseFilter,
2466    max_inputs: usize,
2467    locked_input_policy: &LockedInputPolicy,
2468) -> Result<
2469    Vec<WalletTransparentOutput<()>>,
2470    InputSelectorError<
2471        <DbT as InputSource>::Error,
2472        GreedyInputSelectorError,
2473        ChangeErrT,
2474        Infallible,
2475    >,
2476>
2477where
2478    DbT: InputSource,
2479{
2480    // Gather the spendable UTXOs for every source address in a single query. This avoids issuing
2481    // one query per address (including for the many addresses that have no spendable outputs),
2482    // which is prohibitively expensive for wallets that hold large numbers of transparent
2483    // addresses.
2484    // Input selection honors the selector's configured `locked_input_policy` (see
2485    // `GreedyInputSelector::with_locked_input_policy`): by default (`Exclude`) a locked output is
2486    // never drawn upon, since it belongs to another in-flight proposal and spending it would
2487    // recreate the conflict that locking exists to prevent.
2488    let mut utxos = wallet_db
2489        .get_spendable_transparent_outputs_for_addresses(
2490            source_addrs,
2491            target_height,
2492            confirmations_policy,
2493            output_filter,
2494            LockFilter::Policy(locked_input_policy),
2495        )
2496        .map_err(InputSelectorError::DataSource)?;
2497
2498    // Cap the number of transparent inputs that a single shielding transaction may consume,
2499    // keeping the highest-value UTXOs first (stable tiebreaker by outpoint for determinism). UTXOs
2500    // beyond the cap are left unspent, to be consolidated by a subsequent shielding transaction.
2501    // When `max_inputs` is 0 this empties the set, and the caller's `InsufficientFunds` check
2502    // fires. The cap is applied before the linkability check below so that the check reflects the
2503    // outputs that will actually be spent.
2504    utxos.sort_by(|a, b| {
2505        b.value()
2506            .cmp(&a.value())
2507            .then_with(|| a.outpoint().cmp(b.outpoint()))
2508    });
2509    utxos.truncate(max_inputs);
2510
2511    // We use `recipient_key_scope()` and `recipient_address()` from the returned outputs to
2512    // determine the set of input addresses and which of them are ephemeral, rather than querying
2513    // the wallet again per address.
2514    let ephemeral_addrs = utxos
2515        .iter()
2516        .filter_map(|utxo| {
2517            (utxo.recipient_key_scope() == Some(TransparentKeyScope::EPHEMERAL))
2518                .then_some(utxo.recipient_address())
2519        })
2520        .collect::<BTreeSet<_>>();
2521    let input_addrs = utxos
2522        .iter()
2523        .map(|utxo| utxo.recipient_address())
2524        .collect::<BTreeSet<_>>();
2525
2526    // Funds may be spent from at most one ephemeral address at a time. If there are no
2527    // ephemeral addresses, we allow shielding from multiple transparent addresses.
2528    if !ephemeral_addrs.is_empty() && input_addrs.len() > 1 {
2529        return Err(InputSelectorError::Proposal(
2530            ProposalError::EphemeralAddressLinkability,
2531        ));
2532    }
2533
2534    Ok(utxos
2535        .into_iter()
2536        .map(|utxo| utxo.redact_account_data())
2537        .collect())
2538}
2539
2540/// Resolves a [`ZcashAddress`] destination for a shielding proposal to the
2541/// shielded pool it should be received in.
2542///
2543/// Rejects transparent and TEX addresses with
2544/// [`ProposalError::ShieldingRequiresShieldedRecipient`], and rejects Unified
2545/// Addresses without a shielded receiver with
2546/// [`GreedyInputSelectorError::UnsupportedAddress`].
2547#[cfg(feature = "transparent-inputs")]
2548#[allow(clippy::type_complexity)]
2549fn resolve_shielded_destination<DbT, ChangeErrT, ParamsT>(
2550    addr: &ZcashAddress,
2551    params: &ParamsT,
2552    target_height: TargetHeight,
2553) -> Result<
2554    PoolType,
2555    InputSelectorError<
2556        <DbT as InputSource>::Error,
2557        GreedyInputSelectorError,
2558        ChangeErrT,
2559        Infallible,
2560    >,
2561>
2562where
2563    DbT: InputSource,
2564    ParamsT: consensus::Parameters,
2565{
2566    #[cfg(not(feature = "orchard"))]
2567    let _ = target_height;
2568
2569    let resolved: Address = addr
2570        .clone()
2571        .convert_if_network(params.network_type())
2572        .map_err(InputSelectorError::Address)?;
2573    match resolved {
2574        Address::Sapling(_) => Ok(PoolType::SAPLING),
2575        // A payment to an Orchard-protocol receiver is an Ironwood-pool output once
2576        // Ironwood is active (delivered to the recipient's Orchard receiver via the
2577        // Ironwood bundle), and an Orchard-pool output otherwise.
2578        #[cfg(feature = "orchard")]
2579        Address::Unified(ua) if ua.has_orchard() => {
2580            Ok(if ironwood_active_at(params, target_height) {
2581                PoolType::IRONWOOD
2582            } else {
2583                PoolType::ORCHARD
2584            })
2585        }
2586        Address::Unified(ua) if ua.has_sapling() => Ok(PoolType::SAPLING),
2587        Address::Unified(ua) => Err(InputSelectorError::Selection(
2588            GreedyInputSelectorError::UnsupportedAddress(ua),
2589        )),
2590        Address::Transparent(_) | Address::Tex(_) => Err(InputSelectorError::Proposal(
2591            ProposalError::ShieldingRequiresShieldedRecipient,
2592        )),
2593    }
2594}
2595
2596/// Helper that performs the dust-input retry pattern used by `propose_shielding`.
2597///
2598/// On the first call to [`ChangeStrategy::compute_balance`], if the strategy
2599/// reports [`ChangeError::DustInputs`], those inputs are removed from
2600/// `transparent_inputs` and the balance is recomputed. The resulting proposal
2601/// directs all available value into change (the legacy `propose_shielding`
2602/// "all-change" shape).
2603#[cfg(feature = "transparent-inputs")]
2604#[allow(clippy::type_complexity)]
2605fn compute_shielding_balance_with_dust_retry<DbT, ChangeT, ParamsT>(
2606    change_strategy: &ChangeT,
2607    params: &ParamsT,
2608    target_height: TargetHeight,
2609    anchor_height: BlockHeight,
2610    zip318: &PoolMigrationParams,
2611    transparent_inputs: &mut Vec<WalletTransparentOutput<()>>,
2612    wallet_meta: &<ChangeT as ChangeStrategy>::AccountMetaT,
2613) -> Result<
2614    TransactionBalance,
2615    InputSelectorError<
2616        <DbT as InputSource>::Error,
2617        GreedyInputSelectorError,
2618        ChangeT::Error,
2619        Infallible,
2620    >,
2621>
2622where
2623    DbT: InputSource,
2624    ChangeT: ChangeStrategy<MetaSource = DbT>,
2625    ParamsT: consensus::Parameters,
2626{
2627    let trial = compute_shielding_balance::<DbT, ChangeT, ParamsT>(
2628        change_strategy,
2629        params,
2630        target_height,
2631        anchor_height,
2632        zip318,
2633        transparent_inputs,
2634        wallet_meta,
2635    );
2636
2637    match trial {
2638        Ok(balance) => Ok(balance),
2639        Err(ChangeError::DustInputs { transparent, .. }) => {
2640            let exclusions: BTreeSet<OutPoint> = transparent.into_iter().collect();
2641            transparent_inputs.retain(|i| !exclusions.contains(i.outpoint()));
2642
2643            compute_shielding_balance::<DbT, ChangeT, ParamsT>(
2644                change_strategy,
2645                params,
2646                target_height,
2647                anchor_height,
2648                zip318,
2649                transparent_inputs,
2650                wallet_meta,
2651            )
2652            .map_err(InputSelectorError::Change)
2653        }
2654        Err(other) => Err(InputSelectorError::Change(other)),
2655    }
2656}
2657
2658/// Helper for `propose_shielding`'s balance computation that calls
2659/// `change_strategy.compute_balance` with empty shielded bundle views, allowing
2660/// the change strategy to direct all available transparent input value into
2661/// change.
2662///
2663/// The empty Orchard-family views carry the bundle versions in effect at the
2664/// target height (rather than a fixed default), because the change the strategy
2665/// directs into a shielded pool is charged against that pool's bundle under its
2666/// version's action-count policy.
2667#[cfg(feature = "transparent-inputs")]
2668#[allow(clippy::type_complexity)]
2669fn compute_shielding_balance<DbT, ChangeT, ParamsT>(
2670    change_strategy: &ChangeT,
2671    params: &ParamsT,
2672    target_height: TargetHeight,
2673    anchor_height: BlockHeight,
2674    zip318: &PoolMigrationParams,
2675    transparent_inputs: &[WalletTransparentOutput<()>],
2676    wallet_meta: &<ChangeT as ChangeStrategy>::AccountMetaT,
2677) -> Result<TransactionBalance, ChangeError<ChangeT::Error, Infallible>>
2678where
2679    DbT: InputSource,
2680    ChangeT: ChangeStrategy<MetaSource = DbT>,
2681    ParamsT: consensus::Parameters,
2682{
2683    #[cfg(feature = "orchard")]
2684    let empty_orchard_view = (
2685        orchard_bundle_version_for_height(params, target_height),
2686        &[] as &[Infallible],
2687        &[] as &[Infallible],
2688    );
2689    #[cfg(feature = "orchard")]
2690    let empty_ironwood_view = (
2691        ironwood_bundle_version_for_height(params, target_height),
2692        &[] as &[Infallible],
2693        &[] as &[Infallible],
2694    );
2695
2696    change_strategy.compute_balance(
2697        params,
2698        target_height,
2699        anchor_height,
2700        zip318,
2701        transparent_inputs,
2702        &[] as &[TxOut<Zatoshis>],
2703        &sapling::EmptyBundleView,
2704        #[cfg(feature = "orchard")]
2705        &empty_orchard_view,
2706        #[cfg(feature = "orchard")]
2707        &empty_ironwood_view,
2708        None,
2709        wallet_meta,
2710    )
2711}
2712
2713#[cfg(all(test, feature = "transparent-inputs"))]
2714mod tests {
2715    use super::shielding_max_inputs;
2716
2717    #[test]
2718    fn shielding_max_inputs_from_block_space_percent() {
2719        // max_inputs = (MAX_BLOCK_BYTES * percent / 100) / P2PKH_STANDARD_INPUT_SIZE
2720        //            = (2_000_000 * percent / 100) / 150
2721        assert_eq!(shielding_max_inputs(0), 0);
2722        assert_eq!(shielding_max_inputs(1), 133); // 20_000 / 150
2723        assert_eq!(shielding_max_inputs(10), 1333); // 200_000 / 150
2724        assert_eq!(shielding_max_inputs(100), 13333); // 2_000_000 / 150
2725    }
2726}
2727
2728#[cfg(test)]
2729mod spend_policy_tests {
2730    use super::*;
2731    #[cfg(feature = "transparent-inputs")]
2732    use crate::data_api::CoinbaseFilter;
2733    use crate::wallet::LockOwner;
2734
2735    // The default spend policy preserves the historical `ShieldedOnly` behavior: notes may be
2736    // selected from every shielded pool present in the build, and no transparent UTXOs are
2737    // spent. Restricting the set is what a caller does to prevent pool crossing.
2738    #[test]
2739    fn default_permits_all_shielded_pools_and_no_transparent() {
2740        let policy = SpendPolicy::default();
2741        assert!(policy.permits_shielded(ShieldedPool::Sapling));
2742        #[cfg(feature = "orchard")]
2743        {
2744            assert!(policy.permits_shielded(ShieldedPool::Orchard));
2745            assert!(policy.permits_shielded(ShieldedPool::Ironwood));
2746        }
2747        #[cfg(feature = "transparent-inputs")]
2748        assert!(policy.transparent().is_none());
2749    }
2750
2751    // A caller can restrict selection to a single pool; other pools are then not permitted.
2752    #[test]
2753    fn shielded_pools_restricts_the_permitted_set() {
2754        let policy = SpendPolicy::shielded_pools([ShieldedPool::Orchard]);
2755        assert!(policy.permits_shielded(ShieldedPool::Orchard));
2756        assert!(!policy.permits_shielded(ShieldedPool::Sapling));
2757        assert!(!policy.permits_shielded(ShieldedPool::Ironwood));
2758    }
2759
2760    // The caller-facing coinbase choice maps onto the internal `CoinbaseFilter` query control.
2761    #[cfg(feature = "transparent-inputs")]
2762    #[test]
2763    fn coinbase_policy_maps_to_filter() {
2764        assert_eq!(
2765            CoinbaseFilter::from(CoinbasePolicy::OnlyCoinbase),
2766            CoinbaseFilter::CoinbaseOnly
2767        );
2768        assert_eq!(
2769            CoinbaseFilter::from(CoinbasePolicy::NonCoinbase),
2770            CoinbaseFilter::NonCoinbaseOnly
2771        );
2772    }
2773
2774    // A transparent spend policy spends non-coinbase UTXOs by default, and `with_coinbase`
2775    // overrides that choice while preserving the source.
2776    #[cfg(feature = "transparent-inputs")]
2777    #[test]
2778    fn transparent_policy_coinbase_defaults_and_override() {
2779        let policy = TransparentSpendPolicy::any_account_addr();
2780        assert_eq!(policy.coinbase(), CoinbasePolicy::NonCoinbase);
2781
2782        let policy = policy.with_coinbase(CoinbasePolicy::OnlyCoinbase);
2783        assert_eq!(policy.coinbase(), CoinbasePolicy::OnlyCoinbase);
2784        assert!(matches!(policy.source(), TransparentSource::AnyAccountAddr));
2785    }
2786
2787    // The default `SpendPolicy` excludes locked inputs, and `with_locked_input_policy` overrides
2788    // that choice.
2789    #[test]
2790    fn spend_policy_locked_input_policy_roundtrips() {
2791        let default = SpendPolicy::default();
2792        assert_eq!(default.locked_input_policy(), &LockedInputPolicy::Exclude);
2793        let owners = NonEmptyBTreeSet::singleton(LockOwner::new([9u8; 32]));
2794        let policy = SpendPolicy::default()
2795            .with_locked_input_policy(LockedInputPolicy::PreferLocked(owners.clone()));
2796        assert_eq!(
2797            policy.locked_input_policy(),
2798            &LockedInputPolicy::PreferLocked(owners)
2799        );
2800    }
2801}
2802
2803#[cfg(test)]
2804mod greedy_selection_tests {
2805    use ::sapling::zip32::ExtendedSpendingKey;
2806    use zcash_primitives::transaction::fees::zip317::FeeRule as Zip317FeeRule;
2807    use zcash_protocol::consensus::{Network, NetworkUpgrade, Parameters};
2808    use zip321::Payment;
2809
2810    use super::*;
2811    use crate::{
2812        data_api::{anchor_retention::AnchorRetentionInterval, testing::FixedNotes},
2813        fees::{DustOutputPolicy, zip317::SingleOutputChangeStrategy},
2814    };
2815
2816    /// The account the fixture serves.
2817    const ACCOUNT: u32 = 0;
2818    /// More selections than any of these tests makes before the selector stops; a run that
2819    /// reaches it is looping over the same selection.
2820    const SELECTION_LIMIT: usize = 4;
2821
2822    /// A payment that a Sapling note of `SAPLING_NOTE_VALUE` covers alone, with change under
2823    /// the ZIP 317 dust threshold.
2824    const PAYMENT_VALUE: Zatoshis = Zatoshis::const_from_u64(47_000);
2825    /// The value of a Sapling note that covers `PAYMENT_VALUE` alone.
2826    const SAPLING_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(60_000);
2827    const SAPLING_NOTE_ID: u32 = 0;
2828
2829    /// How a proposal failed.
2830    #[derive(Debug, PartialEq, Eq)]
2831    enum Failure {
2832        InsufficientFunds {
2833            available: Zatoshis,
2834            required: Zatoshis,
2835        },
2836        Selection(GreedyInputSelectorError),
2837    }
2838
2839    fn standard_strategy() -> SingleOutputChangeStrategy<Zip317FeeRule, FixedNotes> {
2840        SingleOutputChangeStrategy::new(
2841            Zip317FeeRule::standard(),
2842            None,
2843            ShieldedPool::Sapling,
2844            DustOutputPolicy::default(),
2845        )
2846    }
2847
2848    /// Proposes a payment of `payment` to a Sapling address from `wallet` with
2849    /// `change_strategy` under the default spend policy, returning the ids of the notes spent,
2850    /// or how the proposal failed.
2851    fn propose_payment<S>(
2852        wallet: &FixedNotes,
2853        payment: Zatoshis,
2854        change_strategy: &S,
2855    ) -> Result<Vec<u32>, Failure>
2856    where
2857        S: ChangeStrategy<MetaSource = FixedNotes>,
2858        S::Error: Debug,
2859    {
2860        propose_payment_under(wallet, payment, change_strategy, &SpendPolicy::default())
2861    }
2862
2863    /// Proposes a payment of `payment` to a Sapling address from `wallet` with
2864    /// `change_strategy` under `spend_policy`, returning the ids of the notes spent, or how
2865    /// the proposal failed.
2866    fn propose_payment_under<S>(
2867        wallet: &FixedNotes,
2868        payment: Zatoshis,
2869        change_strategy: &S,
2870        spend_policy: &SpendPolicy,
2871    ) -> Result<Vec<u32>, Failure>
2872    where
2873        S: ChangeStrategy<MetaSource = FixedNotes>,
2874        S::Error: Debug,
2875    {
2876        let params = Network::TestNetwork;
2877        let anchor_height = params
2878            .activation_height(NetworkUpgrade::Nu5)
2879            .expect("NU5 is active on testnet");
2880        let (_, recipient) = ExtendedSpendingKey::master(&[])
2881            .expect("the master key of the empty seed is valid")
2882            .default_address();
2883        let recipient = Address::from(recipient).to_zcash_address(&params);
2884        let request = TransactionRequest::new(vec![Payment::without_memo(recipient, payment)])
2885            .expect("a single payment is a valid request");
2886
2887        GreedyInputSelector::new()
2888            .propose_transaction(
2889                &params,
2890                wallet,
2891                TargetHeight::from(anchor_height + 1),
2892                anchor_height,
2893                &PoolMigrationParams::new(
2894                    zcash_protocol::zip318::BlockSpacing::UNIFORM,
2895                    AnchorRetentionInterval::ZIP_318,
2896                ),
2897                ConfirmationsPolicy::default(),
2898                ACCOUNT,
2899                request,
2900                change_strategy,
2901                spend_policy,
2902                None,
2903            )
2904            .map(|proposal| {
2905                proposal
2906                    .steps()
2907                    .iter()
2908                    .flat_map(|step| step.shielded_inputs())
2909                    .flat_map(|inputs| inputs.notes().iter().map(|n| *n.internal_note_id()))
2910                    .collect()
2911            })
2912            .map_err(|e| match e {
2913                InputSelectorError::InsufficientFunds {
2914                    available,
2915                    required,
2916                } => Failure::InsufficientFunds {
2917                    available,
2918                    required,
2919                },
2920                InputSelectorError::Selection(e) => Failure::Selection(e),
2921                other => panic!("unexpected input selection error: {other:?}"),
2922            })
2923    }
2924
2925    /// The scenario in which the change from the preferred pool's note alone would be dust, so
2926    /// a standard change strategy draws on a note in another pool as well.
2927    #[cfg(feature = "orchard")]
2928    mod across_pools {
2929        use super::*;
2930
2931        /// The value of the Orchard note, which does not cover the payment alone.
2932        const ORCHARD_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(20_000);
2933        const ORCHARD_NOTE_ID: u32 = 1;
2934
2935        /// The Orchard note is listed first, so a selection that reaches the Sapling note
2936        /// holds both, as a source that orders notes by value returns them.
2937        fn two_pool_notes() -> FixedNotes {
2938            FixedNotes::new(&[
2939                (ShieldedPool::Orchard, ORCHARD_NOTE_ID, ORCHARD_NOTE_VALUE),
2940                (ShieldedPool::Sapling, SAPLING_NOTE_ID, SAPLING_NOTE_VALUE),
2941            ])
2942            .with_selection_limit(SELECTION_LIMIT)
2943        }
2944
2945        #[test]
2946        fn a_standard_strategy_spends_both_notes_at_a_dust_shortfall() {
2947            assert_eq!(
2948                propose_payment(&two_pool_notes(), PAYMENT_VALUE, &standard_strategy()),
2949                Ok(vec![SAPLING_NOTE_ID, ORCHARD_NOTE_ID])
2950            );
2951        }
2952
2953        #[test]
2954        fn a_source_returning_a_pool_not_asked_for_is_a_contract_violation() {
2955            // Only Sapling may be spent, yet every selection returns the Orchard note too.
2956            let wallet = two_pool_notes().ignoring_sources();
2957            let spend_policy = SpendPolicy::shielded_pools([ShieldedPool::Sapling]);
2958
2959            assert_eq!(
2960                propose_payment_under(&wallet, PAYMENT_VALUE, &standard_strategy(), &spend_policy),
2961                Err(Failure::Selection(
2962                    GreedyInputSelectorError::UnrequestedPoolSelected
2963                ))
2964            );
2965        }
2966    }
2967
2968    /// The scenario in which the change strategy names a selected Sapling note as dust.
2969    mod dust_exclusion {
2970        // The fixture is pre-Revision-2 (no NU7 activation), where the fee is the 5000-zatoshi constant.
2971        #![allow(deprecated)]
2972
2973        use zcash_primitives::transaction::fees::zip317::MARGINAL_FEE;
2974        use zcash_protocol::value::COIN;
2975
2976        use super::*;
2977
2978        /// A note of exactly the marginal fee, which the ZIP 317 change strategy reports as
2979        /// uneconomic once the transaction has more spends than outputs, counting the change
2980        /// output.
2981        const DUST_NOTE_VALUE: Zatoshis = MARGINAL_FEE;
2982        /// The value of each of the two notes that fund the payment. One of them, even with
2983        /// the dust note, falls short of a payment of this value plus its fee; both together
2984        /// cover it.
2985        const FUNDING_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(COIN);
2986        const DUST_NOTE_ID: u32 = 0;
2987        const FIRST_FUNDING_NOTE_ID: u32 = 1;
2988        const SECOND_FUNDING_NOTE_ID: u32 = 2;
2989
2990        /// The ZIP 317 fee of a transaction with two logical actions.
2991        fn two_action_fee() -> Zatoshis {
2992            (MARGINAL_FEE + MARGINAL_FEE).expect("no overflow")
2993        }
2994
2995        /// A dust note followed by the two funding notes, in selection order.
2996        fn dust_then_funding_notes() -> FixedNotes {
2997            FixedNotes::new(&[
2998                (ShieldedPool::Sapling, DUST_NOTE_ID, DUST_NOTE_VALUE),
2999                (
3000                    ShieldedPool::Sapling,
3001                    FIRST_FUNDING_NOTE_ID,
3002                    FUNDING_NOTE_VALUE,
3003                ),
3004                (
3005                    ShieldedPool::Sapling,
3006                    SECOND_FUNDING_NOTE_ID,
3007                    FUNDING_NOTE_VALUE,
3008                ),
3009            ])
3010            .with_selection_limit(SELECTION_LIMIT)
3011        }
3012
3013        #[test]
3014        fn excluding_a_dust_note_retries_the_remaining_selection() {
3015            assert_eq!(
3016                propose_payment(
3017                    &dust_then_funding_notes(),
3018                    FUNDING_NOTE_VALUE,
3019                    &standard_strategy()
3020                ),
3021                Ok(vec![FIRST_FUNDING_NOTE_ID, SECOND_FUNDING_NOTE_ID])
3022            );
3023        }
3024
3025        #[test]
3026        fn excluding_a_dust_note_still_reports_a_real_shortfall() {
3027            let funding_value = (FUNDING_NOTE_VALUE + FUNDING_NOTE_VALUE).expect("no overflow");
3028            // Two spends and one output cost the ZIP 317 minimum of two logical actions, so
3029            // the funding notes fall one marginal fee short of the payment and its fee.
3030            // Spending the dust note as well adds one marginal fee of value and one of fee,
3031            // so nothing covers the payment.
3032            let payment = (funding_value - MARGINAL_FEE).expect("no underflow");
3033
3034            assert_eq!(
3035                propose_payment(&dust_then_funding_notes(), payment, &standard_strategy()),
3036                Err(Failure::InsufficientFunds {
3037                    available: funding_value,
3038                    required: (payment + two_action_fee()).expect("no overflow"),
3039                })
3040            );
3041        }
3042
3043        #[test]
3044        fn a_source_returning_an_excluded_note_is_a_contract_violation() {
3045            // Every selection returns all three notes, so the dust note comes back after
3046            // being excluded.
3047            let wallet = dust_then_funding_notes().ignoring_exclude();
3048
3049            assert_eq!(
3050                propose_payment(&wallet, FUNDING_NOTE_VALUE, &standard_strategy()),
3051                Err(Failure::Selection(
3052                    GreedyInputSelectorError::ExcludedNoteSelected
3053                ))
3054            );
3055        }
3056    }
3057
3058    /// Change strategies that break the contract of `ChangeStrategy::compute_balance`.
3059    mod contract_violations {
3060        use transparent::bundle::OutPoint;
3061        use zcash_primitives::transaction::fees::{
3062            transparent as transparent_fees,
3063            zip317::{FeeError as Zip317FeeError, FeeRule as Zip317FeeRule},
3064        };
3065
3066        use super::*;
3067        #[cfg(feature = "orchard")]
3068        use crate::fees::orchard::InputView as _;
3069        use crate::fees::{MetaSource, sapling::InputView as _};
3070
3071        /// A single Sapling note that covers the payment.
3072        fn single_sapling_note() -> FixedNotes {
3073            FixedNotes::new(&[(ShieldedPool::Sapling, SAPLING_NOTE_ID, SAPLING_NOTE_VALUE)])
3074                .with_selection_limit(SELECTION_LIMIT)
3075        }
3076
3077        /// The total value of the shielded inputs a change strategy was given.
3078        fn given_value<NoteRefT>(
3079            sapling: &impl sapling::BundleView<NoteRefT>,
3080            #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
3081            #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
3082        ) -> Zatoshis {
3083            let given = sapling.inputs().iter().map(|input| input.value());
3084            #[cfg(feature = "orchard")]
3085            let given = given
3086                .chain(orchard.inputs().iter().map(|input| input.value()))
3087                .chain(ironwood.inputs().iter().map(|input| input.value()));
3088            given.sum::<Option<Zatoshis>>().expect("no overflow")
3089        }
3090
3091        /// A change strategy that reports the payment as its requirement whatever it is
3092        /// given, as one that forgot the fee would: once the inputs cover the payment, the
3093        /// requirement no longer exceeds them.
3094        struct FeeBlindStrategy {
3095            fee_rule: Zip317FeeRule,
3096        }
3097
3098        impl ChangeStrategy for FeeBlindStrategy {
3099            type FeeRule = Zip317FeeRule;
3100            type Error = Zip317FeeError;
3101            type MetaSource = FixedNotes;
3102            type AccountMetaT = ();
3103
3104            fn fee_rule(&self) -> &Self::FeeRule {
3105                &self.fee_rule
3106            }
3107
3108            fn fetch_wallet_meta<P: consensus::Parameters>(
3109                &self,
3110                _params: &P,
3111                _meta_source: &Self::MetaSource,
3112                _account: <Self::MetaSource as MetaSource>::AccountId,
3113                _target_height: TargetHeight,
3114                _exclude: &[<Self::MetaSource as MetaSource>::NoteRef],
3115            ) -> Result<Self::AccountMetaT, <Self::MetaSource as MetaSource>::Error> {
3116                Ok(())
3117            }
3118
3119            fn compute_balance<P: consensus::Parameters, NoteRefT: Clone>(
3120                &self,
3121                _params: &P,
3122                _target_height: TargetHeight,
3123                _anchor_height: BlockHeight,
3124                _zip318: &PoolMigrationParams,
3125                _transparent_inputs: &[impl transparent_fees::InputView],
3126                _transparent_outputs: &[impl transparent_fees::OutputView],
3127                sapling: &impl sapling::BundleView<NoteRefT>,
3128                #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
3129                #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
3130                _ephemeral_balance: Option<EphemeralBalance>,
3131                _wallet_meta: &Self::AccountMetaT,
3132            ) -> Result<TransactionBalance, ChangeError<Self::Error, NoteRefT>> {
3133                Err(ChangeError::InsufficientFunds {
3134                    available: given_value(
3135                        sapling,
3136                        #[cfg(feature = "orchard")]
3137                        orchard,
3138                        #[cfg(feature = "orchard")]
3139                        ironwood,
3140                    ),
3141                    required: PAYMENT_VALUE,
3142                })
3143            }
3144        }
3145
3146        /// A change strategy that reports the payment as its requirement when given nothing,
3147        /// and a `DustInputs` error otherwise: naming every Sapling input it was given when
3148        /// `names_given`, plus the transparent outpoints in `transparent`, which it is never
3149        /// given.
3150        struct DustNamingStrategy {
3151            fee_rule: Zip317FeeRule,
3152            names_given: bool,
3153            transparent: Vec<OutPoint>,
3154        }
3155
3156        impl ChangeStrategy for DustNamingStrategy {
3157            type FeeRule = Zip317FeeRule;
3158            type Error = Zip317FeeError;
3159            type MetaSource = FixedNotes;
3160            type AccountMetaT = ();
3161
3162            fn fee_rule(&self) -> &Self::FeeRule {
3163                &self.fee_rule
3164            }
3165
3166            fn fetch_wallet_meta<P: consensus::Parameters>(
3167                &self,
3168                _params: &P,
3169                _meta_source: &Self::MetaSource,
3170                _account: <Self::MetaSource as MetaSource>::AccountId,
3171                _target_height: TargetHeight,
3172                _exclude: &[<Self::MetaSource as MetaSource>::NoteRef],
3173            ) -> Result<Self::AccountMetaT, <Self::MetaSource as MetaSource>::Error> {
3174                Ok(())
3175            }
3176
3177            fn compute_balance<P: consensus::Parameters, NoteRefT: Clone>(
3178                &self,
3179                _params: &P,
3180                _target_height: TargetHeight,
3181                _anchor_height: BlockHeight,
3182                _zip318: &PoolMigrationParams,
3183                _transparent_inputs: &[impl transparent_fees::InputView],
3184                _transparent_outputs: &[impl transparent_fees::OutputView],
3185                sapling: &impl sapling::BundleView<NoteRefT>,
3186                #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
3187                #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
3188                _ephemeral_balance: Option<EphemeralBalance>,
3189                _wallet_meta: &Self::AccountMetaT,
3190            ) -> Result<TransactionBalance, ChangeError<Self::Error, NoteRefT>> {
3191                let given = given_value(
3192                    sapling,
3193                    #[cfg(feature = "orchard")]
3194                    orchard,
3195                    #[cfg(feature = "orchard")]
3196                    ironwood,
3197                );
3198                if given == Zatoshis::ZERO {
3199                    Err(ChangeError::InsufficientFunds {
3200                        available: given,
3201                        required: PAYMENT_VALUE,
3202                    })
3203                } else {
3204                    let sapling = if self.names_given {
3205                        sapling
3206                            .inputs()
3207                            .iter()
3208                            .map(|input| input.note_id().clone())
3209                            .collect()
3210                    } else {
3211                        vec![]
3212                    };
3213                    Err(ChangeError::DustInputs {
3214                        transparent: self.transparent.clone(),
3215                        sapling,
3216                        #[cfg(feature = "orchard")]
3217                        orchard: vec![],
3218                        #[cfg(feature = "orchard")]
3219                        ironwood: vec![],
3220                    })
3221                }
3222            }
3223        }
3224
3225        #[test]
3226        fn a_requirement_the_inputs_cover_is_a_contract_violation() {
3227            let change_strategy = FeeBlindStrategy {
3228                fee_rule: Zip317FeeRule::standard(),
3229            };
3230
3231            assert_eq!(
3232                propose_payment(&single_sapling_note(), PAYMENT_VALUE, &change_strategy),
3233                Err(Failure::Selection(
3234                    GreedyInputSelectorError::RequirementCovered {
3235                        required: PAYMENT_VALUE,
3236                        available: SAPLING_NOTE_VALUE,
3237                    }
3238                ))
3239            );
3240        }
3241
3242        #[test]
3243        fn dust_inputs_naming_nothing_is_a_contract_violation() {
3244            let change_strategy = DustNamingStrategy {
3245                fee_rule: Zip317FeeRule::standard(),
3246                names_given: false,
3247                transparent: vec![],
3248            };
3249
3250            assert_eq!(
3251                propose_payment(&single_sapling_note(), PAYMENT_VALUE, &change_strategy),
3252                Err(Failure::Selection(
3253                    GreedyInputSelectorError::DustInputsNotGiven
3254                ))
3255            );
3256        }
3257
3258        #[cfg(feature = "transparent-inputs")]
3259        #[test]
3260        fn dust_inputs_naming_an_input_not_given_is_a_contract_violation() {
3261            let change_strategy = DustNamingStrategy {
3262                fee_rule: Zip317FeeRule::standard(),
3263                names_given: true,
3264                transparent: vec![OutPoint::new([0; 32], 0)],
3265            };
3266
3267            assert_eq!(
3268                propose_payment(&single_sapling_note(), PAYMENT_VALUE, &change_strategy),
3269                Err(Failure::Selection(
3270                    GreedyInputSelectorError::DustInputsNotGiven
3271                ))
3272            );
3273        }
3274    }
3275}