Skip to main content

zcash_client_backend/data_api/
wallet.rs

1//! # Functions for creating Zcash transactions that spend funds belonging to the wallet
2//!
3//!
4//! This module contains several different ways of creating Zcash transactions. This module is
5//! designed around the idea that a Zcash wallet holds its funds in notes in either the Orchard
6//! or Sapling shielded pool. In order to better preserve users' privacy, it does not provide any
7//! functionality that allows users to directly spend transparent funds except by sending them to a
8//! shielded internal address belonging to their wallet.
9//!
10//! The important high-level operations provided by this module are [`propose_transfer`],
11//! and [`create_proposed_transactions`].
12//!
13//! [`propose_transfer`] takes a [`TransactionRequest`] object, selects inputs notes and
14//! computes the fees required to satisfy that request, and returns a [`Proposal`] object that
15//! describes the transaction to be made.
16//!
17//! [`create_proposed_transactions`] constructs one or more Zcash [`Transaction`]s based upon a
18//! provided [`Proposal`], stores them to the wallet database, and returns the [`TxId`] for each
19//! constructed transaction to the caller. The caller can then use the
20//! [`WalletRead::get_transaction`] method to retrieve the newly constructed transactions. It is
21//! the responsibility of the caller to retrieve and serialize the transactions and submit them for
22//! inclusion into the Zcash blockchain.
23//!
24#![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)]
34//! [`TransactionRequest`]: crate::zip321::TransactionRequest
35//! [`propose_transfer`]: crate::data_api::wallet::propose_transfer
36
37use 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/// Information about the proposal from which a PCZT was created.
169///
170/// Stored under the proprietary field `PROPRIETARY_PROPOSAL_INFO`.
171#[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/// Reduced version of [`Recipient`] stored inside a PCZT.
183///
184/// Stored under the proprietary field `PROPRIETARY_OUTPUT_INFO`.
185#[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    // This variant is placed at the end of the enum in order to preserve the encoded
197    // representation of the prior variants.
198    #[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
248/// Scans a [`Transaction`] for any information that can be decrypted by the accounts in
249/// the wallet, and saves it to the wallet.
250pub 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    // Fetch the UnifiedFullViewingKeys we are tracking
261    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
274/// Errors that may be generated in construction of proposals for shielded->shielded or
275/// shielded->transparent transfers.
276pub 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
285/// Errors that may be generated in construction of proposals for shielded->shielded or
286/// shielded->transparent transactions that transfer the maximum value available within an account
287/// and do not produce change outputs.
288pub 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/// Errors that may be generated in construction of proposals for transparent->shielded
298/// wallet-internal transfers.
299#[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
309/// Errors that may be generated in combined creation and execution of transaction proposals.
310pub 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
319/// Errors that may be generated in the execution of proposals that may send shielded inputs.
320pub 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/// Errors that may be generated in the execution of shielding proposals.
330#[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/// Errors that may be generated when extracting a transaction from a PCZT.
341#[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/// A wrapper type around [`BlockHeight`] that represents the _next_ chain tip.
352///
353/// Addition and subtraction are provided by proxying to [`BlockHeight`].
354#[repr(transparent)]
355#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
356pub struct TargetHeight(BlockHeight);
357
358impl TargetHeight {
359    /// Subtracts the provided value from this height, returning [`zcash_protocol::consensus::H0`]
360    /// if this would result in underflow of the wrapped `u32`.
361    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/// A description of the policy that is used to determine what notes are available for spending,
413/// based upon the number of confirmations (the number of blocks in the chain since and including
414/// the block in which a note was produced.)
415///
416/// See [`ZIP 315`] for details including the definitions of "trusted" and "untrusted" notes.
417///
418/// An error indicating that a [`ConfirmationsPolicy`] could not be constructed because the
419/// trusted confirmation count exceeds the untrusted confirmation count.
420#[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/// [`ZIP 315`]: https://zips.z.cash/zip-0315
433#[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
441/// The default confirmations policy according to [`ZIP 315`].
442///
443/// * Require 3 confirmations for "trusted" transaction outputs (outputs produced by the wallet)
444/// * Require 10 confirmations for "untrusted" outputs (those sent to the wallet by external/third
445///   parties)
446/// * Allow zero-conf shielding of transparent UTXOs irrespective of their origin, but treat the
447///   resulting shielding transaction's outputs as though the original transparent UTXOs had
448///   instead been received as untrusted shielded outputs.
449///
450/// [`ZIP 315`]: https://zips.z.cash/zip-0315
451impl Default for ConfirmationsPolicy {
452    fn default() -> Self {
453        ConfirmationsPolicy {
454            // 3
455            trusted: NonZeroU32::MIN.saturating_add(2),
456            // 10
457            untrusted: NonZeroU32::MIN.saturating_add(9),
458            #[cfg(feature = "transparent-inputs")]
459            allow_zero_conf_shielding: true,
460        }
461    }
462}
463
464impl ConfirmationsPolicy {
465    /// A policy to use the minimum number of confirmations possible: 1 confirmation for shielded
466    /// notes irrespective of origin, and 0 confirmations for spends of transparent UTXOs in
467    /// wallet-internal shielding transactions.
468    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    /// Constructs a new `ConfirmationsPolicy` with `trusted` and `untrusted` fields set to the
476    /// provided values.
477    ///
478    /// The number of confirmations required for trusted notes must be less than or equal to the
479    /// number of confirmations required for untrusted notes; this returns an error if this
480    /// invariant is violated.
481    ///
482    /// WARNING: This should only be used with great care to avoid problems of transaction
483    /// distinguishability; prefer [`ConfirmationsPolicy::default()`] instead.
484    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    /// Constructs a new `ConfirmationsPolicy` with `trusted` and `untrusted` fields both
502    /// set to `min_confirmations`.
503    ///
504    /// WARNING: This should only be used with great care to avoid problems of transaction
505    /// distinguishability; prefer [`ConfirmationsPolicy::default()`] instead.
506    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    /// Constructs a new `ConfirmationsPolicy` with `trusted` and `untrusted` fields set to the
519    /// provided values, which must both be nonzero. The number of trusted confirmations required
520    /// must be less than or equal to the number of untrusted confirmations required.
521    ///
522    /// # Panics
523    /// Panics if `trusted > untrusted` or either argument value is zero.
524    #[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    /// Constructs a new `ConfirmationsPolicy` with `trusted` and `untrusted` fields both
540    /// set to `min_confirmations`.
541    ///
542    /// # Panics
543    /// Panics if `min_confirmations == 0`
544    #[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    /// Returns the number of confirmations required before trusted notes may be spent.
557    ///
558    /// See [`ZIP 315`] for details.
559    ///
560    /// [`ZIP 315`]: https://zips.z.cash/zip-0315#trusted-and-untrusted-txos
561    pub fn trusted(&self) -> NonZeroU32 {
562        self.trusted
563    }
564
565    /// Returns the number of confirmations required before untrusted notes may be spent.
566    ///
567    /// See [`ZIP 315`] for details.
568    ///
569    /// [`ZIP 315`]: https://zips.z.cash/zip-0315#trusted-and-untrusted-txos
570    pub fn untrusted(&self) -> NonZeroU32 {
571        self.untrusted
572    }
573
574    /// Returns the shielded anchor height to use for a transaction targeting `target_height` under
575    /// this policy: `target_height` less the number of required trusted confirmations.
576    ///
577    /// This is the anchor used to interpret a proposal step that carries no explicit anchor height —
578    /// a purely transparent step, whose anchor is unused (see
579    /// [`crate::proposal::Step::anchor_height`]).
580    pub fn anchor_height(&self, target_height: TargetHeight) -> BlockHeight {
581        target_height.saturating_sub(u32::from(self.trusted()))
582    }
583
584    /// Returns this policy adjusted so that the shielded anchor for `target_height` lands on a
585    /// boundary of `grid`, or `None` if no boundary is reachable.
586    ///
587    /// A [ZIP 318] pool crossing is proved against a boundary block rather than the chain tip, so
588    /// that many wallets' crossings share a small set of anchors instead of each pinning a unique
589    /// recent block.
590    ///
591    /// Bucketing is expressed as a RAISED CONFIRMATION REQUIREMENT rather than as a separately
592    /// lowered anchor, because the anchor and the bound on which notes may be spent are the same
593    /// quantity: `target_height` less the required confirmations. Moving that one number moves
594    /// both together, which is what makes it impossible to select a note having no witness at the
595    /// bucketed anchor. Lowering the anchor on its own would leave two numbers free to drift.
596    ///
597    /// The untrusted requirement is raised to match when it would otherwise fall below the trusted
598    /// one, preserving this type's `trusted <= untrusted` invariant.
599    ///
600    /// The boundary chosen is the one BEFORE the most recent one — an anchor age of 1, the
601    /// smallest ZIP 318 admits. Anchoring to the most recent boundary would be an age of 0, which
602    /// no migration transfer uses.
603    ///
604    /// `activation_height` is the activation of the pool being crossed into; the chosen boundary
605    /// must lie strictly above it.
606    ///
607    /// Returns `None` when no usable boundary is reachable: when the ordinary anchor lies below the
608    /// first boundary after `activation_height`, or where the required confirmations would reach
609    /// back past the genesis block. Reporting that as "unable to bucket" is what lets a caller fall
610    /// back, rather than build a proposal that is bound to fail.
611    ///
612    /// [ZIP 318]: https://zips.z.cash/zip-0318
613    pub fn bucketed(
614        &self,
615        grid: AnchorGrid,
616        target_height: TargetHeight,
617        activation_height: BlockHeight,
618    ) -> Option<Self> {
619        // ZIP 318 draws an anchor of AGE `a` in `[1, ANCHOR_AGE_CAP]` boundaries behind the most
620        // recent one, so the chosen boundary is always strictly below it. Age 1 is taken here: the
621        // newest admissible boundary, and the modal age under the migration's `Geometric(1/2)`
622        // draw. Anchoring to the most recent boundary instead would be an age of 0, which no
623        // migration transfer ever uses.
624        let most_recent = grid.boundary_at_or_below(self.anchor_height(target_height));
625        let boundary = grid.boundary_before(most_recent)?;
626
627        // The boundary must lie strictly above the activation of the pool being crossed into.
628        // Rounding down can otherwise land on a PRE-ACTIVATION boundary in the window between
629        // activation and the first boundary after it, and ZIP 318's candidate set contains no such
630        // height — anchoring there would be distinguishable rather than shared. Height zero is
631        // excluded by the same bound, its note commitment tree being empty.
632        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    /// Returns whether or not transparent inputs may be spent with zero confirmations in shielding
647    /// transactions.
648    #[cfg(feature = "transparent-inputs")]
649    pub fn allow_zero_conf_shielding(&self) -> bool {
650        self.allow_zero_conf_shielding
651    }
652
653    /// Returns the number of confirmations until a transaction output is considered spendable,
654    /// given information about the output and the inputs to the transaction that produced it.
655    ///
656    /// # Parameters
657    /// - `target_height`: The minimum height at which the output will be potentially spent.
658    /// - `pool_type`: The Zcash pool that the output was received into.
659    /// - `receiving_key_scope`: The ZIP 32 [`Scope`] of the key that received the output,
660    ///   or `None` if the scope is unknown or corresponds to the ephemeral transparent
661    ///   key scope.
662    /// - `mined_height`: The block height at which the transaction that produced the output was
663    ///   mined, if any.
664    /// - `tx_trusted`: A boolean flag indicating whether the received transaction has been
665    ///   explicitly marked as trusted by the user.
666    /// - `max_shielding_input_height`: For outputs that are the result of wallet-internal
667    ///   shielding transactions, the maximum height at which any transparent input to that
668    ///   transaction was received.
669    /// - `tx_shielding_inputs_trusted`: For outputs that are the result of wallet-internal
670    ///   shielding transactions, a flag indicating whether all transparent inputs to that
671    ///   transaction have been explicitly marked as trusted by the user.
672    #[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        // Trusted outputs of transactions mined at heights greater than `trusted_height` will not
684        // be treated as spendable.
685        let trusted_height = target_height.saturating_sub(u32::from(self.trusted));
686        // Untrusted outputs of transactions mined at heights greater than `untrusted_height` will
687        // not be treated as spendable.
688        let untrusted_height = target_height.saturating_sub(u32::from(self.untrusted));
689
690        // Calculate the possible options for confirmations.
691        // - If the output's tx is unmined, we are constantly waiting for the maximum number of
692        //   confirmations.
693        // - If the output's tx is mined, the required number of confirmations decreases to a floor
694        //   of zero.
695        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 the note was the output of a shielding transaction, we use the mined
719                    // height of the transparent source funds & their trust status instead of the
720                    // height at which the shielding transaction was mined.
721                    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/// Select transaction inputs, compute fees, and construct a proposal for a transaction or series
739/// of transactions that can then be authorized and made ready for submission to the network with
740/// [`create_proposed_transactions`].
741///
742/// When `lock_inputs` is `Some(request)`, every input selected by the returned proposal is
743/// locked via [`OutputLockStore::lock_outputs`] on behalf of the request's [`LockOwner`], with an
744/// expiry height of `target_height + request.for_blocks()`, so that the inputs are excluded from
745/// selection by subsequent proposals until that height is reached (or until they are explicitly
746/// released; see below). When it is `None`, no locking is performed.
747///
748/// This is the owner- and height-based generalization of the `lock_notes: bool` parameter
749/// originally proposed in [zcash/librustzcash#2161].
750///
751/// # Concurrency
752///
753/// Locking is how overlapping proposals for the same account are kept from selecting the same
754/// inputs. If a concurrent caller (a different [`LockOwner`]) has already locked one of the
755/// inputs this proposal selected (a check-then-lock race resolved at the storage layer), locking
756/// fails and the error surfaces as [`ProposalError::InputsLocked`] identifying the conflicting
757/// output; the losing caller should treat this as "the account is busy" and retry. Re-locking
758/// under the SAME owner succeeds (an idempotent acquire/extend), so a flow that crashed after
759/// locking may safely retry with its original owner token. A caller that abandons a proposal
760/// whose inputs it locked should release them with [`unlock_proposal_inputs`] under the same
761/// owner; locks are otherwise cleared automatically when the inputs are recorded as spent by
762/// [`WalletWrite::store_transactions_to_be_sent`], when their expiry height is reached, or via
763/// [`OutputLockStore::clear_locked_outputs`].
764///
765/// Note that expiry re-opens the race the lock exists to prevent: if building and proving the
766/// transaction takes longer than the requested lock window, the lock expires and a concurrent
767/// proposal may select and spend the same inputs. Choose the window conservatively with respect
768/// to the worst-case time between proposal creation and transaction storage.
769///
770/// [`LockOwner`]: crate::wallet::LockOwner
771/// [`OutputLockStore::lock_outputs`]: crate::data_api::OutputLockStore::lock_outputs
772/// [`WalletWrite::store_transactions_to_be_sent`]: crate::data_api::WalletWrite::store_transactions_to_be_sent
773/// [`OutputLockStore::clear_locked_outputs`]: crate::data_api::OutputLockStore::clear_locked_outputs
774/// [zcash/librustzcash#2161]: https://github.com/zcash/librustzcash/issues/2161
775#[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    // Using the trusted confirmations results in an anchor_height that will
800    // include the maximum number of notes being selected, and we can filter
801    // later based on the input source (whether it's trusted or not) and the
802    // number of confirmations
803    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    // The ZIP 318 parameters in force for THIS wallet. The anchor bucket grid must come from the
810    // wallet rather than the network defaults: the wallet is the side that retains the
811    // checkpoints, so its grid is the only one a crossing can actually be proved against, and
812    // every decision below that depends on the grid consults this one value.
813    let zip318 = wallet_db.pool_migration_params(params);
814
815    // A payment of a canonical ZIP 318 denomination across the Orchard turnstile is proposed
816    // against a BUCKETED anchor and funded from a single Orchard note, so that the resulting
817    // transaction is indistinguishable from a ZIP 318 migration transfer (see
818    // `Step::is_canonical_crossing`). Whether that is achievable is decided here, before any
819    // proposal is kept, rather than discovered by failure: the common miss is not insufficient
820    // funds but a SUCCESSFUL multi-note selection, which funds perfectly well yet is not a
821    // canonical crossing. Falling back only on insufficient funds would leave such a transaction
822    // carrying a bucketed anchor — up to one interval of extra confirmations on its inputs — while
823    // still being built padded, which is worse than never having tried.
824    //
825    // Selection is restricted to the Orchard pool for the attempt. That is not merely a
826    // preference: a canonical crossing admits no Ironwood spends, and the ordinary selector
827    // prefers to avoid crossing pools, so for an Ironwood-destined payment it reaches for Ironwood
828    // notes whenever the wallet holds them. Without the restriction, a user migrating their own
829    // funds by sending themselves canonical amounts would stall as soon as the first crossing
830    // produced Ironwood notes: every later payment would be funded from Ironwood, crossing
831    // nothing, and no further value would ever leave the Orchard pool.
832    //
833    // The canonical fee for the shape, under the parameters and target height this transaction
834    // will actually be built against. The STANDARD ZIP 317 rule is asked, not the caller's: a
835    // proposal built on a fixed non-standard rule would otherwise be compared against its own fee
836    // and always agree, which is precisely the case ZIP 318 forbids.
837    #[cfg(feature = "orchard")]
838    let canonical_fee = crate::fees::canonical_crossing_fee(params, target_height.into()).ok();
839
840    // The whole attempt is Orchard-gated: without that feature there is no Ironwood pool to cross
841    // into, so there is no canonical crossing to construct.
842    #[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        // A canonical crossing spends an Orchard note; if the caller forbids that, there is no
850        // canonical path to attempt.
851        .filter(|_| spend_policy.permits_shielded(ShieldedPool::Orchard));
852
853    // An anchor must be COMPUTABLE at the chosen boundary, not merely arithmetically valid: the
854    // data source must be able to produce the Orchard tree root there. A wallet that scanned
855    // past NU6.3 activation before boundary checkpointing was repaired is permanently missing
856    // the boundaries whose blocks carried no shielded outputs, and the hole cannot be backfilled
857    // from local state. Abandoning the attempt here degrades to an ordinary crossing — the same
858    // fallback taken when no sufficiently-old note exists — rather than proposing a transaction
859    // whose build must fail with `AnchorNotFound`. Under repaired retention the miss is
860    // temporary: freshly scanned boundaries rotate into the age-1 position within about a grid
861    // interval of upgrading.
862    #[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        // Single-note funding is PREFERRED, not merely hoped for: a migration transfer
874        // spends exactly one note, and accumulation reaches the target through several
875        // small notes whenever the oldest notes are small — funding perfectly well while
876        // losing the canonical shape. Preferring the oldest single covering note makes the
877        // canonical outcome the common one; when no single note covers the payment, the
878        // fallback accumulation funds it and the shape check below discards the attempt,
879        // exactly as before.
880        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    // Only two outcomes justify falling back to an ordinary proposal: the wallet cannot fund the
900    // payment under the stricter policy, or it funded one that is not in fact canonical. Every
901    // other error — data source, selection, change computation, proposal construction, address
902    // parsing, sync state — describes a condition the ordinary attempt would meet just the same,
903    // so suppressing it here would replace a precise diagnosis with a silently different
904    // transaction, or with an identical failure reported from a second, wasted selection pass.
905    #[cfg(feature = "orchard")]
906    let canonical_proposal = match canonical_attempt {
907        Some(Ok(proposal)) => {
908            // The authoritative test is the one the builder will also apply, so that there is
909            // exactly one definition of "canonical" and the two cannot disagree. A proposal that
910            // funded successfully but not from a single Orchard note fails it here and is
911            // discarded, costing a selection pass but no extra confirmations.
912            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    // Record the requested version on the proposal so that it is carried through to transaction
948    // building; when `None`, building falls back to the version implied by the target height.
949    Ok(proposal.with_proposed_version(proposed_version))
950}
951
952/// Returns whether `request` is worth attempting as a canonical ZIP 318 crossing: a single
953/// payment, of a canonical denomination, at a height where the Ironwood pool exists.
954///
955/// This is a cheap gate, not a decision. It deliberately does not resolve the recipient address to
956/// an output pool, nor consider which notes are available: those depend on input selection, which
957/// has not run yet. The authoritative test is [`Step::is_canonical_crossing`] applied to the
958/// resulting proposal, so a request that passes here but produces a non-canonical proposal is
959/// simply discarded. Keeping the gate loose avoids duplicating address-resolution logic that would
960/// then have to be kept in step with input selection.
961#[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/// Returns whether `step` will be built as a canonical ZIP 318 crossing, under the ZIP 318
978/// parameters `wallet_db` reports and the fee the canonical shape costs at `target_height`.
979///
980/// Shared by every path that builds a proposal, so that each asks the same question of the same
981/// data. `create_pczt_from_proposal` in particular applies its expiry override after the builder
982/// has run, and so cannot rely on the check inside `build_proposed_transaction`.
983#[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/// Proposes making a payment to the specified address from the given account.
999///
1000/// Returns the proposal, which may then be executed using [`create_proposed_transactions`].
1001/// Depending upon the recipient address, more than one transaction may be constructed
1002/// in the execution of the returned proposal.
1003///
1004/// This method uses the basic [`GreedyInputSelector`] for input selection.
1005///
1006/// Parameters:
1007/// * `wallet_db`: A read/write reference to the wallet database.
1008/// * `params`: Consensus parameters.
1009/// * `fee_rule`: The fee rule to use in creating the transaction.
1010/// * `spend_from_account`: The unified account that controls the funds that will be spent
1011///   in the resulting transaction. This procedure will return an error if the
1012///   account ID does not correspond to an account known to the wallet.
1013/// * `confirmations_policy`: The minimum number of confirmations that a previously
1014///   received note must have in the blockchain in order to be considered for being
1015///   spent. A value of 10 confirmations is recommended and 0-conf transactions are
1016///   not supported.
1017/// * `to`: The address to which `amount` will be paid.
1018/// * `amount`: The amount to send.
1019/// * `memo`: A memo to be included in the output to the recipient.
1020/// * `change_memo`: A memo to be included in any change output that is created.
1021/// * `fallback_change_pool`: The shielded pool to which change should be sent if
1022///   automatic change pool determination fails.
1023/// * `lock_inputs`: When `Some(request)`, the inputs selected by the proposal are locked on
1024///   behalf of the request's owner until `target_height + request.for_blocks()` to prevent
1025///   concurrent proposals from selecting them; when `None`, no locking is performed. See
1026///   [`propose_transfer`] for the full semantics and concurrency behavior.
1027#[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/// Proposes spending the maximum available value from the given shielded pools, sending it
1096/// to a single recipient.
1097///
1098/// Returns the proposal, which may then be executed using [`create_proposed_transactions`].
1099/// Depending upon the recipient address, more than one transaction may be constructed in the
1100/// execution of the returned proposal.
1101///
1102/// Unlike [`propose_transfer`], the caller does not choose an amount. The value sent is
1103/// whatever remains once the fee for the selected inputs is covered, and that fee is not
1104/// knowable in advance because it depends on which inputs the selector picks. This is the
1105/// reason to prefer this function over computing "balance minus fee" in the caller: only
1106/// input selection knows the fee, so only it can leave nothing behind.
1107///
1108/// The wallet must have been scanned far enough to establish target and anchor heights;
1109/// otherwise [`InputSelectorError::SyncRequired`] is returned.
1110///
1111/// Parameters:
1112/// * `wallet_db`: A read/write reference to the wallet database.
1113/// * `params`: Consensus parameters.
1114/// * `spend_from_account`: The unified account that controls the funds that will be spent
1115///   in the resulting transaction. This procedure will return an error if the account ID
1116///   does not correspond to an account known to the wallet.
1117/// * `spend_pools`: The shielded pools that may be drawn upon. Funds in any pool outside
1118///   this set are left untouched, so this is what makes the function usable for moving a
1119///   single pool rather than emptying the account. Transparent funds are never selected.
1120/// * `fee_rule`: The fee rule to use in creating the transaction.
1121/// * `recipient`: The address to which the spendable value will be paid.
1122/// * `memo`: A memo to be included in the output to the recipient. Supplying a memo for a
1123///   recipient that cannot receive one returns [`zip321::PaymentError::TransparentMemo`].
1124/// * `mode`: How to treat funds in `spend_pools` that are not currently spendable, for
1125///   example because a note lacks confirmations or its witness is not yet available.
1126///   [`MaxSpendMode::MaxSpendable`] skips such notes and proposes a transaction spending
1127///   the rest; [`MaxSpendMode::Everything`] returns an error instead, so that a caller who
1128///   needs the pools genuinely emptied cannot be handed a partial result that looks like a
1129///   complete one.
1130/// * `confirmations_policy`: The minimum number of confirmations that a previously
1131///   received note must have in the blockchain in order to be considered for being
1132///   spent. A value of 10 confirmations is recommended and 0-conf transactions are
1133///   not supported.
1134/// * `locked_input_policy`: Whether a locked note may be drawn upon to reach the requested
1135///   amount, exactly as [`input_selection::SpendPolicy::locked_input_policy`] does for
1136///   [`propose_transfer`]; pass `&LockedInputPolicy::Exclude` (its default) to never select
1137///   a locked note.
1138/// * `lock_inputs`: When `Some(request)`, the inputs selected by the proposal are locked on
1139///   behalf of the request's owner until `target_height + request.for_blocks()` to prevent
1140///   concurrent proposals from selecting them; when `None`, no locking is performed. See
1141///   [`propose_transfer`] for the full semantics and concurrency behavior.
1142#[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/// Constructs a proposal to shield all of the funds belonging to the provided set of
1199/// addresses.
1200///
1201/// The `output_filter` parameter controls which transparent outputs are eligible for
1202/// inclusion in the proposal. See [`CoinbaseFilter`] for details.
1203///
1204/// When `lock_inputs` is `Some(request)`, the inputs selected by the proposal are locked on
1205/// behalf of the request's owner until `target_height + request.for_blocks()` to prevent
1206/// concurrent proposals from selecting them; when `None`, no locking is performed. See
1207/// [`propose_transfer`] for the full semantics and concurrency behavior.
1208#[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/// Errors that may be generated in construction of proposals for shielding coinbase
1264/// transparent outputs to an arbitrary shielded recipient via
1265/// [`propose_shielding_coinbase`].
1266#[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/// Constructs a proposal to shield one or more coinbase transparent outputs to an
1277/// arbitrary shielded recipient.
1278///
1279/// Unlike [`propose_shielding`], this method:
1280///
1281/// - Restricts input selection to coinbase outputs only. The restriction is enforced
1282///   at the API boundary; it cannot be overridden by callers. Coinbase outputs have
1283///   no prior transparent transaction graph, which is what makes it acceptable to
1284///   send them to an arbitrary shielded recipient.
1285/// - Requires `to_address` to be a shielded address (Sapling, or a Unified Address
1286///   with a shielded receiver). Transparent and TEX destinations are rejected with
1287///   [`ProposalError::ShieldingRequiresShieldedRecipient`]. The address may belong
1288///   to an account outside the caller's wallet.
1289/// - Accepts an optional `memo` to be attached to the shielded payment.
1290/// - Accepts an optional `limit` capping the number of transparent inputs to at
1291///   most `n`, keeping the highest-value UTXOs (with a stable tiebreaker by
1292///   outpoint). `Some(0)` selects no inputs and therefore returns
1293///   [`InputSelectorError::InsufficientFunds`].
1294///
1295/// When `lock_inputs` is `Some(request)`, the coinbase inputs selected by the proposal are
1296/// locked on behalf of the request's owner until `target_height + request.for_blocks()` to
1297/// prevent concurrent proposals from selecting them; when `None`, no locking is performed. See
1298/// [`propose_transfer`] for the full semantics and concurrency behavior.
1299///
1300/// The resulting proposal carries an explicit ZIP-321 payment to `to_address` for
1301/// `input_total - fee`. **No change is produced**, in either the transparent or any
1302/// shielded pool: a shielded change output would let the recipient (or any chain
1303/// observer) learn the sender's total selected-coinbase value by summing the public
1304/// transparent input values and subtracting the visible payment amount.
1305///
1306/// [`InputSelectorError::InsufficientFunds`]: crate::data_api::wallet::input_selection::InputSelectorError::InsufficientFunds
1307/// [`ProposalError::ShieldingRequiresShieldedRecipient`]: crate::proposal::ProposalError::ShieldingRequiresShieldedRecipient
1308#[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
1368/// A set of spending keys for an account, for use in execution of transaction proposals.
1369///
1370/// This consists of a [`UnifiedSpendingKey`], which may hold keys for only some protocols, plus (if the `transparent-key-import` feature is
1371/// enabled) a set of standalone transparent spending keys corresponding to inputs being spent in a
1372/// transaction under construction.
1373///
1374/// When this value is dropped, the standalone transparent spending keys it holds are
1375/// overwritten. Copies of those keys made elsewhere are not overwritten, because
1376/// [`secp256k1::SecretKey`] is `Copy`.
1377pub 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    /// Constructs a new [`SpendingKeys`] value from its constituent parts.
1385    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    /// Constructs a new [`SpendingKeys`] value from a [`UnifiedSpendingKey`],
1400    /// without standalone spending keys.
1401    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/// Construct, prove, and sign a transaction or series of transactions using the inputs supplied by
1420/// the given proposal, and persist it to the wallet database.
1421///
1422/// Returns the database identifier for each newly constructed transaction, or an error if
1423/// an error occurs in transaction construction, proving, or signing.
1424///
1425/// `rng` supplies the randomness used to construct, prove, and sign each transaction.
1426///
1427/// The account is the one that the viewing key of `spending_keys`'s [`UnifiedSpendingKey`]
1428/// identifies. That key may hold keys for only some protocols. If the proposal spends from, or
1429/// sends change to, a pool for which it holds no key, this returns [`Error::KeyNotAvailable`].
1430///
1431/// When evaluating multi-step proposals, only transparent outputs of any given step may be spent
1432/// in later steps; attempting to spend a shielded note (including change) output by an earlier
1433/// step is not supported, because the ultimate positions of those notes in the global note
1434/// commitment tree cannot be known until the transaction that produces those notes is mined,
1435/// and therefore the required spend proofs for such notes cannot be constructed.
1436///
1437/// `expiry_height`, when set, replaces the builder-derived expiry for every step's
1438/// transaction before it is built and signed.
1439///
1440/// A nonzero `expiry_height` below the proposal's
1441/// [`min_target_height`](Proposal::min_target_height) is rejected with
1442/// [`Error::ExpiryHeightBelowTargetHeight`]. An `expiry_height` of zero,
1443/// which disables expiry, is exempt from this check.
1444#[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    // The transaction version is carried on the proposal, chosen when the proposal was
1464    // constructed; `None` builds at the version implied by the target height.
1465    let proposed_version = proposal.proposed_version();
1466
1467    // Defense-in-depth: reject oversized proposals at the build entry point, so a
1468    // proposal from a third-party input selector or a deserialized proposal that
1469    // bypassed the `propose_*` wrappers cannot reach the expensive proving path.
1470    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    // The set of transparent `StepOutput`s available and unused from prior steps.
1483    // When a transparent `StepOutput` is created, it is added to the map. When it
1484    // is consumed, it is removed from the map.
1485    #[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    // Ephemeral outputs must be referenced exactly once.
1522    #[cfg(feature = "transparent-inputs")]
1523    for so in unused_transparent_outputs.into_keys() {
1524        if let StepOutputIndex::Change(i) = so.output_index() {
1525            // references have already been checked
1526            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    // Store the transactions only after creating all of them. This avoids undesired
1535    // retransmissions in case a transaction is stored and the creation of a subsequent
1536    // transaction fails.
1537    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/// A recipient of a shielded output under construction, awaiting the decrypted [`Note`]
1563/// that [`ShieldedBuildRecipient::into_recipient`] will attach to produce a [`Recipient`].
1564#[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/// A recipient of a transparent output under construction, awaiting the [`OutPoint`] (for
1599/// ephemeral outputs only) that [`TransparentBuildRecipient::into_recipient`] will attach
1600/// to produce a [`Recipient`].
1601#[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    /// Never constructed. Present only so that `AccountId` remains a used type parameter
1618    /// when `transparent-inputs` is disabled, in which case the two variants above (the
1619    /// only ones that otherwise reference it) do not exist. The uninhabited
1620    /// [`core::convert::Infallible`] field lets every match on this type prove, rather than
1621    /// assert, that this arm is unreachable.
1622    #[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
1701/// Enforces the ZIP 316 Revision 2 address expiration rules for a payment recipient: a
1702/// payment must not be made to an address that is known to have expired, and when the
1703/// recipient defines an expiry height, the transaction must carry a nonzero expiry
1704/// height no greater than it. All recipients of a multi-recipient transaction are
1705/// subject to these constraints.
1706///
1707/// An address that defines an expiry height is expired once the chain has advanced past
1708/// that height. `min_target_height` is the next chain tip, so the tip that expiry is
1709/// evaluated against is one block below it.
1710fn 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        // A clock before the Unix epoch reads as time zero, at which no address with
1741        // expiry-time metadata is expired.
1742        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// `unused_transparent_outputs` maps `StepOutput`s for transparent outputs
1755// that have not been consumed so far, to the corresponding pair of
1756// `TransparentAddress` and `Outpoint`.
1757#[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    // The transactional bundle padding for the Orchard and Ironwood bundles; the PCZT path
1775    // threads the proposal's configured padding here, other callers pass
1776    // `BundlePadding::DEFAULT`.
1777    orchard_pool_padding: BundlePadding,
1778    // Overrides the builder-derived expiry height, when set. Applied immediately after
1779    // `Builder::new` below, before any inputs are added or signatures/proofs are produced.
1780    expiry_height: Option<BlockHeight>,
1781    // The current time, used to enforce recipient address expiry.
1782    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    // We only support spending transparent payments or transparent ephemeral outputs from a
1796    // prior step (when "transparent-inputs" is enabled).
1797    #[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        // Return an error on trying to spend a prior output that is not supported.
1816        #[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    // Every shielded-tree lookup for this step is bound to a single anchor height, so that a
1825    // transaction with only routed shielded outputs (for example, an Orchard-receiver payment
1826    // routed into a fresh Ironwood bundle post-NU6.3) is indistinguishable from one that spends
1827    // real notes in that pool. Any step that produces a shielded bundle carries the anchor selected
1828    // at proposal construction time; a purely transparent step performs no shielded-tree lookup, so
1829    // the value resolved here from the confirmations policy is unused.
1830    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    // The Ironwood bundle is required exactly when the step involves the Ironwood pool, mirroring
1926    // the Sapling and Orchard gating above. A payment to an Orchard-protocol receiver post-NU6.3
1927    // targets the Ironwood pool, so input selection classifies it as an Ironwood-pool output; it
1928    // is therefore captured by `involves(Ironwood)`. Transactions with no Ironwood-pool inputs or
1929    // outputs (for example a pure-Sapling spend or a transparent-to-Sapling shielding) must not
1930    // require an Ironwood anchor, even once Ironwood is active.
1931    #[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    // Create the transaction. The type of the proposal ensures that there
1982    // The Ironwood bundle's padding is DERIVED from the step, independently of the Orchard
1983    // bundle's: it is unpadded for a canonical ZIP 318 crossing and padded otherwise. The two
1984    // pools' padding is deliberately not coupled — an Orchard bundle is always padded, and the
1985    // Ironwood bundle drops its padding only when doing so makes the transaction indistinguishable
1986    // from a migration transfer. The fee model reaches the same conclusion from the same data (see
1987    // `fees::common::single_pool_output_balance`), which is what keeps the computed fee and the
1988    // built bundle in agreement.
1989    #[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    // are no possible transparent inputs, so we ignore those here.
1995    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    // A canonical crossing takes the ZIP 318 rolling expiry, which every crossing in the same
2007    // modulus period shares. The builder's ordinary per-transaction expiry (target height plus a
2008    // small delta) would single it out immediately, undoing the shape the unpadded bundle and the
2009    // bucketed anchor were chosen to produce. A caller-supplied expiry is refused rather than
2010    // silently overridden: the padding and anchor are already fixed by this point, so honouring it
2011    // would emit a transaction that is canonical in every respect but one.
2012    #[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    // The expiry height the built transaction will carry, or `None` if it does not expire.
2034    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        // We assume here that prior step outputs cannot be shielded, due to checks above (and the
2056        // fact that the witness required to spend such outputs could not be computed.)
2057        #[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    // Post-NU6.3 the Orchard bundle enforces the cross-address restriction, so Orchard-pool
2081    // change must be returned to a spent Orchard note's own address to remain in the Orchard pool
2082    #[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                // `wallet_db.get_transparent_address_metadata` includes reserved ephemeral
2117                // addresses in its lookup. We don't need to include these in order to be
2118                // able to construct ZIP 320 transactions, because in that case the ephemeral
2119                // output is represented via a "change" reference to a previous step. However,
2120                // we do need them in order to create a transaction from a proposal that
2121                // explicitly spends an output from an ephemeral address (only for outputs
2122                // already detected by this wallet instance).
2123
2124                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                    // An address imported without key material cannot construct a spend: the
2173                    // wallet holds neither the pubkey nor the redeem script for the input.
2174                    #[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            // A referenced transparent step output must exist and be referenced *at most* once.
2194            // (Exactly once in the case of ephemeral outputs.)
2195            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                        // The payment is built into the Ironwood bundle, so its sent-note record
2328                        // belongs to the Ironwood pool. (Post-NU6.3 an Orchard-pool payment output
2329                        // is forbidden when spending Orchard; only change may return to Orchard.)
2330                        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                    // Legacy Orchard payment (pre-NU6.3). Once Ironwood is active, input
2381                    // selection assigns Orchard-receiver payments the Ironwood output pool
2382                    // instead, so this arm always builds a plain Orchard output.
2383                    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                    // Ironwood payment (post-NU6.3): delivered to the recipient's Orchard
2397                    // receiver, but through the Ironwood bundle, a pool distinct from Orchard.
2398                    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                        // Post-NU6.3 with an Orchard spend: the change stays in the Orchard pool,
2467                        // returned to a spent note's own address so it satisfies the Orchard V3
2468                        // cross-address restriction. Only the payment crosses into Ironwood. The
2469                        // Orchard V3 bundle forbids ordinary outputs, so the change is added via
2470                        // `add_orchard_change_output`, which pairs it with a fabricated same-address
2471                        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                // Transparent change outputs (both ephemeral outputs used in multi-step
2506                // proposals and non-ephemeral change sent to internal-scope addresses)
2507                // are added to the transaction below, after address reservation.
2508                #[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    // This reserves the ephemeral addresses even if transaction construction fails.
2544    // It is not worth the complexity of being able to unreserve them, because there
2545    // are few failure modes after this point that would allow us to do so.
2546    #[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        // We don't need the TransparentAddressSource here; we can look it up from the data source later.
2564        for ((change_index, change_value), (ephemeral_address, _)) in
2565            ephemeral_outputs.iter().zip(addresses_and_metadata)
2566        {
2567            // This output is ephemeral; we will report an error in `create_proposed_transactions`
2568            // if a later step does not consume it.
2569            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    // Add any transparent change outputs, sending them to the next available internal-scope
2583    // (change) transparent addresses of the account. As with ephemeral addresses above, this
2584    // reserves the internal addresses even if transaction construction subsequently fails.
2585    #[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// `unused_transparent_outputs` maps `StepOutput`s for transparent outputs
2642// that have not been consumed so far, to the corresponding pair of
2643// `TransparentAddress` and `Outpoint`.
2644#[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        // The non-PCZT path always builds padded Orchard-pool bundles.
2690        BundlePadding::DEFAULT,
2691        expiry_height,
2692        now,
2693    )?;
2694
2695    // Build the transaction with the specified fee rule
2696    #[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            // Unreachable in practice: inputs from an address imported without key material
2726            // are rejected when the proposed transaction is constructed.
2727            #[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    // The builder adds wallet-internal outputs only to pools for which the spending key holds
2762    // a key, so the IVK for each such output is present.
2763    #[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    // Same-address Orchard change (post-NU6.3, when spending Orchard notes) is returned to a spent
2771    // note's own address, which may be external-scoped; try the external IVK as well so such change
2772    // outputs remain decryptable for recording.
2773    #[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            // The Ironwood output is stored at its raw index within the Ironwood bundle — the same
2843            // index the scanner assigns — so the send and scan write paths agree. Each shielded
2844            // pool has its own received-notes table keyed by (transaction, action_index), so
2845            // Orchard and Ironwood indices never collide despite both starting at zero.
2846            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            // This assumes that transparent outputs are pushed onto `transparent_output_meta`
2911            // with the same indices they have in the transaction's transparent outputs.
2912            // We do not reorder transparent outputs; there is no reason to do so because it
2913            // would not usefully improve privacy.
2914            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/// Constructs a transaction using the inputs supplied by the given proposal.
2947///
2948/// Only single-step proposals are currently supported.
2949///
2950/// Returns a partially-created Zcash transaction (PCZT) that is ready to be authorized.
2951/// You can use the following roles for this:
2952/// - [`pczt::roles::prover::Prover`]
2953/// - [`pczt::roles::signer::Signer`] (if you have local access to the spend authorizing
2954///   keys)
2955/// - [`pczt::roles::combiner::Combiner`] (if you create proofs and apply signatures in
2956///   parallel)
2957///
2958/// Before sending the PCZT to an external Signer, create a signer view with
2959/// [`redact_pczt_for_signer`] and retain the original for combination.
2960/// A Signer that independently obtains the relevant full viewing keys and returns
2961/// only Orchard-protocol signature contributions can instead use
2962/// [`redact_pczt_for_batch_signer`].
2963///
2964/// Once the PCZT fully authorized, call [`extract_and_store_transaction_from_pczt`] to
2965/// finish transaction creation.
2966///
2967/// `expiry_height`, when set, replaces the builder-derived expiry before
2968/// the PCZT is finalized. Applying this override after finalization can invalidate
2969/// dummy spend signatures.
2970///
2971/// A nonzero `expiry_height` below the proposal's
2972/// [`min_target_height`](Proposal::min_target_height) is rejected with
2973/// [`Error::ExpiryHeightBelowTargetHeight`]. An `expiry_height` of zero,
2974/// which disables expiry, is exempt from this check.
2975///
2976/// `orchard_pool_padding` selects the transactional bundle padding for the Orchard
2977/// bundle; pass
2978/// [`BundlePadding::DEFAULT`](zcash_primitives::transaction::builder::BundlePadding).
2979/// The Ironwood bundle's padding is not a caller's to choose: it is derived from the
2980/// proposal by [`Step::ironwood_bundle_padding`](crate::proposal::Step::ironwood_bundle_padding),
2981/// so that it matches the action count the fee was computed from.
2982///
2983/// `rng` supplies the randomness used to construct the PCZT and to sign its dummy spends.
2984#[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    // For now we only support turning single-step proposals into PCZTs.
3012    if proposal.steps().len() > 1 {
3013        return Err(Error::ProposalNotSupported);
3014    }
3015
3016    // Defense-in-depth: reject oversized proposals at the build entry point.
3017    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    // Build at the version the proposal requested, falling back to the version implied by the
3037    // target height (version 6 from NU6.3 onward). Both the version 6 format and its Ironwood
3038    // bundle are fully representable as a PCZT.
3039    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    // Build the transaction with the specified fee rule. The caller's expiry override
3060    // (validated against canonical ZIP 318 crossings) was applied via the builder in
3061    // `build_proposed_transaction` above, so the PCZT parts already carry it.
3062    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            // An action still needs a spend authorization signature if and only if its spend
3134            // requires one: this covers both the requested real spends and the wallet-controlled
3135            // zero-value spends the builder pairs with change outputs in the vanilla-Orchard-pool
3136            // bundle under the post-NU6.3 cross-address rule. Protocol padding dummies are
3137            // pre-signed and cleared by the IO Finalizer, so they are excluded by this check.
3138            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 the account has a known derivation, add the Orchard key path to the PCZT
3148                    // for every spend that still requires a signature (real spends and
3149                    // wallet-controlled zero-value spends), so an external Signer can identify
3150                    // and sign it.
3151                    if let Some(derivation) = account_derivation
3152                        && *needs_derivation
3153                    {
3154                        // All spent notes are from the same account.
3155                        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            // An action still needs a spend authorization signature if and only if its spend
3191            // requires one: this covers both the requested real spends and the wallet-controlled
3192            // zero-value spends the builder pairs with change outputs in the vanilla-Orchard-pool
3193            // bundle under the post-NU6.3 cross-address rule. Protocol padding dummies are
3194            // pre-signed and cleared by the IO Finalizer, so they are excluded by this check.
3195            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                    // Ironwood notes are spent with the account's Orchard spending key, so the key
3205                    // path added here is the Orchard one. If the account has a known derivation,
3206                    // add it for every spend that still requires a signature (real spends and
3207                    // wallet-controlled zero-value spends), so an external Signer can identify
3208                    // and sign it.
3209                    if let Some(derivation) = account_derivation
3210                        && *needs_derivation
3211                    {
3212                        // All spent notes are from the same account.
3213                        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 the account has a known derivation, add the Sapling key path to the PCZT.
3249            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                        // Dummy spends will already have a proof generation key.
3257                        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                        // All non-dummy spent notes are from the same account.
3264                        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 the account has a known derivation, add the transparent key paths to the PCZT.
3305            if let Some(derivation) = account_derivation {
3306                // Match address metadata to the inputs that spend from those addresses.
3307                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                                    // Transparent uses BIP 44 derivation.
3344                                    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/// Selects the view produced by [`redact_pczt_for_signer`], according to the
3389/// capabilities of the receiving Signer.
3390#[cfg(feature = "pczt")]
3391#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3392pub enum SignerView {
3393    /// The conservative signer view, for general-purpose Signers including
3394    /// deployed hardware signers (e.g. the Keystone ordinary send flow), which
3395    /// this view is validated against in the field.
3396    ///
3397    /// It removes wallet metadata, Orchard-protocol and Sapling spend
3398    /// witnesses, and dummy signing keys (a defensive no-op for IO-finalized
3399    /// PCZTs, whose dummy keys were consumed by the IO Finalizer; per the PCZT
3400    /// specification, Signers MUST reject PCZTs that contain them). It retains
3401    /// proofs, binding-signature keys, and anchors, and performs no field
3402    /// compaction, so the view of a v5 transaction remains representable in
3403    /// the v1 PCZT encoding (which [`pczt::Pczt::serialize`] selects for it).
3404    Full,
3405    /// The compact signer view, for receivers that support the v2 PCZT
3406    /// encoding and can restore compacted fields with
3407    /// [`pczt::Pczt::resolve_fields`].
3408    ///
3409    /// In addition to the `Full` redactions — except that Sapling spend
3410    /// witnesses are retained so that the Signer may verify nullifiers —
3411    /// this clears zk-proofs and binding-signature keys, compacts resolvable
3412    /// Orchard-protocol fields, and removes v6 shielded anchors (v5 anchors
3413    /// are retained because signatures commit to them).
3414    Compact,
3415}
3416
3417/// Creates a redacted copy of a wallet PCZT for an external Signer.
3418///
3419/// This is intended for PCZTs returned by [`create_pczt_from_proposal`]. The
3420/// `view` argument selects the redaction policy; see [`SignerView`] for the
3421/// receiver capabilities each view requires. When in doubt — in particular for
3422/// hardware signers whose firmware predates the compact view — use
3423/// [`SignerView::Full`].
3424///
3425/// The returned PCZT retains information that a general-purpose Signer may
3426/// need, including full viewing keys, spend authorization randomizers, key
3427/// derivation paths, output recovery keys, and user-facing addresses.
3428/// Applications may apply additional redaction when they know their Signer's
3429/// capabilities. A Signer that independently obtains the relevant full viewing
3430/// keys and returns only Orchard-protocol signature contributions can instead
3431/// use [`redact_pczt_for_batch_signer`].
3432///
3433/// The caller must retain `pczt` and combine the Signer's contribution into
3434/// that authoritative copy. The returned signer view omits wallet metadata and
3435/// other fields that [`extract_and_store_transaction_from_pczt`] requires.
3436#[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/// Creates a compact wallet PCZT for a batch Signer that obtains its full viewing key
3533/// independently and returns only new Orchard and Ironwood signatures.
3534///
3535/// In addition to the [`SignerView::Compact`] policy of [`redact_pczt_for_signer`],
3536/// this removes spend full viewing keys and existing signatures. It also removes the
3537/// randomizer from actions already authorized in `pczt`, while unsigned actions such as
3538/// wallet controlled zero value spends retain theirs. Sapling signatures require a
3539/// separate signing path.
3540///
3541/// The caller must retain the authoritative PCZT and apply the returned signature
3542/// contributions to it; the returned view is not independently extractable. This
3543/// function must run before its existing signatures are redacted. The returned view
3544/// cannot be signed with the high level
3545/// [`pczt::roles::signer::Signer`] because that role expects full viewing keys.
3546#[cfg(feature = "pczt")]
3547pub fn redact_pczt_for_batch_signer(pczt: &pczt::Pczt) -> pczt::Pczt {
3548    // Snapshot existing signature positions before the batch view clears them.
3549    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        // The batch Signer derives its FVK and returns only new signatures. Existing
3565        // signatures MUST be omitted: deployed batch Signers reject requests that
3566        // already carry signatures. Omitting them strands nothing — this view is a
3567        // signing request, not the authoritative PCZT, and the caller's authoritative
3568        // copy retains them.
3569        redactor.redact_actions(|mut action| {
3570            action.clear_spend_fvk();
3571            action.clear_spend_auth_sig();
3572        });
3573        // Unsigned actions keep alpha, including wallet controlled zero value spends.
3574        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    // Apply the policy shared by every external Signer first.
3583    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/// Finalizes the given PCZT, and persists the transaction to the wallet database.
3594///
3595/// The PCZT should have been created via [`create_pczt_from_proposal`], which adds
3596/// metadata necessary for the wallet backend.
3597///
3598/// Returns the transaction ID for the resulting transaction.
3599///
3600/// - `sapling_vk` is optional to allow the caller to check whether a PCZT has Sapling
3601///   with [`pczt::roles::prover::Prover::requires_sapling_proofs`], and avoid downloading
3602///   the Sapling parameters if they are not needed. If `sapling_vk` is `None`, and the
3603///   PCZT has a Sapling bundle, this function will return an error.
3604/// - `orchard_vk` is optional to allow the caller to control where the Orchard verifying
3605///   key is generated or cached. If `orchard_vk` is `None`, and the PCZT has an Orchard
3606///   bundle, an Orchard verifying key will be generated on the fly.
3607///
3608/// `rng` supplies the randomness for the binding signatures and for verifying the extracted
3609/// transaction.
3610#[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    // The per-action sent-output recovery shared by the Orchard and Ironwood bundles, which
3642    // differ only in the note plaintext version their notes carry (`V2` for Orchard, `V3` —
3643    // ZIP 2005 — for Ironwood): the note reconstructed from the PCZT's output fields, zipped
3644    // with the recipient metadata `create_pczt_from_proposal` attached to the output.
3645    #[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                // If the pczt recipient is not present, this is a dummy note; if the note is not
3701                // present, then the PCZT has been pruned to make this output unrecoverable and so
3702                // we also ignore it.
3703                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            // If the pczt recipient is not present, this is a dummy note; if the note is not
3758            // present, then the PCZT has been pruned to make this output unrecoverable and so we
3759            // also ignore it.
3760            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(&note);
3836        let esk = D::derive_esk(&note).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        // The note commitment tree an output's note is appended to is fully determined by the
3842        // pool the output was created in; recording it mirrors the transaction-builder path
3843        // (`create_proposed_transactions`), which tags every shielded sent output with its tree.
3844        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(&note))?;
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                        // This assumes that transparent outputs are pushed onto `transparent_output_meta`
3997                        // with the same indices they have in the transaction's transparent outputs.
3998                        // We do not reorder transparent outputs; there is no reason to do so because it
3999                        // would not usefully improve privacy.
4000                        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        // We should never obtain a `None` result because we constructed the UTXOs map and the
4068        // transaction from the same PCZT.
4069        .expect("input map was constructed correctly");
4070
4071    // We don't need the spent UTXOs to be in transaction order.
4072    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/// Constructs a transaction that consumes available transparent UTXOs belonging to the specified
4095/// secret key, and sends them to the most-preferred receiver of the default internal address for
4096/// the provided Unified Spending Key.
4097///
4098/// This procedure will not attempt to shield transparent funds if the total amount being shielded
4099/// is less than the default fee to send the transaction. Fees will be paid only from the
4100/// transparent UTXOs being consumed.
4101///
4102/// Parameters:
4103/// * `wallet_db`: A read/write reference to the wallet database
4104/// * `params`: Consensus parameters
4105/// * `rng`: The source of randomness used to construct, prove, and sign the transaction.
4106/// * `spend_prover`: The [`sapling::SpendProver`] to use in constructing the shielded
4107///   transaction.
4108/// * `output_prover`: The [`sapling::OutputProver`] to use in constructing the shielded
4109///   transaction.
4110/// * `input_selector`: The [`InputSelector`] to for note selection and change and fee
4111///   determination
4112/// * `usk`: The unified spending key that will be used to detect and spend transparent UTXOs,
4113///   and that will provide the shielded address to which funds will be sent. Funds will be
4114///   shielded to the internal (change) address associated with the most preferred shielded
4115///   receiver corresponding to this account, or if no shielded receiver can be used for this
4116///   account, this function will return an error. This procedure will return an error if the
4117///   USK does not correspond to an account known to the wallet.
4118/// * `from_addrs`: The list of transparent addresses that will be used to filter transaparent
4119///   UTXOs received by the wallet. Only UTXOs received at one of the provided addresses will
4120///   be selected to be shielded.
4121/// * `min_confirmations`: The minimum number of confirmations that a previously
4122///   received note must have in the blockchain in order to be considered for being
4123///   spent. A value of 10 confirmations is recommended and 0-conf transactions are
4124///   not supported.
4125///
4126/// [`sapling::SpendProver`]: sapling::prover::SpendProver
4127/// [`sapling::OutputProver`]: sapling::prover::OutputProver
4128#[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    /// Bucketing raises the confirmation requirement so that the resulting anchor lands exactly on
4198    /// a grid boundary. Because the anchor and the note-eligibility bound are the same quantity,
4199    /// this is what guarantees every selected note has a witness at that anchor.
4200    #[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            // Age 1: one interval BELOW the most recent boundary, never the most recent itself.
4217            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            // Never fewer confirmations than asked for, and the invariant is preserved.
4225            assert!(bucketed.trusted() >= policy.trusted());
4226            assert!(bucketed.untrusted() >= bucketed.trusted());
4227            // The extra wait is bounded by two intervals: up to one to reach the most recent
4228            // boundary, plus the one that age 1 steps back.
4229            assert!(
4230                u32::from(bucketed.trusted()) - u32::from(policy.trusted())
4231                    < 2 * interval.interval().block_count().get()
4232            );
4233        }
4234    }
4235
4236    /// Even an anchor already sitting on a boundary steps back one interval: that boundary is the
4237    /// most recent, and ZIP 318 admits only ages of 1 or more.
4238    #[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    /// Below the first boundary there is no grid to bucket to, and the policy declines rather than
4256    /// producing a zero or negative confirmation count.
4257    #[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        // The ordinary anchor is 90, whose boundary-at-or-below is 0; there is no boundary an
4262        // interval below that, so no admissible anchor exists.
4263        assert!(
4264            policy
4265                .bucketed(interval, target(100), BlockHeight::from_u32(1))
4266                .is_none()
4267        );
4268    }
4269
4270    /// A shorter test-network interval buckets on its own grid.
4271    #[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        // Most recent boundary at or below 997 is 996; age 1 steps back to 984.
4286        assert_eq!(u32::from(anchor), 984);
4287    }
4288
4289    /// From NU7 activation the grid's boundaries are three times as far apart in blocks, and
4290    /// bucketing steps back one boundary of the scaled grid.
4291    #[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}