Skip to main content

zcash_primitives/transaction/
builder.rs

1//! Structs for building transactions.
2
3use core::{cmp::Ordering, fmt};
4
5use rand_core::{CryptoRng, Rng};
6
7use ::sapling::{Note, PaymentAddress, builder::SaplingMetadata};
8use ::transparent::{address::TransparentAddress, builder::TransparentBuilder, bundle::TxOut};
9use zcash_protocol::{
10    PoolType,
11    consensus::{self, BlockHeight, BranchId, NU7_POW_TARGET_SPACING_RATIO, Parameters},
12    memo::MemoBytes,
13    value::{BalanceError, ZatBalance, Zatoshis},
14};
15use zcash_script::{op, opcode::PushValue, script};
16
17use crate::transaction::{
18    Transaction, TxVersion, coinbase,
19    components::orchard::bundle_version_for_branch,
20    fees::{
21        FeeRule,
22        transparent::{InputView, OutputView},
23    },
24};
25
26#[cfg(feature = "std")]
27use std::sync::mpsc::Sender;
28
29#[cfg(feature = "circuits")]
30use {
31    crate::transaction::{
32        Authorization, Coinbase, TransactionData, Unauthorized,
33        sighash::{PrecomputedSighashData, SignableInput},
34    },
35    ::sapling::prover::{OutputProver, SpendProver},
36    ::transparent::builder::TransparentSigningSet,
37    alloc::{boxed::Box, vec::Vec},
38};
39
40#[cfg(feature = "transparent-inputs")]
41use ::transparent::builder::TransparentInputInfo;
42
43#[cfg(not(feature = "transparent-inputs"))]
44use core::convert::Infallible;
45
46use super::components::sapling::zip212_enforcement;
47
48/// The default transaction expiry delta, in blocks, for transactions targeting a height before
49/// Blossom activation ([ZIP 203]).
50///
51/// [ZIP 203]: https://zips.z.cash/zip-0203
52pub const OVERWINTER_DEFAULT_TX_EXPIRY_DELTA: u32 = 20;
53
54/// The default transaction expiry delta, in blocks, for transactions targeting a height from
55/// Blossom activation until NU7 activation ([ZIP 203]). It is about 50 minutes at the 75-second
56/// target block spacing.
57///
58/// [ZIP 203]: https://zips.z.cash/zip-0203#changes-for-blossom
59pub const BLOSSOM_DEFAULT_TX_EXPIRY_DELTA: u32 = 40;
60
61/// The default transaction expiry delta, in blocks, for transactions targeting a height from NU7
62/// activation onward ([ZIP 218]): 120 blocks, the same 50 minutes as
63/// [`BLOSSOM_DEFAULT_TX_EXPIRY_DELTA`] at the 25-second target block spacing.
64///
65/// [ZIP 218]: https://zips.z.cash/zip-0218#default-expiry-delta
66pub const NU7_DEFAULT_TX_EXPIRY_DELTA: u32 =
67    NU7_POW_TARGET_SPACING_RATIO * BLOSSOM_DEFAULT_TX_EXPIRY_DELTA;
68
69/// The maximum length, in bytes, of the data in a transparent null-data (`OP_RETURN`)
70/// output that nodes relay.
71const MAX_OP_RETURN_RELAY_BYTES: usize = 80;
72
73/// Returns the default expiry delta, in blocks, for a transaction built under the rules of the
74/// given consensus branch.
75///
76/// The builders set a non-coinbase transaction's expiry height to its target height plus this
77/// delta, unless the caller overrides the expiry height.
78pub fn default_tx_expiry_delta(consensus_branch_id: BranchId) -> u32 {
79    match consensus_branch_id {
80        BranchId::Sprout | BranchId::Overwinter | BranchId::Sapling => {
81            OVERWINTER_DEFAULT_TX_EXPIRY_DELTA
82        }
83        BranchId::Blossom
84        | BranchId::Heartwood
85        | BranchId::Canopy
86        | BranchId::Nu5
87        | BranchId::Nu6
88        | BranchId::Nu6_1
89        | BranchId::Nu6_2
90        | BranchId::Nu6_3 => BLOSSOM_DEFAULT_TX_EXPIRY_DELTA,
91        BranchId::Nu7 => NU7_DEFAULT_TX_EXPIRY_DELTA,
92        #[cfg(zcash_unstable = "nutachyon")]
93        BranchId::NuTachyon => NU7_DEFAULT_TX_EXPIRY_DELTA,
94    }
95}
96
97/// Errors that can occur during fee calculation.
98#[derive(Debug)]
99pub enum FeeError<FE> {
100    FeeRule(FE),
101    Bundle(&'static str),
102}
103
104impl<FE: fmt::Display> fmt::Display for FeeError<FE> {
105    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106        match self {
107            FeeError::FeeRule(e) => write!(f, "An error occurred in fee calculation: {e}"),
108            FeeError::Bundle(b) => write!(f, "Bundle structure invalid in fee calculation: {b}"),
109        }
110    }
111}
112
113/// Errors that can occur during transaction construction.
114#[derive(Debug)]
115pub enum Error<FE> {
116    /// Insufficient funds were provided to the transaction builder; the given
117    /// additional amount is required in order to construct the transaction.
118    InsufficientFunds(ZatBalance),
119    /// PCZT does not preserve a nonzero ZIP 233 amount.
120    #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
121    Zip233UnsupportedByPczt,
122    /// The transaction has inputs in excess of outputs and fees; the user must
123    /// add a change output.
124    ChangeRequired(ZatBalance),
125    /// An error occurred in computing the fees for a transaction.
126    Fee(FeeError<FE>),
127    /// An overflow or underflow occurred when computing value balances
128    Balance(BalanceError),
129    /// An error occurred in constructing the transparent parts of a transaction.
130    TransparentBuild(transparent::builder::Error),
131    /// The data for a transparent null-data output is longer than the maximum length
132    /// that is relayed.
133    NullDataTooLong {
134        /// The length of the data provided.
135        actual: usize,
136        /// The maximum length.
137        limit: usize,
138    },
139    /// An error occurred in constructing the Sapling parts of a transaction.
140    SaplingBuild(sapling::builder::Error),
141    /// An error occurred in constructing the Orchard parts of a transaction.
142    OrchardBuild(orchard::builder::BuildError),
143    /// An error occurred in constructing the Ironwood parts of a transaction.
144    IronwoodBuild(orchard::builder::BuildError),
145    /// An error occurred in adding an Orchard Spend to a transaction.
146    OrchardSpend(orchard::builder::SpendError),
147    /// An error occurred in adding an Orchard Output to a transaction.
148    OrchardRecipient(orchard::builder::OutputError),
149    /// An error occurred in adding an Ironwood Spend to a transaction.
150    IronwoodSpend(orchard::builder::SpendError),
151    /// An Ironwood spend note used an unsupported note plaintext version.
152    IronwoodSpendUnsupportedNoteVersion(orchard::NoteVersion),
153    /// An error occurred in adding an Ironwood Output to a transaction.
154    IronwoodRecipient(orchard::builder::OutputError),
155    /// The builder was constructed without support for the Sapling pool, but a Sapling
156    /// spend or output was added.
157    SaplingBuilderNotAvailable,
158    /// The builder was constructed with a target height before NU5 activation, but an Orchard
159    /// spend or output was added.
160    OrchardBuilderNotAvailable,
161    /// The builder was constructed with a target height before NU6.3 activation,
162    /// or without an Ironwood anchor, but an Ironwood spend or output was added.
163    IronwoodBuilderNotAvailable,
164    /// Anchors can be deferred to proving time only under a transaction version whose
165    /// txid and sighash exclude shielded anchors (V6, NU6.3 onward); this version commits
166    /// its signatures to the anchors, so they must be supplied at build time (use
167    /// [`Builder`]).
168    AnchorDeferralUnsupported(TxVersion),
169    /// An error occurred in constructing a coinbase transaction.
170    Coinbase(coinbase::Error),
171    /// A coinbase transaction's expiry height does not match its target block height.
172    CoinbaseExpiryHeightMismatch {
173        target_height: BlockHeight,
174        expiry_height: BlockHeight,
175    },
176    /// The proposed transaction version or the consensus branch id for the target height does not
177    /// support a feature required by the transaction under construction, or the proposed
178    /// transaction version is not supported on the given consensus branch.
179    TargetIncompatible(BranchId, TxVersion, Option<PoolType>),
180}
181
182impl<FE: fmt::Display> fmt::Display for Error<FE> {
183    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184        match self {
185            Error::InsufficientFunds(amount) => write!(
186                f,
187                "Insufficient funds for transaction construction; need an additional {amount:?} zatoshis"
188            ),
189            #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
190            Error::Zip233UnsupportedByPczt => {
191                write!(f, "PCZT does not support a nonzero ZIP 233 amount")
192            }
193            Error::ChangeRequired(amount) => write!(
194                f,
195                "The transaction requires an additional change output of {amount:?} zatoshis"
196            ),
197            Error::Balance(e) => write!(f, "Invalid amount {e:?}"),
198            Error::Fee(e) => write!(f, "An error occurred in fee calculation: {e}"),
199            Error::TransparentBuild(err) => err.fmt(f),
200            Error::NullDataTooLong { actual, limit } => write!(
201                f,
202                "Provided null data is longer than the maximum supported length (actual: {actual}, limit: {limit})"
203            ),
204            Error::SaplingBuild(err) => err.fmt(f),
205            Error::OrchardBuild(err) => write!(f, "{err:?}"),
206            Error::IronwoodBuild(err) => write!(f, "{err:?}"),
207            Error::OrchardSpend(err) => write!(f, "Could not add Orchard spend: {err}"),
208            Error::OrchardRecipient(err) => write!(f, "Could not add Orchard recipient: {err}"),
209            Error::IronwoodSpend(err) => write!(f, "Could not add Ironwood spend: {err}"),
210            Error::IronwoodSpendUnsupportedNoteVersion(version) => write!(
211                f,
212                "Could not add Ironwood spend: note version {version:?} is unsupported"
213            ),
214            Error::IronwoodRecipient(err) => {
215                write!(f, "Could not add Ironwood recipient: {err}")
216            }
217            Error::SaplingBuilderNotAvailable => write!(
218                f,
219                "Cannot create Sapling transactions without a Sapling anchor"
220            ),
221            Error::OrchardBuilderNotAvailable => write!(
222                f,
223                "Cannot create Orchard transactions without an Orchard anchor, or before NU5 activation"
224            ),
225            Error::IronwoodBuilderNotAvailable => write!(
226                f,
227                "Cannot create Ironwood transactions without an Ironwood anchor, or before NU6.3 activation"
228            ),
229            Error::AnchorDeferralUnsupported(version) => write!(
230                f,
231                "Transaction version {version:?} commits its signatures to shielded anchors, so anchors cannot be deferred to proving time"
232            ),
233            Error::Coinbase(err) => write!(
234                f,
235                "An error occurred in constructing a coinbase transaction: {err}"
236            ),
237            Error::CoinbaseExpiryHeightMismatch {
238                target_height,
239                expiry_height,
240            } => write!(
241                f,
242                "Coinbase transaction expiry height {expiry_height} does not match target block height {target_height}"
243            ),
244            Error::TargetIncompatible(branch_id, version, pool_type) => match pool_type {
245                None => write!(
246                    f,
247                    "Proposed transaction version {version:?} is not valid for consensus branch {branch_id:?}"
248                ),
249                Some(t) => write!(
250                    f,
251                    "{t} is not supported for proposed transaction version {version:?} or consensus branch {branch_id:?}"
252                ),
253            },
254        }
255    }
256}
257
258#[cfg(feature = "std")]
259impl<FE: fmt::Debug + fmt::Display> std::error::Error for Error<FE> {}
260
261impl<FE> From<BalanceError> for Error<FE> {
262    fn from(e: BalanceError) -> Self {
263        Error::Balance(e)
264    }
265}
266
267impl<FE> From<FeeError<FE>> for Error<FE> {
268    fn from(e: FeeError<FE>) -> Self {
269        Error::Fee(e)
270    }
271}
272
273impl<FE> From<sapling::builder::Error> for Error<FE> {
274    fn from(e: sapling::builder::Error) -> Self {
275        Error::SaplingBuild(e)
276    }
277}
278
279impl<FE> From<orchard::builder::SpendError> for Error<FE> {
280    fn from(e: orchard::builder::SpendError) -> Self {
281        Error::OrchardSpend(e)
282    }
283}
284
285impl<FE> From<coinbase::Error> for Error<FE> {
286    fn from(e: coinbase::Error) -> Self {
287        Error::Coinbase(e)
288    }
289}
290
291/// Reports on the progress made by the builder towards building a transaction.
292pub struct Progress {
293    /// The number of steps completed.
294    cur: u32,
295    /// The expected total number of steps (as of this progress update), if known.
296    end: Option<u32>,
297}
298
299impl From<(u32, u32)> for Progress {
300    fn from((cur, end): (u32, u32)) -> Self {
301        Self {
302            cur,
303            end: Some(end),
304        }
305    }
306}
307
308impl Progress {
309    /// Returns the number of steps completed so far while building the transaction.
310    ///
311    /// Note that each step may not be of the same complexity/duration.
312    pub fn cur(&self) -> u32 {
313        self.cur
314    }
315
316    /// Returns the total expected number of steps before this transaction will be ready,
317    /// or `None` if the end is unknown as of this progress update.
318    ///
319    /// Note that each step may not be of the same complexity/duration.
320    pub fn end(&self) -> Option<u32> {
321        self.end
322    }
323}
324
325/// The padding policy for a transactional Orchard-family (Orchard or Ironwood) bundle.
326///
327/// This selects only the parameters that vary between transactional bundles: whether a
328/// bundle is produced even when empty, and the minimum action count it is padded to. It
329/// deliberately cannot express an [`orchard::builder::BundleType::Coinbase`] bundle:
330/// coinbase construction is a property of the whole transaction, selected by
331/// [`BuildConfig::Coinbase`], never of an individual pool. Storing padding here rather
332/// than a full `BundleType` keeps the per-pool coinbase state unrepresentable.
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub struct BundlePadding {
335    /// Produce a bundle even when no spends or outputs have been added; the resulting
336    /// bundle then consists entirely of dummy actions.
337    pub bundle_required: bool,
338    /// The minimum number of actions to pad the bundle to. `None` uses the orchard
339    /// builder's default 2-action minimum; `Some(1)` leaves the bundle unpadded, so its
340    /// action count reveals the transaction shape (acceptable when that shape is already
341    /// public, e.g. pool migrations).
342    pub pad_to_minimum: Option<u8>,
343}
344
345impl BundlePadding {
346    /// The default padding, matching [`orchard::builder::BundleType::DEFAULT`]: an empty
347    /// bundle is not produced, and a non-empty bundle is padded to the default minimum.
348    pub const DEFAULT: BundlePadding = BundlePadding {
349        bundle_required: false,
350        pad_to_minimum: None,
351    };
352
353    /// Unpadded transactional padding, matching [`orchard::builder::BundleType::UNPADDED`]:
354    /// the bundle is padded only to the one-action consensus minimum, so it contains
355    /// exactly the requested actions.
356    pub const UNPADDED: BundlePadding = BundlePadding {
357        bundle_required: false,
358        pad_to_minimum: Some(1),
359    };
360
361    /// Returns the orchard [`BundleType`](orchard::builder::BundleType) selecting this
362    /// padding. The result is always a `Transactional` bundle type.
363    pub fn bundle_type(self) -> orchard::builder::BundleType {
364        orchard::builder::BundleType::Transactional {
365            bundle_required: self.bundle_required,
366            pad_to_minimum: self.pad_to_minimum,
367        }
368    }
369}
370
371/// Rules for how the builder should be configured for each shielded pool or coinbase tx.
372#[derive(Clone)]
373pub enum BuildConfig {
374    Standard {
375        sapling_anchor: Option<sapling::Anchor>,
376        orchard_anchor: Option<orchard::Anchor>,
377        ironwood_anchor: Option<orchard::Anchor>,
378        orchard_padding: BundlePadding,
379        ironwood_padding: BundlePadding,
380    },
381    Coinbase {
382        miner_data: Option<PushValue>,
383    },
384}
385
386impl BuildConfig {
387    /// Returns the Sapling bundle type and anchor for this configuration.
388    pub fn sapling_builder_config(
389        &self,
390    ) -> Option<(sapling::builder::BundleType, sapling::Anchor)> {
391        match self {
392            BuildConfig::Standard { sapling_anchor, .. } => sapling_anchor
393                .as_ref()
394                .map(|a| (sapling::builder::BundleType::DEFAULT, *a)),
395            BuildConfig::Coinbase { .. } => Some((
396                sapling::builder::BundleType::Coinbase,
397                sapling::Anchor::empty_tree(),
398            )),
399        }
400    }
401
402    /// Returns the Orchard builder for this configuration.
403    fn orchard_builder(
404        &self,
405        bundle_version: orchard::bundle::BundleVersion,
406    ) -> Option<orchard::builder::Builder> {
407        match self {
408            BuildConfig::Standard {
409                orchard_anchor,
410                orchard_padding,
411                ..
412            } => orchard_anchor.as_ref().map(|a| {
413                orchard::builder::Builder::new(
414                    orchard_padding.bundle_type(),
415                    bundle_version,
416                    bundle_version.default_flags(),
417                    *a,
418                )
419                .expect("a transactional bundle type with default flags is always representable")
420            }),
421            BuildConfig::Coinbase { .. }
422                if bundle_version == orchard::bundle::BundleVersion::orchard_v3() =>
423            {
424                None
425            }
426            BuildConfig::Coinbase { .. } => Some(
427                orchard::builder::Builder::new(
428                    orchard::builder::BundleType::Coinbase,
429                    bundle_version,
430                    // Coinbase transactions have `enableSpends = 0`. Every protocol version
431                    // for which a coinbase Orchard-pool bundle can be built (pre-NU6.3) permits
432                    // cross-address transfers, so the spends-disabled flag set is representable.
433                    orchard::bundle::Flags::SPENDS_DISABLED,
434                    orchard::Anchor::empty_tree(),
435                )
436                .expect("spends-disabled flags are valid for a non-Orchard coinbase bundle"),
437            ),
438        }
439    }
440
441    /// Returns the Ironwood builder for this configuration.
442    fn ironwood_builder(&self) -> Option<orchard::builder::Builder> {
443        let bundle_version = orchard::bundle::BundleVersion::ironwood_v3();
444        match self {
445            BuildConfig::Standard {
446                ironwood_anchor,
447                ironwood_padding,
448                ..
449            } => ironwood_anchor.as_ref().map(|a| {
450                orchard::builder::Builder::new(
451                    ironwood_padding.bundle_type(),
452                    bundle_version,
453                    bundle_version.default_flags(),
454                    *a,
455                )
456                .expect("a transactional bundle type with default flags is always representable")
457            }),
458            BuildConfig::Coinbase { .. } => Some(
459                orchard::builder::Builder::new(
460                    orchard::builder::BundleType::Coinbase,
461                    bundle_version,
462                    orchard::bundle::Flags::SPENDS_DISABLED,
463                    orchard::Anchor::empty_tree(),
464                )
465                .expect("spends-disabled flags are valid for an Ironwood coinbase bundle"),
466            ),
467        }
468    }
469
470    /// Returns `true` if this configuration is for building a coinbase transaction.
471    pub fn is_coinbase(&self) -> bool {
472        matches!(self, BuildConfig::Coinbase { .. })
473    }
474}
475
476fn orchard_action_count(
477    builder: &orchard::builder::Builder,
478    is_coinbase: bool,
479    bundle_version: orchard::bundle::BundleVersion,
480) -> Result<usize, &'static str> {
481    let num_spends = builder.spends().len();
482    let num_outputs = builder
483        .outputs()
484        .len()
485        .checked_add(builder.changes().len())
486        .ok_or("num_outputs + num_changes overflowed")?;
487
488    // The bundle type must match the one the builder was constructed with (see
489    // `orchard_builder` / `ironwood_builder`); read it back from the builder so
490    // the two cannot drift.
491    let bundle_type = builder.bundle_type();
492
493    // The flags must match those the builder constructs for each configuration (see
494    // `orchard_builder`). For a `Coinbase` bundle `num_actions` ignores the flags, but supplying
495    // the matching set keeps the two paths consistent.
496    let flags = if is_coinbase {
497        orchard::bundle::Flags::SPENDS_DISABLED
498    } else {
499        bundle_version.default_flags()
500    };
501
502    bundle_type.num_actions(flags, num_spends, num_outputs)
503}
504
505/// A builder for V6 and later transactions constructed as PCZTs with their
506/// Orchard-family anchors DEFERRED to proving time, per [ZIP 374].
507///
508/// [`Builder`] requires each shielded pool's anchor in its [`BuildConfig`] and a Merkle
509/// witness rooting to it for every spend it adds. This builder takes no anchors at all:
510/// spends are added as bare `(fvk, note)` pairs through the `orchard` crate's own
511/// deferred-anchor support ([`orchard::builder::Builder::new_with_anchor_deferred`]), and the
512/// emitted PCZT carries ABSENT anchor and witness fields, which the PCZT Updater role
513/// (`set_{orchard,ironwood}_anchor` / `set_*_spend_witnesses`) fills in at proving time,
514/// after the transaction has been finalized and SIGNED. This is sound exactly for V6 and later
515/// transaction formats, whose txid and sighash exclude Sapling and Orchard-family anchors (they are
516/// committed only by the authorizing-data digest), so neither the transaction id nor any
517/// signature commits to the deferred values; [`Self::new`] refuses any earlier format.
518/// The witness-to-anchor consistency check that [`Builder`] performs per spend at
519/// add-spend time is performed instead by the PCZT Prover role, once the real anchor and
520/// witnesses are present.
521///
522/// The builder is deliberately restricted to the two Orchard-family pools (Orchard and
523/// Ironwood): their nullifiers are derived from the note alone, so a spend can be signed
524/// before its witness is known. A Sapling nullifier commits to the note's tree position,
525/// so Sapling spends can never defer their witnesses, and transparent inputs are out of
526/// scope for the pre-signing flows this builder serves; use [`Builder`] for those.
527///
528/// [ZIP 374]: https://zips.z.cash/zip-0374
529pub struct DeferredPcztBuilder<P> {
530    params: P,
531    tx_version: TxVersion,
532    consensus_branch_id: BranchId,
533    target_height: BlockHeight,
534    expiry_height: BlockHeight,
535    orchard_builder: orchard::builder::Builder,
536    orchard_bundle_version: orchard::bundle::BundleVersion,
537    ironwood_builder: orchard::builder::Builder,
538}
539
540impl<P: consensus::Parameters> DeferredPcztBuilder<P> {
541    /// Creates a builder targeting the block at `target_height`, with the given
542    /// transactional bundle padding for each Orchard-family pool.
543    ///
544    /// The expiry height defaults to `target_height` plus the
545    /// [`default_tx_expiry_delta`] for the consensus branch in effect at `target_height`;
546    /// override it with [`Self::with_expiry_height`].
547    ///
548    /// Returns [`Error::AnchorDeferralUnsupported`] if the consensus branch in effect at
549    /// `target_height` uses a transaction format older than V6, whose txid and sighash include
550    /// Sapling and Orchard-family anchors; under those formats the anchors cannot outlive
551    /// signing.
552    pub fn new<FE>(
553        params: P,
554        target_height: BlockHeight,
555        orchard_padding: BundlePadding,
556        ironwood_padding: BundlePadding,
557    ) -> Result<Self, Error<FE>> {
558        let consensus_branch_id = BranchId::for_height(&params, target_height);
559        let tx_version = TxVersion::suggested_for_branch(consensus_branch_id);
560        if !tx_version.has_ironwood() {
561            return Err(Error::AnchorDeferralUnsupported(tx_version));
562        }
563        let orchard_bundle_version =
564            bundle_version_for_branch(consensus_branch_id, orchard::ValuePool::Orchard)
565                .expect("a branch with the V6 format supports the Orchard pool");
566        let orchard_builder = orchard::builder::Builder::new_with_anchor_deferred(
567            orchard_padding.bundle_type(),
568            orchard_bundle_version,
569            orchard_bundle_version.default_flags(),
570            orchard::bundle::TxVersion::V6,
571        )
572        .map_err(Error::OrchardBuild)?;
573        let ironwood_bundle_version = orchard::bundle::BundleVersion::ironwood_v3();
574        let ironwood_builder = orchard::builder::Builder::new_with_anchor_deferred(
575            ironwood_padding.bundle_type(),
576            ironwood_bundle_version,
577            ironwood_bundle_version.default_flags(),
578            orchard::bundle::TxVersion::V6,
579        )
580        .map_err(Error::IronwoodBuild)?;
581        Ok(DeferredPcztBuilder {
582            params,
583            tx_version,
584            consensus_branch_id,
585            target_height,
586            expiry_height: target_height + default_tx_expiry_delta(consensus_branch_id),
587            orchard_builder,
588            orchard_bundle_version,
589            ironwood_builder,
590        })
591    }
592
593    /// Overrides the expiry height for the transaction under construction.
594    ///
595    /// A pre-signed transaction is often broadcast well after it is built, so the caller
596    /// typically sets an expiry derived from the intended broadcast schedule rather than
597    /// the build height; the signatures commit to it.
598    pub fn with_expiry_height(mut self, expiry_height: BlockHeight) -> Self {
599        self.expiry_height = expiry_height;
600        self
601    }
602
603    /// Adds an Orchard note to be spent in this bundle, WITHOUT a witness: the witness,
604    /// like the bundle's anchor, is installed at proving time through the PCZT Updater
605    /// role.
606    pub fn add_orchard_spend<FE>(
607        &mut self,
608        fvk: orchard::keys::FullViewingKey,
609        note: orchard::Note,
610    ) -> Result<(), Error<FE>> {
611        self.orchard_builder.add_spend_unwitnessed(fvk, note)?;
612        Ok(())
613    }
614
615    /// Adds an Orchard recipient to the transaction.
616    pub fn add_orchard_output<FE>(
617        &mut self,
618        ovk: Option<orchard::keys::OutgoingViewingKey>,
619        recipient: orchard::Address,
620        value: Zatoshis,
621        memo: MemoBytes,
622    ) -> Result<(), Error<FE>> {
623        self.orchard_builder
624            .add_output(
625                ovk,
626                recipient,
627                orchard::value::NoteValue::from_raw(value.into()),
628                memo.into_bytes(),
629            )
630            .map_err(Error::OrchardRecipient)
631    }
632
633    /// Adds a wallet-controlled Orchard change output to the transaction.
634    pub fn add_orchard_change_output<FE>(
635        &mut self,
636        fvk: orchard::keys::FullViewingKey,
637        ovk: Option<orchard::keys::OutgoingViewingKey>,
638        recipient: orchard::Address,
639        value: Zatoshis,
640        memo: MemoBytes,
641    ) -> Result<(), Error<FE>> {
642        self.orchard_builder
643            .add_change_output(
644                fvk,
645                ovk,
646                recipient,
647                orchard::value::NoteValue::from_raw(value.into()),
648                memo.into_bytes(),
649            )
650            .map_err(Error::OrchardRecipient)
651    }
652
653    /// Adds an Ironwood note to be spent in this bundle, WITHOUT a witness (see
654    /// [`Self::add_orchard_spend`]).
655    ///
656    /// The note must use [`orchard::note::NoteVersion::V3`], the Ironwood note plaintext
657    /// format.
658    pub fn add_ironwood_spend<FE>(
659        &mut self,
660        fvk: orchard::keys::FullViewingKey,
661        note: orchard::Note,
662    ) -> Result<(), Error<FE>> {
663        if note.version() != orchard::note::NoteVersion::V3 {
664            return Err(Error::IronwoodSpendUnsupportedNoteVersion(note.version()));
665        }
666        self.ironwood_builder
667            .add_spend_unwitnessed(fvk, note)
668            .map_err(Error::IronwoodSpend)
669    }
670
671    /// Adds an Ironwood recipient to the transaction.
672    ///
673    /// This uses [`orchard::note::NoteVersion::V3`], the Ironwood note plaintext format.
674    pub fn add_ironwood_output<FE>(
675        &mut self,
676        ovk: Option<orchard::keys::OutgoingViewingKey>,
677        recipient: orchard::Address,
678        value: Zatoshis,
679        memo: MemoBytes,
680    ) -> Result<(), Error<FE>> {
681        self.ironwood_builder
682            .add_output(
683                ovk,
684                recipient,
685                orchard::value::NoteValue::from_raw(value.into()),
686                memo.into_bytes(),
687            )
688            .map_err(Error::IronwoodRecipient)
689    }
690
691    /// Reports the calculated fee given the specified fee rule, as a function of the
692    /// spends and outputs added so far (each pool's action count includes the padding its
693    /// bundle type prescribes).
694    pub fn get_fee<FR: FeeRule>(&self, fee_rule: &FR) -> Result<Zatoshis, FeeError<FR::Error>> {
695        fee_rule
696            .fee_required(
697                &self.params,
698                self.target_height,
699                core::iter::empty::<crate::transaction::fees::transparent::InputSize>(),
700                core::iter::empty::<usize>(),
701                0,
702                0,
703                orchard_action_count(&self.orchard_builder, false, self.orchard_bundle_version)
704                    .map_err(FeeError::Bundle)?,
705                orchard_action_count(
706                    &self.ironwood_builder,
707                    false,
708                    orchard::bundle::BundleVersion::ironwood_v3(),
709                )
710                .map_err(FeeError::Bundle)?,
711            )
712            .map_err(FeeError::FeeRule)
713    }
714
715    /// Builds the added spends and outputs into the parts of an unproven PCZT whose
716    /// anchors and real-spend witnesses are ABSENT, deferred to proving time: pass the
717    /// result to the PCZT Creator (`build_from_parts`), then finalize, sign, and — at
718    /// proving time — install the real anchor and witnesses through the PCZT Updater
719    /// role before proving.
720    pub fn build_for_pczt<R: Rng + CryptoRng, FR: FeeRule>(
721        self,
722        mut rng: R,
723        fee_rule: &FR,
724    ) -> Result<PcztResult<P>, Error<FR::Error>> {
725        fn in_use(builder: &orchard::builder::Builder) -> bool {
726            !builder.spends().is_empty()
727                || !builder.outputs().is_empty()
728                || !builder.changes().is_empty()
729        }
730
731        let fee = self.get_fee(fee_rule).map_err(Error::Fee)?;
732
733        // After fees are accounted for, the value balance of the transaction must be zero.
734        let value_balance = [
735            self.orchard_builder
736                .value_balance::<ZatBalance>()
737                .map_err(|_| BalanceError::Overflow)?,
738            self.ironwood_builder
739                .value_balance::<ZatBalance>()
740                .map_err(|_| BalanceError::Overflow)?,
741        ]
742        .into_iter()
743        .sum::<Option<ZatBalance>>()
744        .ok_or(BalanceError::Overflow)?;
745        let balance_after_fees = (value_balance - fee).ok_or(BalanceError::Underflow)?;
746        match balance_after_fees.cmp(&ZatBalance::zero()) {
747            Ordering::Less => {
748                return Err(Error::InsufficientFunds(-balance_after_fees));
749            }
750            Ordering::Greater => {
751                return Err(Error::ChangeRequired(balance_after_fees));
752            }
753            Ordering::Equal => (),
754        };
755
756        let (orchard_bundle, orchard_meta) = if in_use(&self.orchard_builder) {
757            let (bundle, meta) = self
758                .orchard_builder
759                .build_for_pczt(&mut rng)
760                .map_err(Error::OrchardBuild)?;
761            (Some(bundle), meta)
762        } else {
763            (None, orchard::builder::BundleMetadata::empty())
764        };
765        let (ironwood_bundle, ironwood_meta) = if in_use(&self.ironwood_builder) {
766            let (bundle, meta) = self
767                .ironwood_builder
768                .build_for_pczt(&mut rng)
769                .map_err(Error::IronwoodBuild)?;
770            (Some(bundle), meta)
771        } else {
772            (None, orchard::builder::BundleMetadata::empty())
773        };
774
775        Ok(PcztResult {
776            pczt_parts: PcztParts {
777                params: self.params,
778                version: self.tx_version,
779                consensus_branch_id: self.consensus_branch_id,
780                lock_time: 0,
781                expiry_height: self.expiry_height,
782                transparent: None,
783                sapling: None,
784                orchard: orchard_bundle,
785                ironwood: ironwood_bundle,
786            },
787            sapling_meta: SaplingMetadata::empty(),
788            orchard_meta,
789            ironwood_meta,
790        })
791    }
792}
793
794/// The result of a transaction build operation, which includes the resulting transaction along
795/// with metadata describing how spends and outputs were shuffled in creating the transaction's
796/// shielded bundles.
797#[derive(Debug)]
798pub struct BuildResult {
799    transaction: Transaction,
800    sapling_meta: SaplingMetadata,
801    orchard_meta: orchard::builder::BundleMetadata,
802    ironwood_meta: orchard::builder::BundleMetadata,
803}
804
805impl BuildResult {
806    /// Returns the transaction that was constructed by the builder.
807    pub fn transaction(&self) -> &Transaction {
808        &self.transaction
809    }
810
811    /// Returns the mapping from Sapling inputs and outputs to their randomized positions in the
812    /// Sapling bundle in the newly constructed transaction.
813    pub fn sapling_meta(&self) -> &SaplingMetadata {
814        &self.sapling_meta
815    }
816
817    /// Returns the mapping from Orchard inputs and outputs to the randomized positions of the
818    /// Actions that contain them in the Orchard bundle in the newly constructed transaction.
819    pub fn orchard_meta(&self) -> &orchard::builder::BundleMetadata {
820        &self.orchard_meta
821    }
822
823    /// Returns the mapping from Ironwood inputs and outputs to the randomized
824    /// positions of the Actions that contain them in the Ironwood bundle in
825    /// the newly constructed transaction.
826    pub fn ironwood_meta(&self) -> &orchard::builder::BundleMetadata {
827        &self.ironwood_meta
828    }
829}
830
831/// The result of [`Builder::build_for_pczt`].
832///
833/// It includes the PCZT components along with metadata describing how spends and outputs
834/// were shuffled in creating the transaction's shielded bundles.
835#[derive(Debug)]
836pub struct PcztResult<P: Parameters> {
837    pub pczt_parts: PcztParts<P>,
838    pub sapling_meta: SaplingMetadata,
839    pub orchard_meta: orchard::builder::BundleMetadata,
840    pub ironwood_meta: orchard::builder::BundleMetadata,
841}
842
843/// The components of a PCZT.
844#[derive(Debug)]
845pub struct PcztParts<P: Parameters> {
846    pub params: P,
847    pub version: TxVersion,
848    pub consensus_branch_id: BranchId,
849    pub lock_time: u32,
850    pub expiry_height: BlockHeight,
851    pub transparent: Option<transparent::pczt::Bundle<Zatoshis>>,
852    pub sapling: Option<sapling::pczt::Bundle>,
853    pub orchard: Option<orchard::pczt::Bundle>,
854    pub ironwood: Option<orchard::pczt::Bundle>,
855}
856
857/// Generates a [`Transaction`] from its inputs and outputs.
858pub struct Builder<P, U> {
859    params: P,
860    tx_version: TxVersion,
861    consensus_branch_id: BranchId,
862    build_config: BuildConfig,
863    target_height: BlockHeight,
864    expiry_height: BlockHeight,
865    #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
866    zip233_amount: Zatoshis,
867    transparent_builder: TransparentBuilder<Zatoshis>,
868    sapling_builder: Option<sapling::builder::Builder>,
869    orchard_builder: Option<orchard::builder::Builder>,
870    orchard_bundle_version: Option<orchard::bundle::BundleVersion>,
871    ironwood_builder: Option<orchard::builder::Builder>,
872    _progress_notifier: U,
873}
874
875impl<P, U> Builder<P, U> {
876    /// Returns the network parameters that the builder has been configured for.
877    pub fn params(&self) -> &P {
878        &self.params
879    }
880
881    /// Returns the target height of the transaction under construction.
882    pub fn target_height(&self) -> BlockHeight {
883        self.target_height
884    }
885
886    /// Returns the expiry height of the transaction under construction.
887    ///
888    /// A value of `BlockHeight::from(0)` means that the transaction does not expire.
889    pub fn expiry_height(&self) -> BlockHeight {
890        self.expiry_height
891    }
892
893    /// Returns the set of transparent inputs currently committed to be consumed
894    /// by the transaction.
895    #[cfg(feature = "transparent-inputs")]
896    pub fn transparent_inputs(&self) -> &[TransparentInputInfo<Zatoshis>] {
897        self.transparent_builder.inputs()
898    }
899
900    /// Returns the set of transparent outputs currently set to be produced by
901    /// the transaction.
902    pub fn transparent_outputs(&self) -> &[TxOut<Zatoshis>] {
903        self.transparent_builder.outputs()
904    }
905
906    /// Returns the set of Sapling inputs currently committed to be consumed
907    /// by the transaction.
908    pub fn sapling_inputs(&self) -> &[sapling::builder::SpendInfo] {
909        self.sapling_builder
910            .as_ref()
911            .map_or_else(|| &[][..], |b| b.inputs())
912    }
913
914    /// Returns the set of Sapling outputs currently set to be produced by
915    /// the transaction.
916    pub fn sapling_outputs(&self) -> &[sapling::builder::OutputInfo] {
917        self.sapling_builder
918            .as_ref()
919            .map_or_else(|| &[][..], |b| b.outputs())
920    }
921
922    /// Returns `true` if any Orchard spend, output, or change output has been
923    /// added to this builder (i.e. the transaction will carry an Orchard bundle).
924    fn orchard_in_use(&self) -> bool {
925        self.orchard_builder.as_ref().is_some_and(|b| {
926            !b.spends().is_empty() || !b.outputs().is_empty() || !b.changes().is_empty()
927        })
928    }
929
930    /// Returns `true` if any Ironwood spend, output, or change output has been
931    /// added to this builder (i.e. the transaction will carry an Ironwood bundle).
932    fn ironwood_in_use(&self) -> bool {
933        self.ironwood_builder.as_ref().is_some_and(|b| {
934            !b.spends().is_empty() || !b.outputs().is_empty() || !b.changes().is_empty()
935        })
936    }
937
938    /// Checks that the given version supports all features required by the inputs and
939    /// outputs already added to the builder.
940    fn check_version_compatibility<FE>(&self, version: TxVersion) -> Result<(), Error<FE>> {
941        if !version.valid_in_branch(self.consensus_branch_id) {
942            return Err(Error::TargetIncompatible(
943                self.consensus_branch_id,
944                version,
945                None,
946            ));
947        }
948
949        #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
950        if self.zip233_amount != Zatoshis::ZERO && !version.has_zip233(self.consensus_branch_id) {
951            return Err(Error::TargetIncompatible(
952                self.consensus_branch_id,
953                version,
954                None,
955            ));
956        }
957
958        let sapling_available = version.has_sapling() && self.consensus_branch_id.has_sapling();
959        if !sapling_available
960            && (!self.sapling_inputs().is_empty() || !self.sapling_outputs().is_empty())
961        {
962            return Err(Error::TargetIncompatible(
963                self.consensus_branch_id,
964                version,
965                Some(PoolType::SAPLING),
966            ));
967        }
968
969        let orchard_available = version.has_orchard() && self.consensus_branch_id.has_orchard();
970        if !orchard_available && self.orchard_in_use() {
971            return Err(Error::TargetIncompatible(
972                self.consensus_branch_id,
973                version,
974                Some(PoolType::ORCHARD),
975            ));
976        }
977
978        {
979            // Ironwood is available only when the target version carries an Ironwood bundle
980            // and the consensus branch is one in which Ironwood is active.
981            let ironwood_branch = match self.consensus_branch_id {
982                BranchId::Nu6_3 => true,
983                BranchId::Nu7 => true,
984                #[cfg(zcash_unstable = "nutachyon")]
985                BranchId::NuTachyon => true,
986                _ => false,
987            };
988            let ironwood_available = version.has_ironwood() && ironwood_branch;
989            if !ironwood_available && self.ironwood_in_use() {
990                return Err(Error::TargetIncompatible(
991                    self.consensus_branch_id,
992                    version,
993                    None,
994                ));
995            }
996        }
997
998        Ok(())
999    }
1000
1001    /// Proposes a specific transaction version.
1002    ///
1003    /// Validates that the proposed version supports all features required by
1004    /// the inputs and outputs already added to the builder. Returns
1005    /// [`Error::TargetIncompatible`] if validation fails.
1006    ///
1007    /// The same validation is performed at build time to catch inputs/outputs
1008    /// added after this call.
1009    pub fn propose_version<FE>(&mut self, version: TxVersion) -> Result<(), Error<FE>> {
1010        self.check_version_compatibility(version)?;
1011        self.tx_version = version;
1012        Ok(())
1013    }
1014}
1015
1016impl<P: consensus::Parameters> Builder<P, ()> {
1017    /// Creates a new `Builder` targeted for inclusion in the block with the given height,
1018    /// using default values for general transaction fields.
1019    ///
1020    /// # Default values
1021    ///
1022    /// For a non-coinbase transaction, the expiry height is set to `target_height` plus the
1023    /// [`default_tx_expiry_delta`] for the consensus branch in effect at `target_height`. For a
1024    /// coinbase transaction, it is set to `target_height`. Override it with
1025    /// [`Self::with_expiry_height`].
1026    pub fn new(params: P, target_height: BlockHeight, build_config: BuildConfig) -> Self {
1027        let consensus_branch_id = BranchId::for_height(&params, target_height);
1028        // `bundle_version_for_branch` returns `Some` exactly for the branches in
1029        // which the Orchard pool is supported (NU5 onward), so this also gates
1030        // Orchard builder construction on NU5 activation.
1031        let bundle_version =
1032            bundle_version_for_branch(consensus_branch_id, orchard::ValuePool::Orchard);
1033        // Default transaction version for the branch.
1034        let tx_version = TxVersion::suggested_for_branch(consensus_branch_id);
1035
1036        let orchard_builder = bundle_version.and_then(|v| build_config.orchard_builder(v));
1037        let orchard_bundle_version = orchard_builder.as_ref().and(bundle_version);
1038
1039        // The Ironwood builder exists exactly when the branch's transaction version
1040        // carries an Ironwood bundle.
1041        let ironwood_builder = if tx_version.has_ironwood() {
1042            build_config.ironwood_builder()
1043        } else {
1044            None
1045        };
1046
1047        let sapling_builder = build_config
1048            .sapling_builder_config()
1049            .map(|(bundle_type, anchor)| {
1050                sapling::builder::Builder::new(
1051                    zip212_enforcement(&params, target_height),
1052                    bundle_type,
1053                    anchor,
1054                )
1055            });
1056
1057        // # Consensus Rules
1058        //
1059        // > [NU5 onward] The `nExpiryHeight` field of a coinbase transaction MUST be equal to its
1060        // > block height.
1061        //
1062        // ## Notes
1063        //
1064        // We set the expiry height for coinbase txs to the block height regardless of the network
1065        // upgrade.
1066        let expiry_height = if build_config.is_coinbase() {
1067            target_height
1068        } else {
1069            target_height + default_tx_expiry_delta(consensus_branch_id)
1070        };
1071
1072        Builder {
1073            params,
1074            tx_version,
1075            consensus_branch_id,
1076            build_config,
1077            target_height,
1078            expiry_height,
1079            #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1080            zip233_amount: Zatoshis::ZERO,
1081            transparent_builder: TransparentBuilder::empty(),
1082            sapling_builder,
1083            orchard_builder,
1084            orchard_bundle_version,
1085            ironwood_builder,
1086            _progress_notifier: (),
1087        }
1088    }
1089
1090    /// Sets the notifier channel, where progress of building the transaction is sent.
1091    ///
1092    /// An update is sent after every Sapling Spend or Output is computed, and the `u32`
1093    /// sent represents the total steps completed so far. It will eventually send number
1094    /// of spends + outputs. If there's an error building the transaction, the channel is
1095    /// closed.
1096    #[cfg(feature = "std")]
1097    pub fn with_progress_notifier(
1098        self,
1099        _progress_notifier: Sender<Progress>,
1100    ) -> Builder<P, Sender<Progress>> {
1101        Builder {
1102            params: self.params,
1103            tx_version: self.tx_version,
1104            consensus_branch_id: self.consensus_branch_id,
1105            build_config: self.build_config,
1106            target_height: self.target_height,
1107            expiry_height: self.expiry_height,
1108            #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1109            zip233_amount: self.zip233_amount,
1110            transparent_builder: self.transparent_builder,
1111            sapling_builder: self.sapling_builder,
1112            orchard_builder: self.orchard_builder,
1113            orchard_bundle_version: self.orchard_bundle_version,
1114            ironwood_builder: self.ironwood_builder,
1115            _progress_notifier,
1116        }
1117    }
1118}
1119
1120impl<P: consensus::Parameters, U> Builder<P, U> {
1121    /// Overrides the expiry height for the transaction under construction.
1122    ///
1123    /// For non-coinbase transactions, setting this to `BlockHeight::from(0)`
1124    /// disables transaction expiry. Coinbase builders reject overridden expiry
1125    /// heights that do not match the target block height.
1126    ///
1127    /// Disabling expiry by setting the height to `BlockHeight::from(0)` is not
1128    /// recommended: non-expiring transactions are not yet well tested
1129    /// end-to-end and are known to cause bugs elsewhere in the stack. Callers
1130    /// should avoid a zero expiry height unless they specifically need it.
1131    pub fn with_expiry_height(mut self, expiry_height: BlockHeight) -> Self {
1132        self.expiry_height = expiry_height;
1133        self
1134    }
1135
1136    /// Verifies that a coinbase transaction's expiry height matches its target
1137    /// block height, as required for coinbase transactions.
1138    fn check_coinbase_expiry_height<FE>(&self) -> Result<(), Error<FE>> {
1139        if self.build_config.is_coinbase() && self.expiry_height != self.target_height {
1140            Err(Error::CoinbaseExpiryHeightMismatch {
1141                target_height: self.target_height,
1142                expiry_height: self.expiry_height,
1143            })
1144        } else {
1145            Ok(())
1146        }
1147    }
1148
1149    /// Adds an Orchard note to be spent in this bundle.
1150    ///
1151    /// Returns an error if the given Merkle path does not have the required anchor for
1152    /// the given note.
1153    pub fn add_orchard_spend<FE>(
1154        &mut self,
1155        fvk: orchard::keys::FullViewingKey,
1156        note: orchard::Note,
1157        merkle_path: orchard::tree::MerklePath,
1158    ) -> Result<(), Error<FE>> {
1159        if let Some(builder) = self.orchard_builder.as_mut() {
1160            builder.add_spend(fvk, note, merkle_path)?;
1161            Ok(())
1162        } else {
1163            Err(Error::OrchardBuilderNotAvailable)
1164        }
1165    }
1166
1167    /// Adds an Orchard recipient to the transaction.
1168    pub fn add_orchard_output<FE>(
1169        &mut self,
1170        ovk: Option<orchard::keys::OutgoingViewingKey>,
1171        recipient: orchard::Address,
1172        value: Zatoshis,
1173        memo: MemoBytes,
1174    ) -> Result<(), Error<FE>> {
1175        self.orchard_builder
1176            .as_mut()
1177            .ok_or(Error::OrchardBuilderNotAvailable)?
1178            .add_output(
1179                ovk,
1180                recipient,
1181                orchard::value::NoteValue::from_raw(value.into()),
1182                memo.into_bytes(),
1183            )
1184            .map_err(Error::OrchardRecipient)
1185    }
1186
1187    /// Adds a wallet-controlled Orchard change output to the transaction.
1188    ///
1189    /// Returns [`Error::OrchardBuilderNotAvailable`] if this builder is not
1190    /// configured with an Orchard bundle builder. Returns
1191    /// [`Error::OrchardRecipient`] if the Orchard builder rejects the recipient
1192    /// or cannot construct the output.
1193    pub fn add_orchard_change_output<FE>(
1194        &mut self,
1195        fvk: orchard::keys::FullViewingKey,
1196        ovk: Option<orchard::keys::OutgoingViewingKey>,
1197        recipient: orchard::Address,
1198        value: Zatoshis,
1199        memo: MemoBytes,
1200    ) -> Result<(), Error<FE>> {
1201        self.orchard_builder
1202            .as_mut()
1203            .ok_or(Error::OrchardBuilderNotAvailable)?
1204            .add_change_output(
1205                fvk,
1206                ovk,
1207                recipient,
1208                orchard::value::NoteValue::from_raw(value.into()),
1209                memo.into_bytes(),
1210            )
1211            .map_err(Error::OrchardRecipient)
1212    }
1213
1214    /// Adds an Ironwood note to be spent in this bundle.
1215    ///
1216    /// The note must use [`orchard::note::NoteVersion::V3`], the Ironwood
1217    /// note plaintext format.
1218    ///
1219    /// Returns an error if the given note has an unsupported version, or if
1220    /// the given Merkle path does not have the required Ironwood anchor for the
1221    /// note.
1222    pub fn add_ironwood_spend<FE>(
1223        &mut self,
1224        fvk: orchard::keys::FullViewingKey,
1225        note: orchard::Note,
1226        merkle_path: orchard::tree::MerklePath,
1227    ) -> Result<(), Error<FE>> {
1228        let builder = self
1229            .ironwood_builder
1230            .as_mut()
1231            .ok_or(Error::IronwoodBuilderNotAvailable)?;
1232
1233        if note.version() != orchard::note::NoteVersion::V3 {
1234            return Err(Error::IronwoodSpendUnsupportedNoteVersion(note.version()));
1235        }
1236
1237        builder
1238            .add_spend(fvk, note, merkle_path)
1239            .map_err(Error::IronwoodSpend)?;
1240        Ok(())
1241    }
1242
1243    /// Adds an Ironwood recipient to the transaction.
1244    ///
1245    /// This uses [`orchard::note::NoteVersion::V3`], the Ironwood note
1246    /// plaintext format.
1247    pub fn add_ironwood_output<FE>(
1248        &mut self,
1249        ovk: Option<orchard::keys::OutgoingViewingKey>,
1250        recipient: orchard::Address,
1251        value: Zatoshis,
1252        memo: MemoBytes,
1253    ) -> Result<(), Error<FE>> {
1254        self.ironwood_builder
1255            .as_mut()
1256            .ok_or(Error::IronwoodBuilderNotAvailable)?
1257            .add_output(
1258                ovk,
1259                recipient,
1260                orchard::value::NoteValue::from_raw(value.into()),
1261                memo.into_bytes(),
1262            )
1263            .map_err(Error::IronwoodRecipient)
1264    }
1265
1266    /// Adds a Sapling note to be spent in this transaction.
1267    ///
1268    /// Returns an error if the given Merkle path does not have the same anchor as the
1269    /// paths for previous Sapling notes.
1270    pub fn add_sapling_spend<FE>(
1271        &mut self,
1272        fvk: sapling::keys::FullViewingKey,
1273        note: Note,
1274        merkle_path: sapling::MerklePath,
1275    ) -> Result<(), Error<FE>> {
1276        if let Some(builder) = self.sapling_builder.as_mut() {
1277            builder.add_spend(fvk, note, merkle_path)?;
1278            Ok(())
1279        } else {
1280            Err(Error::SaplingBuilderNotAvailable)
1281        }
1282    }
1283
1284    /// Adds a Sapling address to send funds to.
1285    pub fn add_sapling_output<FE>(
1286        &mut self,
1287        ovk: Option<sapling::keys::OutgoingViewingKey>,
1288        to: PaymentAddress,
1289        value: Zatoshis,
1290        memo: MemoBytes,
1291    ) -> Result<(), Error<FE>> {
1292        self.sapling_builder
1293            .as_mut()
1294            .ok_or(Error::SaplingBuilderNotAvailable)?
1295            .add_output(
1296                ovk,
1297                to,
1298                sapling::value::NoteValue::from_raw(u64::from(value)),
1299                memo.into_bytes(),
1300            )
1301            .map_err(Error::SaplingBuild)
1302    }
1303
1304    /// Adds a transparent coin to be spent in this transaction.
1305    #[cfg(feature = "transparent-inputs")]
1306    pub fn add_transparent_input(&mut self, input: TransparentInputInfo<Zatoshis>) {
1307        self.transparent_builder.add_input(input)
1308    }
1309
1310    /// Adds a transparent P2PKH coin to be spent in this transaction.
1311    #[cfg(feature = "transparent-inputs")]
1312    pub fn add_transparent_p2pkh_input(
1313        &mut self,
1314        pubkey: secp256k1::PublicKey,
1315        utxo: transparent::bundle::OutPoint,
1316        coin: TxOut<Zatoshis>,
1317    ) -> Result<(), transparent::builder::Error> {
1318        self.transparent_builder.add_p2pkh_input(pubkey, utxo, coin)
1319    }
1320
1321    /// Adds a transparent P2SH coin to be spent in this transaction.
1322    #[cfg(feature = "transparent-inputs")]
1323    pub fn add_transparent_p2sh_input(
1324        &mut self,
1325        redeem_script: script::FromChain,
1326        utxo: transparent::bundle::OutPoint,
1327        coin: TxOut<Zatoshis>,
1328    ) -> Result<(), transparent::builder::Error> {
1329        self.transparent_builder
1330            .add_p2sh_input(redeem_script, utxo, coin)
1331    }
1332
1333    /// Adds a transparent address to send funds to.
1334    pub fn add_transparent_output(
1335        &mut self,
1336        to: &TransparentAddress,
1337        value: Zatoshis,
1338    ) -> Result<(), transparent::builder::Error> {
1339        self.transparent_builder.add_output(to, value)
1340    }
1341
1342    /// Adds a zero-value transparent "null data" (`OP_RETURN`) output that carries
1343    /// `data`.
1344    ///
1345    /// Returns [`Error::NullDataTooLong`] if `data` is longer than 80 bytes.
1346    pub fn add_transparent_null_data_output<FE>(&mut self, data: &[u8]) -> Result<(), Error<FE>> {
1347        if data.len() > MAX_OP_RETURN_RELAY_BYTES {
1348            return Err(Error::NullDataTooLong {
1349                actual: data.len(),
1350                limit: MAX_OP_RETURN_RELAY_BYTES,
1351            });
1352        }
1353
1354        let script = script::Component(vec![
1355            op::RETURN,
1356            op::push_value(data).expect("length checked"),
1357        ]);
1358
1359        self.transparent_builder
1360            .add_script_output(&script, Zatoshis::ZERO);
1361        Ok(())
1362    }
1363
1364    /// Returns the sum of the transparent, Sapling, Orchard, Ironwood, and any
1365    /// experimental ZIP 233 value balances.
1366    fn value_balance(&self) -> Result<ZatBalance, BalanceError> {
1367        let value_balances = [
1368            transparent_value_balance(&self.transparent_builder)?,
1369            self.sapling_builder
1370                .as_ref()
1371                .map_or_else(ZatBalance::zero, |builder| {
1372                    builder.value_balance::<ZatBalance>()
1373                }),
1374            self.orchard_builder.as_ref().map_or_else(
1375                || Ok(ZatBalance::zero()),
1376                |builder| {
1377                    builder
1378                        .value_balance::<ZatBalance>()
1379                        .map_err(|_| BalanceError::Overflow)
1380                },
1381            )?,
1382            self.ironwood_builder.as_ref().map_or_else(
1383                || Ok(ZatBalance::zero()),
1384                |builder| {
1385                    builder
1386                        .value_balance::<ZatBalance>()
1387                        .map_err(|_| BalanceError::Overflow)
1388                },
1389            )?,
1390            #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1391            -ZatBalance::from(self.zip233_amount),
1392        ];
1393
1394        value_balances
1395            .into_iter()
1396            .sum::<Option<_>>()
1397            .ok_or(BalanceError::Overflow)
1398    }
1399
1400    /// Reports the calculated fee given the specified fee rule.
1401    ///
1402    /// This fee is a function of the spends and outputs that have been added to the builder,
1403    /// pursuant to the specified [`FeeRule`].
1404    pub fn get_fee<FR: FeeRule>(&self, fee_rule: &FR) -> Result<Zatoshis, FeeError<FR::Error>> {
1405        #[cfg(feature = "transparent-inputs")]
1406        let transparent_inputs = self.transparent_builder.inputs();
1407
1408        #[cfg(not(feature = "transparent-inputs"))]
1409        let transparent_inputs: &[Infallible] = &[];
1410
1411        let sapling_spends = self
1412            .sapling_builder
1413            .as_ref()
1414            .map_or(0, |builder| builder.inputs().len());
1415
1416        let ironwood_actions = self
1417            .ironwood_builder
1418            .as_ref()
1419            .map_or(Ok(0), |builder| {
1420                orchard_action_count(
1421                    builder,
1422                    self.build_config.is_coinbase(),
1423                    orchard::bundle::BundleVersion::ironwood_v3(),
1424                )
1425            })
1426            .map_err(FeeError::Bundle)?;
1427
1428        fee_rule
1429            .fee_required(
1430                &self.params,
1431                self.target_height,
1432                transparent_inputs.iter().map(|i| i.serialized_size()),
1433                self.transparent_builder
1434                    .outputs()
1435                    .iter()
1436                    .map(|i| i.serialized_size()),
1437                sapling_spends,
1438                self.sapling_builder
1439                    .as_ref()
1440                    .zip(self.build_config.sapling_builder_config())
1441                    .map_or(Ok(0), |(builder, (bundle_type, _))| {
1442                        bundle_type
1443                            .num_outputs(sapling_spends, builder.outputs().len())
1444                            .map_err(FeeError::Bundle)
1445                    })?,
1446                self.orchard_builder
1447                    .as_ref()
1448                    .map_or(Ok(0), |builder| {
1449                        orchard_action_count(
1450                            builder,
1451                            self.build_config.is_coinbase(),
1452                            self.orchard_bundle_version
1453                                .expect("orchard builder present implies bundle version"),
1454                        )
1455                    })
1456                    .map_err(FeeError::Bundle)?,
1457                ironwood_actions,
1458            )
1459            .map_err(FeeError::FeeRule)
1460    }
1461
1462    #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1463    /// Sets the experimental ZIP 233 amount. No implemented transaction format supports
1464    /// a nonzero amount; transaction construction rejects it.
1465    pub fn set_zip233_amount(&mut self, zip233_amount: Zatoshis) {
1466        self.zip233_amount = zip233_amount;
1467    }
1468}
1469
1470/// Returns the value of the transparent inputs added to `builder`, minus the value of
1471/// its transparent outputs.
1472fn transparent_value_balance(
1473    builder: &TransparentBuilder<Zatoshis>,
1474) -> Result<ZatBalance, BalanceError> {
1475    #[cfg(feature = "transparent-inputs")]
1476    let input_sum = builder
1477        .inputs()
1478        .iter()
1479        .map(|input| input.coin().value())
1480        .sum::<Option<Zatoshis>>()
1481        .ok_or(BalanceError::Overflow)?;
1482
1483    #[cfg(not(feature = "transparent-inputs"))]
1484    let input_sum = Zatoshis::ZERO;
1485
1486    let output_sum = builder
1487        .outputs()
1488        .iter()
1489        .map(|vo| vo.value())
1490        .sum::<Option<Zatoshis>>()
1491        .ok_or(BalanceError::Overflow)?;
1492
1493    (ZatBalance::from(input_sum) - ZatBalance::from(output_sum)).ok_or(BalanceError::Underflow)
1494}
1495
1496impl<P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder<P, U> {
1497    /// Builds a transaction from the configured spends and outputs.
1498    ///
1499    /// Upon success, returns a [`BuildResult`] containing:
1500    ///
1501    /// - the [final transaction],
1502    /// - the [Sapling metadata], and
1503    /// - the [Orchard metadata]
1504    ///
1505    /// generated during the build process.
1506    ///
1507    /// [Sapling metadata]: ::sapling::builder::SaplingMetadata
1508    /// [Orchard metadata]: ::orchard::builder::BundleMetadata
1509    /// [final transaction]: Transaction
1510    #[allow(clippy::too_many_arguments)]
1511    #[cfg(feature = "circuits")]
1512    pub fn build<R: Rng + CryptoRng, SP: SpendProver, OP: OutputProver, FR: FeeRule>(
1513        self,
1514        transparent_signing_set: &TransparentSigningSet,
1515        sapling_extsks: &[sapling::zip32::ExtendedSpendingKey],
1516        orchard_saks: &[orchard::keys::SpendAuthorizingKey],
1517        rng: R,
1518        spend_prover: &SP,
1519        output_prover: &OP,
1520        fee_rule: &FR,
1521    ) -> Result<BuildResult, Error<FR::Error>> {
1522        match &self.build_config {
1523            BuildConfig::Coinbase { miner_data } => {
1524                let target_height = self.target_height;
1525                let miner_data = miner_data.clone();
1526
1527                self.build_internal::<Coinbase, _, _, _, _>(
1528                    |b| {
1529                        coinbase::build_transparent_bundle(b, target_height, miner_data)
1530                            .map(Some)
1531                            .map_err(Error::Coinbase)
1532                    },
1533                    |b, _| Ok(b.clone().map_authorization(coinbase::Coinbase)),
1534                    &[],
1535                    &[],
1536                    rng,
1537                    spend_prover,
1538                    output_prover,
1539                    None,
1540                )
1541            }
1542            BuildConfig::Standard { .. } => {
1543                let fee = self.get_fee(fee_rule).map_err(Error::Fee)?;
1544
1545                self.build_internal::<Unauthorized, _, _, _, _>(
1546                    |b| Ok(b.build()),
1547                    |b, sighash_data| {
1548                        authorize_transparent(b, sighash_data, transparent_signing_set)
1549                    },
1550                    sapling_extsks,
1551                    orchard_saks,
1552                    rng,
1553                    spend_prover,
1554                    output_prover,
1555                    Some(fee),
1556                )
1557            }
1558        }
1559    }
1560
1561    #[allow(clippy::too_many_arguments)]
1562    #[cfg(feature = "circuits")]
1563    fn build_internal<A, R, SP, OP, FE>(
1564        self,
1565        build_transparent: impl FnOnce(
1566            TransparentBuilder<Zatoshis>,
1567        ) -> Result<
1568            Option<transparent::bundle::Bundle<A::TransparentAuth, Zatoshis>>,
1569            Error<FE>,
1570        >,
1571        authorize_transparent: impl FnOnce(
1572            &transparent::bundle::Bundle<A::TransparentAuth, Zatoshis>,
1573            &PrecomputedSighashData<A>,
1574        ) -> Result<
1575            transparent::bundle::Bundle<transparent::bundle::Authorized, Zatoshis>,
1576            transparent::builder::Error,
1577        >,
1578        sapling_extsks: &[sapling::zip32::ExtendedSpendingKey],
1579        orchard_saks: &[orchard::keys::SpendAuthorizingKey],
1580        mut rng: R,
1581        spend_prover: &SP,
1582        output_prover: &OP,
1583        fee: Option<Zatoshis>,
1584    ) -> Result<BuildResult, Error<FE>>
1585    where
1586        A: Authorization<
1587                SaplingAuth = sapling::builder::InProgress<
1588                    sapling::builder::Proven,
1589                    sapling::builder::Unsigned,
1590                >,
1591                OrchardAuth = orchard::builder::InProgress<
1592                    orchard::builder::Unproven,
1593                    orchard::builder::Unauthorized,
1594                >,
1595            >,
1596        A::TransparentAuth: transparent::sighash::TransparentAuthorizingContext<Zatoshis>,
1597        R: Rng + CryptoRng,
1598        SP: SpendProver,
1599        OP: OutputProver,
1600    {
1601        self.check_version_compatibility::<FE>(self.tx_version)?;
1602        self.check_coinbase_expiry_height::<FE>()?;
1603
1604        //
1605        // Consistency checks
1606        //
1607
1608        assert_eq!(self.build_config.is_coinbase(), fee.is_none());
1609        if let Some(fee) = fee {
1610            // After fees are accounted for, the value balance of the transaction must be zero.
1611            let balance_after_fees =
1612                (self.value_balance()? - fee).ok_or(BalanceError::Underflow)?;
1613
1614            match balance_after_fees.cmp(&ZatBalance::zero()) {
1615                Ordering::Less => {
1616                    return Err(Error::InsufficientFunds(-balance_after_fees));
1617                }
1618                Ordering::Greater => {
1619                    return Err(Error::ChangeRequired(balance_after_fees));
1620                }
1621                Ordering::Equal => (),
1622            };
1623        }
1624
1625        let transparent_bundle = build_transparent(self.transparent_builder)?;
1626
1627        let (sapling_bundle, sapling_meta) = match self
1628            .sapling_builder
1629            .and_then(|builder| {
1630                builder
1631                    .build::<SP, OP, _, _>(sapling_extsks, &mut rng)
1632                    .map_err(Error::SaplingBuild)
1633                    .transpose()
1634                    .map(|res| {
1635                        res.map(|(bundle, sapling_meta)| {
1636                            // We need to create proofs before signatures, because we still support
1637                            // creating V4 transactions, which commit to the Sapling proofs in the
1638                            // transaction digest.
1639                            (
1640                                bundle.create_proofs(
1641                                    spend_prover,
1642                                    output_prover,
1643                                    &mut rng,
1644                                    self._progress_notifier,
1645                                ),
1646                                sapling_meta,
1647                            )
1648                        })
1649                    })
1650            })
1651            .transpose()?
1652        {
1653            Some((bundle, meta)) => (Some(bundle), meta),
1654            None => (None, SaplingMetadata::empty()),
1655        };
1656
1657        let (orchard_bundle, orchard_meta) = match self
1658            .orchard_builder
1659            .and_then(|builder| {
1660                builder
1661                    .build(&mut rng)
1662                    .map_err(Error::OrchardBuild)
1663                    .transpose()
1664            })
1665            .transpose()?
1666        {
1667            Some((bundle, meta)) => (Some(bundle), meta),
1668            None => (None, orchard::builder::BundleMetadata::empty()),
1669        };
1670
1671        let (ironwood_bundle, ironwood_meta) = match self
1672            .ironwood_builder
1673            .and_then(|builder| {
1674                builder
1675                    .build(&mut rng)
1676                    .map_err(Error::IronwoodBuild)
1677                    .transpose()
1678            })
1679            .transpose()?
1680        {
1681            Some((bundle, meta)) => (Some(bundle), meta),
1682            None => (None, orchard::builder::BundleMetadata::empty()),
1683        };
1684
1685        let unauthed_tx: TransactionData<A> = TransactionData {
1686            version: self.tx_version,
1687            consensus_branch_id: self.consensus_branch_id,
1688            lock_time: 0,
1689            expiry_height: self.expiry_height,
1690            #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1691            zip233_amount: self.zip233_amount,
1692            transparent_bundle,
1693            // We don't support constructing Sprout bundles.
1694            //
1695            // # Consensus
1696            //
1697            // > A coinbase transaction MUST NOT have any JoinSplit descriptions.
1698            //
1699            // > A coinbase transaction MUST NOT have any Spend descriptions.
1700            //
1701            // <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
1702            sprout_bundle: None,
1703            sapling_bundle: sapling_bundle.map(Box::new),
1704            orchard_bundle: orchard_bundle.map(Box::new),
1705            ironwood_bundle: ironwood_bundle.map(Box::new),
1706        };
1707
1708        //
1709        // Signatures -- everything but the signatures must already have been added.
1710        //
1711        let sighash_data = PrecomputedSighashData::new(unauthed_tx);
1712
1713        let transparent_bundle = sighash_data
1714            .tx()
1715            .transparent_bundle
1716            .as_ref()
1717            .map(|b| authorize_transparent(b, &sighash_data))
1718            .transpose()
1719            .map_err(Error::TransparentBuild)?;
1720
1721        // the commitment being signed is shared across all Sapling inputs; once
1722        // V4 transactions are deprecated this should just be the txid, but
1723        // for now we need to continue to compute it here.
1724        let shielded_sig_commitment = sighash_data.signature_hash(&SignableInput::Shielded);
1725        let unauthed_tx = sighash_data.into_tx();
1726
1727        let sapling_asks = sapling_extsks
1728            .iter()
1729            .map(|extsk| extsk.expsk().ask().clone())
1730            .collect::<Vec<_>>();
1731        let sapling_bundle = unauthed_tx
1732            .sapling_bundle
1733            .map(|b| b.apply_signatures(&mut rng, *shielded_sig_commitment.as_ref(), &sapling_asks))
1734            .transpose()
1735            .map_err(Error::SaplingBuild)?;
1736
1737        // The Orchard and Ironwood circuit version is fixed by the transaction's
1738        // consensus branch (both pools share the post-NU6.3 circuit), so derive it
1739        // once from the branch rather than from a bundle. Only obtain the key when
1740        // an Orchard or Ironwood bundle is actually present.
1741        let orchard_circuit_version = {
1742            let build_proving_key =
1743                unauthed_tx.orchard_bundle.is_some() || unauthed_tx.ironwood_bundle.is_some();
1744            build_proving_key.then(|| {
1745                bundle_version_for_branch(
1746                    unauthed_tx.consensus_branch_id,
1747                    orchard::ValuePool::Orchard,
1748                )
1749                .expect("an Orchard or Ironwood bundle implies an NU5+ consensus branch")
1750                .circuit_version()
1751            })
1752        };
1753
1754        // Reuse a process-wide cached proving key rather than reconstructing it on
1755        // every `build` call. See `cached_orchard_proving_key`.
1756        #[cfg(feature = "std")]
1757        let orchard_proving_key: Option<&orchard::circuit::ProvingKey> =
1758            orchard_circuit_version.map(cached_orchard_proving_key);
1759        // Without `std` there is no thread-safe cache; build the key once for this
1760        // transaction. (Proving requires `std` in practice, so this path does not
1761        // run when actually creating proofs.)
1762        #[cfg(not(feature = "std"))]
1763        let orchard_proving_key_storage =
1764            orchard_circuit_version.map(orchard::circuit::ProvingKey::build);
1765        #[cfg(not(feature = "std"))]
1766        let orchard_proving_key: Option<&orchard::circuit::ProvingKey> =
1767            orchard_proving_key_storage.as_ref();
1768
1769        let orchard_bundle = unauthed_tx
1770            .orchard_bundle
1771            .map(|b| {
1772                b.create_proof(
1773                    orchard_proving_key
1774                        .expect("proving key is built when an Orchard bundle is present"),
1775                    &mut rng,
1776                )
1777                .and_then(|b| {
1778                    b.apply_signatures(&mut rng, *shielded_sig_commitment.as_ref(), orchard_saks)
1779                })
1780            })
1781            .transpose()
1782            .map_err(Error::OrchardBuild)?;
1783
1784        let ironwood_bundle = unauthed_tx
1785            .ironwood_bundle
1786            .map(|b| {
1787                b.create_proof(
1788                    orchard_proving_key
1789                        .expect("proving key is built when an Ironwood bundle is present"),
1790                    &mut rng,
1791                )
1792                .and_then(|b| {
1793                    // Ironwood actions use the Orchard bundle type and the same
1794                    // Orchard spend authority. The `IronwoodNu6_3Onward` pool
1795                    // restrictions select the Ironwood circuit and flag rules;
1796                    // `apply_signatures` only signs actions whose `ak` matches
1797                    // a supplied spend authorizing key.
1798                    b.apply_signatures(&mut rng, *shielded_sig_commitment.as_ref(), orchard_saks)
1799                })
1800            })
1801            .transpose()
1802            .map_err(Error::IronwoodBuild)?;
1803
1804        let authorized_tx = TransactionData {
1805            version: unauthed_tx.version,
1806            consensus_branch_id: unauthed_tx.consensus_branch_id,
1807            lock_time: unauthed_tx.lock_time,
1808            expiry_height: unauthed_tx.expiry_height,
1809            #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1810            zip233_amount: unauthed_tx.zip233_amount,
1811            transparent_bundle,
1812            sprout_bundle: unauthed_tx.sprout_bundle,
1813            sapling_bundle: sapling_bundle.map(Box::new),
1814            orchard_bundle: orchard_bundle.map(Box::new),
1815            ironwood_bundle: ironwood_bundle.map(Box::new),
1816        };
1817
1818        // The unwrap() here is safe because the txid hashing
1819        // of freeze() should be infalliable.
1820        Ok(BuildResult {
1821            transaction: authorized_tx.freeze().unwrap(),
1822            sapling_meta,
1823            orchard_meta,
1824            ironwood_meta,
1825        })
1826    }
1827}
1828
1829impl<P: consensus::Parameters, U> Builder<P, U> {
1830    /// Builds a PCZT from the configured spends and outputs.
1831    ///
1832    /// Upon success, returns a struct containing the PCZT components, and the
1833    /// [`SaplingMetadata`] and [`orchard::builder::BundleMetadata`] generated during the
1834    /// build process.
1835    ///
1836    /// Experimental ZIP 233 builds reject nonzero ZIP 233 amounts because PCZT cannot
1837    /// preserve them through extraction.
1838    pub fn build_for_pczt<R: Rng + CryptoRng, FR: FeeRule>(
1839        self,
1840        mut rng: R,
1841        fee_rule: &FR,
1842    ) -> Result<PcztResult<P>, Error<FR::Error>> {
1843        #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
1844        if self.zip233_amount != Zatoshis::ZERO {
1845            return Err(Error::Zip233UnsupportedByPczt);
1846        }
1847        let fee = self.get_fee(fee_rule).map_err(Error::Fee)?;
1848        self.check_version_compatibility::<FR::Error>(self.tx_version)?;
1849        self.check_coinbase_expiry_height::<FR::Error>()?;
1850
1851        //
1852        // Consistency checks
1853        //
1854
1855        // After fees are accounted for, the value balance of the transaction must be zero.
1856        let balance_after_fees = (self.value_balance()? - fee).ok_or(BalanceError::Underflow)?;
1857
1858        match balance_after_fees.cmp(&ZatBalance::zero()) {
1859            Ordering::Less => {
1860                return Err(Error::InsufficientFunds(-balance_after_fees));
1861            }
1862            Ordering::Greater => {
1863                return Err(Error::ChangeRequired(balance_after_fees));
1864            }
1865            Ordering::Equal => (),
1866        };
1867
1868        let transparent_bundle = self.transparent_builder.build_for_pczt();
1869
1870        let (sapling_bundle, sapling_meta) = match self
1871            .sapling_builder
1872            .map(|builder| {
1873                builder
1874                    .build_for_pczt(&mut rng)
1875                    .map_err(Error::SaplingBuild)
1876            })
1877            .transpose()?
1878        {
1879            Some((bundle, meta)) => (Some(bundle), meta),
1880            None => (None, SaplingMetadata::empty()),
1881        };
1882
1883        let (orchard_bundle, orchard_meta) = match self
1884            .orchard_builder
1885            .map(|builder| {
1886                builder
1887                    .build_for_pczt(&mut rng)
1888                    .map_err(Error::OrchardBuild)
1889            })
1890            .transpose()?
1891        {
1892            Some((bundle, meta)) => (Some(bundle), meta),
1893            None => (None, orchard::builder::BundleMetadata::empty()),
1894        };
1895
1896        let (ironwood_bundle, ironwood_meta) = if self.tx_version.has_ironwood() {
1897            match self
1898                .ironwood_builder
1899                .map(|builder| {
1900                    builder
1901                        .build_for_pczt(&mut rng)
1902                        .map_err(Error::IronwoodBuild)
1903                })
1904                .transpose()?
1905            {
1906                Some((bundle, meta)) => (Some(bundle), meta),
1907                None => (None, orchard::builder::BundleMetadata::empty()),
1908            }
1909        } else {
1910            (None, orchard::builder::BundleMetadata::empty())
1911        };
1912
1913        Ok(PcztResult {
1914            pczt_parts: PcztParts {
1915                params: self.params,
1916                version: self.tx_version,
1917                consensus_branch_id: self.consensus_branch_id,
1918                lock_time: 0,
1919                expiry_height: self.expiry_height,
1920                transparent: transparent_bundle,
1921                sapling: sapling_bundle,
1922                orchard: orchard_bundle,
1923                ironwood: ironwood_bundle,
1924            },
1925            sapling_meta,
1926            orchard_meta,
1927            ironwood_meta,
1928        })
1929    }
1930}
1931
1932/// Returns a process-wide cached Orchard proving key for the given circuit version.
1933///
1934/// Building an Orchard proving key is expensive, and the transaction builder would
1935/// otherwise reconstruct it on every call to [`Builder::build`]. Callers that build
1936/// many transactions in a process therefore share a single key per circuit version.
1937///
1938/// The cache is keyed by [`orchard::circuit::OrchardCircuitVersion`] because the
1939/// verifying (and hence proving) keys differ between circuit versions; mixing them
1940/// would produce proofs against the wrong key.
1941///
1942/// This is only available when the `std` feature is enabled, as it relies on
1943/// [`std::sync::OnceLock`] for thread-safe lazy initialization. Proving requires
1944/// `std` in practice, so this covers the paths that actually create proofs.
1945#[cfg(all(feature = "circuits", feature = "std"))]
1946use {
1947    orchard::circuit::{OrchardCircuitVersion, ProvingKey},
1948    std::sync::OnceLock,
1949};
1950
1951#[cfg(all(feature = "circuits", feature = "std"))]
1952pub fn cached_orchard_proving_key(
1953    circuit_version: orchard::circuit::OrchardCircuitVersion,
1954) -> &'static orchard::circuit::ProvingKey {
1955    static INSECURE_PRE_NU6_2: OnceLock<ProvingKey> = OnceLock::new();
1956    static FIXED_POST_NU6_2: OnceLock<ProvingKey> = OnceLock::new();
1957    static POST_NU6_3: OnceLock<ProvingKey> = OnceLock::new();
1958
1959    let cell = match circuit_version {
1960        OrchardCircuitVersion::InsecurePreNu6_2 => &INSECURE_PRE_NU6_2,
1961        OrchardCircuitVersion::FixedPostNu6_2 => &FIXED_POST_NU6_2,
1962        OrchardCircuitVersion::PostNu6_3 => &POST_NU6_3,
1963    };
1964    cell.get_or_init(|| ProvingKey::build(circuit_version))
1965}
1966
1967#[cfg(feature = "circuits")]
1968fn authorize_transparent(
1969    b: &transparent::bundle::Bundle<transparent::builder::Unauthorized<Zatoshis>, Zatoshis>,
1970    sighash_data: &PrecomputedSighashData<Unauthorized>,
1971    transparent_signing_set: &TransparentSigningSet,
1972) -> Result<
1973    transparent::bundle::Bundle<transparent::bundle::Authorized, Zatoshis>,
1974    transparent::builder::Error,
1975> {
1976    b.clone().apply_signatures(
1977        |input| {
1978            *sighash_data
1979                .signature_hash(&SignableInput::Transparent(input))
1980                .as_ref()
1981        },
1982        transparent_signing_set,
1983    )
1984}
1985
1986#[cfg(all(any(test, feature = "test-dependencies"), feature = "circuits"))]
1987mod testing {
1988    use core::convert::Infallible;
1989
1990    use rand_core::{Rng, TryCryptoRng, TryRng};
1991
1992    use ::sapling::prover::mock::{MockOutputProver, MockSpendProver};
1993    use ::transparent::builder::TransparentSigningSet;
1994    use zcash_protocol::consensus;
1995
1996    use super::{BuildResult, Builder, Error};
1997    use crate::transaction::fees::zip317;
1998
1999    impl<P: consensus::Parameters, U: sapling::builder::ProverProgress> Builder<P, U> {
2000        /// Build the transaction using mocked randomness and proving capabilities.
2001        /// DO NOT USE EXCEPT FOR UNIT TESTING.
2002        pub fn mock_build<R: Rng>(
2003            self,
2004            transparent_signing_set: &TransparentSigningSet,
2005            sapling_extsks: &[sapling::zip32::ExtendedSpendingKey],
2006            orchard_saks: &[orchard::keys::SpendAuthorizingKey],
2007            rng: R,
2008        ) -> Result<BuildResult, Error<zip317::FeeError>> {
2009            struct FakeCryptoRng<R: Rng>(R);
2010            impl<R: Rng> TryRng for FakeCryptoRng<R> {
2011                type Error = Infallible;
2012
2013                fn try_next_u32(&mut self) -> Result<u32, Infallible> {
2014                    Ok(self.0.next_u32())
2015                }
2016
2017                fn try_next_u64(&mut self) -> Result<u64, Infallible> {
2018                    Ok(self.0.next_u64())
2019                }
2020
2021                fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> {
2022                    self.0.fill_bytes(dest);
2023                    Ok(())
2024                }
2025            }
2026            impl<R: Rng> TryCryptoRng for FakeCryptoRng<R> {}
2027
2028            self.build(
2029                transparent_signing_set,
2030                sapling_extsks,
2031                orchard_saks,
2032                FakeCryptoRng(rng),
2033                &MockSpendProver,
2034                &MockOutputProver,
2035                #[allow(deprecated)]
2036                &zip317::FeeRule::standard(),
2037            )
2038        }
2039    }
2040}
2041
2042#[cfg(test)]
2043mod tests {
2044    // Fixtures are pre-Revision-2 (no NU7 activation), where the fee is the 5000-zatoshi constant.
2045    #![allow(deprecated)]
2046
2047    #[cfg(all(feature = "circuits", feature = "std"))]
2048    use {super::cached_orchard_proving_key, core::ptr, orchard::circuit::OrchardCircuitVersion};
2049
2050    #[cfg(feature = "circuits")]
2051    use {
2052        super::{
2053            BLOSSOM_DEFAULT_TX_EXPIRY_DELTA, Builder, DeferredPcztBuilder, Error,
2054            MAX_OP_RETURN_RELAY_BYTES, NU7_DEFAULT_TX_EXPIRY_DELTA,
2055        },
2056        crate::transaction::{
2057            builder::{BuildConfig, BundlePadding},
2058            fees::zip317::MINIMUM_FEE,
2059        },
2060        ::sapling::{Node, Rseed, zip32::ExtendedSpendingKey},
2061        ::transparent::{address::TransparentAddress, builder::TransparentSigningSet},
2062        assert_matches::assert_matches,
2063        core::convert::Infallible,
2064        ff::Field,
2065        incrementalmerkletree::{frontier::CommitmentTree, witness::IncrementalWitness},
2066        rand::rngs::SysRng,
2067        rand_core::UnwrapErr,
2068        zcash_protocol::{
2069            consensus::{BlockHeight, NetworkUpgrade, Parameters, TEST_NETWORK},
2070            memo::MemoBytes,
2071            value::{BalanceError, ZatBalance, Zatoshis},
2072        },
2073    };
2074
2075    #[cfg(all(feature = "transparent-inputs", feature = "circuits"))]
2076    use {
2077        crate::transaction::{
2078            TxVersion,
2079            builder::{self, TransparentBuilder, default_tx_expiry_delta},
2080        },
2081        ::transparent::bundle::{OutPoint, TxOut},
2082        zcash_protocol::consensus::BranchId,
2083    };
2084
2085    /// A fixed secp256k1 secret key for tests that need a spendable transparent coin.
2086    #[cfg(all(feature = "transparent-inputs", feature = "circuits"))]
2087    const TEST_TRANSPARENT_SECRET_KEY: [u8; 32] = [1; 32];
2088
2089    // The Ironwood tests below reference `TxVersion`/`BranchId` directly; without the
2090    // `transparent-inputs` feature these are not otherwise in scope.
2091    #[cfg(all(feature = "circuits", not(feature = "transparent-inputs")))]
2092    use {crate::transaction::TxVersion, zcash_protocol::consensus::BranchId};
2093
2094    #[cfg(feature = "circuits")]
2095    fn nu6_3_test_network() -> zcash_protocol::local_consensus::LocalNetwork {
2096        zcash_protocol::local_consensus::LocalNetwork {
2097            overwinter: Some(BlockHeight::from_u32(1)),
2098            sapling: Some(BlockHeight::from_u32(2)),
2099            blossom: Some(BlockHeight::from_u32(3)),
2100            heartwood: Some(BlockHeight::from_u32(4)),
2101            canopy: Some(BlockHeight::from_u32(5)),
2102            nu5: Some(BlockHeight::from_u32(6)),
2103            nu6: Some(BlockHeight::from_u32(7)),
2104            nu6_1: Some(BlockHeight::from_u32(8)),
2105            nu6_2: Some(BlockHeight::from_u32(9)),
2106            nu6_3: Some(BlockHeight::from_u32(10)),
2107            nu7: None,
2108            #[cfg(zcash_unstable = "nutachyon")]
2109            nu_tachyon: None,
2110        }
2111    }
2112
2113    #[cfg(feature = "circuits")]
2114    fn nu7_test_network() -> zcash_protocol::local_consensus::LocalNetwork {
2115        zcash_protocol::local_consensus::LocalNetwork {
2116            overwinter: Some(BlockHeight::from_u32(1)),
2117            sapling: Some(BlockHeight::from_u32(2)),
2118            blossom: Some(BlockHeight::from_u32(3)),
2119            heartwood: Some(BlockHeight::from_u32(4)),
2120            canopy: Some(BlockHeight::from_u32(5)),
2121            nu5: Some(BlockHeight::from_u32(6)),
2122            nu6: Some(BlockHeight::from_u32(7)),
2123            nu6_1: Some(BlockHeight::from_u32(8)),
2124            nu6_2: Some(BlockHeight::from_u32(9)),
2125            nu6_3: Some(BlockHeight::from_u32(10)),
2126            nu7: Some(BlockHeight::from_u32(11)),
2127            #[cfg(zcash_unstable = "nutachyon")]
2128            nu_tachyon: None,
2129        }
2130    }
2131
2132    #[cfg(feature = "circuits")]
2133    fn standard_build_config() -> BuildConfig {
2134        BuildConfig::Standard {
2135            sapling_anchor: None,
2136            orchard_anchor: None,
2137            ironwood_anchor: None,
2138            orchard_padding: BundlePadding::DEFAULT,
2139            ironwood_padding: BundlePadding::DEFAULT,
2140        }
2141    }
2142
2143    #[test]
2144    #[cfg(feature = "circuits")]
2145    fn default_expiry_delta_increases_at_nu7_activation() {
2146        let params = nu7_test_network();
2147        let nu7_activation = params.activation_height(NetworkUpgrade::Nu7).unwrap();
2148        let last_pre_nu7_height = nu7_activation - 1;
2149
2150        let pre_nu7 = Builder::new(params, last_pre_nu7_height, standard_build_config());
2151        assert_eq!(
2152            pre_nu7.expiry_height(),
2153            last_pre_nu7_height + BLOSSOM_DEFAULT_TX_EXPIRY_DELTA
2154        );
2155
2156        let post_nu7 = Builder::new(params, nu7_activation, standard_build_config());
2157        assert_eq!(
2158            post_nu7.expiry_height(),
2159            nu7_activation + NU7_DEFAULT_TX_EXPIRY_DELTA
2160        );
2161    }
2162
2163    #[test]
2164    #[cfg(feature = "circuits")]
2165    fn deferred_pczt_builder_default_expiry_delta_increases_at_nu7_activation() {
2166        let params = nu7_test_network();
2167        let nu7_activation = params.activation_height(NetworkUpgrade::Nu7).unwrap();
2168        let last_pre_nu7_height = nu7_activation - 1;
2169
2170        let pre_nu7 = DeferredPcztBuilder::new::<Infallible>(
2171            params,
2172            last_pre_nu7_height,
2173            BundlePadding::DEFAULT,
2174            BundlePadding::DEFAULT,
2175        )
2176        .unwrap();
2177        assert_eq!(
2178            pre_nu7.expiry_height,
2179            last_pre_nu7_height + BLOSSOM_DEFAULT_TX_EXPIRY_DELTA
2180        );
2181
2182        let post_nu7 = DeferredPcztBuilder::new::<Infallible>(
2183            params,
2184            nu7_activation,
2185            BundlePadding::DEFAULT,
2186            BundlePadding::DEFAULT,
2187        )
2188        .unwrap();
2189        assert_eq!(
2190            post_nu7.expiry_height,
2191            nu7_activation + NU7_DEFAULT_TX_EXPIRY_DELTA
2192        );
2193    }
2194
2195    #[test]
2196    #[cfg(feature = "circuits")]
2197    fn coinbase_expiry_height_ignores_nu7_default_expiry_delta() {
2198        let params = nu7_test_network();
2199        let nu7_activation = params.activation_height(NetworkUpgrade::Nu7).unwrap();
2200
2201        let builder = Builder::new(
2202            params,
2203            nu7_activation,
2204            BuildConfig::Coinbase { miner_data: None },
2205        );
2206        assert_eq!(builder.expiry_height(), nu7_activation);
2207    }
2208
2209    /// `OP_RETURN`.
2210    #[cfg(feature = "circuits")]
2211    const OP_RETURN: u8 = 0x6a;
2212
2213    /// `OP_PUSHDATA1`, which precedes a one-byte length and 76 to 255 bytes of data.
2214    #[cfg(feature = "circuits")]
2215    const OP_PUSHDATA1: u8 = 0x4c;
2216
2217    /// An arbitrary byte that fills the data of a null-data output in tests.
2218    #[cfg(feature = "circuits")]
2219    const NULL_DATA_FILL: u8 = 0xab;
2220
2221    /// Returns a standard builder at NU7 activation with no shielded components.
2222    #[cfg(feature = "circuits")]
2223    fn unshielded_test_builder() -> Builder<zcash_protocol::local_consensus::LocalNetwork, ()> {
2224        let params = nu7_test_network();
2225        let nu7_activation = params.activation_height(NetworkUpgrade::Nu7).unwrap();
2226        Builder::new(params, nu7_activation, standard_build_config())
2227    }
2228
2229    #[test]
2230    #[cfg(feature = "circuits")]
2231    fn null_data_output_is_op_return_with_zero_value() {
2232        let mut builder = unshielded_test_builder();
2233        builder
2234            .add_transparent_null_data_output::<Infallible>(&[0xde, 0xad])
2235            .unwrap();
2236
2237        let outputs = builder.transparent_outputs();
2238        assert_eq!(outputs.len(), 1);
2239        assert_eq!(outputs[0].value(), Zatoshis::ZERO);
2240        // `OP_RETURN`, then a push of two bytes.
2241        assert_eq!(
2242            outputs[0].script_pubkey().0.0,
2243            [OP_RETURN, 0x02, 0xde, 0xad]
2244        );
2245    }
2246
2247    #[test]
2248    #[cfg(feature = "circuits")]
2249    fn null_data_output_accepts_the_maximum_length() {
2250        let mut builder = unshielded_test_builder();
2251        builder
2252            .add_transparent_null_data_output::<Infallible>(
2253                &[NULL_DATA_FILL; MAX_OP_RETURN_RELAY_BYTES],
2254            )
2255            .unwrap();
2256
2257        let outputs = builder.transparent_outputs();
2258        assert_eq!(outputs.len(), 1);
2259        // `OP_RETURN`, then `OP_PUSHDATA1` with a one-byte length, then the data.
2260        let mut expected = vec![OP_RETURN, OP_PUSHDATA1, MAX_OP_RETURN_RELAY_BYTES as u8];
2261        expected.extend_from_slice(&[NULL_DATA_FILL; MAX_OP_RETURN_RELAY_BYTES]);
2262        assert_eq!(outputs[0].script_pubkey().0.0, expected);
2263    }
2264
2265    #[test]
2266    #[cfg(feature = "circuits")]
2267    fn null_data_output_rejects_data_over_the_maximum_length() {
2268        let mut builder = unshielded_test_builder();
2269        assert_matches!(
2270            builder.add_transparent_null_data_output::<Infallible>(
2271                &[0u8; MAX_OP_RETURN_RELAY_BYTES + 1]
2272            ),
2273            Err(Error::NullDataTooLong { actual, limit })
2274                if actual == MAX_OP_RETURN_RELAY_BYTES + 1 && limit == MAX_OP_RETURN_RELAY_BYTES
2275        );
2276        assert!(builder.transparent_outputs().is_empty());
2277    }
2278
2279    #[test]
2280    #[cfg(feature = "circuits")]
2281    fn nu6_3_standard_builder_uses_v6_orchard_protocol() {
2282        let builder = Builder::new(
2283            nu6_3_test_network(),
2284            zcash_protocol::consensus::BlockHeight::from_u32(10),
2285            BuildConfig::Standard {
2286                sapling_anchor: None,
2287                orchard_anchor: Some(orchard::Anchor::empty_tree()),
2288                ironwood_anchor: None,
2289                orchard_padding: BundlePadding::DEFAULT,
2290                ironwood_padding: BundlePadding::DEFAULT,
2291            },
2292        );
2293
2294        assert_eq!(builder.tx_version, crate::transaction::TxVersion::V6);
2295        assert_eq!(
2296            builder.orchard_bundle_version,
2297            Some(orchard::bundle::BundleVersion::orchard_v3())
2298        );
2299    }
2300
2301    #[test]
2302    #[cfg(feature = "circuits")]
2303    fn nu6_3_standard_builder_preserves_branch_orchard_protocol_for_explicit_v5() {
2304        let mut builder = Builder::new(
2305            nu6_3_test_network(),
2306            zcash_protocol::consensus::BlockHeight::from_u32(10),
2307            BuildConfig::Standard {
2308                sapling_anchor: None,
2309                orchard_anchor: Some(orchard::Anchor::empty_tree()),
2310                ironwood_anchor: None,
2311                orchard_padding: BundlePadding::DEFAULT,
2312                ironwood_padding: BundlePadding::DEFAULT,
2313            },
2314        );
2315
2316        builder
2317            .propose_version::<Infallible>(crate::transaction::TxVersion::V5)
2318            .unwrap();
2319
2320        assert_eq!(
2321            builder.orchard_bundle_version,
2322            Some(orchard::bundle::BundleVersion::orchard_v3())
2323        );
2324    }
2325
2326    #[test]
2327    #[cfg(feature = "circuits")]
2328    fn nu6_3_coinbase_builder_does_not_expose_orchard() {
2329        let builder = Builder::new(
2330            nu6_3_test_network(),
2331            zcash_protocol::consensus::BlockHeight::from_u32(10),
2332            BuildConfig::Coinbase { miner_data: None },
2333        );
2334
2335        assert!(builder.orchard_builder.is_none());
2336    }
2337
2338    #[test]
2339    #[cfg(feature = "circuits")]
2340    fn nu7_coinbase_builder_does_not_expose_orchard() {
2341        let builder = Builder::new(
2342            nu7_test_network(),
2343            zcash_protocol::consensus::BlockHeight::from_u32(11),
2344            BuildConfig::Coinbase { miner_data: None },
2345        );
2346
2347        assert!(builder.orchard_builder.is_none());
2348    }
2349
2350    #[test]
2351    #[cfg(feature = "circuits")]
2352    fn nu6_3_coinbase_builder_uses_ironwood_not_orchard() {
2353        let builder = Builder::new(
2354            nu6_3_test_network(),
2355            zcash_protocol::consensus::BlockHeight::from_u32(10),
2356            BuildConfig::Coinbase { miner_data: None },
2357        );
2358
2359        assert!(builder.orchard_builder.is_none());
2360        assert_eq!(
2361            builder
2362                .ironwood_builder
2363                .as_ref()
2364                .map(|_| orchard::bundle::BundleVersion::ironwood_v3()),
2365            Some(orchard::bundle::BundleVersion::ironwood_v3())
2366        );
2367    }
2368
2369    #[test]
2370    #[cfg(feature = "circuits")]
2371    fn nu6_3_coinbase_builder_has_ironwood_output_option() {
2372        let recipient = orchard::keys::FullViewingKey::from(
2373            &orchard::keys::SpendingKey::from_bytes([0; 32]).unwrap(),
2374        )
2375        .address_at(0u32, orchard::keys::Scope::External);
2376        let mut builder = Builder::new(
2377            nu6_3_test_network(),
2378            10u32.into(),
2379            BuildConfig::Coinbase { miner_data: None },
2380        );
2381
2382        assert_matches!(
2383            builder.add_orchard_output::<Infallible>(
2384                None,
2385                recipient,
2386                Zatoshis::const_from_u64(10_000),
2387                MemoBytes::empty(),
2388            ),
2389            Err(Error::OrchardBuilderNotAvailable)
2390        );
2391
2392        builder
2393            .add_ironwood_output::<Infallible>(
2394                None,
2395                recipient,
2396                Zatoshis::const_from_u64(10_000),
2397                MemoBytes::empty(),
2398            )
2399            .unwrap();
2400        assert_eq!(
2401            builder.ironwood_builder.as_ref().map(|b| b.outputs().len()),
2402            Some(1)
2403        );
2404        assert_eq!(
2405            super::orchard_action_count(
2406                builder.ironwood_builder.as_ref().unwrap(),
2407                true,
2408                orchard::bundle::BundleVersion::ironwood_v3()
2409            )
2410            .unwrap(),
2411            1
2412        );
2413    }
2414
2415    #[test]
2416    #[cfg(all(feature = "circuits", feature = "zip-233", zcash_unstable = "zip233"))]
2417    fn build_for_pczt_rejects_nonzero_zip233_amount() {
2418        let mut builder = Builder::new(
2419            nu6_3_test_network(),
2420            10u32.into(),
2421            BuildConfig::Standard {
2422                sapling_anchor: None,
2423                orchard_anchor: None,
2424                ironwood_anchor: None,
2425                orchard_padding: BundlePadding::DEFAULT,
2426                ironwood_padding: BundlePadding::DEFAULT,
2427            },
2428        );
2429        builder.set_zip233_amount(Zatoshis::const_from_u64(1));
2430        assert!(matches!(
2431            builder.check_version_compatibility::<Infallible>(TxVersion::V6),
2432            Err(Error::TargetIncompatible(
2433                BranchId::Nu6_3,
2434                TxVersion::V6,
2435                None
2436            ))
2437        ));
2438        builder.consensus_branch_id = BranchId::Nu7;
2439        for version in [TxVersion::V5, TxVersion::V6] {
2440            assert!(matches!(
2441                builder.check_version_compatibility::<Infallible>(version),
2442                Err(Error::TargetIncompatible(BranchId::Nu7, _, None))
2443            ));
2444        }
2445        assert!(matches!(
2446            builder.build_for_pczt(
2447                UnwrapErr(SysRng),
2448                &crate::transaction::fees::zip317::FeeRule::standard()
2449            ),
2450            Err(Error::Zip233UnsupportedByPczt)
2451        ));
2452    }
2453
2454    #[test]
2455    #[cfg(all(feature = "circuits", feature = "transparent-inputs"))]
2456    fn build_for_pczt_preserves_explicit_v6_without_ironwood() {
2457        let mut builder = Builder::new(
2458            nu6_3_test_network(),
2459            10u32.into(),
2460            BuildConfig::Standard {
2461                sapling_anchor: None,
2462                orchard_anchor: None,
2463                ironwood_anchor: None,
2464                orchard_padding: BundlePadding::DEFAULT,
2465                ironwood_padding: BundlePadding::DEFAULT,
2466            },
2467        );
2468        builder
2469            .propose_version::<Infallible>(TxVersion::V6)
2470            .unwrap();
2471
2472        let mut transparent_signing_set = TransparentSigningSet::new();
2473        let sk = secp256k1::SecretKey::from_secret_bytes(TEST_TRANSPARENT_SECRET_KEY).unwrap();
2474        let pubkey = transparent_signing_set.add_key(sk);
2475        let prev_coin = TxOut::new(
2476            Zatoshis::const_from_u64(50000),
2477            TransparentAddress::from_pubkey(&pubkey).script().into(),
2478        );
2479
2480        builder
2481            .add_transparent_p2pkh_input(pubkey, OutPoint::fake(), prev_coin)
2482            .unwrap();
2483        builder
2484            .add_transparent_output(
2485                &TransparentAddress::PublicKeyHash([0; 20]),
2486                Zatoshis::const_from_u64(40000),
2487            )
2488            .unwrap();
2489
2490        let res = builder
2491            .build_for_pczt(
2492                UnwrapErr(SysRng),
2493                &crate::transaction::fees::zip317::FeeRule::standard(),
2494            )
2495            .unwrap();
2496        assert_eq!(res.pczt_parts.version, TxVersion::V6);
2497        assert_eq!(
2498            res.pczt_parts.consensus_branch_id,
2499            zcash_protocol::consensus::BranchId::Nu6_3
2500        );
2501    }
2502
2503    #[test]
2504    #[cfg(feature = "circuits")]
2505    fn build_for_pczt_accepts_v6_when_ironwood_is_used() {
2506        let mut builder = Builder::new(
2507            nu6_3_test_network(),
2508            10u32.into(),
2509            BuildConfig::Standard {
2510                sapling_anchor: None,
2511                orchard_anchor: None,
2512                ironwood_anchor: Some(orchard::Anchor::empty_tree()),
2513                orchard_padding: BundlePadding::DEFAULT,
2514                ironwood_padding: BundlePadding::DEFAULT,
2515            },
2516        );
2517        let recipient = orchard::keys::FullViewingKey::from(
2518            &orchard::keys::SpendingKey::from_bytes([0; 32]).unwrap(),
2519        )
2520        .address_at(0u32, orchard::keys::Scope::External);
2521        builder
2522            .add_ironwood_output::<crate::transaction::fees::zip317::FeeRule>(
2523                None,
2524                recipient,
2525                Zatoshis::const_from_u64(10_000),
2526                MemoBytes::empty(),
2527            )
2528            .unwrap();
2529
2530        assert_matches!(
2531            builder.build_for_pczt(
2532                UnwrapErr(SysRng),
2533                &crate::transaction::fees::zip317::FeeRule::standard(),
2534            ),
2535            Err(Error::InsufficientFunds(_))
2536        );
2537    }
2538
2539    #[test]
2540    #[cfg(feature = "circuits")]
2541    fn build_for_pczt_rejects_explicit_v5_when_ironwood_is_used() {
2542        let mut builder = Builder::new(
2543            nu6_3_test_network(),
2544            10u32.into(),
2545            BuildConfig::Standard {
2546                sapling_anchor: None,
2547                orchard_anchor: None,
2548                ironwood_anchor: Some(orchard::Anchor::empty_tree()),
2549                orchard_padding: BundlePadding::DEFAULT,
2550                ironwood_padding: BundlePadding::DEFAULT,
2551            },
2552        );
2553        builder
2554            .propose_version::<Infallible>(TxVersion::V5)
2555            .unwrap();
2556
2557        let recipient = orchard::keys::FullViewingKey::from(
2558            &orchard::keys::SpendingKey::from_bytes([0; 32]).unwrap(),
2559        )
2560        .address_at(0u32, orchard::keys::Scope::External);
2561        builder
2562            .add_ironwood_output::<crate::transaction::fees::zip317::FeeRule>(
2563                None,
2564                recipient,
2565                Zatoshis::const_from_u64(10_000),
2566                MemoBytes::empty(),
2567            )
2568            .unwrap();
2569
2570        assert_matches!(
2571            builder.build_for_pczt(
2572                UnwrapErr(SysRng),
2573                &crate::transaction::fees::zip317::FeeRule::standard(),
2574            ),
2575            Err(Error::TargetIncompatible(
2576                BranchId::Nu6_3,
2577                TxVersion::V5,
2578                None
2579            ))
2580        );
2581    }
2582
2583    /// Test helper: returns a full viewing key, an Orchard note carrying the given
2584    /// note plaintext `version`, and a dummy Merkle path, for exercising the
2585    /// Ironwood builder's note-version handling.
2586    #[cfg(feature = "circuits")]
2587    fn ironwood_note_with_version(
2588        version: orchard::note::NoteVersion,
2589    ) -> (
2590        orchard::keys::FullViewingKey,
2591        orchard::Note,
2592        orchard::tree::MerklePath,
2593    ) {
2594        let sk = orchard::keys::SpendingKey::from_bytes([7; 32]).unwrap();
2595        let fvk = orchard::keys::FullViewingKey::from(&sk);
2596        let recipient = fvk.address_at(0u32, orchard::keys::Scope::External);
2597        let value = orchard::value::NoteValue::from_raw(99);
2598        let rho = orchard::note::Rho::from_bytes(&[1; 32]).unwrap();
2599        let rseed = (0u8..=255)
2600            .find_map(|b| orchard::note::RandomSeed::from_bytes([b; 32], &rho).into_option())
2601            .expect("at least one test rseed is valid");
2602        let note = orchard::Note::from_parts(recipient, value, rho, rseed, version).unwrap();
2603        let zero = orchard::tree::MerkleHashOrchard::from_bytes(&[0; 32]).unwrap();
2604        let merkle_path = orchard::tree::MerklePath::from_parts(0, [zero; 32]);
2605
2606        (fvk, note, merkle_path)
2607    }
2608
2609    #[test]
2610    #[cfg(feature = "circuits")]
2611    fn note_commitment_and_nullifier_depend_on_note_version() {
2612        let (fvk, v2_note, _) = ironwood_note_with_version(orchard::note::NoteVersion::V2);
2613        let (_, v3_note, _) = ironwood_note_with_version(orchard::note::NoteVersion::V3);
2614
2615        // The notes share every field except the note plaintext version (lead byte
2616        // 0x02 vs 0x03), which must domain-separate both the commitment and the
2617        // nullifier.
2618        assert_ne!(
2619            orchard::note::ExtractedNoteCommitment::from(v2_note.commitment()).to_bytes(),
2620            orchard::note::ExtractedNoteCommitment::from(v3_note.commitment()).to_bytes(),
2621        );
2622        assert_ne!(
2623            v2_note.nullifier(&fvk).to_bytes(),
2624            v3_note.nullifier(&fvk).to_bytes(),
2625        );
2626    }
2627
2628    #[test]
2629    #[cfg(feature = "circuits")]
2630    fn add_ironwood_spend_rejects_v2_note_version() {
2631        let mut builder = Builder::new(
2632            nu6_3_test_network(),
2633            10u32.into(),
2634            BuildConfig::Standard {
2635                sapling_anchor: None,
2636                orchard_anchor: None,
2637                ironwood_anchor: Some(orchard::Anchor::empty_tree()),
2638                orchard_padding: BundlePadding::DEFAULT,
2639                ironwood_padding: BundlePadding::DEFAULT,
2640            },
2641        );
2642        let (fvk, note, merkle_path) = ironwood_note_with_version(orchard::note::NoteVersion::V2);
2643
2644        assert_matches!(
2645            builder.add_ironwood_spend::<Infallible>(fvk, note, merkle_path),
2646            Err(Error::IronwoodSpendUnsupportedNoteVersion(
2647                orchard::note::NoteVersion::V2
2648            ))
2649        );
2650    }
2651
2652    #[test]
2653    #[cfg(feature = "circuits")]
2654    fn orchard_action_count_uses_cross_address_disabled_count() {
2655        let spend_sk = orchard::keys::SpendingKey::from_bytes([7; 32]).unwrap();
2656        let spend_fvk = orchard::keys::FullViewingKey::from(&spend_sk);
2657        let spend_recipient = spend_fvk.address_at(0u32, orchard::keys::Scope::External);
2658        let rho = orchard::note::Rho::from_bytes(&[1; 32]).unwrap();
2659        let rseed = (0u8..=255)
2660            .find_map(|b| orchard::note::RandomSeed::from_bytes([b; 32], &rho).into_option())
2661            .expect("at least one test rseed is valid");
2662        let note = orchard::Note::from_parts(
2663            spend_recipient,
2664            orchard::value::NoteValue::from_raw(10_000),
2665            rho,
2666            rseed,
2667            orchard::note::NoteVersion::V2,
2668        )
2669        .unwrap();
2670        let leaf = orchard::tree::MerkleHashOrchard::from_cmx(&note.commitment().into());
2671        let mut tree = CommitmentTree::<orchard::tree::MerkleHashOrchard, 32>::empty();
2672        tree.append(leaf).unwrap();
2673        let witness = IncrementalWitness::from_tree(tree).unwrap();
2674        let anchor = witness.root().into();
2675        let merkle_path = witness.path().unwrap().into();
2676
2677        let mut builder = orchard::builder::Builder::new(
2678            orchard::builder::BundleType::DEFAULT,
2679            orchard::bundle::BundleVersion::orchard_v3(),
2680            orchard::bundle::BundleVersion::orchard_v3().default_flags(),
2681            anchor,
2682        )
2683        .unwrap();
2684
2685        builder.add_spend(spend_fvk, note, merkle_path).unwrap();
2686
2687        for seed in [[8u8; 32], [9u8; 32]] {
2688            let change_fvk = orchard::keys::FullViewingKey::from(
2689                &orchard::keys::SpendingKey::from_bytes(seed).unwrap(),
2690            );
2691            let recipient = change_fvk.address_at(0u32, orchard::keys::Scope::Internal);
2692            builder
2693                .add_change_output(
2694                    change_fvk,
2695                    None,
2696                    recipient,
2697                    orchard::value::NoteValue::from_raw(1_000),
2698                    [0u8; 512],
2699                )
2700                .unwrap();
2701        }
2702
2703        assert_eq!(builder.spends().len(), 1);
2704        assert_eq!(builder.changes().len(), 2);
2705        assert_eq!(
2706            super::orchard_action_count(
2707                &builder,
2708                false,
2709                orchard::bundle::BundleVersion::orchard_v3(),
2710            )
2711            .unwrap(),
2712            3
2713        );
2714    }
2715
2716    /// `BuildConfig::Standard`'s `orchard_padding` controls padding: the
2717    /// padded default counts a single-output bundle as 2 actions, while
2718    /// `UNPADDED` counts exactly the requested single action.
2719    #[test]
2720    #[cfg(feature = "circuits")]
2721    fn orchard_padding_controls_padding() {
2722        let recipient = orchard::keys::FullViewingKey::from(
2723            &orchard::keys::SpendingKey::from_bytes([0; 32]).unwrap(),
2724        )
2725        .address_at(0u32, orchard::keys::Scope::External);
2726
2727        let config_with = |padding| BuildConfig::Standard {
2728            sapling_anchor: None,
2729            orchard_anchor: Some(orchard::Anchor::empty_tree()),
2730            ironwood_anchor: Some(orchard::Anchor::empty_tree()),
2731            orchard_padding: padding,
2732            ironwood_padding: BundlePadding::DEFAULT,
2733        };
2734
2735        // `orchard_v2` here: the NU6.3 `orchard_v3` version disables cross-address
2736        // transfers, so a bare output cannot be added.
2737        let count_for = |padding| {
2738            let config = config_with(padding);
2739            let mut builder = config
2740                .orchard_builder(orchard::bundle::BundleVersion::orchard_v2())
2741                .unwrap();
2742            builder
2743                .add_output(
2744                    None,
2745                    recipient,
2746                    orchard::value::NoteValue::from_raw(10_000),
2747                    [0u8; 512],
2748                )
2749                .unwrap();
2750            super::orchard_action_count(
2751                &builder,
2752                false,
2753                orchard::bundle::BundleVersion::orchard_v2(),
2754            )
2755            .unwrap()
2756        };
2757
2758        assert_eq!(count_for(BundlePadding::DEFAULT), 2);
2759        assert_eq!(count_for(BundlePadding::UNPADDED), 1);
2760    }
2761
2762    /// Each Orchard protocol value pool's builder takes its padding from its
2763    /// own `BuildConfig::Standard` field.
2764    #[test]
2765    #[cfg(feature = "circuits")]
2766    fn orchard_protocol_padding_is_per_pool() {
2767        let bundle_types = |orchard_padding, ironwood_padding| {
2768            let builder = Builder::new(
2769                nu6_3_test_network(),
2770                zcash_protocol::consensus::BlockHeight::from_u32(10),
2771                BuildConfig::Standard {
2772                    sapling_anchor: None,
2773                    orchard_anchor: Some(orchard::Anchor::empty_tree()),
2774                    ironwood_anchor: Some(orchard::Anchor::empty_tree()),
2775                    orchard_padding,
2776                    ironwood_padding,
2777                },
2778            );
2779
2780            (
2781                builder.orchard_builder.as_ref().unwrap().bundle_type(),
2782                builder.ironwood_builder.as_ref().unwrap().bundle_type(),
2783            )
2784        };
2785
2786        for (orchard_padding, ironwood_padding) in [
2787            (BundlePadding::DEFAULT, BundlePadding::DEFAULT),
2788            (BundlePadding::UNPADDED, BundlePadding::DEFAULT),
2789            (BundlePadding::DEFAULT, BundlePadding::UNPADDED),
2790        ] {
2791            assert_eq!(
2792                bundle_types(orchard_padding, ironwood_padding),
2793                (
2794                    orchard_padding.bundle_type(),
2795                    ironwood_padding.bundle_type()
2796                ),
2797            );
2798        }
2799    }
2800
2801    /// A padded Orchard bundle and an unpadded Ironwood bundle can be combined in
2802    /// one transaction: one real Orchard spend pads to 2 actions while the single
2803    /// Ironwood output stays at 1.
2804    #[test]
2805    #[cfg(feature = "circuits")]
2806    fn per_pool_bundle_types_build_two_plus_one_pczt() {
2807        let spend_fvk = orchard::keys::FullViewingKey::from(
2808            &orchard::keys::SpendingKey::from_bytes([7; 32]).unwrap(),
2809        );
2810        let recipient = spend_fvk.address_at(0u32, orchard::keys::Scope::External);
2811        let rho = orchard::note::Rho::from_bytes(&[1; 32]).unwrap();
2812        let rseed = (0u8..=255)
2813            .find_map(|b| orchard::note::RandomSeed::from_bytes([b; 32], &rho).into_option())
2814            .expect("at least one test rseed is valid");
2815        let note = orchard::Note::from_parts(
2816            recipient,
2817            orchard::value::NoteValue::from_raw(100_000),
2818            rho,
2819            rseed,
2820            orchard::note::NoteVersion::V2,
2821        )
2822        .unwrap();
2823        let zero = orchard::tree::MerkleHashOrchard::from_bytes(&[0; 32]).unwrap();
2824        let merkle_path = orchard::tree::MerklePath::from_parts(0, [zero; 32]);
2825        let orchard_anchor = merkle_path.root(note.commitment().into());
2826
2827        let mut builder = Builder::new(
2828            nu6_3_test_network(),
2829            zcash_protocol::consensus::BlockHeight::from_u32(10),
2830            BuildConfig::Standard {
2831                sapling_anchor: None,
2832                orchard_anchor: Some(orchard_anchor),
2833                ironwood_anchor: Some(orchard::Anchor::empty_tree()),
2834                orchard_padding: BundlePadding::DEFAULT,
2835                ironwood_padding: BundlePadding::UNPADDED,
2836            },
2837        );
2838        builder
2839            .add_orchard_spend::<crate::transaction::fees::zip317::FeeRule>(
2840                spend_fvk,
2841                note,
2842                merkle_path,
2843            )
2844            .unwrap();
2845        builder
2846            .add_ironwood_output::<crate::transaction::fees::zip317::FeeRule>(
2847                None,
2848                recipient,
2849                Zatoshis::const_from_u64(85_000),
2850                MemoBytes::empty(),
2851            )
2852            .unwrap();
2853
2854        let result = builder
2855            .build_for_pczt(
2856                UnwrapErr(SysRng),
2857                &crate::transaction::fees::zip317::FeeRule::standard(),
2858            )
2859            .unwrap();
2860        assert_eq!(
2861            result.pczt_parts.orchard.as_ref().unwrap().actions().len(),
2862            2
2863        );
2864        assert_eq!(
2865            result.pczt_parts.ironwood.as_ref().unwrap().actions().len(),
2866            1
2867        );
2868    }
2869
2870    #[test]
2871    #[cfg(feature = "circuits")]
2872    fn add_orchard_change_output_records_change() {
2873        let target_height = TEST_NETWORK.activation_height(NetworkUpgrade::Nu5).unwrap();
2874        let mut builder = Builder::new(
2875            TEST_NETWORK,
2876            target_height,
2877            BuildConfig::Standard {
2878                sapling_anchor: None,
2879                orchard_anchor: Some(orchard::Anchor::empty_tree()),
2880                ironwood_anchor: None,
2881                orchard_padding: BundlePadding::DEFAULT,
2882                ironwood_padding: BundlePadding::DEFAULT,
2883            },
2884        );
2885        let fvk = orchard::keys::FullViewingKey::from(
2886            &orchard::keys::SpendingKey::from_bytes([0; 32]).unwrap(),
2887        );
2888        let recipient = fvk.address_at(0u32, orchard::keys::Scope::Internal);
2889
2890        builder
2891            .add_orchard_change_output::<Infallible>(
2892                fvk,
2893                None,
2894                recipient,
2895                Zatoshis::const_from_u64(5_000),
2896                MemoBytes::empty(),
2897            )
2898            .unwrap();
2899
2900        assert_eq!(
2901            builder.orchard_builder.as_ref().map(|b| b.changes().len()),
2902            Some(1)
2903        );
2904    }
2905
2906    // This test only works with the transparent_inputs feature because we have to
2907    // be able to create a tx with a valid balance, without using Sapling inputs.
2908    #[test]
2909    #[cfg(all(feature = "transparent-inputs", feature = "circuits"))]
2910    fn binding_sig_absent_if_no_shielded_spend_or_output() {
2911        let sapling_activation_height = TEST_NETWORK
2912            .activation_height(NetworkUpgrade::Sapling)
2913            .unwrap();
2914
2915        // Create a builder with 0 fee, so we can construct t outputs
2916        let consensus_branch_id = BranchId::for_height(&TEST_NETWORK, sapling_activation_height);
2917        let mut builder = builder::Builder {
2918            params: TEST_NETWORK,
2919            tx_version: TxVersion::suggested_for_branch(consensus_branch_id),
2920            consensus_branch_id,
2921            build_config: BuildConfig::Standard {
2922                sapling_anchor: Some(sapling::Anchor::empty_tree()),
2923                orchard_anchor: Some(orchard::Anchor::empty_tree()),
2924                ironwood_anchor: None,
2925                orchard_padding: BundlePadding::DEFAULT,
2926                ironwood_padding: BundlePadding::DEFAULT,
2927            },
2928            target_height: sapling_activation_height,
2929            expiry_height: sapling_activation_height + default_tx_expiry_delta(consensus_branch_id),
2930            #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
2931            zip233_amount: Zatoshis::ZERO,
2932            transparent_builder: TransparentBuilder::empty(),
2933            sapling_builder: None,
2934            orchard_builder: None,
2935            orchard_bundle_version: None,
2936            ironwood_builder: None,
2937            _progress_notifier: (),
2938        };
2939
2940        let mut transparent_signing_set = TransparentSigningSet::new();
2941        let sk = secp256k1::SecretKey::from_secret_bytes(TEST_TRANSPARENT_SECRET_KEY).unwrap();
2942        let pubkey = transparent_signing_set.add_key(sk);
2943        let prev_coin = TxOut::new(
2944            Zatoshis::const_from_u64(50000),
2945            TransparentAddress::from_pubkey(&pubkey).script().into(),
2946        );
2947        builder
2948            .add_transparent_p2pkh_input(pubkey, OutPoint::fake(), prev_coin)
2949            .unwrap();
2950
2951        // Create a tx with only t output. No binding_sig should be present
2952        builder
2953            .add_transparent_output(
2954                &TransparentAddress::PublicKeyHash([0; 20]),
2955                Zatoshis::const_from_u64(40000),
2956            )
2957            .unwrap();
2958
2959        let res = builder
2960            .mock_build(&transparent_signing_set, &[], &[], UnwrapErr(SysRng))
2961            .unwrap();
2962        // No binding signature, because only t input and outputs
2963        assert!(res.transaction().sapling_bundle.is_none());
2964    }
2965
2966    #[test]
2967    #[cfg(all(feature = "circuits", feature = "transparent-inputs"))]
2968    fn build_uses_overridden_expiry_height() {
2969        let tx_height = TEST_NETWORK
2970            .activation_height(NetworkUpgrade::Sapling)
2971            .unwrap();
2972        let build_config = BuildConfig::Standard {
2973            sapling_anchor: None,
2974            orchard_anchor: None,
2975            ironwood_anchor: None,
2976            orchard_padding: BundlePadding::DEFAULT,
2977            ironwood_padding: BundlePadding::DEFAULT,
2978        };
2979        let mut builder =
2980            Builder::new(TEST_NETWORK, tx_height, build_config).with_expiry_height(0u32.into());
2981
2982        let mut transparent_signing_set = TransparentSigningSet::new();
2983        let sk = secp256k1::SecretKey::from_secret_bytes(TEST_TRANSPARENT_SECRET_KEY).unwrap();
2984        let pubkey = transparent_signing_set.add_key(sk);
2985        let prev_coin = TxOut::new(
2986            Zatoshis::const_from_u64(50_000),
2987            TransparentAddress::from_pubkey(&pubkey).script().into(),
2988        );
2989        builder
2990            .add_transparent_p2pkh_input(pubkey, OutPoint::fake(), prev_coin)
2991            .unwrap();
2992        builder
2993            .add_transparent_output(
2994                &TransparentAddress::PublicKeyHash([0; 20]),
2995                Zatoshis::const_from_u64(40_000),
2996            )
2997            .unwrap();
2998
2999        let res = builder
3000            .mock_build(&transparent_signing_set, &[], &[], UnwrapErr(SysRng))
3001            .unwrap();
3002        assert_eq!(res.transaction().expiry_height(), 0u32.into());
3003    }
3004
3005    #[test]
3006    #[cfg(feature = "circuits")]
3007    fn build_rejects_mismatched_coinbase_expiry_height() {
3008        let tx_height = TEST_NETWORK
3009            .activation_height(NetworkUpgrade::Sapling)
3010            .unwrap();
3011        let build_config = BuildConfig::Coinbase { miner_data: None };
3012        let mut builder =
3013            Builder::new(TEST_NETWORK, tx_height, build_config).with_expiry_height(0u32.into());
3014
3015        builder
3016            .add_transparent_output(
3017                &TransparentAddress::PublicKeyHash([0; 20]),
3018                Zatoshis::const_from_u64(50_000),
3019            )
3020            .unwrap();
3021
3022        assert_matches!(
3023            builder.mock_build(&TransparentSigningSet::new(), &[], &[], UnwrapErr(SysRng)),
3024            Err(Error::CoinbaseExpiryHeightMismatch {
3025                target_height,
3026                expiry_height,
3027            }) if target_height == tx_height && expiry_height == 0u32.into()
3028        );
3029    }
3030
3031    #[test]
3032    #[cfg(feature = "circuits")]
3033    fn binding_sig_present_if_shielded_spend() {
3034        let extsk =
3035            ExtendedSpendingKey::master(&[]).expect("the derivation path yields a valid key");
3036        let dfvk = extsk.to_diversifiable_full_viewing_key();
3037        let to = dfvk.default_address().1;
3038
3039        let mut rng = UnwrapErr(SysRng);
3040
3041        let note1 = to.create_note(
3042            sapling::value::NoteValue::from_raw(50000),
3043            Rseed::BeforeZip212(jubjub::Fr::random(&mut rng)),
3044        );
3045        let cmu1 = Node::from_cmu(&note1.cmu());
3046        let mut tree = CommitmentTree::<Node, 32>::empty();
3047        tree.append(cmu1).unwrap();
3048        let witness1 = IncrementalWitness::from_tree(tree).unwrap();
3049
3050        let tx_height = TEST_NETWORK
3051            .activation_height(NetworkUpgrade::Sapling)
3052            .unwrap();
3053
3054        let build_config = BuildConfig::Standard {
3055            sapling_anchor: Some(witness1.root().into()),
3056            orchard_anchor: None,
3057            ironwood_anchor: None,
3058            orchard_padding: BundlePadding::DEFAULT,
3059            ironwood_padding: BundlePadding::DEFAULT,
3060        };
3061        let mut builder = Builder::new(TEST_NETWORK, tx_height, build_config);
3062
3063        // Create a tx with a sapling spend. binding_sig should be present
3064        builder
3065            .add_sapling_spend::<Infallible>(dfvk.fvk().clone(), note1, witness1.path().unwrap())
3066            .unwrap();
3067
3068        builder
3069            .add_transparent_output(
3070                &TransparentAddress::PublicKeyHash([0; 20]),
3071                Zatoshis::const_from_u64(35000),
3072            )
3073            .unwrap();
3074
3075        // A binding signature (and bundle) is present because there is a Sapling spend.
3076        let res = builder
3077            .mock_build(
3078                &TransparentSigningSet::new(),
3079                &[extsk],
3080                &[],
3081                UnwrapErr(SysRng),
3082            )
3083            .unwrap();
3084        assert!(res.transaction().sapling_bundle().is_some());
3085    }
3086
3087    #[test]
3088    #[cfg(feature = "circuits")]
3089    fn fails_on_negative_change() {
3090        let mut rng = UnwrapErr(SysRng);
3091
3092        // Just use the master key as the ExtendedSpendingKey for this test
3093        let extsk =
3094            ExtendedSpendingKey::master(&[]).expect("the derivation path yields a valid key");
3095        let tx_height = TEST_NETWORK
3096            .activation_height(NetworkUpgrade::Sapling)
3097            .unwrap();
3098
3099        // Fails with no inputs or outputs
3100        // 0.0001 t-ZEC fee
3101        {
3102            let build_config = BuildConfig::Standard {
3103                sapling_anchor: None,
3104                orchard_anchor: None,
3105                ironwood_anchor: None,
3106                orchard_padding: BundlePadding::DEFAULT,
3107                ironwood_padding: BundlePadding::DEFAULT,
3108            };
3109            let builder = Builder::new(TEST_NETWORK, tx_height, build_config);
3110            assert_matches!(
3111                builder.mock_build(&TransparentSigningSet::new(), &[], &[], UnwrapErr(SysRng)),
3112                Err(Error::InsufficientFunds(expected)) if expected == MINIMUM_FEE.into()
3113            );
3114        }
3115
3116        let dfvk = extsk.to_diversifiable_full_viewing_key();
3117        let ovk = Some(dfvk.fvk().ovk);
3118        let to = dfvk.default_address().1;
3119
3120        let extsks = &[extsk];
3121
3122        // Fail if there is only a Sapling output
3123        // 0.0005 z-ZEC out, 0.0001 t-ZEC fee
3124        {
3125            let build_config = BuildConfig::Standard {
3126                sapling_anchor: Some(sapling::Anchor::empty_tree()),
3127                orchard_anchor: Some(orchard::Anchor::empty_tree()),
3128                ironwood_anchor: None,
3129                orchard_padding: BundlePadding::DEFAULT,
3130                ironwood_padding: BundlePadding::DEFAULT,
3131            };
3132            let mut builder = Builder::new(TEST_NETWORK, tx_height, build_config);
3133            builder
3134                .add_sapling_output::<Infallible>(
3135                    ovk,
3136                    to,
3137                    Zatoshis::const_from_u64(50000),
3138                    MemoBytes::empty(),
3139                )
3140                .unwrap();
3141            assert_matches!(
3142                builder.mock_build(&TransparentSigningSet::new(), extsks, &[], UnwrapErr(SysRng)),
3143                Err(Error::InsufficientFunds(expected)) if
3144                    expected == (Zatoshis::const_from_u64(50000) + MINIMUM_FEE).unwrap().into()
3145            );
3146        }
3147
3148        // Fail if there is only a transparent output
3149        // 0.0005 t-ZEC out, 0.0001 t-ZEC fee
3150        {
3151            let build_config = BuildConfig::Standard {
3152                sapling_anchor: Some(sapling::Anchor::empty_tree()),
3153                orchard_anchor: Some(orchard::Anchor::empty_tree()),
3154                ironwood_anchor: None,
3155                orchard_padding: BundlePadding::DEFAULT,
3156                ironwood_padding: BundlePadding::DEFAULT,
3157            };
3158            let mut builder = Builder::new(TEST_NETWORK, tx_height, build_config);
3159            builder
3160                .add_transparent_output(
3161                    &TransparentAddress::PublicKeyHash([0; 20]),
3162                    Zatoshis::const_from_u64(50000),
3163                )
3164                .unwrap();
3165            assert_matches!(
3166                builder.mock_build(&TransparentSigningSet::new(), extsks, &[], UnwrapErr(SysRng)),
3167                Err(Error::InsufficientFunds(expected)) if expected ==
3168                    (Zatoshis::const_from_u64(50000) + MINIMUM_FEE).unwrap().into()
3169            );
3170        }
3171
3172        // Fail if there is only a burn
3173        // 0.0005 burned, 0.0001 t-ZEC fee
3174        #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
3175        {
3176            let build_config = BuildConfig::Standard {
3177                sapling_anchor: Some(sapling::Anchor::empty_tree()),
3178                orchard_anchor: Some(orchard::Anchor::empty_tree()),
3179                ironwood_anchor: None,
3180                orchard_padding: BundlePadding::DEFAULT,
3181                ironwood_padding: BundlePadding::DEFAULT,
3182            };
3183            let mut builder =
3184                Builder::new(nu7_test_network(), BlockHeight::from_u32(11), build_config);
3185            builder.set_zip233_amount(Zatoshis::const_from_u64(50000));
3186
3187            assert_matches!(
3188                builder.mock_build(
3189                    &TransparentSigningSet::new(),
3190                    extsks,
3191                    &[],
3192                    UnwrapErr(SysRng)
3193                ),
3194                Err(Error::TargetIncompatible(BranchId::Nu7, _, None))
3195            );
3196        }
3197
3198        let note1 = to.create_note(
3199            sapling::value::NoteValue::from_raw(59999),
3200            Rseed::BeforeZip212(jubjub::Fr::random(&mut rng)),
3201        );
3202        let cmu1 = Node::from_cmu(&note1.cmu());
3203        let mut tree = CommitmentTree::<Node, 32>::empty();
3204        tree.append(cmu1).unwrap();
3205        let mut witness1 = IncrementalWitness::from_tree(tree.clone()).unwrap();
3206
3207        // Fail if there is insufficient input
3208        // 0.0003 z-ZEC out, 0.00015 t-ZEC out, 0.00015 t-ZEC fee, 0.00059999 z-ZEC in
3209        {
3210            let build_config = BuildConfig::Standard {
3211                sapling_anchor: Some(witness1.root().into()),
3212                orchard_anchor: Some(orchard::Anchor::empty_tree()),
3213                ironwood_anchor: None,
3214                orchard_padding: BundlePadding::DEFAULT,
3215                ironwood_padding: BundlePadding::DEFAULT,
3216            };
3217            let mut builder = Builder::new(TEST_NETWORK, tx_height, build_config);
3218            builder
3219                .add_sapling_spend::<Infallible>(
3220                    dfvk.fvk().clone(),
3221                    note1.clone(),
3222                    witness1.path().unwrap(),
3223                )
3224                .unwrap();
3225            builder
3226                .add_sapling_output::<Infallible>(
3227                    ovk,
3228                    to,
3229                    Zatoshis::const_from_u64(30000),
3230                    MemoBytes::empty(),
3231                )
3232                .unwrap();
3233            builder
3234                .add_transparent_output(
3235                    &TransparentAddress::PublicKeyHash([0; 20]),
3236                    Zatoshis::const_from_u64(15000),
3237                )
3238                .unwrap();
3239            assert_matches!(
3240                builder.mock_build(&TransparentSigningSet::new(), extsks, &[], UnwrapErr(SysRng)),
3241                Err(Error::InsufficientFunds(expected)) if expected == ZatBalance::const_from_i64(1)
3242            );
3243        }
3244
3245        // Fail if there is insufficient input
3246        // 0.0003 z-ZEC out, 0.00005 t-ZEC out, 0.0001 burned, 0.00015 t-ZEC fee, 0.00059999 z-ZEC in
3247        #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
3248        {
3249            let build_config = BuildConfig::Standard {
3250                sapling_anchor: Some(witness1.root().into()),
3251                orchard_anchor: Some(orchard::Anchor::empty_tree()),
3252                ironwood_anchor: None,
3253                orchard_padding: BundlePadding::DEFAULT,
3254                ironwood_padding: BundlePadding::DEFAULT,
3255            };
3256            let mut builder =
3257                Builder::new(nu7_test_network(), BlockHeight::from_u32(11), build_config);
3258            builder
3259                .add_sapling_spend::<Infallible>(
3260                    dfvk.fvk().clone(),
3261                    note1.clone(),
3262                    witness1.path().unwrap(),
3263                )
3264                .unwrap();
3265            builder
3266                .add_sapling_output::<Infallible>(
3267                    ovk,
3268                    to,
3269                    Zatoshis::const_from_u64(30000),
3270                    MemoBytes::empty(),
3271                )
3272                .unwrap();
3273            builder
3274                .add_transparent_output(
3275                    &TransparentAddress::PublicKeyHash([0; 20]),
3276                    Zatoshis::const_from_u64(5000),
3277                )
3278                .unwrap();
3279            builder.set_zip233_amount(Zatoshis::const_from_u64(10000));
3280            assert_matches!(
3281                builder.mock_build(
3282                    &TransparentSigningSet::new(),
3283                    extsks,
3284                    &[],
3285                    UnwrapErr(SysRng)
3286                ),
3287                Err(Error::TargetIncompatible(BranchId::Nu7, _, None))
3288            );
3289        }
3290
3291        let note2 = to.create_note(
3292            sapling::value::NoteValue::from_raw(1),
3293            Rseed::BeforeZip212(jubjub::Fr::random(&mut rng)),
3294        );
3295        let cmu2 = Node::from_cmu(&note2.cmu());
3296        tree.append(cmu2).unwrap();
3297        witness1.append(cmu2).unwrap();
3298        let witness2 = IncrementalWitness::from_tree(tree).unwrap();
3299
3300        // Succeeds if there is sufficient input
3301        // 0.0003 z-ZEC out, 0.00015 t-ZEC out, 0.00015 t-ZEC fee, 0.0006 z-ZEC in
3302        {
3303            let build_config = BuildConfig::Standard {
3304                sapling_anchor: Some(witness1.root().into()),
3305                orchard_anchor: Some(orchard::Anchor::empty_tree()),
3306                ironwood_anchor: None,
3307                orchard_padding: BundlePadding::DEFAULT,
3308                ironwood_padding: BundlePadding::DEFAULT,
3309            };
3310            let mut builder = Builder::new(TEST_NETWORK, tx_height, build_config);
3311            builder
3312                .add_sapling_spend::<Infallible>(
3313                    dfvk.fvk().clone(),
3314                    note1.clone(),
3315                    witness1.path().unwrap(),
3316                )
3317                .unwrap();
3318            builder
3319                .add_sapling_spend::<Infallible>(
3320                    dfvk.fvk().clone(),
3321                    note2.clone(),
3322                    witness2.path().unwrap(),
3323                )
3324                .unwrap();
3325            builder
3326                .add_sapling_output::<Infallible>(
3327                    ovk,
3328                    to,
3329                    Zatoshis::const_from_u64(30000),
3330                    MemoBytes::empty(),
3331                )
3332                .unwrap();
3333            builder
3334                .add_transparent_output(
3335                    &TransparentAddress::PublicKeyHash([0; 20]),
3336                    Zatoshis::const_from_u64(15000),
3337                )
3338                .unwrap();
3339            let res = builder
3340                .mock_build(
3341                    &TransparentSigningSet::new(),
3342                    extsks,
3343                    &[],
3344                    UnwrapErr(SysRng),
3345                )
3346                .unwrap();
3347            assert_eq!(
3348                res.transaction()
3349                    .fee_paid(|_| Err(BalanceError::Overflow))
3350                    .unwrap(),
3351                Some(Zatoshis::const_from_u64(15_000))
3352            );
3353        }
3354
3355        // NU7 rejects voluntary removal even when the inputs cover the requested amount.
3356        #[cfg(all(feature = "zip-233", zcash_unstable = "zip233"))]
3357        {
3358            let build_config = BuildConfig::Standard {
3359                sapling_anchor: Some(witness1.root().into()),
3360                orchard_anchor: Some(orchard::Anchor::empty_tree()),
3361                ironwood_anchor: None,
3362                orchard_padding: BundlePadding::DEFAULT,
3363                ironwood_padding: BundlePadding::DEFAULT,
3364            };
3365            let mut builder =
3366                Builder::new(nu7_test_network(), BlockHeight::from_u32(11), build_config);
3367            builder
3368                .add_sapling_spend::<Infallible>(
3369                    dfvk.fvk().clone(),
3370                    note1,
3371                    witness1.path().unwrap(),
3372                )
3373                .unwrap();
3374            builder
3375                .add_sapling_spend::<Infallible>(
3376                    dfvk.fvk().clone(),
3377                    note2,
3378                    witness2.path().unwrap(),
3379                )
3380                .unwrap();
3381            builder
3382                .add_sapling_output::<Infallible>(
3383                    ovk,
3384                    to,
3385                    Zatoshis::const_from_u64(30000),
3386                    MemoBytes::empty(),
3387                )
3388                .unwrap();
3389            builder
3390                .add_transparent_output(
3391                    &TransparentAddress::PublicKeyHash([0; 20]),
3392                    Zatoshis::const_from_u64(5000),
3393                )
3394                .unwrap();
3395            builder.set_zip233_amount(Zatoshis::const_from_u64(10000));
3396            assert_matches!(
3397                builder.mock_build(
3398                    &TransparentSigningSet::new(),
3399                    extsks,
3400                    &[],
3401                    UnwrapErr(SysRng)
3402                ),
3403                Err(Error::TargetIncompatible(BranchId::Nu7, _, None))
3404            );
3405        }
3406    }
3407
3408    #[cfg(all(feature = "circuits", feature = "std"))]
3409    #[test]
3410    fn cached_orchard_proving_key_reuses_one_instance_per_version() {
3411        // Repeated calls for the same circuit version return the very same cached
3412        // key, so building many transactions does not reconstruct it each time.
3413        let first = cached_orchard_proving_key(OrchardCircuitVersion::FixedPostNu6_2);
3414        let second = cached_orchard_proving_key(OrchardCircuitVersion::FixedPostNu6_2);
3415        assert!(ptr::eq(first, second));
3416
3417        // Distinct circuit versions are cached independently.
3418        let other = cached_orchard_proving_key(OrchardCircuitVersion::PostNu6_3);
3419        assert!(!ptr::eq(first, other));
3420    }
3421}