1use core::cmp::{Ordering, max, min};
2use std::num::{NonZeroU64, NonZeroUsize};
3
4#[cfg(feature = "orchard")]
5use zcash_primitives::transaction::builder::BundlePadding;
6use zcash_primitives::transaction::fees::{
7 FeeRule, transparent,
8 zip317::{P2PKH_STANDARD_OUTPUT_SIZE, minimum_fee},
9};
10#[cfg(feature = "orchard")]
11use zcash_protocol::zip318::PoolMigrationConstants;
12
13use crate::data_api::anchor_retention::PoolMigrationParams;
14use zcash_protocol::{
15 PoolType, ShieldedPool,
16 consensus::{self, BlockHeight, NetworkUpgrade},
17 memo::MemoBytes,
18 value::{BalanceError, Zatoshis},
19};
20
21use crate::data_api::{AccountMeta, ChangeReceivers, wallet::TargetHeight};
22
23use super::{
24 ChangeError, ChangeValue, DummyOutputCounts, DustAction, DustOutputPolicy, EphemeralBalance,
25 SplitPolicy, TransactionBalance, sapling as sapling_fees,
26};
27
28#[cfg(feature = "orchard")]
29use super::orchard::{self as orchard_fees, OutputView as _};
30#[cfg(feature = "transparent-inputs")]
31use {super::TransparentChangePolicy, crate::data_api::TransparentChangeKind};
32
33pub(crate) const DUST_TO_FEE_CAP_MINIMUM_FEES: u64 = 10;
37
38pub(crate) struct NetFlows {
39 t_in: Zatoshis,
40 t_out: Zatoshis,
41 sapling_in: Zatoshis,
42 sapling_out: Zatoshis,
43 orchard_in: Zatoshis,
44 orchard_out: Zatoshis,
45 ironwood_in: Zatoshis,
51 ironwood_out: Zatoshis,
52}
53
54impl NetFlows {
55 fn total_in(&self) -> Result<Zatoshis, BalanceError> {
56 (self.t_in + self.sapling_in + self.orchard_in + self.ironwood_in)
57 .ok_or(BalanceError::Overflow)
58 }
59 fn total_out(&self) -> Result<Zatoshis, BalanceError> {
60 (self.t_out + self.sapling_out + self.orchard_out + self.ironwood_out)
61 .ok_or(BalanceError::Overflow)
62 }
63 fn is_transparent(&self) -> bool {
65 !(self.sapling_in.is_positive()
66 || self.sapling_out.is_positive()
67 || self.orchard_in.is_positive()
68 || self.orchard_out.is_positive()
69 || self.ironwood_in.is_positive()
70 || self.ironwood_out.is_positive())
71 }
72}
73
74#[allow(clippy::too_many_arguments)]
75pub(crate) fn calculate_net_flows<NoteRefT: Clone, F: FeeRule, E>(
76 transparent_inputs: &[impl transparent::InputView],
77 transparent_outputs: &[impl transparent::OutputView],
78 sapling: &impl sapling_fees::BundleView<NoteRefT>,
79 #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
80 #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
81 ephemeral_balance: Option<EphemeralBalance>,
82) -> Result<NetFlows, ChangeError<E, NoteRefT>>
83where
84 E: From<F::Error> + From<BalanceError>,
85{
86 let overflow = || ChangeError::StrategyError(E::from(BalanceError::Overflow));
87
88 let t_in = transparent_inputs
89 .iter()
90 .map(|t_in| t_in.coin().value())
91 .chain(ephemeral_balance.and_then(|b| b.ephemeral_input_amount()))
92 .sum::<Option<_>>()
93 .ok_or_else(overflow)?;
94 let t_out = transparent_outputs
95 .iter()
96 .map(|t_out| t_out.value())
97 .chain(ephemeral_balance.and_then(|b| b.ephemeral_output_amount()))
98 .sum::<Option<_>>()
99 .ok_or_else(overflow)?;
100 let sapling_in = sapling
101 .inputs()
102 .iter()
103 .map(sapling_fees::InputView::<NoteRefT>::value)
104 .sum::<Option<_>>()
105 .ok_or_else(overflow)?;
106 let sapling_out = sapling
107 .outputs()
108 .iter()
109 .map(sapling_fees::OutputView::value)
110 .sum::<Option<_>>()
111 .ok_or_else(overflow)?;
112
113 #[cfg(feature = "orchard")]
114 let orchard_in = orchard
115 .inputs()
116 .iter()
117 .map(orchard_fees::InputView::<NoteRefT>::value)
118 .sum::<Option<_>>()
119 .ok_or_else(overflow)?;
120 #[cfg(not(feature = "orchard"))]
121 let orchard_in = Zatoshis::ZERO;
122
123 #[cfg(feature = "orchard")]
124 let orchard_out = orchard
125 .outputs()
126 .iter()
127 .map(orchard_fees::OutputView::value)
128 .sum::<Option<_>>()
129 .ok_or_else(overflow)?;
130 #[cfg(not(feature = "orchard"))]
131 let orchard_out = Zatoshis::ZERO;
132
133 #[cfg(feature = "orchard")]
134 let ironwood_in = ironwood
135 .inputs()
136 .iter()
137 .map(orchard_fees::InputView::<NoteRefT>::value)
138 .sum::<Option<_>>()
139 .ok_or_else(overflow)?;
140 #[cfg(not(feature = "orchard"))]
141 let ironwood_in = Zatoshis::ZERO;
142
143 #[cfg(feature = "orchard")]
144 let ironwood_out = ironwood
145 .outputs()
146 .iter()
147 .map(orchard_fees::OutputView::value)
148 .sum::<Option<_>>()
149 .ok_or_else(overflow)?;
150 #[cfg(not(feature = "orchard"))]
151 let ironwood_out = Zatoshis::ZERO;
152
153 Ok(NetFlows {
154 t_in,
155 t_out,
156 sapling_in,
157 sapling_out,
158 orchard_in,
159 orchard_out,
160 ironwood_in,
161 ironwood_out,
162 })
163}
164
165pub(crate) fn select_change_pool(
180 _net_flows: &NetFlows,
181 _fallback_change_pool: ShieldedPool,
182 _change_receivers: &ChangeReceivers,
183 _ironwood_active: bool,
184 _max_change_value: Zatoshis,
185) -> ShieldedPool {
186 #[cfg(feature = "orchard")]
188 {
189 let flow_pools = [
193 (
194 ShieldedPool::Orchard,
195 _net_flows.orchard_in.is_positive() || _net_flows.orchard_out.is_positive(),
196 ),
197 (
198 ShieldedPool::Ironwood,
199 _net_flows.ironwood_in.is_positive() || _net_flows.ironwood_out.is_positive(),
200 ),
201 (
202 ShieldedPool::Sapling,
203 _net_flows.sapling_in.is_positive() || _net_flows.sapling_out.is_positive(),
204 ),
205 ]
206 .into_iter()
207 .filter_map(|(pool, has_flows)| has_flows.then_some(pool));
208
209 let flow_preferred = flow_pools.clone().next().unwrap_or(_fallback_change_pool);
212
213 let preferred = flow_pools
214 .chain([
215 _fallback_change_pool,
216 ShieldedPool::Orchard,
217 ShieldedPool::Sapling,
218 ])
219 .find(|pool| _change_receivers.can_receive(PoolType::Shielded(*pool)))
220 .unwrap_or(flow_preferred);
221
222 if _ironwood_active
229 && preferred == ShieldedPool::Orchard
230 && (!_net_flows.orchard_in.is_positive() || _max_change_value >= _net_flows.orchard_in)
231 {
232 ShieldedPool::Ironwood
233 } else {
234 preferred
235 }
236 }
237 #[cfg(not(feature = "orchard"))]
238 ShieldedPool::Sapling
239}
240
241#[derive(Clone, Copy, Debug)]
242pub(crate) struct OutputManifest {
243 transparent: usize,
244 sapling: usize,
245 orchard: usize,
246 ironwood: usize,
247}
248
249impl OutputManifest {
250 const ZERO: OutputManifest = OutputManifest {
251 transparent: 0,
252 sapling: 0,
253 orchard: 0,
254 ironwood: 0,
255 };
256
257 pub(crate) fn sapling(&self) -> usize {
258 self.sapling
259 }
260
261 pub(crate) fn orchard(&self) -> usize {
262 self.orchard
263 }
264
265 pub(crate) fn ironwood(&self) -> usize {
266 self.ironwood
267 }
268
269 #[cfg(feature = "orchard")]
270 pub(crate) fn transparent(&self) -> usize {
271 self.transparent
272 }
273
274 pub(crate) fn total_shielded(&self) -> usize {
275 self.sapling + self.orchard + self.ironwood
276 }
277
278 fn for_pool(pool: ShieldedPool, count: usize) -> Self {
280 Self {
281 transparent: 0,
282 sapling: if pool == ShieldedPool::Sapling {
283 count
284 } else {
285 0
286 },
287 orchard: if pool == ShieldedPool::Orchard {
288 count
289 } else {
290 0
291 },
292 ironwood: if pool == ShieldedPool::Ironwood {
293 count
294 } else {
295 0
296 },
297 }
298 }
299}
300
301pub(crate) struct SinglePoolBalanceConfig<'a, P, F> {
302 params: &'a P,
303 fee_rule: &'a F,
304 dust_output_policy: &'a DustOutputPolicy,
305 default_dust_threshold: Zatoshis,
306 split_policy: &'a SplitPolicy,
307 fallback_change_pool: ShieldedPool,
308 #[cfg(feature = "transparent-inputs")]
309 transparent_change_policy: TransparentChangePolicy,
310 marginal_fee: Zatoshis,
311 grace_actions: usize,
312}
313
314impl<'a, P, F> SinglePoolBalanceConfig<'a, P, F> {
315 #[allow(clippy::too_many_arguments)]
316 pub(crate) fn new(
317 params: &'a P,
318 fee_rule: &'a F,
319 dust_output_policy: &'a DustOutputPolicy,
320 default_dust_threshold: Zatoshis,
321 split_policy: &'a SplitPolicy,
322 fallback_change_pool: ShieldedPool,
323 #[cfg(feature = "transparent-inputs")] transparent_change_policy: TransparentChangePolicy,
324 marginal_fee: Zatoshis,
325 grace_actions: usize,
326 ) -> Self {
327 Self {
328 params,
329 fee_rule,
330 dust_output_policy,
331 default_dust_threshold,
332 split_policy,
333 fallback_change_pool,
334 #[cfg(feature = "transparent-inputs")]
335 transparent_change_policy,
336 marginal_fee,
337 grace_actions,
338 }
339 }
340}
341
342#[allow(clippy::too_many_arguments)]
343pub(crate) fn single_pool_output_balance<P: consensus::Parameters, NoteRefT: Clone, F: FeeRule, E>(
344 cfg: SinglePoolBalanceConfig<P, F>,
345 wallet_meta: Option<&AccountMeta>,
346 change_receivers: &ChangeReceivers,
347 target_height: TargetHeight,
348 transparent_inputs: &[impl transparent::InputView],
349 transparent_outputs: &[impl transparent::OutputView],
350 sapling: &impl sapling_fees::BundleView<NoteRefT>,
351 #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
352 #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
353 #[cfg(feature = "orchard")] orchard_padding: BundlePadding,
365 _anchor_height: BlockHeight,
371 _zip318: &PoolMigrationParams,
372 change_memo: Option<&MemoBytes>,
373 ephemeral_balance: Option<EphemeralBalance>,
374) -> Result<TransactionBalance, ChangeError<E, NoteRefT>>
375where
376 E: From<F::Error> + From<BalanceError>,
377{
378 let change_memo = change_memo.filter(|_| ephemeral_balance.is_none_or(|b| !b.is_input()));
382
383 let overflow = || ChangeError::StrategyError(E::from(BalanceError::Overflow));
384 let underflow = || ChangeError::StrategyError(E::from(BalanceError::Underflow));
385
386 let net_flows = calculate_net_flows::<NoteRefT, F, E>(
387 transparent_inputs,
388 transparent_outputs,
389 sapling,
390 #[cfg(feature = "orchard")]
391 orchard,
392 #[cfg(feature = "orchard")]
393 ironwood,
394 ephemeral_balance,
395 )?;
396
397 let fully_transparent = net_flows.is_transparent() && change_memo.is_none();
399
400 #[cfg(feature = "transparent-inputs")]
405 let wants_transparent_change = fully_transparent
406 && cfg.transparent_change_policy == TransparentChangePolicy::TransparentChangeAllowed;
407 #[cfg(not(feature = "transparent-inputs"))]
408 let wants_transparent_change = false;
409
410 #[cfg(feature = "transparent-inputs")]
415 let transparent_change_size = change_receivers
416 .transparent()
417 .filter(|_| wants_transparent_change)
418 .map(|kind| kind.output_size());
419 #[cfg(not(feature = "transparent-inputs"))]
420 let transparent_change_size = None;
421
422 let total_in = net_flows
423 .total_in()
424 .map_err(|e| ChangeError::StrategyError(E::from(e)))?;
425 let subtotal_out = net_flows
426 .total_out()
427 .map_err(|e| ChangeError::StrategyError(E::from(e)))?;
428
429 let sapling_input_count = sapling
430 .bundle_type()
431 .num_spends(sapling.inputs().len())
432 .map_err(ChangeError::BundleError)?;
433 let sapling_output_count = |change_count| {
434 sapling
435 .bundle_type()
436 .num_outputs(
437 sapling.inputs().len(),
438 sapling.outputs().len() + change_count,
439 )
440 .map_err(ChangeError::BundleError)
441 };
442
443 #[cfg(feature = "orchard")]
444 let orchard_action_count = |change_count| {
445 orchard_fees::transactional_action_count(
446 orchard_padding.bundle_type(),
447 orchard.bundle_version(),
448 orchard.inputs().len(),
449 orchard.outputs().len() + change_count,
450 )
451 .map_err(ChangeError::BundleError)
452 };
453 #[cfg(not(feature = "orchard"))]
454 let orchard_action_count = |change_count: usize| -> Result<usize, ChangeError<E, NoteRefT>> {
455 if change_count != 0 {
456 Err(ChangeError::BundleError(
457 "Nonzero Orchard change requested but the `orchard` feature is not enabled.",
458 ))
459 } else {
460 Ok(0)
461 }
462 };
463
464 #[cfg(feature = "orchard")]
482 let ironwood_is_canonical_crossing = |change: OutputManifest| {
483 let constants = _zip318;
484 orchard.inputs().len() == 1
485 && ironwood.inputs().is_empty()
486 && change.ironwood() == 0
487 && change.orchard() <= 1
493 && change.sapling() == 0
494 && change.transparent() == 0
495 && match ironwood.outputs() {
496 [output] => constants.is_canonical_denomination(output.value()),
497 _ => false,
498 }
499 && constants
500 .anchor_grid().is_boundary(_anchor_height)
501 };
502 #[cfg(feature = "orchard")]
503 let ironwood_action_count = |change: OutputManifest| {
504 let padding = if ironwood_is_canonical_crossing(change) {
507 BundlePadding::UNPADDED
508 } else {
509 BundlePadding::DEFAULT
510 };
511 orchard_fees::transactional_action_count(
512 padding.bundle_type(),
513 ironwood.bundle_version(),
514 ironwood.inputs().len(),
515 ironwood.outputs().len() + change.ironwood(),
516 )
517 .map_err(ChangeError::BundleError)
518 };
519 #[cfg(not(feature = "orchard"))]
520 let ironwood_action_count =
521 |change: OutputManifest| -> Result<usize, ChangeError<E, NoteRefT>> {
522 if change.ironwood() != 0 {
523 Err(ChangeError::BundleError(
524 "Nonzero Ironwood change requested but the `orchard` feature is not enabled.",
525 ))
526 } else {
527 Ok(0)
528 }
529 };
530
531 let transparent_input_sizes = transparent_inputs
532 .iter()
533 .map(|i| i.serialized_size())
534 .chain(
535 ephemeral_balance
536 .and_then(|b| b.ephemeral_input_amount())
537 .map(|_| transparent::InputSize::STANDARD_P2PKH),
538 );
539 let transparent_output_sizes = transparent_outputs
540 .iter()
541 .map(|i| i.serialized_size())
542 .chain(
543 ephemeral_balance
544 .and_then(|b| b.ephemeral_output_amount())
545 .map(|_| P2PKH_STANDARD_OUTPUT_SIZE),
546 );
547
548 let min_fee = cfg
569 .fee_rule
570 .fee_required(
571 cfg.params,
572 BlockHeight::from(target_height),
573 transparent_input_sizes.clone(),
574 transparent_output_sizes.clone(),
575 sapling_input_count,
576 sapling_output_count(0)?,
577 orchard_action_count(0)?,
578 ironwood_action_count(OutputManifest::ZERO)?,
579 )
580 .map_err(|fee_error| ChangeError::StrategyError(E::from(fee_error)))?;
581
582 let total_out_with_min_fee = (subtotal_out + min_fee).ok_or_else(overflow)?;
583
584 let change_pool = select_change_pool(
587 &net_flows,
588 cfg.fallback_change_pool,
589 change_receivers,
590 cfg.params
591 .is_nu_active(NetworkUpgrade::Nu6_3, target_height.into()),
592 (total_in - total_out_with_min_fee).unwrap_or(Zatoshis::ZERO),
593 );
594
595 let (target_change_count, target_change_counts) = if wants_transparent_change {
596 (
600 1,
601 OutputManifest {
602 transparent: 1,
603 sapling: 0,
604 orchard: 0,
605 ironwood: 0,
606 },
607 )
608 } else {
609 let target_change_count = wallet_meta.map_or(1, |m| {
610 usize::from(cfg.split_policy.target_output_count)
611 .saturating_sub(m.total_note_count().unwrap_or(usize::MAX))
613 .max(1)
614 });
615 let target_change_counts = OutputManifest {
616 transparent: 0,
617 sapling: if change_pool == ShieldedPool::Sapling {
618 target_change_count
619 } else {
620 0
621 },
622 orchard: if change_pool == ShieldedPool::Orchard {
623 target_change_count
624 } else {
625 0
626 },
627 ironwood: if change_pool == ShieldedPool::Ironwood {
628 target_change_count
629 } else {
630 0
631 },
632 };
633 assert!(target_change_counts.total_shielded() == target_change_count);
634 (target_change_count, target_change_counts)
635 };
636
637 if cfg.marginal_fee.is_positive() {
641 let possible_change = {
645 if fully_transparent
647 || (cfg.dust_output_policy.action() == DustAction::AddDustToFee
648 && change_memo.is_none())
649 {
650 vec![OutputManifest::ZERO, target_change_counts]
651 } else {
652 vec![target_change_counts]
653 }
654 };
655
656 check_for_uneconomic_inputs(
657 transparent_inputs,
658 transparent_outputs,
659 sapling,
660 #[cfg(feature = "orchard")]
661 orchard,
662 #[cfg(feature = "orchard")]
663 ironwood,
664 #[cfg(feature = "orchard")]
665 orchard_padding,
666 #[cfg(feature = "orchard")]
667 _anchor_height,
668 #[cfg(feature = "orchard")]
669 _zip318,
670 cfg.marginal_fee,
671 cfg.grace_actions,
672 &possible_change[..],
673 ephemeral_balance,
674 )?;
675 }
676
677 #[allow(unused_mut)]
678 let (mut change, fee) = match total_in.cmp(&total_out_with_min_fee) {
679 Ordering::Less => {
680 return Err(ChangeError::InsufficientFunds {
683 available: total_in,
684 required: total_out_with_min_fee,
685 });
686 }
687 Ordering::Equal if fully_transparent => {
688 (vec![], min_fee)
691 }
692 _ => {
693 let max_fee = max(
694 min_fee,
695 cfg.fee_rule
696 .fee_required(
697 cfg.params,
698 BlockHeight::from(target_height),
699 transparent_input_sizes.clone(),
700 transparent_output_sizes
701 .clone()
702 .chain(transparent_change_size),
705 sapling_input_count,
706 sapling_output_count(target_change_counts.sapling())?,
707 orchard_action_count(target_change_counts.orchard())?,
708 ironwood_action_count(target_change_counts)?,
709 )
710 .map_err(|fee_error| ChangeError::StrategyError(E::from(fee_error)))?,
711 );
712
713 let total_out_with_max_fee = (subtotal_out + max_fee).ok_or_else(overflow)?;
714
715 let split_count = if wants_transparent_change {
720 1
721 } else {
722 usize::from(wallet_meta.map_or(NonZeroUsize::MIN, |wm| {
723 cfg.split_policy.split_count(
724 wm.total_note_count(),
725 wm.total_value(),
726 (total_in - total_out_with_max_fee).unwrap_or(Zatoshis::ZERO),
730 )
731 }))
732 };
733
734 let total_fee = if split_count < target_change_count {
736 cfg.fee_rule
737 .fee_required(
738 cfg.params,
739 BlockHeight::from(target_height),
740 transparent_input_sizes,
741 transparent_output_sizes,
742 sapling_input_count,
743 sapling_output_count(if change_pool == ShieldedPool::Sapling {
744 split_count
745 } else {
746 0
747 })?,
748 orchard_action_count(if change_pool == ShieldedPool::Orchard {
749 split_count
750 } else {
751 0
752 })?,
753 ironwood_action_count(OutputManifest::for_pool(change_pool, split_count))?,
754 )
755 .map_err(|fee_error| ChangeError::StrategyError(E::from(fee_error)))?
756 } else {
757 max_fee
758 };
759
760 let total_out = (subtotal_out + total_fee).ok_or_else(overflow)?;
761 let total_change =
762 (total_in - total_out).ok_or_else(|| ChangeError::InsufficientFunds {
763 available: total_in,
764 required: total_out,
765 })?;
766
767 let per_output_change = total_change.div_with_remainder(
768 NonZeroU64::new(u64::try_from(split_count).expect("usize fits into u64")).unwrap(),
769 );
770 let simple_case = || {
771 #[cfg(feature = "transparent-inputs")]
772 if wants_transparent_change {
773 return (
774 if total_change.is_zero() {
775 vec![]
780 } else {
781 vec![ChangeValue::transparent(total_change)]
782 },
783 total_fee,
784 );
785 }
786
787 (
788 (0usize..split_count)
789 .map(|i| {
790 ChangeValue::shielded(
791 change_pool,
792 if i == 0 {
793 (*per_output_change.quotient() + *per_output_change.remainder())
795 .unwrap()
796 } else {
797 *per_output_change.quotient()
800 },
801 change_memo.cloned(),
802 )
803 })
804 .collect(),
805 total_fee,
806 )
807 };
808
809 let change_dust_threshold = cfg
810 .dust_output_policy
811 .dust_threshold()
812 .unwrap_or(cfg.default_dust_threshold);
813
814 if total_change < change_dust_threshold {
815 match cfg.dust_output_policy.action() {
816 DustAction::Reject => {
817 if total_change.is_zero() {
824 simple_case()
825 } else {
826 let shortfall =
827 (change_dust_threshold - total_change).ok_or_else(underflow)?;
828
829 return Err(ChangeError::InsufficientFunds {
830 available: total_in,
831 required: (total_in + shortfall).ok_or_else(overflow)?,
832 });
833 }
834 }
835 DustAction::AllowDustChange => simple_case(),
836 DustAction::AddDustToFee => {
837 let fee_with_dust = (total_change + total_fee).ok_or_else(overflow)?;
840
841 let dust_cap = (minimum_fee(cfg.params, target_height.into())
842 * DUST_TO_FEE_CAP_MINIMUM_FEES)
843 .ok_or_else(overflow)?;
844 let reasonable_fee = (total_fee + dust_cap).ok_or_else(overflow)?;
845
846 if fee_with_dust > reasonable_fee {
847 simple_case()
850 } else if change_memo.is_some() {
851 (
852 vec![ChangeValue::shielded(
853 change_pool,
854 Zatoshis::ZERO,
855 change_memo.cloned(),
856 )],
857 fee_with_dust,
858 )
859 } else {
860 (vec![], fee_with_dust)
861 }
862 }
863 }
864 } else {
865 simple_case()
866 }
867 }
868 };
869
870 #[cfg(feature = "transparent-inputs")]
871 change.extend(
872 ephemeral_balance
873 .and_then(|b| b.ephemeral_output_amount())
874 .map(ChangeValue::ephemeral_transparent),
875 );
876
877 for change_value in &change {
878 if !can_receive_change(change_receivers, change_value) {
879 return Err(ChangeError::UnsupportedChangePool(
880 change_value.output_pool(),
881 ));
882 }
883 }
884
885 let final_change = OutputManifest {
889 transparent: change
890 .iter()
891 .filter(|c| c.output_pool() == PoolType::TRANSPARENT)
892 .count(),
893 sapling: change
894 .iter()
895 .filter(|c| c.output_pool() == PoolType::SAPLING)
896 .count(),
897 orchard: change
898 .iter()
899 .filter(|c| c.output_pool() == PoolType::ORCHARD)
900 .count(),
901 ironwood: change
902 .iter()
903 .filter(|c| c.output_pool() == PoolType::IRONWOOD)
904 .count(),
905 };
906 let sapling_real_outputs = sapling.outputs().len() + final_change.sapling();
907 let sapling_dummy_outputs = sapling_output_count(final_change.sapling())?
908 .checked_sub(sapling_real_outputs)
909 .expect("the Sapling action count includes every real output");
910 #[cfg(feature = "orchard")]
911 let orchard_dummy_outputs = orchard_action_count(final_change.orchard())?
912 .checked_sub(orchard.outputs().len() + final_change.orchard())
913 .expect("the Orchard action count includes every real output");
914 #[cfg(feature = "orchard")]
915 let ironwood_dummy_outputs = ironwood_action_count(final_change)?
916 .checked_sub(ironwood.outputs().len() + final_change.ironwood())
917 .expect("the Ironwood action count includes every real output");
918
919 TransactionBalance::new(change, fee)
920 .map(|balance| {
921 balance.with_dummy_outputs(DummyOutputCounts::new(
922 sapling_dummy_outputs,
923 #[cfg(feature = "orchard")]
924 orchard_dummy_outputs,
925 #[cfg(feature = "orchard")]
926 ironwood_dummy_outputs,
927 ))
928 })
929 .map_err(|_| overflow())
930}
931
932fn can_receive_change(change_receivers: &ChangeReceivers, change: &ChangeValue) -> bool {
935 #[cfg(feature = "transparent-inputs")]
936 if change.is_ephemeral() {
937 return matches!(
938 change_receivers.transparent(),
939 Some(TransparentChangeKind::P2pkh)
940 );
941 }
942 change_receivers.can_receive(change.output_pool())
943}
944
945#[allow(clippy::too_many_arguments)]
959pub(crate) fn check_for_uneconomic_inputs<NoteRefT: Clone, E>(
960 transparent_inputs: &[impl transparent::InputView],
961 transparent_outputs: &[impl transparent::OutputView],
962 sapling: &impl sapling_fees::BundleView<NoteRefT>,
963 #[cfg(feature = "orchard")] orchard: &impl orchard_fees::BundleView<NoteRefT>,
964 #[cfg(feature = "orchard")] ironwood: &impl orchard_fees::BundleView<NoteRefT>,
965 #[cfg(feature = "orchard")] orchard_padding: BundlePadding,
968 #[cfg(feature = "orchard")] anchor_height: BlockHeight,
969 #[cfg(feature = "orchard")] zip318: &PoolMigrationParams,
970 marginal_fee: Zatoshis,
971 grace_actions: usize,
972 possible_change: &[OutputManifest],
973 ephemeral_balance: Option<EphemeralBalance>,
974) -> Result<(), ChangeError<E, NoteRefT>> {
975 let mut t_dust: Vec<_> = transparent_inputs
976 .iter()
977 .filter_map(|i| {
978 if i.coin().value() <= marginal_fee {
981 Some(i.outpoint().clone())
982 } else {
983 None
984 }
985 })
986 .collect();
987
988 let mut s_dust: Vec<_> = sapling
989 .inputs()
990 .iter()
991 .filter_map(|i| {
992 if sapling_fees::InputView::<NoteRefT>::value(i) <= marginal_fee {
993 Some(sapling_fees::InputView::<NoteRefT>::note_id(i).clone())
994 } else {
995 None
996 }
997 })
998 .collect();
999
1000 #[cfg(feature = "orchard")]
1001 let mut o_dust: Vec<NoteRefT> = orchard
1002 .inputs()
1003 .iter()
1004 .filter_map(|i| {
1005 if orchard_fees::InputView::<NoteRefT>::value(i) <= marginal_fee {
1006 Some(orchard_fees::InputView::<NoteRefT>::note_id(i).clone())
1007 } else {
1008 None
1009 }
1010 })
1011 .collect();
1012 #[cfg(not(feature = "orchard"))]
1013 let mut o_dust: Vec<NoteRefT> = vec![];
1014
1015 #[cfg(feature = "orchard")]
1016 let mut i_dust: Vec<NoteRefT> = ironwood
1017 .inputs()
1018 .iter()
1019 .filter_map(|i| {
1020 if orchard_fees::InputView::<NoteRefT>::value(i) <= marginal_fee {
1021 Some(orchard_fees::InputView::<NoteRefT>::note_id(i).clone())
1022 } else {
1023 None
1024 }
1025 })
1026 .collect();
1027 #[cfg(not(feature = "orchard"))]
1028 let mut i_dust: Vec<NoteRefT> = vec![];
1029
1030 if t_dust.is_empty() && s_dust.is_empty() && o_dust.is_empty() && i_dust.is_empty() {
1032 return Ok(());
1033 }
1034
1035 let (t_inputs_len, t_outputs_len) = (
1036 transparent_inputs.len() + usize::from(ephemeral_balance.is_some_and(|b| b.is_input())),
1037 transparent_outputs.len() + usize::from(ephemeral_balance.is_some_and(|b| b.is_output())),
1038 );
1039 let (s_inputs_len, s_outputs_len) = (sapling.inputs().len(), sapling.outputs().len());
1040 #[cfg(feature = "orchard")]
1041 let (o_inputs_len, o_outputs_len) = (orchard.inputs().len(), orchard.outputs().len());
1042 #[cfg(not(feature = "orchard"))]
1043 let (o_inputs_len, o_outputs_len) = (0usize, 0usize);
1044 #[cfg(feature = "orchard")]
1045 let (i_inputs_len, i_outputs_len) = (ironwood.inputs().len(), ironwood.outputs().len());
1046 #[cfg(not(feature = "orchard"))]
1047 let (i_inputs_len, i_outputs_len) = (0usize, 0usize);
1048
1049 let t_non_dust = t_inputs_len.checked_sub(t_dust.len()).unwrap();
1050 let s_non_dust = s_inputs_len.checked_sub(s_dust.len()).unwrap();
1051 let o_non_dust = o_inputs_len.checked_sub(o_dust.len()).unwrap();
1052 let i_non_dust = i_inputs_len.checked_sub(i_dust.len()).unwrap();
1053
1054 let allowed_dust = |change: &OutputManifest| {
1056 let t_allowed = min(
1069 t_dust.len(),
1070 (t_outputs_len + change.transparent).saturating_sub(t_non_dust),
1071 );
1072 let s_allowed = min(
1073 s_dust.len(),
1074 (s_outputs_len + change.sapling).saturating_sub(s_non_dust),
1075 );
1076 let o_allowed = min(
1077 o_dust.len(),
1078 (o_outputs_len + change.orchard).saturating_sub(o_non_dust),
1079 );
1080 let i_allowed = min(
1081 i_dust.len(),
1082 (i_outputs_len + change.ironwood).saturating_sub(i_non_dust),
1083 );
1084
1085 let t_req_inputs = t_non_dust + t_allowed;
1087 let s_req_inputs = s_non_dust + s_allowed;
1088 #[cfg(feature = "orchard")]
1089 let o_req_inputs = o_non_dust + o_allowed;
1090 #[cfg(feature = "orchard")]
1091 let i_req_inputs = i_non_dust + i_allowed;
1092
1093 let hypothetical_actions = |t_extra, s_extra, _o_extra, _i_extra| {
1101 let s_spend_count = sapling
1102 .bundle_type()
1103 .num_spends(s_req_inputs + s_extra)
1104 .map_err(ChangeError::BundleError)?;
1105
1106 let s_output_count = sapling
1107 .bundle_type()
1108 .num_outputs(s_req_inputs + s_extra, s_outputs_len + change.sapling)
1109 .map_err(ChangeError::BundleError)?;
1110
1111 #[cfg(feature = "orchard")]
1112 let o_action_count = orchard_fees::transactional_action_count(
1113 orchard_padding.bundle_type(),
1114 orchard.bundle_version(),
1115 o_req_inputs + _o_extra,
1116 o_outputs_len + change.orchard,
1117 )
1118 .map_err(ChangeError::BundleError)?;
1119 #[cfg(not(feature = "orchard"))]
1120 let o_action_count = 0;
1121
1122 #[cfg(feature = "orchard")]
1126 let i_padding = {
1127 let constants = zip318;
1128 let canonical = o_req_inputs + _o_extra == 1
1129 && i_req_inputs + _i_extra == 0
1130 && change.ironwood == 0
1131 && match ironwood.outputs() {
1132 [output] => constants.is_canonical_denomination(output.value()),
1133 _ => false,
1134 }
1135 && constants.anchor_grid().is_boundary(anchor_height);
1136 if canonical {
1137 BundlePadding::UNPADDED
1138 } else {
1139 BundlePadding::DEFAULT
1140 }
1141 };
1142 #[cfg(feature = "orchard")]
1143 let i_action_count = orchard_fees::transactional_action_count(
1144 i_padding.bundle_type(),
1145 ironwood.bundle_version(),
1146 i_req_inputs + _i_extra,
1147 i_outputs_len + change.ironwood,
1148 )
1149 .map_err(ChangeError::BundleError)?;
1150 #[cfg(not(feature = "orchard"))]
1151 let i_action_count = 0;
1152
1153 Ok(
1156 max(t_req_inputs + t_extra, t_outputs_len + change.transparent)
1157 + max(s_spend_count, s_output_count)
1158 + o_action_count
1159 + i_action_count,
1160 )
1161 };
1162
1163 let baseline = hypothetical_actions(0, 0, 0, 0)?;
1174
1175 let (t_extra, s_extra, o_extra, i_extra) = if baseline >= grace_actions {
1176 (0, 0, 0, 0)
1177 } else if t_dust.len() > t_allowed && hypothetical_actions(1, 0, 0, 0)? <= baseline {
1178 (1, 0, 0, 0)
1179 } else if s_dust.len() > s_allowed && hypothetical_actions(0, 1, 0, 0)? <= baseline {
1180 (0, 1, 0, 0)
1181 } else if o_dust.len() > o_allowed && hypothetical_actions(0, 0, 1, 0)? <= baseline {
1182 (0, 0, 1, 0)
1183 } else if i_dust.len() > i_allowed && hypothetical_actions(0, 0, 0, 1)? <= baseline {
1184 (0, 0, 0, 1)
1185 } else {
1186 (0, 0, 0, 0)
1187 };
1188 Ok(OutputManifest {
1189 transparent: t_allowed + t_extra,
1190 sapling: s_allowed + s_extra,
1191 orchard: o_allowed + o_extra,
1192 ironwood: i_allowed + i_extra,
1193 })
1194 };
1195
1196 let allowed = possible_change
1198 .iter()
1199 .map(allowed_dust)
1200 .collect::<Result<Vec<_>, _>>()?
1201 .into_iter()
1202 .reduce(|l, r| OutputManifest {
1203 transparent: min(l.transparent, r.transparent),
1204 sapling: min(l.sapling, r.sapling),
1205 orchard: min(l.orchard, r.orchard),
1206 ironwood: min(l.ironwood, r.ironwood),
1207 })
1208 .expect("possible_change is nonempty");
1209
1210 let t_dust = t_dust.split_off(allowed.transparent);
1213 let s_dust = s_dust.split_off(allowed.sapling);
1214 let o_dust = o_dust.split_off(allowed.orchard);
1215 let i_dust = i_dust.split_off(allowed.ironwood);
1216
1217 if t_dust.is_empty() && s_dust.is_empty() && o_dust.is_empty() && i_dust.is_empty() {
1218 Ok(())
1219 } else {
1220 Err(ChangeError::DustInputs {
1221 transparent: t_dust,
1222 sapling: s_dust,
1223 #[cfg(feature = "orchard")]
1224 orchard: o_dust,
1225 #[cfg(feature = "orchard")]
1226 ironwood: i_dust,
1227 })
1228 }
1229}
1230
1231#[cfg(all(test, feature = "orchard"))]
1232mod tests {
1233 use super::{NetFlows, select_change_pool};
1234 use crate::data_api::ChangeReceivers;
1235 use zcash_protocol::{ShieldedPool, value::Zatoshis};
1236
1237 fn receivers(sapling: bool, orchard: bool) -> ChangeReceivers {
1240 ChangeReceivers::new(
1241 sapling,
1242 orchard,
1243 #[cfg(feature = "transparent-inputs")]
1244 None,
1245 )
1246 }
1247
1248 fn all_receivers() -> ChangeReceivers {
1250 receivers(true, true)
1251 }
1252
1253 fn flows(orchard_in: u64, ironwood_in: u64, sapling_in: u64) -> NetFlows {
1254 NetFlows {
1255 t_in: Zatoshis::ZERO,
1256 t_out: Zatoshis::ZERO,
1257 sapling_in: Zatoshis::const_from_u64(sapling_in),
1258 sapling_out: Zatoshis::ZERO,
1259 orchard_in: Zatoshis::const_from_u64(orchard_in),
1260 orchard_out: Zatoshis::ZERO,
1261 ironwood_in: Zatoshis::const_from_u64(ironwood_in),
1262 ironwood_out: Zatoshis::ZERO,
1263 }
1264 }
1265
1266 #[test]
1267 fn select_change_pool_routes_ironwood_spend_to_ironwood() {
1268 assert_eq!(
1271 select_change_pool(
1272 &flows(0, 10_000, 0),
1273 ShieldedPool::Sapling,
1274 &all_receivers(),
1275 true,
1276 Zatoshis::const_from_u64(5_000)
1277 ),
1278 ShieldedPool::Ironwood
1279 );
1280
1281 assert_eq!(
1284 select_change_pool(
1285 &flows(10_000, 10_000, 0),
1286 ShieldedPool::Sapling,
1287 &all_receivers(),
1288 true,
1289 Zatoshis::const_from_u64(5_000)
1290 ),
1291 ShieldedPool::Orchard
1292 );
1293
1294 assert_eq!(
1297 select_change_pool(
1298 &flows(0, 10_000, 10_000),
1299 ShieldedPool::Sapling,
1300 &all_receivers(),
1301 true,
1302 Zatoshis::const_from_u64(5_000)
1303 ),
1304 ShieldedPool::Ironwood
1305 );
1306
1307 assert_eq!(
1309 select_change_pool(
1310 &flows(0, 0, 10_000),
1311 ShieldedPool::Orchard,
1312 &all_receivers(),
1313 true,
1314 Zatoshis::const_from_u64(5_000)
1315 ),
1316 ShieldedPool::Sapling
1317 );
1318 }
1319
1320 #[test]
1321 fn select_change_pool_enforces_orchard_turnstile() {
1322 assert_eq!(
1325 select_change_pool(
1326 &flows(10_000, 0, 10_000),
1327 ShieldedPool::Sapling,
1328 &all_receivers(),
1329 false,
1330 Zatoshis::const_from_u64(15_000)
1331 ),
1332 ShieldedPool::Orchard
1333 );
1334
1335 assert_eq!(
1338 select_change_pool(
1339 &flows(10_000, 0, 10_000),
1340 ShieldedPool::Sapling,
1341 &all_receivers(),
1342 true,
1343 Zatoshis::const_from_u64(9_999)
1344 ),
1345 ShieldedPool::Orchard
1346 );
1347
1348 assert_eq!(
1351 select_change_pool(
1352 &flows(10_000, 0, 10_000),
1353 ShieldedPool::Sapling,
1354 &all_receivers(),
1355 true,
1356 Zatoshis::const_from_u64(10_000)
1357 ),
1358 ShieldedPool::Ironwood
1359 );
1360
1361 assert_eq!(
1364 select_change_pool(
1365 &NetFlows {
1366 t_in: Zatoshis::const_from_u64(10_000),
1367 t_out: Zatoshis::ZERO,
1368 sapling_in: Zatoshis::ZERO,
1369 sapling_out: Zatoshis::ZERO,
1370 orchard_in: Zatoshis::ZERO,
1371 orchard_out: Zatoshis::ZERO,
1372 ironwood_in: Zatoshis::ZERO,
1373 ironwood_out: Zatoshis::ZERO,
1374 },
1375 ShieldedPool::Orchard,
1376 &all_receivers(),
1377 true,
1378 Zatoshis::const_from_u64(10_000)
1379 ),
1380 ShieldedPool::Ironwood
1381 );
1382 }
1383
1384 #[test]
1385 fn select_change_pool_uses_a_pool_the_account_can_receive() {
1386 let orchard_out = |sapling_in: u64, orchard_out: u64| NetFlows {
1387 sapling_in: Zatoshis::const_from_u64(sapling_in),
1388 orchard_out: Zatoshis::const_from_u64(orchard_out),
1389 ..flows(0, 0, 0)
1390 };
1391
1392 assert_eq!(
1395 select_change_pool(
1396 &orchard_out(10_000, 5_000),
1397 ShieldedPool::Orchard,
1398 &receivers(true, false),
1399 false,
1400 Zatoshis::const_from_u64(4_000)
1401 ),
1402 ShieldedPool::Sapling
1403 );
1404
1405 assert_eq!(
1408 select_change_pool(
1409 &flows(0, 0, 10_000),
1410 ShieldedPool::Sapling,
1411 &receivers(false, true),
1412 false,
1413 Zatoshis::const_from_u64(5_000)
1414 ),
1415 ShieldedPool::Orchard
1416 );
1417
1418 assert_eq!(
1421 select_change_pool(
1422 &flows(0, 0, 10_000),
1423 ShieldedPool::Sapling,
1424 &receivers(false, true),
1425 true,
1426 Zatoshis::const_from_u64(5_000)
1427 ),
1428 ShieldedPool::Ironwood
1429 );
1430
1431 let transparent_flows = NetFlows {
1434 t_in: Zatoshis::const_from_u64(10_000),
1435 ..flows(0, 0, 0)
1436 };
1437 assert_eq!(
1438 select_change_pool(
1439 &transparent_flows,
1440 ShieldedPool::Orchard,
1441 &receivers(true, false),
1442 true,
1443 Zatoshis::const_from_u64(5_000)
1444 ),
1445 ShieldedPool::Sapling
1446 );
1447
1448 assert_eq!(
1451 select_change_pool(
1452 &orchard_out(10_000, 5_000),
1453 ShieldedPool::Sapling,
1454 &receivers(false, false),
1455 false,
1456 Zatoshis::const_from_u64(4_000)
1457 ),
1458 ShieldedPool::Orchard
1459 );
1460 }
1461}