1#![cfg_attr(
25 feature = "transparent-inputs",
26 doc = "
27Another important high-level operation provided by this module is [`propose_shielding`], which
28takes a set of transparent source addresses, and constructs a [`Proposal`] to send those funds
29to a wallet-internal shielded address, as described in [ZIP 316](https://zips.z.cash/zip-0316).
30
31[`propose_shielding`]: crate::data_api::wallet::propose_shielding
32"
33)]
34use nonempty::NonEmpty;
38use rand_core::CryptoRng;
39use std::{
40 num::NonZeroU32,
41 ops::{Add, Sub},
42 time::SystemTime,
43};
44
45use shardtree::error::{QueryError, ShardTreeError};
46
47pub use super::locking::{LockRequest, unlock_proposal_inputs};
48use super::{InputSource, locking::lock_proposal_inputs};
49use crate::{
50 data_api::{
51 Account, MaxSpendMode, NoteCommitmentTree, SentTransaction, SentTransactionOutput,
52 WalletCommitmentTrees, WalletRead, WalletWrite,
53 error::{AddressExpiryError, Error},
54 wallet::input_selection::propose_send_max,
55 },
56 decrypt_transaction,
57 fees::{
58 ChangeStrategy, DustOutputPolicy, StandardFeeRule, standard::SingleOutputChangeStrategy,
59 },
60 proposal::{Proposal, ProposalError, Step, StepOutputIndex},
61 util::Clock,
62 wallet::{Note, OvkPolicy, Recipient},
63};
64use sapling::{
65 note_encryption::{PreparedIncomingViewingKey, try_sapling_note_decryption},
66 prover::{OutputProver, SpendProver},
67};
68use transparent::{address::TransparentAddress, builder::TransparentSigningSet, bundle::OutPoint};
69use zcash_address::ZcashAddress;
70use zcash_keys::{
71 address::{Address, UnifiedAddress},
72 keys::{UnifiedFullViewingKey, UnifiedSpendingKey},
73};
74use zcash_primitives::transaction::{
75 Transaction, TxId, TxVersion,
76 builder::{BuildConfig, BuildResult, Builder, BundlePadding},
77 components::sapling::zip212_enforcement,
78 fees::FeeRule,
79};
80use zcash_protocol::{
81 PoolType, ShieldedPool,
82 consensus::{self, BlockHeight},
83 memo::MemoBytes,
84 value::Zatoshis,
85 zip318::AnchorGrid,
86};
87use zip32::Scope;
88use zip321::Payment;
89#[cfg(feature = "orchard")]
90use {
91 crate::data_api::anchor_retention::PoolMigrationParams,
92 zcash_protocol::{consensus::NetworkUpgrade, zip318::PoolMigrationConstants},
93};
94
95#[cfg(feature = "transparent-inputs")]
96use {
97 super::CoinbaseFilter,
98 crate::{
99 fees::ChangeValue,
100 proposal::StepOutput,
101 wallet::{TransparentAddressMetadata, TransparentAddressSource},
102 },
103 core::convert::Infallible,
104 input_selection::ShieldingSelector,
105 std::collections::HashMap,
106 transparent::bundle::TxOut,
107};
108
109#[cfg(feature = "transparent-key-import")]
110use zcash_script::script::{self as zs_script, Evaluable};
111
112#[cfg(feature = "pczt")]
113use {
114 crate::data_api::error::PcztError,
115 bip32::ChildNumber,
116 orchard::note_encryption::{IronwoodDomain, OrchardDomain},
117 pczt::roles::{
118 creator::Creator, io_finalizer::IoFinalizer, redactor::Redactor,
119 spend_finalizer::SpendFinalizer, tx_extractor::TransactionExtractor, updater::Updater,
120 },
121 sapling::note_encryption::SaplingDomain,
122 serde::{Deserialize, Serialize},
123 std::collections::BTreeMap,
124 transparent::pczt::Bip32Derivation,
125 zcash_note_encryption::{Domain, ShieldedOutput, try_output_recovery_with_pkd_esk},
126 zcash_protocol::{consensus::NetworkConstants, value::BalanceError},
127};
128
129pub mod input_selection;
130use input_selection::{
131 GreedyInputSelector, GreedyInputSelectorError, InputSelector, InputSelectorError,
132};
133
134#[cfg(feature = "pczt")]
135const PROPRIETARY_PROPOSAL_INFO: &str = "zcash_client_backend:proposal_info";
136#[cfg(feature = "pczt")]
137const PROPRIETARY_OUTPUT_INFO: &str = "zcash_client_backend:output_info";
138
139#[cfg(feature = "orchard")]
140fn ironwood_active_at<ParamsT: consensus::Parameters, H: Into<BlockHeight>>(
141 params: &ParamsT,
142 target_height: H,
143) -> bool {
144 params.is_nu_active(NetworkUpgrade::Nu6_3, target_height.into())
145}
146
147#[cfg(feature = "pczt")]
148fn serialize_target_height<S>(
149 target_height: &TargetHeight,
150 serializer: S,
151) -> Result<S::Ok, S::Error>
152where
153 S: serde::Serializer,
154{
155 let u: u32 = BlockHeight::from(*target_height).into();
156 u.serialize(serializer)
157}
158
159#[cfg(feature = "pczt")]
160fn deserialize_target_height<'de, D>(deserializer: D) -> Result<TargetHeight, D::Error>
161where
162 D: serde::Deserializer<'de>,
163{
164 let u = u32::deserialize(deserializer)?;
165 Ok(BlockHeight::from_u32(u).into())
166}
167
168#[cfg(feature = "pczt")]
172#[derive(Serialize, Deserialize)]
173struct ProposalInfo<AccountId> {
174 from_account: AccountId,
175 #[serde(
176 serialize_with = "serialize_target_height",
177 deserialize_with = "deserialize_target_height"
178 )]
179 target_height: TargetHeight,
180}
181
182#[cfg(feature = "pczt")]
186#[derive(Serialize, Deserialize)]
187enum PcztRecipient<AccountId> {
188 External,
189 #[cfg(feature = "transparent-inputs")]
190 EphemeralTransparent {
191 receiving_account: AccountId,
192 },
193 InternalShielded {
194 receiving_account: AccountId,
195 },
196 #[cfg(feature = "transparent-inputs")]
199 InternalTransparent {
200 receiving_account: AccountId,
201 },
202}
203
204#[cfg(feature = "pczt")]
205impl<AccountId: Copy> PcztRecipient<AccountId> {
206 fn from_shielded_recipient(
207 recipient: ShieldedBuildRecipient<AccountId>,
208 ) -> (Self, Option<ZcashAddress>) {
209 match recipient {
210 ShieldedBuildRecipient::External {
211 recipient_address, ..
212 } => (PcztRecipient::External, Some(recipient_address)),
213 ShieldedBuildRecipient::InternalShielded {
214 receiving_account,
215 external_address,
216 } => (
217 PcztRecipient::InternalShielded { receiving_account },
218 external_address,
219 ),
220 }
221 }
222
223 fn from_transparent_recipient(
224 recipient: TransparentBuildRecipient<AccountId>,
225 ) -> (Self, Option<ZcashAddress>) {
226 match recipient {
227 TransparentBuildRecipient::External {
228 recipient_address, ..
229 } => (PcztRecipient::External, Some(recipient_address)),
230 #[cfg(feature = "transparent-inputs")]
231 TransparentBuildRecipient::EphemeralTransparent {
232 receiving_account, ..
233 } => (
234 PcztRecipient::EphemeralTransparent { receiving_account },
235 None,
236 ),
237 #[cfg(feature = "transparent-inputs")]
238 TransparentBuildRecipient::InternalTransparent {
239 receiving_account, ..
240 } => (
241 PcztRecipient::InternalTransparent { receiving_account },
242 None,
243 ),
244 }
245 }
246}
247
248pub fn decrypt_and_store_transaction<ParamsT, DbT>(
251 params: &ParamsT,
252 data: &mut DbT,
253 tx: &Transaction,
254 mined_height: Option<BlockHeight>,
255) -> Result<(), <DbT as WalletRead>::Error>
256where
257 ParamsT: consensus::Parameters,
258 DbT: WalletWrite,
259{
260 let ufvks = data.get_unified_full_viewing_keys()?;
262
263 data.store_decrypted_tx(decrypt_transaction(
264 params,
265 mined_height.map_or_else(|| data.get_tx_height(tx.txid()), |h| Ok(Some(h)))?,
266 data.chain_height()?,
267 tx,
268 &ufvks,
269 ))?;
270
271 Ok(())
272}
273
274pub type ProposeTransferErrT<DbT, CommitmentTreeErrT, InputsT, ChangeT> = Error<
277 <DbT as WalletRead>::Error,
278 CommitmentTreeErrT,
279 <InputsT as InputSelector>::Error,
280 <<ChangeT as ChangeStrategy>::FeeRule as FeeRule>::Error,
281 <ChangeT as ChangeStrategy>::Error,
282 <<InputsT as InputSelector>::InputSource as InputSource>::NoteRef,
283>;
284
285pub type ProposeSendMaxErrT<DbT, CommitmentTreeErrT, FeeRuleT> = Error<
289 <DbT as WalletRead>::Error,
290 CommitmentTreeErrT,
291 GreedyInputSelectorError,
292 <FeeRuleT as FeeRule>::Error,
293 <FeeRuleT as FeeRule>::Error,
294 <DbT as InputSource>::NoteRef,
295>;
296
297#[cfg(feature = "transparent-inputs")]
300pub type ProposeShieldingErrT<DbT, CommitmentTreeErrT, InputsT, ChangeT> = Error<
301 <DbT as WalletRead>::Error,
302 CommitmentTreeErrT,
303 <InputsT as ShieldingSelector>::Error,
304 <<ChangeT as ChangeStrategy>::FeeRule as FeeRule>::Error,
305 <ChangeT as ChangeStrategy>::Error,
306 Infallible,
307>;
308
309pub type CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N> = Error<
311 <DbT as WalletRead>::Error,
312 <DbT as WalletCommitmentTrees>::Error,
313 InputsErrT,
314 <FeeRuleT as FeeRule>::Error,
315 ChangeErrT,
316 N,
317>;
318
319pub type TransferErrT<DbT, InputsT, ChangeT> = Error<
321 <DbT as WalletRead>::Error,
322 <DbT as WalletCommitmentTrees>::Error,
323 <InputsT as InputSelector>::Error,
324 <<ChangeT as ChangeStrategy>::FeeRule as FeeRule>::Error,
325 <ChangeT as ChangeStrategy>::Error,
326 <<InputsT as InputSelector>::InputSource as InputSource>::NoteRef,
327>;
328
329#[cfg(feature = "transparent-inputs")]
331pub type ShieldErrT<DbT, InputsT, ChangeT> = Error<
332 <DbT as WalletRead>::Error,
333 <DbT as WalletCommitmentTrees>::Error,
334 <InputsT as ShieldingSelector>::Error,
335 <<ChangeT as ChangeStrategy>::FeeRule as FeeRule>::Error,
336 <ChangeT as ChangeStrategy>::Error,
337 Infallible,
338>;
339
340#[cfg(feature = "pczt")]
342pub type ExtractErrT<DbT, N> = Error<
343 <DbT as WalletRead>::Error,
344 <DbT as WalletCommitmentTrees>::Error,
345 Infallible,
346 Infallible,
347 Infallible,
348 N,
349>;
350
351#[repr(transparent)]
355#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
356pub struct TargetHeight(BlockHeight);
357
358impl TargetHeight {
359 pub fn saturating_sub(self, value: u32) -> BlockHeight {
362 self.0.saturating_sub(value)
363 }
364}
365
366impl From<BlockHeight> for TargetHeight {
367 fn from(value: BlockHeight) -> Self {
368 TargetHeight(value)
369 }
370}
371
372impl From<TargetHeight> for BlockHeight {
373 fn from(value: TargetHeight) -> Self {
374 value.0
375 }
376}
377
378impl From<TargetHeight> for u32 {
379 fn from(value: TargetHeight) -> Self {
380 u32::from(value.0)
381 }
382}
383
384impl From<u32> for TargetHeight {
385 fn from(value: u32) -> Self {
386 TargetHeight(BlockHeight::from_u32(value))
387 }
388}
389
390impl<I> Add<I> for TargetHeight
391where
392 BlockHeight: Add<I>,
393{
394 type Output = <BlockHeight as Add<I>>::Output;
395
396 fn add(self, rhs: I) -> Self::Output {
397 self.0 + rhs
398 }
399}
400
401impl<I> Sub<I> for TargetHeight
402where
403 BlockHeight: Sub<I>,
404{
405 type Output = <BlockHeight as Sub<I>>::Output;
406
407 fn sub(self, rhs: I) -> Self::Output {
408 self.0 - rhs
409 }
410}
411
412#[derive(Clone, Copy, Debug, PartialEq, Eq)]
421pub struct ConfirmationsPolicyError;
422
423impl core::fmt::Display for ConfirmationsPolicyError {
424 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
425 write!(
426 f,
427 "Trusted confirmations must not exceed untrusted confirmations"
428 )
429 }
430}
431
432#[derive(Clone, Copy, Debug, PartialEq, Eq)]
434pub struct ConfirmationsPolicy {
435 trusted: NonZeroU32,
436 untrusted: NonZeroU32,
437 #[cfg(feature = "transparent-inputs")]
438 allow_zero_conf_shielding: bool,
439}
440
441impl Default for ConfirmationsPolicy {
452 fn default() -> Self {
453 ConfirmationsPolicy {
454 trusted: NonZeroU32::MIN.saturating_add(2),
456 untrusted: NonZeroU32::MIN.saturating_add(9),
458 #[cfg(feature = "transparent-inputs")]
459 allow_zero_conf_shielding: true,
460 }
461 }
462}
463
464impl ConfirmationsPolicy {
465 pub const MIN: Self = ConfirmationsPolicy {
469 trusted: NonZeroU32::MIN,
470 untrusted: NonZeroU32::MIN,
471 #[cfg(feature = "transparent-inputs")]
472 allow_zero_conf_shielding: true,
473 };
474
475 pub fn new(
485 trusted: NonZeroU32,
486 untrusted: NonZeroU32,
487 #[cfg(feature = "transparent-inputs")] allow_zero_conf_shielding: bool,
488 ) -> Result<Self, ConfirmationsPolicyError> {
489 if trusted > untrusted {
490 Err(ConfirmationsPolicyError)
491 } else {
492 Ok(Self {
493 trusted,
494 untrusted,
495 #[cfg(feature = "transparent-inputs")]
496 allow_zero_conf_shielding,
497 })
498 }
499 }
500
501 pub fn new_symmetrical(
507 min_confirmations: NonZeroU32,
508 #[cfg(feature = "transparent-inputs")] allow_zero_conf_shielding: bool,
509 ) -> Self {
510 Self {
511 trusted: min_confirmations,
512 untrusted: min_confirmations,
513 #[cfg(feature = "transparent-inputs")]
514 allow_zero_conf_shielding,
515 }
516 }
517
518 #[cfg(any(test, feature = "test-dependencies"))]
525 pub fn new_unchecked(
526 trusted: u32,
527 untrusted: u32,
528 #[cfg(feature = "transparent-inputs")] allow_zero_conf_shielding: bool,
529 ) -> Self {
530 Self::new(
531 NonZeroU32::new(trusted).expect("trusted must be nonzero"),
532 NonZeroU32::new(untrusted).expect("untrusted must be nonzero"),
533 #[cfg(feature = "transparent-inputs")]
534 allow_zero_conf_shielding,
535 )
536 .expect("trusted must be <= untrusted")
537 }
538
539 #[cfg(any(test, feature = "test-dependencies"))]
545 pub fn new_symmetrical_unchecked(
546 min_confirmations: u32,
547 #[cfg(feature = "transparent-inputs")] allow_zero_conf_shielding: bool,
548 ) -> Self {
549 Self::new_symmetrical(
550 NonZeroU32::new(min_confirmations).expect("min_confirmations must be nonzero"),
551 #[cfg(feature = "transparent-inputs")]
552 allow_zero_conf_shielding,
553 )
554 }
555
556 pub fn trusted(&self) -> NonZeroU32 {
562 self.trusted
563 }
564
565 pub fn untrusted(&self) -> NonZeroU32 {
571 self.untrusted
572 }
573
574 pub fn anchor_height(&self, target_height: TargetHeight) -> BlockHeight {
581 target_height.saturating_sub(u32::from(self.trusted()))
582 }
583
584 pub fn bucketed(
614 &self,
615 grid: AnchorGrid,
616 target_height: TargetHeight,
617 activation_height: BlockHeight,
618 ) -> Option<Self> {
619 let most_recent = grid.boundary_at_or_below(self.anchor_height(target_height));
625 let boundary = grid.boundary_before(most_recent)?;
626
627 if boundary <= activation_height {
633 return None;
634 }
635 let bucketed = u32::from(target_height).checked_sub(u32::from(boundary))?;
636 let trusted = NonZeroU32::new(bucketed)?;
637 Self::new(
638 trusted,
639 core::cmp::max(self.untrusted(), trusted),
640 #[cfg(feature = "transparent-inputs")]
641 self.allow_zero_conf_shielding(),
642 )
643 .ok()
644 }
645
646 #[cfg(feature = "transparent-inputs")]
649 pub fn allow_zero_conf_shielding(&self) -> bool {
650 self.allow_zero_conf_shielding
651 }
652
653 #[allow(clippy::too_many_arguments)]
673 pub fn confirmations_until_spendable(
674 &self,
675 target_height: TargetHeight,
676 pool_type: PoolType,
677 receiving_key_scope: Option<Scope>,
678 mined_height: Option<BlockHeight>,
679 tx_trusted: bool,
680 max_shielding_input_height: Option<BlockHeight>,
681 tx_shielding_inputs_trusted: bool,
682 ) -> u32 {
683 let trusted_height = target_height.saturating_sub(u32::from(self.trusted));
686 let untrusted_height = target_height.saturating_sub(u32::from(self.untrusted));
689
690 let confs_for_trusted =
696 mined_height.map_or(u32::from(self.trusted), |h| h - trusted_height);
697 let confs_for_untrusted =
698 mined_height.map_or(u32::from(self.untrusted), |h| h - untrusted_height);
699 match pool_type {
700 PoolType::Transparent => {
701 #[cfg(feature = "transparent-inputs")]
702 let zc_shielding = self.allow_zero_conf_shielding;
703 #[cfg(not(feature = "transparent-inputs"))]
704 let zc_shielding = false;
705
706 if zc_shielding {
707 0
708 } else if tx_trusted || receiving_key_scope == Some(Scope::Internal) {
709 confs_for_trusted
710 } else {
711 confs_for_untrusted
712 }
713 }
714 PoolType::Shielded(_) => {
715 if tx_trusted {
716 confs_for_trusted
717 } else if receiving_key_scope == Some(Scope::Internal) {
718 if let Some(h) = max_shielding_input_height {
722 if tx_shielding_inputs_trusted {
723 h - trusted_height
724 } else {
725 h - untrusted_height
726 }
727 } else {
728 confs_for_trusted
729 }
730 } else {
731 confs_for_untrusted
732 }
733 }
734 }
735 }
736}
737
738#[allow(clippy::too_many_arguments)]
776#[allow(clippy::type_complexity)]
777pub fn propose_transfer<DbT, ParamsT, InputsT, ChangeT, CommitmentTreeErrT>(
778 wallet_db: &mut DbT,
779 params: &ParamsT,
780 spend_from_account: <DbT as InputSource>::AccountId,
781 input_selector: &InputsT,
782 change_strategy: &ChangeT,
783 request: zip321::TransactionRequest,
784 confirmations_policy: ConfirmationsPolicy,
785 spend_policy: &input_selection::SpendPolicy,
786 lock_inputs: Option<LockRequest>,
787 proposed_version: Option<TxVersion>,
788) -> Result<
789 Proposal<ChangeT::FeeRule, <DbT as InputSource>::NoteRef>,
790 ProposeTransferErrT<DbT, CommitmentTreeErrT, InputsT, ChangeT>,
791>
792where
793 DbT: WalletWrite + InputSource<Error = <DbT as WalletRead>::Error>,
794 <DbT as InputSource>::NoteRef: Copy + Eq + Ord,
795 ParamsT: consensus::Parameters + Clone,
796 InputsT: InputSelector<InputSource = DbT>,
797 ChangeT: ChangeStrategy<MetaSource = DbT>,
798{
799 let maybe_intial_heights = wallet_db
804 .get_target_and_anchor_heights(confirmations_policy.trusted)
805 .map_err(InputSelectorError::DataSource)?;
806 let (target_height, anchor_height) =
807 maybe_intial_heights.ok_or_else(|| InputSelectorError::SyncRequired)?;
808
809 let zip318 = wallet_db.pool_migration_params(params);
814
815 #[cfg(feature = "orchard")]
838 let canonical_fee = crate::fees::canonical_crossing_fee(params, target_height.into()).ok();
839
840 #[cfg(feature = "orchard")]
843 let bucketed_policy = canonical_crossing_candidate(params, &zip318, &request, target_height)
844 .then(|| params.activation_height(NetworkUpgrade::Nu6_3))
845 .flatten()
846 .and_then(|activation| {
847 confirmations_policy.bucketed(zip318.anchor_grid(), target_height, activation)
848 })
849 .filter(|_| spend_policy.permits_shielded(ShieldedPool::Orchard));
852
853 #[cfg(feature = "orchard")]
863 let bucketed_policy = match bucketed_policy {
864 Some(policy) => wallet_db
865 .anchor_computable(ShieldedPool::Orchard, policy.anchor_height(target_height))
866 .map_err(|e| Error::from(InputSelectorError::DataSource(e)))?
867 .then_some(policy),
868 None => None,
869 };
870
871 #[cfg(feature = "orchard")]
872 let canonical_attempt = bucketed_policy.map(|bucketed_policy| {
873 let orchard_only = input_selection::SpendPolicy::shielded_pools([ShieldedPool::Orchard])
881 .with_locked_input_policy(spend_policy.locked_input_policy().clone())
882 .with_note_selection(input_selection::NoteSelection::PreferSingle);
883
884 input_selector.propose_transaction(
885 params,
886 wallet_db,
887 target_height,
888 bucketed_policy.anchor_height(target_height),
889 &zip318,
890 bucketed_policy,
891 spend_from_account,
892 request.clone(),
893 change_strategy,
894 &orchard_only,
895 proposed_version,
896 )
897 });
898
899 #[cfg(feature = "orchard")]
906 let canonical_proposal = match canonical_attempt {
907 Some(Ok(proposal)) => {
908 let is_canonical = proposal.steps().len() == 1
913 && canonical_fee.is_some_and(|fee| {
914 proposal.steps().first().is_canonical_crossing(&zip318, fee)
915 });
916 is_canonical.then_some(proposal)
917 }
918 Some(Err(InputSelectorError::InsufficientFunds { .. })) | None => None,
919 Some(Err(other)) => return Err(other.into()),
920 };
921
922 #[cfg(not(feature = "orchard"))]
923 let canonical_proposal = None;
924
925 let proposal = match canonical_proposal {
926 Some(proposal) => proposal,
927 None => input_selector.propose_transaction(
928 params,
929 wallet_db,
930 target_height,
931 anchor_height,
932 &zip318,
933 confirmations_policy,
934 spend_from_account,
935 request,
936 change_strategy,
937 spend_policy,
938 proposed_version,
939 )?,
940 };
941 proposal.check_transaction_size()?;
942 if let Some(request) = lock_inputs {
943 let lock_expiry_height = target_height + request.for_blocks();
944 lock_proposal_inputs(wallet_db, &proposal, request.owner(), lock_expiry_height)?;
945 }
946
947 Ok(proposal.with_proposed_version(proposed_version))
950}
951
952#[cfg(feature = "orchard")]
962fn canonical_crossing_candidate<ParamsT: consensus::Parameters>(
963 params: &ParamsT,
964 zip318: &PoolMigrationParams,
965 request: &zip321::TransactionRequest,
966 target_height: TargetHeight,
967) -> bool {
968 params.is_nu_active(NetworkUpgrade::Nu6_3, target_height.into())
969 && match request.payments().values().collect::<Vec<_>>()[..] {
970 [payment] => payment
971 .amount()
972 .is_some_and(|amount| zip318.is_canonical_denomination(amount)),
973 _ => false,
974 }
975}
976
977#[cfg(feature = "orchard")]
984fn step_is_canonical_crossing<DbT, ParamsT, N>(
985 wallet_db: &DbT,
986 params: &ParamsT,
987 step: &Step<N>,
988 target_height: TargetHeight,
989) -> bool
990where
991 DbT: WalletRead,
992 ParamsT: consensus::Parameters,
993{
994 crate::fees::canonical_crossing_fee(params, target_height.into())
995 .is_ok_and(|fee| step.is_canonical_crossing(&wallet_db.pool_migration_params(params), fee))
996}
997
998#[allow(clippy::too_many_arguments)]
1028#[allow(clippy::type_complexity)]
1029pub fn propose_standard_transfer_to_address<DbT, ParamsT, CommitmentTreeErrT>(
1030 wallet_db: &mut DbT,
1031 params: &ParamsT,
1032 fee_rule: StandardFeeRule,
1033 spend_from_account: <DbT as InputSource>::AccountId,
1034 confirmations_policy: ConfirmationsPolicy,
1035 to: &Address,
1036 amount: Zatoshis,
1037 memo: Option<MemoBytes>,
1038 change_memo: Option<MemoBytes>,
1039 fallback_change_pool: ShieldedPool,
1040 lock_inputs: Option<LockRequest>,
1041 proposed_version: Option<TxVersion>,
1042) -> Result<
1043 Proposal<StandardFeeRule, DbT::NoteRef>,
1044 ProposeTransferErrT<
1045 DbT,
1046 CommitmentTreeErrT,
1047 GreedyInputSelector<DbT>,
1048 SingleOutputChangeStrategy<DbT>,
1049 >,
1050>
1051where
1052 ParamsT: consensus::Parameters + Clone,
1053 DbT: InputSource,
1054 DbT: WalletWrite,
1055 DbT: WalletRead<Error = <DbT as InputSource>::Error, AccountId = <DbT as InputSource>::AccountId>,
1056 DbT::NoteRef: Copy + Eq + Ord,
1057{
1058 let request = zip321::TransactionRequest::new(vec![
1059 Payment::new(
1060 to.to_zcash_address(params),
1061 Some(amount),
1062 memo,
1063 None,
1064 None,
1065 vec![],
1066 )
1067 .map_err(Error::Payment)?,
1068 ])
1069 .expect(
1070 "It should not be possible for this to violate ZIP 321 request construction invariants.",
1071 );
1072
1073 let input_selector = GreedyInputSelector::<DbT>::new();
1074 let change_strategy = SingleOutputChangeStrategy::<DbT>::new(
1075 fee_rule,
1076 change_memo,
1077 fallback_change_pool,
1078 DustOutputPolicy::default(),
1079 );
1080
1081 propose_transfer(
1082 wallet_db,
1083 params,
1084 spend_from_account,
1085 &input_selector,
1086 &change_strategy,
1087 request,
1088 confirmations_policy,
1089 &input_selection::SpendPolicy::default(),
1090 lock_inputs,
1091 proposed_version,
1092 )
1093}
1094
1095#[allow(clippy::too_many_arguments)]
1143#[allow(clippy::type_complexity)]
1144pub fn propose_send_max_transfer<DbT, ParamsT, FeeRuleT, CommitmentTreeErrT>(
1145 wallet_db: &mut DbT,
1146 params: &ParamsT,
1147 spend_from_account: <DbT as InputSource>::AccountId,
1148 spend_pools: &[ShieldedPool],
1149 fee_rule: &FeeRuleT,
1150 recipient: ZcashAddress,
1151 memo: Option<MemoBytes>,
1152 mode: MaxSpendMode,
1153 confirmations_policy: ConfirmationsPolicy,
1154 locked_input_policy: &input_selection::LockedInputPolicy,
1155 lock_inputs: Option<LockRequest>,
1156) -> Result<
1157 Proposal<FeeRuleT, <DbT as InputSource>::NoteRef>,
1158 ProposeSendMaxErrT<DbT, CommitmentTreeErrT, FeeRuleT>,
1159>
1160where
1161 DbT: WalletWrite + InputSource<Error = <DbT as WalletRead>::Error>,
1162 <DbT as InputSource>::NoteRef: Copy + Eq + Ord,
1163 ParamsT: consensus::Parameters + Clone,
1164 FeeRuleT: FeeRule + Clone,
1165{
1166 let (target_height, anchor_height) = wallet_db
1167 .get_target_and_anchor_heights(confirmations_policy.trusted())
1168 .map_err(|e| Error::from(InputSelectorError::DataSource(e)))?
1169 .ok_or_else(|| Error::from(InputSelectorError::SyncRequired))?;
1170
1171 if memo.is_some() && !recipient.can_receive_memo() {
1172 return Err(Error::Payment(zip321::PaymentError::TransparentMemo));
1173 }
1174
1175 let proposal = propose_send_max(
1176 params,
1177 wallet_db,
1178 fee_rule,
1179 spend_from_account,
1180 spend_pools,
1181 target_height,
1182 anchor_height,
1183 mode,
1184 confirmations_policy,
1185 recipient,
1186 memo,
1187 locked_input_policy,
1188 )?;
1189
1190 if let Some(request) = lock_inputs {
1191 let lock_expiry_height = target_height + request.for_blocks();
1192 lock_proposal_inputs(wallet_db, &proposal, request.owner(), lock_expiry_height)?;
1193 }
1194
1195 Ok(proposal)
1196}
1197
1198#[cfg(feature = "transparent-inputs")]
1209#[allow(clippy::too_many_arguments)]
1210#[allow(clippy::type_complexity)]
1211pub fn propose_shielding<DbT, ParamsT, InputsT, ChangeT, CommitmentTreeErrT>(
1212 wallet_db: &mut DbT,
1213 params: &ParamsT,
1214 input_selector: &InputsT,
1215 change_strategy: &ChangeT,
1216 shielding_threshold: Zatoshis,
1217 from_addrs: &[TransparentAddress],
1218 to_account: <DbT as InputSource>::AccountId,
1219 confirmations_policy: ConfirmationsPolicy,
1220 output_filter: CoinbaseFilter,
1221 lock_inputs: Option<LockRequest>,
1222) -> Result<
1223 Proposal<ChangeT::FeeRule, Infallible>,
1224 ProposeShieldingErrT<DbT, CommitmentTreeErrT, InputsT, ChangeT>,
1225>
1226where
1227 ParamsT: consensus::Parameters,
1228 DbT: WalletWrite + InputSource<Error = <DbT as WalletRead>::Error>,
1229 InputsT: ShieldingSelector<InputSource = DbT>,
1230 ChangeT: ChangeStrategy<MetaSource = DbT>,
1231{
1232 let (target_height, anchor_height) = wallet_db
1233 .get_target_and_anchor_heights(confirmations_policy.trusted)
1234 .map_err(|e| Error::from(InputSelectorError::DataSource(e)))?
1235 .ok_or_else(|| Error::from(InputSelectorError::SyncRequired))?;
1236
1237 let proposal = input_selector
1238 .propose_shielding(
1239 params,
1240 wallet_db,
1241 change_strategy,
1242 shielding_threshold,
1243 from_addrs,
1244 to_account,
1245 target_height,
1246 anchor_height,
1247 &wallet_db.pool_migration_params(params),
1248 confirmations_policy,
1249 output_filter,
1250 )
1251 .map_err(Error::from)?;
1252
1253 proposal.check_transaction_size()?;
1254
1255 if let Some(request) = lock_inputs {
1256 let lock_expiry_height = target_height + request.for_blocks();
1257 lock_proposal_inputs(wallet_db, &proposal, request.owner(), lock_expiry_height)?;
1258 }
1259
1260 Ok(proposal)
1261}
1262
1263#[cfg(feature = "transparent-inputs")]
1267pub type ProposeShieldingCoinbaseErrT<DbT, CommitmentTreeErrT, InputsT, FeeRuleT> = Error<
1268 <DbT as WalletRead>::Error,
1269 CommitmentTreeErrT,
1270 <InputsT as ShieldingSelector>::Error,
1271 <FeeRuleT as FeeRule>::Error,
1272 <FeeRuleT as FeeRule>::Error,
1273 Infallible,
1274>;
1275
1276#[cfg(feature = "transparent-inputs")]
1309#[allow(clippy::too_many_arguments)]
1310#[allow(clippy::type_complexity)]
1311pub fn propose_shielding_coinbase<DbT, ParamsT, InputsT, FeeRuleT, CommitmentTreeErrT>(
1312 wallet_db: &mut DbT,
1313 params: &ParamsT,
1314 input_selector: &InputsT,
1315 fee_rule: &FeeRuleT,
1316 shielding_threshold: Zatoshis,
1317 from_addrs: &[TransparentAddress],
1318 to_address: ZcashAddress,
1319 memo: Option<MemoBytes>,
1320 limit: Option<usize>,
1321 lock_inputs: Option<LockRequest>,
1322) -> Result<
1323 Proposal<FeeRuleT, Infallible>,
1324 ProposeShieldingCoinbaseErrT<DbT, CommitmentTreeErrT, InputsT, FeeRuleT>,
1325>
1326where
1327 ParamsT: consensus::Parameters,
1328 DbT: WalletWrite + InputSource<Error = <DbT as WalletRead>::Error>,
1329 InputsT: ShieldingSelector<InputSource = DbT>,
1330 FeeRuleT: FeeRule + Clone,
1331{
1332 let (target_height, anchor_height) = wallet_db
1333 .get_target_and_anchor_heights(ConfirmationsPolicy::default().trusted)
1334 .map_err(|e| Error::from(InputSelectorError::DataSource(e)))?
1335 .ok_or_else(|| Error::from(InputSelectorError::SyncRequired))?;
1336
1337 let proposal = input_selector
1338 .propose_shielding_coinbase(
1339 params,
1340 wallet_db,
1341 fee_rule,
1342 shielding_threshold,
1343 from_addrs,
1344 to_address,
1345 memo,
1346 limit,
1347 target_height,
1348 anchor_height,
1349 )
1350 .map_err(Error::from)?;
1351
1352 if let Some(request) = lock_inputs {
1353 let lock_expiry_height = target_height + request.for_blocks();
1354 lock_proposal_inputs(wallet_db, &proposal, request.owner(), lock_expiry_height)?;
1355 }
1356
1357 Ok(proposal)
1358}
1359
1360struct StepResult<AccountId> {
1361 build_result: BuildResult,
1362 outputs: Vec<SentTransactionOutput<AccountId>>,
1363 fee_amount: Zatoshis,
1364 #[cfg(feature = "transparent-inputs")]
1365 utxos_spent: Vec<OutPoint>,
1366}
1367
1368pub struct SpendingKeys {
1378 usk: UnifiedSpendingKey,
1379 #[cfg(feature = "transparent-key-import")]
1380 standalone_transparent_keys: HashMap<TransparentAddress, Vec<secp256k1::SecretKey>>,
1381}
1382
1383impl SpendingKeys {
1384 pub fn new(
1386 usk: UnifiedSpendingKey,
1387 #[cfg(feature = "transparent-key-import")] standalone_transparent_keys: HashMap<
1388 TransparentAddress,
1389 Vec<secp256k1::SecretKey>,
1390 >,
1391 ) -> Self {
1392 Self {
1393 usk,
1394 #[cfg(feature = "transparent-key-import")]
1395 standalone_transparent_keys,
1396 }
1397 }
1398
1399 pub fn from_unified_spending_key(usk: UnifiedSpendingKey) -> Self {
1402 Self {
1403 usk,
1404 #[cfg(feature = "transparent-key-import")]
1405 standalone_transparent_keys: HashMap::new(),
1406 }
1407 }
1408}
1409
1410#[cfg(feature = "transparent-key-import")]
1411impl Drop for SpendingKeys {
1412 fn drop(&mut self) {
1413 for secret_key in self.standalone_transparent_keys.values_mut().flatten() {
1414 secret_key.non_secure_erase();
1415 }
1416 }
1417}
1418
1419#[allow(clippy::too_many_arguments)]
1445#[allow(clippy::type_complexity)]
1446pub fn create_proposed_transactions<DbT, ParamsT, InputsErrT, FeeRuleT, ChangeErrT, N>(
1447 wallet_db: &mut DbT,
1448 params: &ParamsT,
1449 clock: &impl Clock,
1450 rng: &mut impl CryptoRng,
1451 spend_prover: &impl SpendProver,
1452 output_prover: &impl OutputProver,
1453 spending_keys: &SpendingKeys,
1454 ovk_policy: OvkPolicy,
1455 proposal: &Proposal<FeeRuleT, N>,
1456 expiry_height: Option<BlockHeight>,
1457) -> Result<NonEmpty<TxId>, CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>>
1458where
1459 DbT: WalletWrite + WalletCommitmentTrees,
1460 ParamsT: consensus::Parameters + Clone,
1461 FeeRuleT: FeeRule,
1462{
1463 let proposed_version = proposal.proposed_version();
1466
1467 proposal.check_transaction_size()?;
1471
1472 if let Some(expiry_height) = expiry_height {
1473 let min_target_height = BlockHeight::from(proposal.min_target_height());
1474 if expiry_height != consensus::H0 && expiry_height < min_target_height {
1475 return Err(Error::ExpiryHeightBelowTargetHeight {
1476 expiry_height,
1477 min_target_height,
1478 });
1479 }
1480 }
1481
1482 #[cfg(feature = "transparent-inputs")]
1486 let mut unused_transparent_outputs = HashMap::new();
1487
1488 let account_id = wallet_db
1489 .get_account_for_ufvk(&spending_keys.usk.to_unified_full_viewing_key())
1490 .map_err(Error::DataSource)?
1491 .ok_or(Error::KeyNotRecognized)?
1492 .id();
1493
1494 let now = clock.now();
1495
1496 let mut step_results = Vec::with_capacity(proposal.steps().len());
1497 for step in proposal.steps() {
1498 let step_result: StepResult<_> = create_proposed_transaction(
1499 wallet_db,
1500 params,
1501 &mut *rng,
1502 spend_prover,
1503 output_prover,
1504 spending_keys,
1505 account_id,
1506 ovk_policy.clone(),
1507 proposal.fee_rule(),
1508 proposal.min_target_height(),
1509 proposal.confirmations_policy(),
1510 &step_results,
1511 step,
1512 #[cfg(feature = "transparent-inputs")]
1513 &mut unused_transparent_outputs,
1514 proposed_version,
1515 expiry_height,
1516 now,
1517 )?;
1518 step_results.push((step, step_result));
1519 }
1520
1521 #[cfg(feature = "transparent-inputs")]
1523 for so in unused_transparent_outputs.into_keys() {
1524 if let StepOutputIndex::Change(i) = so.output_index() {
1525 if step_results[so.step_index()].0.balance().proposed_change()[i].is_ephemeral() {
1527 return Err(ProposalError::EphemeralOutputLeftUnspent(so).into());
1528 }
1529 }
1530 }
1531
1532 let created = time::OffsetDateTime::from(now);
1533
1534 let mut transactions = Vec::with_capacity(step_results.len());
1538 let mut txids = Vec::with_capacity(step_results.len());
1539 #[allow(unused_variables)]
1540 for (_, step_result) in step_results.iter() {
1541 let tx = step_result.build_result.transaction();
1542 transactions.push(SentTransaction::new(
1543 tx,
1544 created,
1545 proposal.min_target_height(),
1546 account_id,
1547 &step_result.outputs,
1548 step_result.fee_amount,
1549 #[cfg(feature = "transparent-inputs")]
1550 &step_result.utxos_spent,
1551 ));
1552 txids.push(tx.txid());
1553 }
1554
1555 wallet_db
1556 .store_transactions_to_be_sent(&transactions)
1557 .map_err(Error::DataSource)?;
1558
1559 Ok(NonEmpty::from_vec(txids).expect("proposal.steps is NonEmpty"))
1560}
1561
1562#[derive(Debug, Clone)]
1565enum ShieldedBuildRecipient<AccountId> {
1566 External {
1567 recipient_address: ZcashAddress,
1568 output_pool: PoolType,
1569 },
1570 InternalShielded {
1571 receiving_account: AccountId,
1572 external_address: Option<ZcashAddress>,
1573 },
1574}
1575
1576impl<AccountId> ShieldedBuildRecipient<AccountId> {
1577 fn into_recipient(self, note: impl FnOnce() -> Note) -> Recipient<AccountId> {
1578 match self {
1579 ShieldedBuildRecipient::External {
1580 recipient_address,
1581 output_pool,
1582 } => Recipient::External {
1583 recipient_address,
1584 output_pool,
1585 },
1586 ShieldedBuildRecipient::InternalShielded {
1587 receiving_account,
1588 external_address,
1589 } => Recipient::InternalShielded {
1590 receiving_account,
1591 external_address,
1592 note: Box::new(note()),
1593 },
1594 }
1595 }
1596}
1597
1598#[derive(Debug, Clone)]
1602enum TransparentBuildRecipient<AccountId> {
1603 External {
1604 recipient_address: ZcashAddress,
1605 output_pool: PoolType,
1606 },
1607 #[cfg(feature = "transparent-inputs")]
1608 EphemeralTransparent {
1609 receiving_account: AccountId,
1610 ephemeral_address: TransparentAddress,
1611 },
1612 #[cfg(feature = "transparent-inputs")]
1613 InternalTransparent {
1614 receiving_account: AccountId,
1615 recipient_address: TransparentAddress,
1616 },
1617 #[cfg(not(feature = "transparent-inputs"))]
1623 #[doc(hidden)]
1624 #[allow(dead_code)]
1625 Unconstructible(
1626 core::marker::PhantomData<AccountId>,
1627 core::convert::Infallible,
1628 ),
1629}
1630
1631impl<AccountId> TransparentBuildRecipient<AccountId> {
1632 fn into_recipient(
1633 self,
1634 #[cfg(feature = "transparent-inputs")] outpoint: OutPoint,
1635 ) -> Recipient<AccountId> {
1636 match self {
1637 TransparentBuildRecipient::External {
1638 recipient_address,
1639 output_pool,
1640 } => Recipient::External {
1641 recipient_address,
1642 output_pool,
1643 },
1644 #[cfg(feature = "transparent-inputs")]
1645 TransparentBuildRecipient::EphemeralTransparent {
1646 receiving_account,
1647 ephemeral_address,
1648 } => Recipient::EphemeralTransparent {
1649 receiving_account,
1650 ephemeral_address,
1651 outpoint,
1652 },
1653 #[cfg(feature = "transparent-inputs")]
1654 TransparentBuildRecipient::InternalTransparent {
1655 receiving_account,
1656 recipient_address,
1657 } => Recipient::InternalTransparent {
1658 receiving_account,
1659 recipient_address,
1660 },
1661 #[cfg(not(feature = "transparent-inputs"))]
1662 TransparentBuildRecipient::Unconstructible(_, absurd) => match absurd {},
1663 }
1664 }
1665}
1666
1667#[allow(clippy::type_complexity)]
1668struct BuildState<P, AccountId> {
1669 #[cfg(feature = "transparent-inputs")]
1670 step_index: usize,
1671 builder: Builder<P, ()>,
1672 #[cfg(feature = "transparent-inputs")]
1673 transparent_input_addresses: HashMap<TransparentAddress, TransparentAddressMetadata>,
1674 #[cfg(feature = "orchard")]
1675 orchard_output_meta: Vec<(
1676 ShieldedBuildRecipient<AccountId>,
1677 Zatoshis,
1678 Option<MemoBytes>,
1679 )>,
1680 #[cfg(feature = "orchard")]
1681 ironwood_output_meta: Vec<(
1682 ShieldedBuildRecipient<AccountId>,
1683 Zatoshis,
1684 Option<MemoBytes>,
1685 )>,
1686 sapling_output_meta: Vec<(
1687 ShieldedBuildRecipient<AccountId>,
1688 Zatoshis,
1689 Option<MemoBytes>,
1690 )>,
1691 transparent_output_meta: Vec<(
1692 TransparentBuildRecipient<AccountId>,
1693 TransparentAddress,
1694 Zatoshis,
1695 StepOutputIndex,
1696 )>,
1697 #[cfg(feature = "transparent-inputs")]
1698 utxos_spent: Vec<OutPoint>,
1699}
1700
1701fn check_recipient_expiry(
1711 ua: &UnifiedAddress,
1712 min_target_height: TargetHeight,
1713 tx_expiry_height: Option<BlockHeight>,
1714 now: SystemTime,
1715) -> Result<(), AddressExpiryError> {
1716 if let Some(address_expiry) = ua.expiry_height() {
1717 let chain_height = min_target_height.saturating_sub(1);
1718 if chain_height > address_expiry {
1719 return Err(AddressExpiryError::HeightExpired {
1720 address_expiry,
1721 chain_height,
1722 });
1723 }
1724
1725 match tx_expiry_height {
1726 None => {
1727 return Err(AddressExpiryError::TransactionExpiryDisabled { address_expiry });
1728 }
1729 Some(transaction_expiry) if transaction_expiry > address_expiry => {
1730 return Err(AddressExpiryError::ExpiryHeightConflict {
1731 address_expiry,
1732 transaction_expiry,
1733 });
1734 }
1735 Some(_) => {}
1736 }
1737 }
1738
1739 if let Some(expiry_time) = ua.expiry_time() {
1740 let now_secs = now
1743 .duration_since(SystemTime::UNIX_EPOCH)
1744 .map(|d| d.as_secs())
1745 .unwrap_or(0);
1746 if now_secs > expiry_time {
1747 return Err(AddressExpiryError::TimeExpired { expiry_time });
1748 }
1749 }
1750
1751 Ok(())
1752}
1753
1754#[allow(clippy::too_many_arguments)]
1758#[allow(clippy::type_complexity)]
1759fn build_proposed_transaction<DbT, ParamsT, InputsErrT, FeeRuleT, ChangeErrT, N>(
1760 wallet_db: &mut DbT,
1761 params: &ParamsT,
1762 ufvk: &UnifiedFullViewingKey,
1763 account_id: <DbT as WalletRead>::AccountId,
1764 ovk_policy: OvkPolicy,
1765 min_target_height: TargetHeight,
1766 confirmations_policy: ConfirmationsPolicy,
1767 prior_step_results: &[(&Step<N>, StepResult<<DbT as WalletRead>::AccountId>)],
1768 proposal_step: &Step<N>,
1769 #[cfg(feature = "transparent-inputs")] unused_transparent_outputs: &mut HashMap<
1770 StepOutput,
1771 (TransparentAddress, OutPoint),
1772 >,
1773 proposed_version: Option<TxVersion>,
1774 orchard_pool_padding: BundlePadding,
1778 expiry_height: Option<BlockHeight>,
1781 now: SystemTime,
1783) -> Result<
1784 BuildState<ParamsT, <DbT as WalletRead>::AccountId>,
1785 CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>,
1786>
1787where
1788 DbT: WalletWrite + WalletCommitmentTrees,
1789 ParamsT: consensus::Parameters + Clone,
1790 FeeRuleT: FeeRule,
1791{
1792 #[cfg(feature = "transparent-inputs")]
1793 let step_index = prior_step_results.len();
1794
1795 #[allow(clippy::never_loop)]
1798 for input_ref in proposal_step.prior_step_inputs() {
1799 let (prior_step, _) = prior_step_results
1800 .get(input_ref.step_index())
1801 .ok_or(ProposalError::ReferenceError(*input_ref))?;
1802
1803 #[allow(unused_variables)]
1804 let output_pool = match input_ref.output_index() {
1805 StepOutputIndex::Payment(i) => prior_step.payment_pools().get(&i).cloned(),
1806 StepOutputIndex::Change(i) => match prior_step.balance().proposed_change().get(i) {
1807 Some(change) if !change.is_ephemeral() => {
1808 return Err(ProposalError::SpendsChange(*input_ref).into());
1809 }
1810 other => other.map(|change| change.output_pool()),
1811 },
1812 }
1813 .ok_or(ProposalError::ReferenceError(*input_ref))?;
1814
1815 #[cfg(feature = "transparent-inputs")]
1817 if output_pool != PoolType::TRANSPARENT {
1818 return Err(Error::ProposalNotSupported);
1819 }
1820 #[cfg(not(feature = "transparent-inputs"))]
1821 return Err(Error::ProposalNotSupported);
1822 }
1823
1824 let anchor_height = proposal_step
1831 .anchor_height()
1832 .unwrap_or_else(|| confirmations_policy.anchor_height(min_target_height));
1833
1834 let (sapling_anchor, sapling_inputs) = if proposal_step
1835 .involves(PoolType::Shielded(ShieldedPool::Sapling))
1836 {
1837 wallet_db.with_sapling_tree_mut::<_, _, Error<_, _, _, _, _, _>>(|sapling_tree| {
1838 let anchor = sapling_tree
1839 .root_at_checkpoint_id(&anchor_height)?
1840 .ok_or(ProposalError::AnchorNotFound(anchor_height))?
1841 .into();
1842
1843 let sapling_inputs = proposal_step
1844 .shielded_inputs()
1845 .map(|inputs| {
1846 inputs
1847 .notes()
1848 .iter()
1849 .filter_map(|selected| match selected.note() {
1850 Note::Sapling(note) => sapling_tree
1851 .witness_at_checkpoint_id_caching(
1852 selected.note_commitment_tree_position(),
1853 &anchor_height,
1854 )
1855 .and_then(|witness| {
1856 witness
1857 .ok_or(ShardTreeError::Query(QueryError::CheckpointPruned))
1858 })
1859 .map(|merkle_path| {
1860 Some((selected.spending_key_scope(), note, merkle_path))
1861 })
1862 .map_err(Error::from)
1863 .transpose(),
1864 #[cfg(feature = "orchard")]
1865 Note::Orchard { .. } => None,
1866 })
1867 .collect::<Result<Vec<_>, Error<_, _, _, _, _, _>>>()
1868 })
1869 .transpose()?
1870 .unwrap_or_default();
1871
1872 Ok((Some(anchor), sapling_inputs))
1873 })?
1874 } else {
1875 (None, vec![])
1876 };
1877
1878 #[cfg(feature = "orchard")]
1879 let (orchard_anchor, orchard_inputs) = if proposal_step
1880 .involves(PoolType::Shielded(ShieldedPool::Orchard))
1881 {
1882 wallet_db.with_orchard_tree_mut::<_, _, Error<_, _, _, _, _, _>>(|orchard_tree| {
1883 let anchor = orchard_tree
1884 .root_at_checkpoint_id(&anchor_height)?
1885 .ok_or(ProposalError::AnchorNotFound(anchor_height))?
1886 .into();
1887
1888 let orchard_inputs = proposal_step
1889 .shielded_inputs()
1890 .map(|inputs| {
1891 inputs
1892 .notes()
1893 .iter()
1894 .filter_map(|selected| match selected.note() {
1895 Note::Orchard {
1896 note,
1897 pool: orchard::ValuePool::Orchard,
1898 } => orchard_tree
1899 .witness_at_checkpoint_id_caching(
1900 selected.note_commitment_tree_position(),
1901 &anchor_height,
1902 )
1903 .and_then(|witness| {
1904 witness
1905 .ok_or(ShardTreeError::Query(QueryError::CheckpointPruned))
1906 })
1907 .map(|merkle_path| Some((note, merkle_path.into())))
1908 .map_err(Error::from)
1909 .transpose(),
1910 _ => None,
1911 })
1912 .collect::<Result<Vec<_>, Error<_, _, _, _, _, _>>>()
1913 })
1914 .transpose()?
1915 .unwrap_or_default();
1916
1917 Ok((Some(anchor), orchard_inputs))
1918 })?
1919 } else {
1920 (None, vec![])
1921 };
1922 #[cfg(not(feature = "orchard"))]
1923 let orchard_anchor = None;
1924
1925 #[cfg(feature = "orchard")]
1932 let (ironwood_anchor, ironwood_inputs) =
1933 if proposal_step.involves(PoolType::Shielded(ShieldedPool::Ironwood)) {
1934 wallet_db
1935 .with_ironwood_tree_mut::<_, _, Error<_, _, _, _, _, _>>(|ironwood_tree| {
1936 let anchor = ironwood_tree
1937 .root_at_checkpoint_id(&anchor_height)?
1938 .ok_or(ProposalError::AnchorNotFound(anchor_height))?
1939 .into();
1940
1941 let ironwood_inputs = proposal_step
1942 .shielded_inputs()
1943 .map(|inputs| {
1944 inputs
1945 .notes()
1946 .iter()
1947 .filter_map(|selected| match selected.note() {
1948 Note::Orchard {
1949 note,
1950 pool: orchard::ValuePool::Ironwood,
1951 } => ironwood_tree
1952 .witness_at_checkpoint_id_caching(
1953 selected.note_commitment_tree_position(),
1954 &anchor_height,
1955 )
1956 .and_then(|witness| {
1957 witness.ok_or(ShardTreeError::Query(
1958 QueryError::CheckpointPruned,
1959 ))
1960 })
1961 .map(|merkle_path| Some((note, merkle_path.into())))
1962 .map_err(Error::from)
1963 .transpose(),
1964 _ => None,
1965 })
1966 .collect::<Result<Vec<_>, Error<_, _, _, _, _, _>>>()
1967 })
1968 .transpose()?
1969 .unwrap_or_default();
1970
1971 Ok((Some(anchor), ironwood_inputs))
1972 })?
1973 .ok_or(Error::ProposalNotSupported)?
1974 } else {
1975 (None, vec![])
1976 };
1977
1978 #[cfg(not(feature = "orchard"))]
1979 let ironwood_anchor = None;
1980
1981 #[cfg(feature = "orchard")]
1990 let ironwood_padding = proposal_step.ironwood_bundle_padding();
1991 #[cfg(not(feature = "orchard"))]
1992 let ironwood_padding = orchard_pool_padding;
1993
1994 let mut builder = Builder::new(
1996 params.clone(),
1997 BlockHeight::from(min_target_height),
1998 BuildConfig::Standard {
1999 sapling_anchor,
2000 orchard_anchor,
2001 ironwood_anchor,
2002 orchard_padding: orchard_pool_padding,
2003 ironwood_padding,
2004 },
2005 );
2006 #[cfg(feature = "orchard")]
2013 let expiry_height = {
2014 if step_is_canonical_crossing(wallet_db, params, proposal_step, min_target_height) {
2015 match expiry_height {
2016 Some(requested) => {
2017 return Err(Error::ExpiryHeightConflictsWithCanonicalCrossing { requested });
2018 }
2019 None => Some(zcash_protocol::zip318::expiry_height(
2020 &zcash_protocol::zip318::BlockSpacing::for_network(params),
2021 min_target_height.into(),
2022 )),
2023 }
2024 } else {
2025 expiry_height
2026 }
2027 };
2028
2029 if let Some(expiry_height) = expiry_height {
2030 builder = builder.with_expiry_height(expiry_height);
2031 }
2032
2033 let tx_expiry_height = Some(builder.expiry_height()).filter(|h| *h != consensus::H0);
2035
2036 if let Some(version) = proposed_version {
2037 builder.propose_version(version)?;
2038 }
2039
2040 #[cfg(all(feature = "transparent-inputs", not(feature = "orchard")))]
2041 let has_shielded_inputs = !sapling_inputs.is_empty();
2042 #[cfg(all(feature = "transparent-inputs", feature = "orchard"))]
2043 let has_shielded_inputs =
2044 !(sapling_inputs.is_empty() && orchard_inputs.is_empty() && ironwood_inputs.is_empty());
2045
2046 let input_sources = NonEmpty::from_vec({
2047 let mut sources = vec![];
2048 if !sapling_inputs.is_empty() {
2049 sources.push(PoolType::SAPLING);
2050 }
2051 #[cfg(feature = "orchard")]
2052 if !orchard_inputs.is_empty() || !ironwood_inputs.is_empty() {
2053 sources.push(PoolType::ORCHARD);
2054 }
2055 #[cfg(feature = "transparent-inputs")]
2058 if !(proposal_step.transparent_inputs().is_empty()
2059 && proposal_step.prior_step_inputs().is_empty())
2060 {
2061 sources.push(PoolType::Transparent);
2062 }
2063 sources
2064 })
2065 .ok_or(Error::ProposalNotSupported)?;
2066
2067 for (_sapling_key_scope, sapling_note, merkle_path) in sapling_inputs.into_iter() {
2068 let key = match _sapling_key_scope {
2069 Scope::External => ufvk.sapling().map(|k| k.fvk().clone()),
2070 Scope::Internal => ufvk.sapling().map(|k| k.to_internal_fvk()),
2071 };
2072
2073 builder.add_sapling_spend(
2074 key.ok_or(Error::KeyNotAvailable(PoolType::SAPLING))?,
2075 sapling_note.clone(),
2076 merkle_path,
2077 )?;
2078 }
2079
2080 #[cfg(feature = "orchard")]
2083 for (orchard_note, merkle_path) in orchard_inputs.into_iter() {
2084 builder.add_orchard_spend(
2085 ufvk.orchard()
2086 .cloned()
2087 .ok_or(Error::KeyNotAvailable(PoolType::ORCHARD))?,
2088 *orchard_note,
2089 merkle_path,
2090 )?;
2091 }
2092
2093 #[cfg(feature = "orchard")]
2094 for (ironwood_note, merkle_path) in ironwood_inputs.into_iter() {
2095 builder.add_ironwood_spend(
2096 ufvk.orchard()
2097 .cloned()
2098 .ok_or(Error::KeyNotAvailable(PoolType::ORCHARD))?,
2099 *ironwood_note,
2100 merkle_path,
2101 )?;
2102 }
2103
2104 #[cfg(feature = "transparent-inputs")]
2105 let mut transparent_input_addresses =
2106 HashMap::<TransparentAddress, TransparentAddressMetadata>::new();
2107
2108 #[cfg(feature = "transparent-inputs")]
2109 let mut metadata_from_address = |addr: &TransparentAddress| -> Result<
2110 TransparentAddressMetadata,
2111 CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>,
2112 > {
2113 match transparent_input_addresses.get(addr) {
2114 Some(result) => Ok(result.clone()),
2115 None => {
2116 let result = wallet_db
2125 .get_transparent_address_metadata(account_id, addr)
2126 .map_err(InputSelectorError::DataSource)?
2127 .ok_or(Error::AddressNotRecognized(*addr))?;
2128
2129 transparent_input_addresses.insert(*addr, result.clone());
2130 Ok(result)
2131 }
2132 }
2133 };
2134
2135 #[cfg(feature = "transparent-inputs")]
2136 let utxos_spent = {
2137 let mut utxos_spent: Vec<OutPoint> = vec![];
2138 let mut add_transparent_input =
2139 |builder: &mut Builder<_, _>,
2140 utxos_spent: &mut Vec<_>,
2141 recipient_address: &TransparentAddress,
2142 outpoint: OutPoint,
2143 txout: TxOut<Zatoshis>|
2144 -> Result<(), CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>> {
2145 let metadata = metadata_from_address(recipient_address)?;
2146 match metadata.source() {
2147 TransparentAddressSource::Derived {
2148 scope,
2149 address_index,
2150 } => {
2151 let pubkey = ufvk
2152 .p2pkh()
2153 .ok_or(Error::KeyNotAvailable(PoolType::Transparent))?
2154 .derive_address_pubkey(*scope, *address_index)
2155 .expect("spending key derivation should not fail");
2156 utxos_spent.push(outpoint.clone());
2157 builder.add_transparent_p2pkh_input(pubkey, outpoint, txout)?;
2158 }
2159 #[cfg(feature = "transparent-key-import")]
2160 TransparentAddressSource::StandalonePubkey(pubkey) => {
2161 utxos_spent.push(outpoint.clone());
2162 builder.add_transparent_p2pkh_input(*pubkey, outpoint, txout)?;
2163 }
2164 #[cfg(feature = "transparent-key-import")]
2165 TransparentAddressSource::StandaloneScript(redeem_script) => {
2166 let from_chain =
2167 zs_script::FromChain::parse(&zs_script::Code(redeem_script.to_bytes()))
2168 .map_err(|_| ::transparent::builder::Error::UnsupportedScript)?;
2169 utxos_spent.push(outpoint.clone());
2170 builder.add_transparent_p2sh_input(from_chain, outpoint, txout)?;
2171 }
2172 #[cfg(feature = "transparent-key-import")]
2175 TransparentAddressSource::StandaloneAddress => {
2176 return Err(Error::KeyNotAvailable(PoolType::Transparent));
2177 }
2178 }
2179
2180 Ok(())
2181 };
2182
2183 for utxo in proposal_step.transparent_inputs() {
2184 add_transparent_input(
2185 &mut builder,
2186 &mut utxos_spent,
2187 utxo.recipient_address(),
2188 utxo.outpoint().clone(),
2189 utxo.txout().clone(),
2190 )?;
2191 }
2192 for input_ref in proposal_step.prior_step_inputs() {
2193 let (address, outpoint) = unused_transparent_outputs
2196 .remove(input_ref)
2197 .ok_or(Error::Proposal(ProposalError::ReferenceError(*input_ref)))?;
2198
2199 let txout = &prior_step_results[input_ref.step_index()]
2200 .1
2201 .build_result
2202 .transaction()
2203 .transparent_bundle()
2204 .ok_or(ProposalError::ReferenceError(*input_ref))?
2205 .vout[outpoint.n() as usize];
2206
2207 add_transparent_input(
2208 &mut builder,
2209 &mut utxos_spent,
2210 &address,
2211 outpoint,
2212 txout.clone(),
2213 )?;
2214 }
2215 utxos_spent
2216 };
2217
2218 let (external_ovk, internal_ovk) = match ovk_policy {
2219 OvkPolicy::Sender => (
2220 Some(
2221 ufvk.select_ovk(zip32::Scope::External, &input_sources)
2222 .ok_or(Error::KeyNotAvailable(input_sources.head))?,
2223 ),
2224 None,
2225 ),
2226 OvkPolicy::Custom {
2227 external_ovk,
2228 internal_ovk,
2229 } => (Some(external_ovk), internal_ovk),
2230 OvkPolicy::Discard => (None, None),
2231 };
2232
2233 #[cfg(feature = "orchard")]
2234 let mut orchard_output_meta: Vec<(ShieldedBuildRecipient<_>, Zatoshis, Option<MemoBytes>)> =
2235 vec![];
2236 #[cfg(feature = "orchard")]
2237 let mut ironwood_output_meta: Vec<(
2238 ShieldedBuildRecipient<_>,
2239 Zatoshis,
2240 Option<MemoBytes>,
2241 )> = vec![];
2242 let mut sapling_output_meta: Vec<(ShieldedBuildRecipient<_>, Zatoshis, Option<MemoBytes>)> =
2243 vec![];
2244 let mut transparent_output_meta: Vec<(
2245 TransparentBuildRecipient<_>,
2246 TransparentAddress,
2247 Zatoshis,
2248 StepOutputIndex,
2249 )> = vec![];
2250
2251 for (&payment_index, output_pool) in proposal_step.payment_pools() {
2252 let payment = proposal_step
2253 .transaction_request()
2254 .payments()
2255 .get(&payment_index)
2256 .expect(
2257 "The mapping between payment index and payment is checked in step construction",
2258 );
2259 let payment_amount = payment
2260 .amount()
2261 .ok_or(ProposalError::PaymentAmountMissing(payment_index))?;
2262 let recipient_address = payment.recipient_address();
2263
2264 let add_sapling_output =
2265 |builder: &mut Builder<_, _>,
2266 sapling_output_meta: &mut Vec<_>,
2267 to: sapling::PaymentAddress|
2268 -> Result<(), CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>> {
2269 let memo = payment.memo().map_or_else(MemoBytes::empty, |m| m.clone());
2270 builder.add_sapling_output(
2271 external_ovk.map(|k| k.into()),
2272 to,
2273 payment_amount,
2274 memo.clone(),
2275 )?;
2276 sapling_output_meta.push((
2277 ShieldedBuildRecipient::External {
2278 recipient_address: recipient_address.clone(),
2279 output_pool: PoolType::SAPLING,
2280 },
2281 payment_amount,
2282 Some(memo),
2283 ));
2284 Ok(())
2285 };
2286
2287 #[cfg(feature = "orchard")]
2288 let add_orchard_output =
2289 |builder: &mut Builder<_, _>,
2290 orchard_output_meta: &mut Vec<_>,
2291 to: orchard::Address|
2292 -> Result<(), CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>> {
2293 let memo = payment.memo().map_or_else(MemoBytes::empty, |m| m.clone());
2294 builder.add_orchard_output(
2295 external_ovk.map(|k| k.into()),
2296 to,
2297 payment_amount,
2298 memo.clone(),
2299 )?;
2300 orchard_output_meta.push((
2301 ShieldedBuildRecipient::External {
2302 recipient_address: recipient_address.clone(),
2303 output_pool: PoolType::ORCHARD,
2304 },
2305 payment_amount,
2306 Some(memo),
2307 ));
2308 Ok(())
2309 };
2310
2311 #[cfg(feature = "orchard")]
2312 let add_ironwood_output =
2313 |builder: &mut Builder<_, _>,
2314 ironwood_output_meta: &mut Vec<_>,
2315 to: orchard::Address|
2316 -> Result<(), CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>> {
2317 let memo = payment.memo().map_or_else(MemoBytes::empty, |m| m.clone());
2318 builder.add_ironwood_output(
2319 external_ovk.map(|k| k.into()),
2320 to,
2321 payment_amount,
2322 memo.clone(),
2323 )?;
2324 ironwood_output_meta.push((
2325 ShieldedBuildRecipient::External {
2326 recipient_address: recipient_address.clone(),
2327 output_pool: PoolType::IRONWOOD,
2331 },
2332 payment_amount,
2333 Some(memo),
2334 ));
2335 Ok(())
2336 };
2337
2338 let add_transparent_output =
2339 |builder: &mut Builder<_, _>,
2340 transparent_output_meta: &mut Vec<_>,
2341 to: TransparentAddress|
2342 -> Result<(), CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>> {
2343 if payment.memo().is_some() {
2344 return Err(Error::Payment(zip321::PaymentError::TransparentMemo));
2345 }
2346 builder.add_transparent_output(&to, payment_amount)?;
2347 transparent_output_meta.push((
2348 TransparentBuildRecipient::External {
2349 recipient_address: recipient_address.clone(),
2350 output_pool: PoolType::TRANSPARENT,
2351 },
2352 to,
2353 payment_amount,
2354 StepOutputIndex::Payment(payment_index),
2355 ));
2356 Ok(())
2357 };
2358
2359 let recipient = recipient_address
2360 .clone()
2361 .convert_if_network(params.network_type())?;
2362
2363 if let Address::Unified(ua) = &recipient {
2364 check_recipient_expiry(ua, min_target_height, tx_expiry_height, now).map_err(
2365 |error| Error::RecipientAddressExpiry {
2366 payment_index,
2367 error,
2368 },
2369 )?;
2370 }
2371
2372 match recipient {
2373 Address::Unified(ua) => match output_pool {
2374 #[cfg(not(feature = "orchard"))]
2375 PoolType::Shielded(ShieldedPool::Orchard) => {
2376 return Err(Error::ProposalNotSupported);
2377 }
2378 #[cfg(feature = "orchard")]
2379 PoolType::Shielded(ShieldedPool::Orchard) => {
2380 let to = *ua.orchard().expect("The mapping between payment pool and receiver is checked in step construction");
2384 add_orchard_output(&mut builder, &mut orchard_output_meta, to)?;
2385 }
2386 PoolType::Shielded(ShieldedPool::Sapling) => {
2387 let to = *ua.sapling().expect("The mapping between payment pool and receiver is checked in step construction");
2388 add_sapling_output(&mut builder, &mut sapling_output_meta, to)?;
2389 }
2390 PoolType::Transparent => {
2391 let to = *ua.transparent().expect("The mapping between payment pool and receiver is checked in step construction");
2392 add_transparent_output(&mut builder, &mut transparent_output_meta, to)?;
2393 }
2394 #[cfg(feature = "orchard")]
2395 PoolType::Shielded(ShieldedPool::Ironwood) => {
2396 let to = *ua.orchard().expect("The mapping between payment pool and receiver is checked in step construction");
2399 add_ironwood_output(&mut builder, &mut ironwood_output_meta, to)?;
2400 }
2401 #[cfg(not(feature = "orchard"))]
2402 PoolType::Shielded(ShieldedPool::Ironwood) => {
2403 return Err(Error::ProposalNotSupported);
2404 }
2405 },
2406 Address::Sapling(to) => {
2407 add_sapling_output(&mut builder, &mut sapling_output_meta, *to)?;
2408 }
2409 Address::Transparent(to) => {
2410 add_transparent_output(&mut builder, &mut transparent_output_meta, to)?;
2411 }
2412 #[cfg(not(feature = "transparent-inputs"))]
2413 Address::Tex(_) => {
2414 return Err(Error::ProposalNotSupported);
2415 }
2416 #[cfg(feature = "transparent-inputs")]
2417 Address::Tex(data) => {
2418 if has_shielded_inputs {
2419 return Err(ProposalError::PaysTexFromShielded.into());
2420 }
2421 let to = TransparentAddress::PublicKeyHash(data);
2422 add_transparent_output(&mut builder, &mut transparent_output_meta, to)?;
2423 }
2424 }
2425 }
2426
2427 for change_value in proposal_step.balance().proposed_change() {
2428 let memo = change_value
2429 .memo()
2430 .map_or_else(MemoBytes::empty, |m| m.clone());
2431 let output_pool = change_value.output_pool();
2432 match output_pool {
2433 PoolType::Shielded(ShieldedPool::Sapling) => {
2434 builder.add_sapling_output(
2435 internal_ovk.map(|k| k.into()),
2436 ufvk.sapling()
2437 .ok_or(Error::KeyNotAvailable(PoolType::SAPLING))?
2438 .change_address()
2439 .1,
2440 change_value.value(),
2441 memo.clone(),
2442 )?;
2443 sapling_output_meta.push((
2444 ShieldedBuildRecipient::InternalShielded {
2445 receiving_account: account_id,
2446 external_address: None,
2447 },
2448 change_value.value(),
2449 Some(memo),
2450 ))
2451 }
2452 PoolType::Shielded(ShieldedPool::Orchard) => {
2453 #[cfg(not(feature = "orchard"))]
2454 return Err(Error::UnsupportedChangeType(output_pool));
2455
2456 #[cfg(feature = "orchard")]
2457 {
2458 let orchard_fvk = ufvk
2459 .orchard()
2460 .ok_or(Error::KeyNotAvailable(PoolType::ORCHARD))?;
2461
2462 let change_address =
2463 orchard_fvk.address_at(0u32, orchard::keys::Scope::Internal);
2464
2465 if ironwood_active_at(params, min_target_height) {
2466 builder.add_orchard_change_output(
2472 orchard_fvk.clone(),
2473 internal_ovk.map(|k| k.into()),
2474 change_address,
2475 change_value.value(),
2476 memo.clone(),
2477 )?;
2478 orchard_output_meta.push((
2479 ShieldedBuildRecipient::InternalShielded {
2480 receiving_account: account_id,
2481 external_address: None,
2482 },
2483 change_value.value(),
2484 Some(memo),
2485 ))
2486 } else {
2487 builder.add_orchard_output(
2488 internal_ovk.map(|k| k.into()),
2489 change_address,
2490 change_value.value(),
2491 memo.clone(),
2492 )?;
2493 orchard_output_meta.push((
2494 ShieldedBuildRecipient::InternalShielded {
2495 receiving_account: account_id,
2496 external_address: None,
2497 },
2498 change_value.value(),
2499 Some(memo),
2500 ))
2501 }
2502 }
2503 }
2504 PoolType::Transparent => {
2505 #[cfg(not(feature = "transparent-inputs"))]
2509 return Err(Error::UnsupportedChangeType(output_pool));
2510 }
2511 PoolType::Shielded(ShieldedPool::Ironwood) => {
2512 #[cfg(not(feature = "orchard"))]
2513 return Err(Error::UnsupportedChangeType(output_pool));
2514
2515 #[cfg(feature = "orchard")]
2516 {
2517 let orchard_fvk = ufvk
2518 .orchard()
2519 .ok_or(Error::KeyNotAvailable(PoolType::ORCHARD))?;
2520
2521 let change_address =
2522 orchard_fvk.address_at(0u32, orchard::keys::Scope::Internal);
2523
2524 builder.add_ironwood_output(
2525 internal_ovk.map(|k| k.into()),
2526 change_address,
2527 change_value.value(),
2528 memo.clone(),
2529 )?;
2530 ironwood_output_meta.push((
2531 ShieldedBuildRecipient::InternalShielded {
2532 receiving_account: account_id,
2533 external_address: None,
2534 },
2535 change_value.value(),
2536 Some(memo),
2537 ))
2538 }
2539 }
2540 }
2541 }
2542
2543 #[cfg(feature = "transparent-inputs")]
2547 {
2548 let ephemeral_outputs: Vec<(usize, &ChangeValue)> = proposal_step
2549 .balance()
2550 .proposed_change()
2551 .iter()
2552 .enumerate()
2553 .filter(|(_, change_value)| {
2554 change_value.is_ephemeral() && change_value.output_pool() == PoolType::Transparent
2555 })
2556 .collect();
2557
2558 let addresses_and_metadata = wallet_db
2559 .reserve_next_n_ephemeral_addresses(account_id, ephemeral_outputs.len())
2560 .map_err(Error::DataSource)?;
2561 assert_eq!(addresses_and_metadata.len(), ephemeral_outputs.len());
2562
2563 for ((change_index, change_value), (ephemeral_address, _)) in
2565 ephemeral_outputs.iter().zip(addresses_and_metadata)
2566 {
2567 builder.add_transparent_output(&ephemeral_address, change_value.value())?;
2570 transparent_output_meta.push((
2571 TransparentBuildRecipient::EphemeralTransparent {
2572 receiving_account: account_id,
2573 ephemeral_address,
2574 },
2575 ephemeral_address,
2576 change_value.value(),
2577 StepOutputIndex::Change(*change_index),
2578 ))
2579 }
2580 }
2581
2582 #[cfg(feature = "transparent-inputs")]
2586 {
2587 let transparent_change_outputs: Vec<(usize, &ChangeValue)> = proposal_step
2588 .balance()
2589 .proposed_change()
2590 .iter()
2591 .enumerate()
2592 .filter(|(_, change_value)| {
2593 !change_value.is_ephemeral() && change_value.output_pool() == PoolType::Transparent
2594 })
2595 .collect();
2596
2597 if !transparent_change_outputs.is_empty() {
2598 let addresses_and_metadata = wallet_db
2599 .reserve_next_n_internal_addresses(account_id, transparent_change_outputs.len())
2600 .map_err(Error::DataSource)?;
2601 assert_eq!(
2602 addresses_and_metadata.len(),
2603 transparent_change_outputs.len()
2604 );
2605
2606 for ((change_index, change_value), (change_address, _)) in transparent_change_outputs
2607 .iter()
2608 .zip(addresses_and_metadata)
2609 {
2610 builder.add_transparent_output(&change_address, change_value.value())?;
2611 transparent_output_meta.push((
2612 TransparentBuildRecipient::InternalTransparent {
2613 receiving_account: account_id,
2614 recipient_address: change_address,
2615 },
2616 change_address,
2617 change_value.value(),
2618 StepOutputIndex::Change(*change_index),
2619 ))
2620 }
2621 }
2622 }
2623
2624 Ok(BuildState {
2625 #[cfg(feature = "transparent-inputs")]
2626 step_index,
2627 builder,
2628 #[cfg(feature = "transparent-inputs")]
2629 transparent_input_addresses,
2630 #[cfg(feature = "orchard")]
2631 orchard_output_meta,
2632 #[cfg(feature = "orchard")]
2633 ironwood_output_meta,
2634 sapling_output_meta,
2635 transparent_output_meta,
2636 #[cfg(feature = "transparent-inputs")]
2637 utxos_spent,
2638 })
2639}
2640
2641#[allow(clippy::too_many_arguments)]
2645#[allow(clippy::type_complexity)]
2646fn create_proposed_transaction<DbT, ParamsT, InputsErrT, FeeRuleT, ChangeErrT, N>(
2647 wallet_db: &mut DbT,
2648 params: &ParamsT,
2649 rng: &mut impl CryptoRng,
2650 spend_prover: &impl SpendProver,
2651 output_prover: &impl OutputProver,
2652 spending_keys: &SpendingKeys,
2653 account_id: <DbT as WalletRead>::AccountId,
2654 ovk_policy: OvkPolicy,
2655 fee_rule: &FeeRuleT,
2656 min_target_height: TargetHeight,
2657 confirmations_policy: ConfirmationsPolicy,
2658 prior_step_results: &[(&Step<N>, StepResult<<DbT as WalletRead>::AccountId>)],
2659 proposal_step: &Step<N>,
2660 #[cfg(feature = "transparent-inputs")] unused_transparent_outputs: &mut HashMap<
2661 StepOutput,
2662 (TransparentAddress, OutPoint),
2663 >,
2664 proposed_version: Option<TxVersion>,
2665 expiry_height: Option<BlockHeight>,
2666 now: SystemTime,
2667) -> Result<
2668 StepResult<<DbT as WalletRead>::AccountId>,
2669 CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>,
2670>
2671where
2672 DbT: WalletWrite + WalletCommitmentTrees,
2673 ParamsT: consensus::Parameters + Clone,
2674 FeeRuleT: FeeRule,
2675{
2676 let build_state = build_proposed_transaction::<_, _, _, FeeRuleT, _, _>(
2677 wallet_db,
2678 params,
2679 &spending_keys.usk.to_unified_full_viewing_key(),
2680 account_id,
2681 ovk_policy,
2682 min_target_height,
2683 confirmations_policy,
2684 prior_step_results,
2685 proposal_step,
2686 #[cfg(feature = "transparent-inputs")]
2687 unused_transparent_outputs,
2688 proposed_version,
2689 BundlePadding::DEFAULT,
2691 expiry_height,
2692 now,
2693 )?;
2694
2695 #[cfg_attr(not(feature = "transparent-inputs"), allow(unused_mut))]
2697 let mut transparent_signing_set = TransparentSigningSet::new();
2698 #[cfg(feature = "transparent-inputs")]
2699 for (_address, address_metadata) in build_state.transparent_input_addresses {
2700 match address_metadata.source() {
2701 TransparentAddressSource::Derived {
2702 scope,
2703 address_index,
2704 } => {
2705 transparent_signing_set.add_key(
2706 spending_keys
2707 .usk
2708 .transparent()
2709 .ok_or(Error::KeyNotAvailable(PoolType::Transparent))?
2710 .derive_secret_key(*scope, *address_index)
2711 .expect("spending key derivation should not fail"),
2712 );
2713 }
2714 #[cfg(feature = "transparent-key-import")]
2715 TransparentAddressSource::StandalonePubkey(_)
2716 | TransparentAddressSource::StandaloneScript(_) => {
2717 let keys = spending_keys
2718 .standalone_transparent_keys
2719 .get(&_address)
2720 .ok_or(Error::AddressNotRecognized(_address))?;
2721 for key in keys {
2722 transparent_signing_set.add_key(*key);
2723 }
2724 }
2725 #[cfg(feature = "transparent-key-import")]
2728 TransparentAddressSource::StandaloneAddress => {
2729 return Err(Error::AddressNotRecognized(_address));
2730 }
2731 }
2732 }
2733 let sapling_extsks = match spending_keys.usk.sapling() {
2734 Some(extsk) => vec![
2735 extsk.clone(),
2736 extsk
2737 .derive_internal()
2738 .ok_or(Error::KeyNotAvailable(PoolType::SAPLING))?,
2739 ],
2740 None => vec![],
2741 };
2742 #[cfg(feature = "orchard")]
2743 let orchard_saks: Vec<orchard::keys::SpendAuthorizingKey> = spending_keys
2744 .usk
2745 .orchard()
2746 .map(|sk| sk.into())
2747 .into_iter()
2748 .collect();
2749 #[cfg(not(feature = "orchard"))]
2750 let orchard_saks = vec![];
2751 let build_result = build_state.builder.build(
2752 &transparent_signing_set,
2753 &sapling_extsks,
2754 &orchard_saks,
2755 rng,
2756 spend_prover,
2757 output_prover,
2758 fee_rule,
2759 )?;
2760
2761 #[cfg(feature = "orchard")]
2764 let orchard_fvk: Option<orchard::keys::FullViewingKey> =
2765 spending_keys.usk.orchard().map(|sk| sk.into());
2766 #[cfg(feature = "orchard")]
2767 let orchard_internal_ivk = orchard_fvk
2768 .as_ref()
2769 .map(|fvk| fvk.to_ivk(orchard::keys::Scope::Internal));
2770 #[cfg(feature = "orchard")]
2774 let orchard_external_ivk = orchard_fvk
2775 .as_ref()
2776 .map(|fvk| fvk.to_ivk(orchard::keys::Scope::External));
2777 #[cfg(feature = "orchard")]
2778 let orchard_outputs = build_state.orchard_output_meta.into_iter().enumerate().map(
2779 |(i, (recipient, value, memo))| {
2780 let output_index = build_result
2781 .orchard_meta()
2782 .output_action_index(i)
2783 .expect("An action should exist in the transaction for each Orchard output.");
2784
2785 let recipient = recipient.into_recipient(|| {
2786 build_result
2787 .transaction()
2788 .orchard_bundle()
2789 .zip(
2790 orchard_internal_ivk
2791 .as_ref()
2792 .zip(orchard_external_ivk.as_ref()),
2793 )
2794 .and_then(|(bundle, (internal_ivk, external_ivk))| {
2795 bundle
2796 .decrypt_output_with_key(output_index, internal_ivk)
2797 .or_else(|| bundle.decrypt_output_with_key(output_index, external_ivk))
2798 .map(|(note, _, _)| Note::Orchard {
2799 note,
2800 pool: orchard::ValuePool::Orchard,
2801 })
2802 })
2803 .expect("Wallet-internal outputs must be decryptable with the wallet's IVK")
2804 });
2805
2806 SentTransactionOutput::from_parts_in_tree(
2807 Some(NoteCommitmentTree::Orchard),
2808 output_index,
2809 recipient,
2810 value,
2811 memo,
2812 )
2813 },
2814 );
2815
2816 #[cfg(feature = "orchard")]
2817 let ironwood_outputs = build_state
2818 .ironwood_output_meta
2819 .into_iter()
2820 .enumerate()
2821 .map(|(i, (recipient, value, memo))| {
2822 let raw_output_index = build_result
2823 .ironwood_meta()
2824 .output_action_index(i)
2825 .expect("An action should exist in the transaction for each Ironwood output.");
2826
2827 let recipient = recipient.into_recipient(|| {
2828 build_result
2829 .transaction()
2830 .ironwood_bundle()
2831 .zip(orchard_internal_ivk.as_ref())
2832 .and_then(|(bundle, internal_ivk)| {
2833 bundle
2834 .decrypt_output_with_key(raw_output_index, internal_ivk)
2835 .map(|(note, _, _)| Note::Orchard { note, pool: orchard::ValuePool::Ironwood })
2836 })
2837 .expect(
2838 "Wallet-internal Ironwood outputs must be decryptable with the wallet's IVK",
2839 )
2840 });
2841
2842 SentTransactionOutput::from_parts_in_tree(
2847 Some(NoteCommitmentTree::Ironwood),
2848 raw_output_index,
2849 recipient,
2850 value,
2851 memo,
2852 )
2853 });
2854
2855 let sapling_internal_ivk = spending_keys.usk.sapling().map(|extsk| {
2856 PreparedIncomingViewingKey::new(
2857 &extsk
2858 .to_diversifiable_full_viewing_key()
2859 .to_ivk(Scope::Internal),
2860 )
2861 });
2862 let sapling_outputs = build_state.sapling_output_meta.into_iter().enumerate().map(
2863 |(i, (recipient, value, memo))| {
2864 let output_index = build_result
2865 .sapling_meta()
2866 .output_index(i)
2867 .expect("An output should exist in the transaction for each Sapling payment.");
2868
2869 let recipient = recipient.into_recipient(|| {
2870 build_result
2871 .transaction()
2872 .sapling_bundle()
2873 .zip(sapling_internal_ivk.as_ref())
2874 .and_then(|(bundle, internal_ivk)| {
2875 try_sapling_note_decryption(
2876 internal_ivk,
2877 &bundle.shielded_outputs()[output_index],
2878 zip212_enforcement(params, min_target_height.into()),
2879 )
2880 .map(|(note, _, _)| Note::Sapling(note))
2881 })
2882 .expect("Wallet-internal outputs must be decryptable with the wallet's IVK")
2883 });
2884
2885 SentTransactionOutput::from_parts_in_tree(
2886 Some(NoteCommitmentTree::Sapling),
2887 output_index,
2888 recipient,
2889 value,
2890 memo,
2891 )
2892 },
2893 );
2894
2895 let txid: [u8; 32] = build_result.transaction().txid().into();
2896 assert_eq!(
2897 build_state.transparent_output_meta.len(),
2898 build_result
2899 .transaction()
2900 .transparent_bundle()
2901 .map_or(0, |b| b.vout.len()),
2902 );
2903
2904 #[allow(unused_variables)]
2905 let transparent_outputs = build_state
2906 .transparent_output_meta
2907 .into_iter()
2908 .enumerate()
2909 .map(|(n, (recipient, address, value, step_output_index))| {
2910 let outpoint = OutPoint::new(txid, n as u32);
2915
2916 let recipient = recipient.into_recipient(
2917 #[cfg(feature = "transparent-inputs")]
2918 outpoint.clone(),
2919 );
2920
2921 #[cfg(feature = "transparent-inputs")]
2922 unused_transparent_outputs.insert(
2923 StepOutput::new(build_state.step_index, step_output_index),
2924 (address, outpoint),
2925 );
2926 SentTransactionOutput::from_parts(n, recipient, value, None)
2927 });
2928
2929 let mut outputs: Vec<SentTransactionOutput<_>> = vec![];
2930 #[cfg(feature = "orchard")]
2931 outputs.extend(orchard_outputs);
2932 #[cfg(feature = "orchard")]
2933 outputs.extend(ironwood_outputs);
2934 outputs.extend(sapling_outputs);
2935 outputs.extend(transparent_outputs);
2936
2937 Ok(StepResult {
2938 build_result,
2939 outputs,
2940 fee_amount: proposal_step.balance().fee_required(),
2941 #[cfg(feature = "transparent-inputs")]
2942 utxos_spent: build_state.utxos_spent,
2943 })
2944}
2945
2946#[allow(clippy::too_many_arguments)]
2985#[allow(clippy::type_complexity)]
2986#[cfg(feature = "pczt")]
2987pub fn create_pczt_from_proposal<DbT, ParamsT, InputsErrT, FeeRuleT, ChangeErrT, N>(
2988 wallet_db: &mut DbT,
2989 params: &ParamsT,
2990 clock: &impl Clock,
2991 rng: &mut impl CryptoRng,
2992 account_id: <DbT as WalletRead>::AccountId,
2993 ovk_policy: OvkPolicy,
2994 proposal: &Proposal<FeeRuleT, N>,
2995 expiry_height: Option<BlockHeight>,
2996 orchard_pool_padding: BundlePadding,
2997) -> Result<pczt::Pczt, CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>>
2998where
2999 DbT: WalletWrite + WalletCommitmentTrees,
3000 ParamsT: consensus::Parameters + Clone,
3001 FeeRuleT: FeeRule,
3002 <DbT as WalletRead>::AccountId: serde::Serialize,
3003{
3004 let account = wallet_db
3005 .get_account(account_id)
3006 .map_err(Error::DataSource)?
3007 .ok_or(Error::AccountIdNotRecognized)?;
3008 let ufvk = account.ufvk().ok_or(Error::AccountCannotSpend)?;
3009 let account_derivation = account.source().key_derivation();
3010
3011 if proposal.steps().len() > 1 {
3013 return Err(Error::ProposalNotSupported);
3014 }
3015
3016 proposal.check_transaction_size()?;
3018
3019 let fee_rule = proposal.fee_rule();
3020 let min_target_height = proposal.min_target_height();
3021
3022 if let Some(expiry_height) = expiry_height {
3023 let min_target_height = BlockHeight::from(min_target_height);
3024 if expiry_height != consensus::H0 && expiry_height < min_target_height {
3025 return Err(Error::ExpiryHeightBelowTargetHeight {
3026 expiry_height,
3027 min_target_height,
3028 });
3029 }
3030 }
3031
3032 let prior_step_results = &[];
3033 let proposal_step = proposal.steps().first();
3034
3035 let unused_transparent_outputs = &mut HashMap::new();
3036 let proposed_version = proposal.proposed_version();
3040
3041 let build_state = build_proposed_transaction::<_, _, _, FeeRuleT, _, _>(
3042 wallet_db,
3043 params,
3044 ufvk,
3045 account_id,
3046 ovk_policy,
3047 min_target_height,
3048 proposal.confirmations_policy(),
3049 prior_step_results,
3050 proposal_step,
3051 #[cfg(feature = "transparent-inputs")]
3052 unused_transparent_outputs,
3053 proposed_version,
3054 orchard_pool_padding,
3055 expiry_height,
3056 clock.now(),
3057 )?;
3058
3059 let build_result = build_state.builder.build_for_pczt(&mut *rng, fee_rule)?;
3063
3064 let created = Creator::build_from_parts(build_result.pczt_parts).ok_or(PcztError::Build)?;
3065
3066 let io_finalized = IoFinalizer::new(created).finalize_io(rng)?;
3067
3068 #[cfg(feature = "orchard")]
3069 let orchard_outputs = build_state
3070 .orchard_output_meta
3071 .into_iter()
3072 .enumerate()
3073 .map(|(i, (recipient, _, _))| {
3074 let output_index = build_result
3075 .orchard_meta
3076 .output_action_index(i)
3077 .expect("An action should exist in the transaction for each Orchard output.");
3078
3079 (
3080 output_index,
3081 PcztRecipient::from_shielded_recipient(recipient),
3082 )
3083 })
3084 .collect::<HashMap<_, _>>();
3085
3086 #[cfg(feature = "orchard")]
3087 let ironwood_outputs = build_state
3088 .ironwood_output_meta
3089 .into_iter()
3090 .enumerate()
3091 .map(|(i, (recipient, _, _))| {
3092 let output_index = build_result
3093 .ironwood_meta
3094 .output_action_index(i)
3095 .expect("An action should exist in the transaction for each Ironwood output.");
3096
3097 (
3098 output_index,
3099 PcztRecipient::from_shielded_recipient(recipient),
3100 )
3101 })
3102 .collect::<HashMap<_, _>>();
3103
3104 let sapling_outputs = build_state
3105 .sapling_output_meta
3106 .into_iter()
3107 .enumerate()
3108 .map(|(i, (recipient, _, _))| {
3109 let output_index = build_result
3110 .sapling_meta
3111 .output_index(i)
3112 .expect("An output should exist in the transaction for each Sapling output.");
3113
3114 (
3115 output_index,
3116 PcztRecipient::from_shielded_recipient(recipient),
3117 )
3118 })
3119 .collect::<HashMap<_, _>>();
3120
3121 let pczt = Updater::new(io_finalized)
3122 .update_global_with(|mut updater| {
3123 updater.set_proprietary(
3124 PROPRIETARY_PROPOSAL_INFO.into(),
3125 postcard::to_allocvec(&ProposalInfo::<<DbT as WalletRead>::AccountId> {
3126 from_account: account_id,
3127 target_height: proposal.min_target_height(),
3128 })
3129 .expect("postcard encoding of PCZT proposal metadata should not fail"),
3130 )
3131 })
3132 .update_orchard_with(|mut updater| {
3133 let spend_needs_derivation = updater
3139 .bundle()
3140 .actions()
3141 .iter()
3142 .map(|action| action.spend().spend_auth_sig().is_none())
3143 .collect::<Vec<_>>();
3144
3145 for (index, needs_derivation) in spend_needs_derivation.iter().enumerate() {
3146 updater.update_action_with(index, |mut action_updater| {
3147 if let Some(derivation) = account_derivation
3152 && *needs_derivation
3153 {
3154 action_updater.set_spend_zip32_derivation(
3156 orchard::pczt::Zip32Derivation::parse(
3157 derivation.seed_fingerprint().to_bytes(),
3158 vec![
3159 zip32::ChildIndex::hardened(32).index(),
3160 zip32::ChildIndex::hardened(params.network_type().coin_type())
3161 .index(),
3162 zip32::ChildIndex::hardened(u32::from(
3163 derivation.account_index(),
3164 ))
3165 .index(),
3166 ],
3167 )
3168 .expect("valid"),
3169 );
3170 }
3171
3172 if let Some((pczt_recipient, external_address)) = orchard_outputs.get(&index) {
3173 if let Some(user_address) = external_address {
3174 action_updater.set_output_user_address(user_address.encode());
3175 }
3176 action_updater.set_output_proprietary(
3177 PROPRIETARY_OUTPUT_INFO.into(),
3178 postcard::to_allocvec(pczt_recipient).expect(
3179 "postcard encoding of PCZT recipient metadata should not fail",
3180 ),
3181 );
3182 }
3183
3184 Ok(())
3185 })?;
3186 }
3187 Ok(())
3188 })?
3189 .update_ironwood_with(|mut updater| {
3190 let spend_needs_derivation = updater
3196 .bundle()
3197 .actions()
3198 .iter()
3199 .map(|action| action.spend().spend_auth_sig().is_none())
3200 .collect::<Vec<_>>();
3201
3202 for (index, needs_derivation) in spend_needs_derivation.iter().enumerate() {
3203 updater.update_action_with(index, |mut action_updater| {
3204 if let Some(derivation) = account_derivation
3210 && *needs_derivation
3211 {
3212 action_updater.set_spend_zip32_derivation(
3214 orchard::pczt::Zip32Derivation::parse(
3215 derivation.seed_fingerprint().to_bytes(),
3216 vec![
3217 zip32::ChildIndex::hardened(32).index(),
3218 zip32::ChildIndex::hardened(params.network_type().coin_type())
3219 .index(),
3220 zip32::ChildIndex::hardened(u32::from(
3221 derivation.account_index(),
3222 ))
3223 .index(),
3224 ],
3225 )
3226 .expect("valid"),
3227 );
3228 }
3229
3230 if let Some((pczt_recipient, external_address)) = ironwood_outputs.get(&index) {
3231 if let Some(user_address) = external_address {
3232 action_updater.set_output_user_address(user_address.encode());
3233 }
3234 action_updater.set_output_proprietary(
3235 PROPRIETARY_OUTPUT_INFO.into(),
3236 postcard::to_allocvec(pczt_recipient).expect(
3237 "postcard encoding of PCZT recipient metadata should not fail",
3238 ),
3239 );
3240 }
3241
3242 Ok(())
3243 })?;
3244 }
3245 Ok(())
3246 })?
3247 .update_sapling_with(|mut updater| {
3248 if let Some(derivation) = account_derivation {
3250 let non_dummy_spends = updater
3251 .bundle()
3252 .spends()
3253 .iter()
3254 .enumerate()
3255 .filter_map(|(index, spend)| {
3256 spend.proof_generation_key().is_none().then_some(index)
3258 })
3259 .collect::<Vec<_>>();
3260
3261 for index in non_dummy_spends {
3262 updater.update_spend_with(index, |mut spend_updater| {
3263 spend_updater.set_zip32_derivation(
3265 sapling::pczt::Zip32Derivation::parse(
3266 derivation.seed_fingerprint().to_bytes(),
3267 vec![
3268 zip32::ChildIndex::hardened(32).index(),
3269 zip32::ChildIndex::hardened(params.network_type().coin_type())
3270 .index(),
3271 zip32::ChildIndex::hardened(u32::from(
3272 derivation.account_index(),
3273 ))
3274 .index(),
3275 ],
3276 )
3277 .expect("valid"),
3278 );
3279 Ok(())
3280 })?;
3281 }
3282 }
3283
3284 for index in 0..updater.bundle().outputs().len() {
3285 if let Some((pczt_recipient, external_address)) = sapling_outputs.get(&index) {
3286 updater.update_output_with(index, |mut output_updater| {
3287 if let Some(user_address) = external_address {
3288 output_updater.set_user_address(user_address.encode());
3289 }
3290 output_updater.set_proprietary(
3291 PROPRIETARY_OUTPUT_INFO.into(),
3292 postcard::to_allocvec(pczt_recipient).expect(
3293 "postcard encoding of PCZT recipient metadata should not fail",
3294 ),
3295 );
3296 Ok(())
3297 })?;
3298 }
3299 }
3300
3301 Ok(())
3302 })?
3303 .update_transparent_with(|mut updater| {
3304 if let Some(derivation) = account_derivation {
3306 let inputs_to_update = updater
3308 .bundle()
3309 .inputs()
3310 .iter()
3311 .enumerate()
3312 .filter_map(|(index, input)| {
3313 let address_metadata = build_state.transparent_input_addresses.get(
3314 &TransparentAddress::from_script_from_chain(input.script_pubkey())
3315 .expect("we created this with a supported transparent address"),
3316 )?;
3317 match address_metadata.source() {
3318 TransparentAddressSource::Derived {
3319 scope,
3320 address_index,
3321 } => Some((index, *scope, *address_index)),
3322 #[cfg(feature = "transparent-key-import")]
3323 TransparentAddressSource::StandalonePubkey(_)
3324 | TransparentAddressSource::StandaloneScript(_)
3325 | TransparentAddressSource::StandaloneAddress => None,
3326 }
3327 })
3328 .collect::<Vec<_>>();
3329
3330 for (index, scope, address_index) in inputs_to_update {
3331 updater.update_input_with(index, |mut input_updater| {
3332 let pubkey = ufvk
3333 .p2pkh()
3334 .expect("we derived this successfully in build_proposed_transaction")
3335 .derive_address_pubkey(scope, address_index)
3336 .expect("spending key derivation should not fail");
3337
3338 input_updater.set_bip32_derivation(
3339 pubkey.serialize(),
3340 Bip32Derivation::parse(
3341 derivation.seed_fingerprint().to_bytes(),
3342 vec![
3343 44 | ChildNumber::HARDENED_FLAG,
3345 params.network_type().coin_type() | ChildNumber::HARDENED_FLAG,
3346 u32::from(derivation.account_index())
3347 | ChildNumber::HARDENED_FLAG,
3348 ChildNumber::from(scope).into(),
3349 ChildNumber::from(address_index).into(),
3350 ],
3351 )
3352 .expect("valid"),
3353 );
3354 Ok(())
3355 })?;
3356 }
3357 }
3358
3359 assert_eq!(
3360 build_state.transparent_output_meta.len(),
3361 updater.bundle().outputs().len(),
3362 );
3363 for (index, (recipient, _, _, _)) in
3364 build_state.transparent_output_meta.into_iter().enumerate()
3365 {
3366 updater.update_output_with(index, |mut output_updater| {
3367 let (pczt_recipient, external_address) =
3368 PcztRecipient::from_transparent_recipient(recipient);
3369 if let Some(user_address) = external_address {
3370 output_updater.set_user_address(user_address.encode());
3371 }
3372 output_updater.set_proprietary(
3373 PROPRIETARY_OUTPUT_INFO.into(),
3374 postcard::to_allocvec(&pczt_recipient)
3375 .expect("postcard encoding of pczt recipient metadata should not fail"),
3376 );
3377 Ok(())
3378 })?;
3379 }
3380
3381 Ok(())
3382 })?
3383 .finish();
3384
3385 Ok(pczt)
3386}
3387
3388#[cfg(feature = "pczt")]
3391#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3392pub enum SignerView {
3393 Full,
3405 Compact,
3415}
3416
3417#[cfg(feature = "pczt")]
3437pub fn redact_pczt_for_signer(pczt: &pczt::Pczt, view: SignerView) -> pczt::Pczt {
3438 match view {
3439 SignerView::Full => full_signer_view(pczt),
3440 SignerView::Compact => compact_signer_view(pczt),
3441 }
3442}
3443
3444#[cfg(feature = "pczt")]
3445fn full_signer_view(pczt: &pczt::Pczt) -> pczt::Pczt {
3446 fn redact_orchard_bundle(mut redactor: pczt::roles::redactor::orchard::OrchardRedactor<'_>) {
3447 redactor.redact_actions(|mut action| {
3448 action.clear_spend_witness();
3449 action.clear_spend_dummy_sk();
3450 action.redact_output_proprietary(PROPRIETARY_OUTPUT_INFO);
3451 });
3452 }
3453
3454 Redactor::new(pczt.clone())
3455 .redact_global_with(|mut redactor| {
3456 redactor.redact_proprietary(PROPRIETARY_PROPOSAL_INFO);
3457 })
3458 .redact_transparent_with(|mut redactor| {
3459 redactor.redact_outputs(|mut output| {
3460 output.redact_proprietary(PROPRIETARY_OUTPUT_INFO);
3461 });
3462 })
3463 .redact_sapling_with(|mut redactor| {
3464 redactor.redact_spends(|mut spend| {
3465 spend.clear_witness();
3466 spend.clear_dummy_ask();
3467 });
3468 redactor.redact_outputs(|mut output| {
3469 output.redact_proprietary(PROPRIETARY_OUTPUT_INFO);
3470 });
3471 })
3472 .redact_orchard_with(redact_orchard_bundle)
3473 .redact_ironwood_with(redact_orchard_bundle)
3474 .finish()
3475}
3476
3477#[cfg(feature = "pczt")]
3478fn compact_signer_view(pczt: &pczt::Pczt) -> pczt::Pczt {
3479 let redact_v6_anchors = *pczt.global().tx_version() == zcash_protocol::constants::V6_TX_VERSION;
3480
3481 fn redact_orchard_bundle(
3482 mut redactor: pczt::roles::redactor::orchard::OrchardRedactor<'_>,
3483 redact_v6_anchor: bool,
3484 ) {
3485 redactor.clear_zkproof();
3486 redactor.clear_bsk();
3487 redactor.redact_actions(|mut action| {
3488 action.clear_spend_witness();
3489 action.clear_spend_dummy_sk();
3490 action.redact_output_proprietary(PROPRIETARY_OUTPUT_INFO);
3491 });
3492
3493 redactor.compact_resolvable_fields();
3494
3495 if redact_v6_anchor {
3496 redactor.clear_anchor();
3497 }
3498 }
3499
3500 Redactor::new(pczt.clone())
3501 .redact_global_with(|mut redactor| {
3502 redactor.redact_proprietary(PROPRIETARY_PROPOSAL_INFO);
3503 })
3504 .redact_transparent_with(|mut redactor| {
3505 redactor.redact_outputs(|mut output| {
3506 output.redact_proprietary(PROPRIETARY_OUTPUT_INFO);
3507 });
3508 })
3509 .redact_sapling_with(|mut redactor| {
3510 redactor.clear_bsk();
3511 redactor.redact_spends(|mut spend| {
3512 spend.clear_zkproof();
3513 spend.clear_dummy_ask();
3514 });
3515 redactor.redact_outputs(|mut output| {
3516 output.clear_zkproof();
3517 output.redact_proprietary(PROPRIETARY_OUTPUT_INFO);
3518 });
3519 if redact_v6_anchors {
3520 redactor.clear_anchor();
3521 }
3522 })
3523 .redact_orchard_with(|redactor| {
3524 redact_orchard_bundle(redactor, redact_v6_anchors);
3525 })
3526 .redact_ironwood_with(|redactor| {
3527 redact_orchard_bundle(redactor, redact_v6_anchors);
3528 })
3529 .finish()
3530}
3531
3532#[cfg(feature = "pczt")]
3547pub fn redact_pczt_for_batch_signer(pczt: &pczt::Pczt) -> pczt::Pczt {
3548 fn preauthorized_action_indices(bundle: &pczt::orchard::Bundle) -> Vec<usize> {
3550 bundle
3551 .actions()
3552 .iter()
3553 .enumerate()
3554 .filter_map(|(index, action)| {
3555 action.spend().spend_auth_sig().is_some().then_some(index)
3556 })
3557 .collect()
3558 }
3559
3560 fn redact_orchard_bundle(
3561 mut redactor: pczt::roles::redactor::orchard::OrchardRedactor<'_>,
3562 preauthorized_action_indices: &[usize],
3563 ) {
3564 redactor.redact_actions(|mut action| {
3570 action.clear_spend_fvk();
3571 action.clear_spend_auth_sig();
3572 });
3573 for &index in preauthorized_action_indices {
3575 redactor.redact_action(index, |mut action| action.clear_spend_alpha());
3576 }
3577 }
3578
3579 let orchard_preauthorized = preauthorized_action_indices(pczt.orchard());
3580 let ironwood_preauthorized = preauthorized_action_indices(pczt.ironwood());
3581
3582 Redactor::new(redact_pczt_for_signer(pczt, SignerView::Compact))
3584 .redact_orchard_with(|redactor| {
3585 redact_orchard_bundle(redactor, &orchard_preauthorized);
3586 })
3587 .redact_ironwood_with(|redactor| {
3588 redact_orchard_bundle(redactor, &ironwood_preauthorized);
3589 })
3590 .finish()
3591}
3592
3593#[cfg(feature = "pczt")]
3611pub fn extract_and_store_transaction_from_pczt<DbT, N>(
3612 wallet_db: &mut DbT,
3613 clock: &impl Clock,
3614 rng: &mut impl CryptoRng,
3615 pczt: pczt::Pczt,
3616 sapling_vk: Option<(
3617 &sapling::circuit::SpendVerifyingKey,
3618 &sapling::circuit::OutputVerifyingKey,
3619 )>,
3620 #[cfg(feature = "orchard")] orchard_vk: Option<&orchard::circuit::VerifyingKey>,
3621) -> Result<TxId, ExtractErrT<DbT, N>>
3622where
3623 DbT: WalletWrite + WalletCommitmentTrees,
3624 <DbT as WalletRead>::AccountId: serde::de::DeserializeOwned,
3625{
3626 let finalized = SpendFinalizer::new(pczt).finalize_spends()?;
3627
3628 let proposal_info = finalized
3629 .global()
3630 .proprietary()
3631 .get(PROPRIETARY_PROPOSAL_INFO)
3632 .ok_or_else(|| PcztError::Invalid("PCZT missing proprietary proposal info field".into()))
3633 .and_then(|v| {
3634 postcard::from_bytes::<ProposalInfo<<DbT as WalletRead>::AccountId>>(v).map_err(|e| {
3635 PcztError::Invalid(format!(
3636 "Postcard decoding of proprietary proposal info failed: {e}"
3637 ))
3638 })
3639 })?;
3640
3641 #[allow(clippy::type_complexity)]
3646 fn orchard_protocol_output_info<AccountId: serde::de::DeserializeOwned>(
3647 actions: &[pczt::orchard::Action],
3648 note_version: orchard::note::NoteVersion,
3649 ) -> Result<
3650 Vec<
3651 Option<(
3652 (PcztRecipient<AccountId>, Option<ZcashAddress>),
3653 orchard::Note,
3654 )>,
3655 >,
3656 PcztError,
3657 > {
3658 actions
3659 .iter()
3660 .map(|act| {
3661 let note = || {
3662 let recipient = act.output().recipient().as_ref().and_then(|b| {
3663 ::orchard::Address::from_raw_address_bytes(b).into_option()
3664 })?;
3665 let value = act
3666 .output()
3667 .value()
3668 .map(orchard::value::NoteValue::from_raw)?;
3669 let rho =
3670 orchard::note::Rho::from_bytes(act.spend().nullifier()).into_option()?;
3671 let rseed = act.output().rseed().as_ref().and_then(|rseed| {
3672 orchard::note::RandomSeed::from_bytes(*rseed, &rho).into_option()
3673 })?;
3674
3675 orchard::Note::from_parts(recipient, value, rho, rseed, note_version)
3676 .into_option()
3677 };
3678
3679 let external_address = act
3680 .output()
3681 .user_address()
3682 .as_deref()
3683 .map(ZcashAddress::try_from_encoded)
3684 .transpose()
3685 .map_err(|e| PcztError::Invalid(format!("Invalid user_address: {e}")))?;
3686
3687 let pczt_recipient = act
3688 .output()
3689 .proprietary()
3690 .get(PROPRIETARY_OUTPUT_INFO)
3691 .map(|v| postcard::from_bytes::<PcztRecipient<AccountId>>(v))
3692 .transpose()
3693 .map_err(|e: postcard::Error| {
3694 PcztError::Invalid(format!(
3695 "Postcard decoding of proprietary output info failed: {e}"
3696 ))
3697 })?
3698 .map(|pczt_recipient| (pczt_recipient, external_address));
3699
3700 Ok(pczt_recipient.zip(note()))
3704 })
3705 .collect::<Result<Vec<_>, PcztError>>()
3706 }
3707
3708 let orchard_output_info = orchard_protocol_output_info::<<DbT as WalletRead>::AccountId>(
3709 finalized.orchard().actions(),
3710 orchard::note::NoteVersion::V2,
3711 )?;
3712
3713 let ironwood_output_info = orchard_protocol_output_info::<<DbT as WalletRead>::AccountId>(
3714 finalized.ironwood().actions(),
3715 orchard::note::NoteVersion::V3,
3716 )?;
3717
3718 let sapling_output_info = finalized
3719 .sapling()
3720 .outputs()
3721 .iter()
3722 .map(|out| {
3723 let note = || {
3724 let recipient = out
3725 .recipient()
3726 .as_ref()
3727 .and_then(::sapling::PaymentAddress::from_bytes)?;
3728 let value = out.value().map(::sapling::value::NoteValue::from_raw)?;
3729 let rseed = out
3730 .rseed()
3731 .as_ref()
3732 .cloned()
3733 .map(::sapling::note::Rseed::AfterZip212)?;
3734
3735 Some(::sapling::Note::from_parts(recipient, value, rseed))
3736 };
3737
3738 let external_address = out
3739 .user_address()
3740 .as_deref()
3741 .map(ZcashAddress::try_from_encoded)
3742 .transpose()
3743 .map_err(|e| PcztError::Invalid(format!("Invalid user_address: {e}")))?;
3744
3745 let pczt_recipient = out
3746 .proprietary()
3747 .get(PROPRIETARY_OUTPUT_INFO)
3748 .map(|v| postcard::from_bytes::<PcztRecipient<<DbT as WalletRead>::AccountId>>(v))
3749 .transpose()
3750 .map_err(|e: postcard::Error| {
3751 PcztError::Invalid(format!(
3752 "Postcard decoding of proprietary output info failed: {e}"
3753 ))
3754 })?
3755 .map(|pczt_recipient| (pczt_recipient, external_address));
3756
3757 Ok(pczt_recipient.zip(note()))
3761 })
3762 .collect::<Result<Vec<_>, PcztError>>()?;
3763
3764 let transparent_output_info = finalized
3765 .transparent()
3766 .outputs()
3767 .iter()
3768 .map(|out| {
3769 let external_address = out
3770 .user_address()
3771 .as_deref()
3772 .map(ZcashAddress::try_from_encoded)
3773 .transpose()
3774 .map_err(|e| PcztError::Invalid(format!("Invalid user_address: {e}")))?;
3775
3776 let pczt_recipient = out
3777 .proprietary()
3778 .get(PROPRIETARY_OUTPUT_INFO)
3779 .map(|v| postcard::from_bytes::<PcztRecipient<<DbT as WalletRead>::AccountId>>(v))
3780 .transpose()
3781 .map_err(|e: postcard::Error| {
3782 PcztError::Invalid(format!(
3783 "Postcard decoding of proprietary output info failed: {e}"
3784 ))
3785 })?
3786 .map(|pczt_recipient| (pczt_recipient, external_address));
3787
3788 Ok(pczt_recipient)
3789 })
3790 .collect::<Result<Vec<_>, PcztError>>()?;
3791
3792 let utxos_map = finalized
3793 .transparent()
3794 .inputs()
3795 .iter()
3796 .map(|input| {
3797 Zatoshis::from_u64(*input.value()).map(|value| {
3798 (
3799 OutPoint::new(*input.prevout_txid(), *input.prevout_index()),
3800 value,
3801 )
3802 })
3803 })
3804 .collect::<Result<BTreeMap<_, _>, _>>()?;
3805
3806 let mut tx_extractor = TransactionExtractor::new(finalized);
3807 if let Some((spend_vk, output_vk)) = sapling_vk {
3808 tx_extractor = tx_extractor.with_sapling(spend_vk, output_vk);
3809 }
3810 if let Some(orchard_vk) = orchard_vk {
3811 tx_extractor = tx_extractor.with_orchard(orchard_vk);
3812 }
3813 let transaction = tx_extractor.extract(rng)?;
3814 let txid = transaction.txid();
3815
3816 #[allow(clippy::too_many_arguments)]
3817 fn to_sent_transaction_output<
3818 AccountId: Copy,
3819 D: Domain,
3820 O: ShieldedOutput<D>,
3821 DbT: WalletRead + WalletCommitmentTrees,
3822 N,
3823 >(
3824 domain: D,
3825 note: D::Note,
3826 output: &O,
3827 output_pool: ShieldedPool,
3828 output_index: usize,
3829 pczt_recipient: PcztRecipient<AccountId>,
3830 external_address: Option<ZcashAddress>,
3831 note_value: impl Fn(&D::Note) -> u64,
3832 memo_bytes: impl Fn(&D::Memo) -> &[u8; 512],
3833 wallet_note: impl Fn(D::Note) -> Note,
3834 ) -> Result<SentTransactionOutput<AccountId>, ExtractErrT<DbT, N>> {
3835 let pk_d = D::get_pk_d(¬e);
3836 let esk = D::derive_esk(¬e).expect("notes are post-ZIP 212");
3837 let memo = try_output_recovery_with_pkd_esk(&domain, pk_d, esk, output).map(|(_, _, m)| {
3838 MemoBytes::from_bytes(memo_bytes(&m)).expect("Memo is the correct length.")
3839 });
3840
3841 let note_commitment_tree = match output_pool {
3845 ShieldedPool::Sapling => NoteCommitmentTree::Sapling,
3846 ShieldedPool::Orchard => NoteCommitmentTree::Orchard,
3847 ShieldedPool::Ironwood => NoteCommitmentTree::Ironwood,
3848 };
3849
3850 let note_value = Zatoshis::try_from(note_value(¬e))?;
3851 let recipient = match (pczt_recipient, external_address) {
3852 (PcztRecipient::External, Some(addr)) => Ok(Recipient::External {
3853 recipient_address: addr,
3854 output_pool: PoolType::Shielded(output_pool),
3855 }),
3856 (PcztRecipient::External, None) => Err(PcztError::Invalid(
3857 "external recipient needs to have its user_address field set".into(),
3858 )),
3859 #[cfg(feature = "transparent-inputs")]
3860 (PcztRecipient::EphemeralTransparent { .. }, _) => Err(PcztError::Invalid(
3861 "shielded output cannot be EphemeralTransparent".into(),
3862 )),
3863 #[cfg(feature = "transparent-inputs")]
3864 (PcztRecipient::InternalTransparent { .. }, _) => Err(PcztError::Invalid(
3865 "shielded output cannot be InternalTransparent".into(),
3866 )),
3867 (PcztRecipient::InternalShielded { receiving_account }, external_address) => {
3868 Ok(Recipient::InternalShielded {
3869 receiving_account,
3870 external_address,
3871 note: Box::new(wallet_note(note)),
3872 })
3873 }
3874 }?;
3875
3876 Ok(SentTransactionOutput::from_parts_in_tree(
3877 Some(note_commitment_tree),
3878 output_index,
3879 recipient,
3880 note_value,
3881 memo,
3882 ))
3883 }
3884
3885 #[cfg(feature = "orchard")]
3886 let orchard_outputs = transaction
3887 .orchard_bundle()
3888 .map(|bundle| {
3889 assert_eq!(bundle.actions().len(), orchard_output_info.len());
3890 bundle
3891 .actions()
3892 .iter()
3893 .zip(orchard_output_info)
3894 .enumerate()
3895 .filter_map(|(output_index, (action, output_info))| {
3896 output_info.map(|((pczt_recipient, external_address), note)| {
3897 let domain = OrchardDomain::for_action(action);
3898 to_sent_transaction_output::<_, _, _, DbT, _>(
3899 domain,
3900 note,
3901 action,
3902 ShieldedPool::Orchard,
3903 output_index,
3904 pczt_recipient,
3905 external_address,
3906 |note| note.value().inner(),
3907 |memo| memo,
3908 |note| Note::Orchard {
3909 note,
3910 pool: orchard::ValuePool::Orchard,
3911 },
3912 )
3913 })
3914 })
3915 .collect::<Result<Vec<_>, _>>()
3916 })
3917 .transpose()?;
3918
3919 #[cfg(feature = "orchard")]
3920 let ironwood_outputs = transaction
3921 .ironwood_bundle()
3922 .map(|bundle| {
3923 assert_eq!(bundle.actions().len(), ironwood_output_info.len());
3924 bundle
3925 .actions()
3926 .iter()
3927 .zip(ironwood_output_info)
3928 .enumerate()
3929 .filter_map(|(output_index, (action, output_info))| {
3930 output_info.map(|((pczt_recipient, external_address), note)| {
3931 let domain = IronwoodDomain::for_action(action);
3932 to_sent_transaction_output::<_, _, _, DbT, _>(
3933 domain,
3934 note,
3935 action,
3936 ShieldedPool::Ironwood,
3937 output_index,
3938 pczt_recipient,
3939 external_address,
3940 |note| note.value().inner(),
3941 |memo| memo,
3942 |note| Note::Orchard {
3943 note,
3944 pool: orchard::ValuePool::Ironwood,
3945 },
3946 )
3947 })
3948 })
3949 .collect::<Result<Vec<_>, _>>()
3950 })
3951 .transpose()?;
3952
3953 let sapling_outputs = transaction
3954 .sapling_bundle()
3955 .map(|bundle| {
3956 assert_eq!(bundle.shielded_outputs().len(), sapling_output_info.len());
3957 bundle
3958 .shielded_outputs()
3959 .iter()
3960 .zip(sapling_output_info)
3961 .enumerate()
3962 .filter_map(|(output_index, (action, output_info))| {
3963 output_info.map(|((pczt_recipient, external_address), note)| {
3964 let domain =
3965 SaplingDomain::new(sapling::note_encryption::Zip212Enforcement::On);
3966 to_sent_transaction_output::<_, _, _, DbT, _>(
3967 domain,
3968 note,
3969 action,
3970 ShieldedPool::Sapling,
3971 output_index,
3972 pczt_recipient,
3973 external_address,
3974 |note| note.value().inner(),
3975 |memo| memo,
3976 Note::Sapling,
3977 )
3978 })
3979 })
3980 .collect::<Result<Vec<_>, _>>()
3981 })
3982 .transpose()?;
3983
3984 #[allow(unused_variables)]
3985 let transparent_outputs = transaction
3986 .transparent_bundle()
3987 .map(|bundle| {
3988 assert_eq!(bundle.vout.len(), transparent_output_info.len());
3989 bundle
3990 .vout
3991 .iter()
3992 .zip(transparent_output_info)
3993 .enumerate()
3994 .filter_map(|(output_index, (output, output_info))| {
3995 output_info.map(|(pczt_recipient, external_address)| {
3996 let outpoint = OutPoint::new(txid.into(), output_index as u32);
4001
4002 let recipient = match (pczt_recipient, external_address) {
4003 (PcztRecipient::External, Some(addr)) => {
4004 Ok(Recipient::External {
4005 recipient_address: addr,
4006 output_pool: PoolType::Transparent,
4007 })
4008 }
4009 (PcztRecipient::External, None) => Err(PcztError::Invalid(
4010 "external recipient needs to have its user_address field set".into(),
4011 )),
4012 #[cfg(feature = "transparent-inputs")]
4013 (PcztRecipient::EphemeralTransparent { receiving_account }, _) => output
4014 .recipient_address()
4015 .ok_or(PcztError::Invalid(
4016 "Ephemeral outputs cannot have a non-standard script_pubkey"
4017 .into(),
4018 ))
4019 .map(|ephemeral_address| Recipient::EphemeralTransparent {
4020 receiving_account,
4021 ephemeral_address,
4022 outpoint,
4023 }),
4024 #[cfg(feature = "transparent-inputs")]
4025 (PcztRecipient::InternalTransparent { receiving_account }, _) => output
4026 .recipient_address()
4027 .ok_or(PcztError::Invalid(
4028 "Transparent change outputs cannot have a non-standard script_pubkey"
4029 .into(),
4030 ))
4031 .map(|recipient_address| Recipient::InternalTransparent {
4032 receiving_account,
4033 recipient_address,
4034 }),
4035 (
4036 PcztRecipient::InternalShielded {
4037 receiving_account,
4038 },
4039 _,
4040 ) => Err(PcztError::Invalid(
4041 "Transparent output cannot be InternalShielded".into(),
4042 )),
4043 }?;
4044
4045 Ok(SentTransactionOutput::from_parts(
4046 output_index,
4047 recipient,
4048 output.value(),
4049 None,
4050 ))
4051 })
4052 })
4053 .collect::<Result<Vec<_>, ExtractErrT<DbT, _>>>()
4054 })
4055 .transpose()?;
4056
4057 let mut outputs: Vec<SentTransactionOutput<_>> = vec![];
4058 #[cfg(feature = "orchard")]
4059 outputs.extend(orchard_outputs.into_iter().flatten());
4060 #[cfg(feature = "orchard")]
4061 outputs.extend(ironwood_outputs.into_iter().flatten());
4062 outputs.extend(sapling_outputs.into_iter().flatten());
4063 outputs.extend(transparent_outputs.into_iter().flatten());
4064
4065 let fee_amount = transaction
4066 .fee_paid(|outpoint| Ok::<_, BalanceError>(utxos_map.get(outpoint).copied()))?
4067 .expect("input map was constructed correctly");
4070
4071 let utxos_spent = utxos_map.into_keys().collect::<Vec<_>>();
4073
4074 let created = time::OffsetDateTime::from(clock.now());
4075
4076 let transactions = vec![SentTransaction::new(
4077 &transaction,
4078 created,
4079 proposal_info.target_height,
4080 proposal_info.from_account,
4081 &outputs,
4082 fee_amount,
4083 #[cfg(feature = "transparent-inputs")]
4084 &utxos_spent,
4085 )];
4086
4087 wallet_db
4088 .store_transactions_to_be_sent(&transactions)
4089 .map_err(Error::DataSource)?;
4090
4091 Ok(txid)
4092}
4093
4094#[cfg(feature = "transparent-inputs")]
4129#[allow(clippy::too_many_arguments)]
4130#[allow(clippy::type_complexity)]
4131pub fn shield_transparent_funds<DbT, ParamsT, InputsT, ChangeT>(
4132 wallet_db: &mut DbT,
4133 params: &ParamsT,
4134 clock: &impl Clock,
4135 rng: &mut impl CryptoRng,
4136 spend_prover: &impl SpendProver,
4137 output_prover: &impl OutputProver,
4138 input_selector: &InputsT,
4139 change_strategy: &ChangeT,
4140 shielding_threshold: Zatoshis,
4141 spending_keys: &SpendingKeys,
4142 from_addrs: &[TransparentAddress],
4143 to_account: <DbT as InputSource>::AccountId,
4144 confirmations_policy: ConfirmationsPolicy,
4145) -> Result<NonEmpty<TxId>, ShieldErrT<DbT, InputsT, ChangeT>>
4146where
4147 ParamsT: consensus::Parameters,
4148 DbT: WalletWrite + WalletCommitmentTrees + InputSource<Error = <DbT as WalletRead>::Error>,
4149 InputsT: ShieldingSelector<InputSource = DbT>,
4150 ChangeT: ChangeStrategy<MetaSource = DbT>,
4151{
4152 let proposal = propose_shielding(
4153 wallet_db,
4154 params,
4155 input_selector,
4156 change_strategy,
4157 shielding_threshold,
4158 from_addrs,
4159 to_account,
4160 confirmations_policy,
4161 CoinbaseFilter::AllTransparentOutputs,
4162 None,
4163 )?;
4164
4165 create_proposed_transactions(
4166 wallet_db,
4167 params,
4168 clock,
4169 rng,
4170 spend_prover,
4171 output_prover,
4172 spending_keys,
4173 OvkPolicy::Sender,
4174 &proposal,
4175 None,
4176 )
4177}
4178
4179#[cfg(test)]
4180mod tests {
4181 use super::*;
4182
4183 use zcash_protocol::zip318::{AnchorBucketInterval, BlockSpacing};
4184
4185 fn policy(confirmations: u32) -> ConfirmationsPolicy {
4186 ConfirmationsPolicy::new_symmetrical_unchecked(
4187 confirmations,
4188 #[cfg(feature = "transparent-inputs")]
4189 false,
4190 )
4191 }
4192
4193 fn target(height: u32) -> TargetHeight {
4194 TargetHeight::from(BlockHeight::from_u32(height))
4195 }
4196
4197 #[test]
4201 fn bucketed_policy_lands_the_anchor_on_a_boundary() {
4202 let interval = AnchorGrid::new(AnchorBucketInterval::ZIP_318, BlockSpacing::UNIFORM);
4203 let policy = policy(10);
4204
4205 for height in [2_000_000u32, 2_000_143, 2_000_144, 1_000_000] {
4206 let target = target(height);
4207 let bucketed = policy
4208 .bucketed(interval, target, BlockHeight::from_u32(1))
4209 .expect("a boundary is reachable well above the grid's origin");
4210 let anchor = bucketed.anchor_height(target);
4211
4212 assert!(
4213 interval.is_boundary(anchor),
4214 "anchor {anchor:?} off the grid"
4215 );
4216 let most_recent = interval.boundary_at_or_below(policy.anchor_height(target));
4218 assert_eq!(
4219 u32::from(anchor),
4220 u32::from(most_recent) - interval.interval().block_count().get(),
4221 "the chosen boundary must be exactly one interval below the most recent"
4222 );
4223 assert!(anchor < most_recent, "an age of 0 is not admissible");
4224 assert!(bucketed.trusted() >= policy.trusted());
4226 assert!(bucketed.untrusted() >= bucketed.trusted());
4227 assert!(
4230 u32::from(bucketed.trusted()) - u32::from(policy.trusted())
4231 < 2 * interval.interval().block_count().get()
4232 );
4233 }
4234 }
4235
4236 #[test]
4239 fn bucketing_never_chooses_the_most_recent_boundary() {
4240 let interval = AnchorGrid::new(AnchorBucketInterval::ZIP_318, BlockSpacing::UNIFORM);
4241 let policy = policy(10);
4242 let aligned_anchor = interval.boundary_at_or_below(BlockHeight::from_u32(2_000_000));
4243 let target = target(u32::from(aligned_anchor) + 10);
4244
4245 let bucketed = policy
4246 .bucketed(interval, target, BlockHeight::from_u32(1))
4247 .expect("reachable");
4248 assert_eq!(
4249 u32::from(bucketed.anchor_height(target)),
4250 u32::from(aligned_anchor) - interval.interval().block_count().get()
4251 );
4252 assert!(bucketed.trusted() > policy.trusted());
4253 }
4254
4255 #[test]
4258 fn bucketing_declines_below_the_first_boundary() {
4259 let interval = AnchorGrid::new(AnchorBucketInterval::ZIP_318, BlockSpacing::UNIFORM);
4260 let policy = policy(10);
4261 assert!(
4264 policy
4265 .bucketed(interval, target(100), BlockHeight::from_u32(1))
4266 .is_none()
4267 );
4268 }
4269
4270 #[test]
4272 fn bucketing_honours_a_custom_interval() {
4273 let interval = AnchorGrid::new(
4274 AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero")),
4275 BlockSpacing::UNIFORM,
4276 );
4277 let policy = policy(3);
4278 let target = target(1_000);
4279
4280 let bucketed = policy
4281 .bucketed(interval, target, BlockHeight::from_u32(1))
4282 .expect("reachable");
4283 let anchor = bucketed.anchor_height(target);
4284 assert!(interval.is_boundary(anchor));
4285 assert_eq!(u32::from(anchor), 984);
4287 }
4288
4289 #[test]
4292 fn bucketing_follows_the_scaled_grid_from_nu7() {
4293 let activation = 1_000_000u32;
4294 let grid = AnchorGrid::new(
4295 AnchorBucketInterval::ZIP_318,
4296 BlockSpacing::with_nu7_activation(BlockHeight::from_u32(activation)),
4297 );
4298 let scaled_interval = consensus::NU7_POW_TARGET_SPACING_RATIO
4299 * AnchorBucketInterval::ZIP_318.block_count().get();
4300 let policy = policy(10);
4301 let target = target(2_000_000);
4302
4303 let bucketed = policy
4304 .bucketed(grid, target, BlockHeight::from_u32(1))
4305 .expect("reachable");
4306 let anchor = u32::from(bucketed.anchor_height(target));
4307 let most_recent = u32::from(grid.boundary_at_or_below(policy.anchor_height(target)));
4308 assert_eq!(most_recent % scaled_interval, 0);
4309 assert_eq!(anchor, most_recent - scaled_interval);
4310 }
4311}