1#[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#[derive(Debug)]
61#[non_exhaustive]
62pub enum InputSelectorError<DbErrT, SelectorErrT, ChangeErrT, N> {
63 DataSource(DbErrT),
65 Selection(SelectorErrT),
67 Change(ChangeError<ChangeErrT, N>),
69 Proposal(ProposalError),
71 Address(ConversionError<&'static str>),
73 InsufficientFunds {
76 available: Zatoshis,
77 required: Zatoshis,
78 },
79 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
168pub trait InputSelector {
174 type Error;
176
177 type InputSource: InputSource;
183
184 #[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#[cfg(feature = "transparent-inputs")]
240pub trait ShieldingSelector {
241 type Error;
243 type InputSource: InputSource;
249
250 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
356#[non_exhaustive]
357pub enum GreedyInputSelectorError {
358 Balance(BalanceError),
360 UnsupportedAddress(Box<UnifiedAddress>),
362 UnsupportedTexAddress,
364 RequirementCovered {
367 required: Zatoshis,
369 available: Zatoshis,
371 },
372 DustInputsNotGiven,
375 ExcludedNoteSelected,
379 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 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#[cfg(feature = "transparent-inputs")]
486const DEFAULT_SHIELDING_BLOCK_SPACE_PERCENT: u32 = 10;
487
488#[derive(Clone, Debug, PartialEq, Eq)]
493pub struct NonEmptyBTreeSet<T>(BTreeSet<T>);
494
495impl<T: Ord> NonEmptyBTreeSet<T> {
496 pub fn singleton(value: T) -> Self {
498 Self(BTreeSet::from_iter([value]))
499 }
500
501 pub fn from_nonempty(values: NonEmpty<T>) -> Self {
504 Self(values.into_iter().collect())
505 }
506
507 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 pub fn as_set(&self) -> &BTreeSet<T> {
516 &self.0
517 }
518
519 pub fn iter(&self) -> std::collections::btree_set::Iter<'_, T> {
521 self.0.iter()
522 }
523}
524
525#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
550pub enum NoteSelection {
551 #[default]
553 Accumulate,
554 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 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 pub fn permits_shielded(&self, pool: ShieldedPool) -> bool {
590 self.shielded.contains(&pool)
591 }
592
593 pub fn shielded(&self) -> &BTreeSet<ShieldedPool> {
595 &self.shielded
596 }
597
598 #[cfg(feature = "transparent-inputs")]
600 pub fn with_transparent(mut self, transparent: TransparentSpendPolicy) -> Self {
601 self.transparent = Some(transparent);
602 self
603 }
604
605 #[cfg(feature = "transparent-inputs")]
607 pub fn transparent(&self) -> Option<&TransparentSpendPolicy> {
608 self.transparent.as_ref()
609 }
610
611 pub fn with_locked_input_policy(mut self, policy: LockedInputPolicy) -> Self {
613 self.locked_input_policy = policy;
614 self
615 }
616
617 pub fn locked_input_policy(&self) -> &LockedInputPolicy {
619 &self.locked_input_policy
620 }
621
622 pub fn with_note_selection(mut self, note_selection: NoteSelection) -> Self {
625 self.note_selection = note_selection;
626 self
627 }
628
629 pub fn note_selection(&self) -> NoteSelection {
631 self.note_selection
632 }
633}
634
635#[derive(Clone, Copy, Debug, PartialEq, Eq)]
641pub enum CoinbasePolicy {
642 OnlyCoinbase,
644 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#[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 pub fn any_account_addr() -> Self {
679 Self {
680 source: TransparentSource::AnyAccountAddr,
681 coinbase: CoinbasePolicy::NonCoinbase,
682 }
683 }
684
685 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 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 pub fn with_coinbase(mut self, coinbase: CoinbasePolicy) -> Self {
704 self.coinbase = coinbase;
705 self
706 }
707
708 pub fn source(&self) -> &TransparentSource {
710 &self.source
711 }
712
713 pub fn coinbase(&self) -> CoinbasePolicy {
715 self.coinbase
716 }
717
718 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#[cfg(feature = "transparent-inputs")]
730#[derive(Clone, Debug)]
731pub enum TransparentSource {
732 AnyAccountAddr,
735 FromAddresses(NonEmptyBTreeSet<TransparentAddress>),
737}
738
739pub struct GreedyInputSelector<DbT> {
745 #[cfg(feature = "transparent-inputs")]
750 shielding_block_space_percent: u32,
751 #[cfg(feature = "transparent-inputs")]
759 locked_input_policy: LockedInputPolicy,
760 _ds_type: PhantomData<DbT>,
761}
762
763impl<DbT> GreedyInputSelector<DbT> {
764 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 #[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 #[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 address_allow_list: Option<&[TransparentAddress]>,
824 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 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#[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 #[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 #[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 #[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 let pool = if ironwood_active_at(params, target_height) {
1026 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 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 #[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 #[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 pool_preference.retain(|pool| spend_policy.permits_shielded(*pool));
1133
1134 loop {
1144 #[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 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 #[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 #[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 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 Err(ChangeError::InsufficientFunds { required, .. }) => {
1311 return Err(InputSelectorError::Selection(
1312 GreedyInputSelectorError::RequirementCovered {
1313 required,
1314 available: Zatoshis::ZERO,
1315 },
1316 ));
1317 }
1318 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, };
1327
1328 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 #[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 #[cfg(not(feature = "transparent-inputs"))]
1390 let transparent_inputs_changed = false;
1391 #[cfg(feature = "transparent-inputs")]
1392 let mut transparent_inputs_changed = false;
1393 let mut shielded_dust_excluded = false;
1397
1398 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 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 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 if transparent_inputs.len() != len_before {
1500 transparent_inputs_changed = true;
1501 }
1502 }
1503 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 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 #[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 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 .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 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 check_selection(&shielded_inputs, &pool_preference, &exclude)?;
1615
1616 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
1633fn 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
1647fn 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#[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#[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 .unwrap_or(::orchard::bundle::BundleVersion::orchard_insecure_v1())
1738}
1739
1740#[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 .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 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 #[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 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 #[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 ::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 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 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 #[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 let total_fee_required = (tr0_fee + tr1_fee.unwrap_or(Zatoshis::ZERO)).ok_or(
2000 InputSelectorError::Selection(GreedyInputSelectorError::Balance(BalanceError::Overflow)),
2001 )?;
2002
2003 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 #[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 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 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 let transparent_inputs = gather_shielding_inputs::<DbT, FeeRuleT::Error>(
2311 wallet_db,
2312 source_addrs,
2313 target_height,
2314 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 #[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 #[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 _ => {
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 .map_err(|e| InputSelectorError::Change(ChangeError::StrategyError(e)))?;
2392
2393 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 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 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#[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 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 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 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 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#[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 #[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#[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#[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 assert_eq!(shielding_max_inputs(0), 0);
2722 assert_eq!(shielding_max_inputs(1), 133); assert_eq!(shielding_max_inputs(10), 1333); assert_eq!(shielding_max_inputs(100), 13333); }
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 #[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 #[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 #[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 #[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 #[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 const ACCOUNT: u32 = 0;
2818 const SELECTION_LIMIT: usize = 4;
2821
2822 const PAYMENT_VALUE: Zatoshis = Zatoshis::const_from_u64(47_000);
2825 const SAPLING_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(60_000);
2827 const SAPLING_NOTE_ID: u32 = 0;
2828
2829 #[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 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 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(¶ms);
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 ¶ms,
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 #[cfg(feature = "orchard")]
2928 mod across_pools {
2929 use super::*;
2930
2931 const ORCHARD_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(20_000);
2933 const ORCHARD_NOTE_ID: u32 = 1;
2934
2935 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 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 mod dust_exclusion {
2970 #![allow(deprecated)]
2972
2973 use zcash_primitives::transaction::fees::zip317::MARGINAL_FEE;
2974 use zcash_protocol::value::COIN;
2975
2976 use super::*;
2977
2978 const DUST_NOTE_VALUE: Zatoshis = MARGINAL_FEE;
2982 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 fn two_action_fee() -> Zatoshis {
2992 (MARGINAL_FEE + MARGINAL_FEE).expect("no overflow")
2993 }
2994
2995 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 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 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 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 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 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 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 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}