Skip to main content

zcash_keys/
keys.rs

1//! Helper functions for managing light client key material.
2use alloc::{collections::BTreeSet, string::String, vec::Vec};
3use core::fmt::{self, Display};
4use nonempty::NonEmpty;
5#[cfg(feature = "transparent-inputs")]
6use {
7    crate::keys::transparent::{
8        IncomingViewingKey, NonHardenedChildIndex, TransparentKeyScope,
9        zip48::{P2shFullViewingKey, P2shIncomingViewingKey},
10    },
11    core::convert::TryInto,
12};
13
14use zcash_address::unified::{self, Container, Encoding, MetadataItem, Revision, Typecode, Uitem};
15use zcash_protocol::{PoolType, consensus};
16use zip32::{AccountId, DiversifierIndex};
17
18use crate::{
19    address::UnifiedAddress,
20    encoding::{UnifiedDecodingError, UnifiedEncodingError},
21};
22
23// The requirement combinators and the `ReceiverRequirements` constants below name these
24// variants bare.
25use ReceiverRequirement::*;
26
27#[cfg(any(feature = "sapling", feature = "orchard"))]
28use zcash_protocol::consensus::NetworkConstants;
29
30#[cfg(feature = "transparent-inputs")]
31#[cfg(all(
32    feature = "transparent-inputs",
33    any(test, feature = "test-dependencies")
34))]
35use ::transparent::address::TransparentAddress;
36
37#[cfg(feature = "unstable")]
38use {
39    byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt},
40    core::convert::TryFrom,
41    corez::io::{Read, Write},
42    secrecy::SecretVec,
43    zcash_encoding::CompactSize,
44    zcash_protocol::consensus::BranchId,
45};
46
47#[cfg(all(
48    feature = "unstable",
49    any(feature = "sapling", feature = "transparent-inputs")
50))]
51use secrecy::zeroize::Zeroizing;
52
53#[cfg(feature = "orchard")]
54use orchard::{self, keys::Scope};
55
56#[cfg(all(feature = "sapling", feature = "unstable"))]
57use ::sapling::zip32::ExtendedFullViewingKey;
58
59#[cfg(test)]
60pub(crate) mod test_vectors {
61    pub(crate) mod unified_viewing_keys_r2;
62}
63
64#[cfg(feature = "sapling")]
65pub mod sapling {
66    pub use sapling::zip32::{
67        DiversifiableFullViewingKey, ExtendedFullViewingKey, ExtendedSpendingKey,
68    };
69    use zip32::{AccountId, ChildIndex};
70
71    /// Derives the ZIP 32 [`ExtendedSpendingKey`] for a given coin type and account from the
72    /// given seed.
73    ///
74    /// Returns `None` if the derivation path produces an invalid Sapling spending key.
75    ///
76    /// # Panics
77    ///
78    /// Panics if `seed` is shorter than 32 bytes.
79    ///
80    /// # Examples
81    ///
82    /// ```
83    /// use zcash_protocol::constants::testnet::COIN_TYPE;
84    /// use zcash_keys::keys::sapling;
85    /// use zip32::AccountId;
86    ///
87    /// let extsk = sapling::spending_key(&[0; 32][..], COIN_TYPE, AccountId::ZERO).expect("the derivation path yields a valid key");
88    /// ```
89    /// [`ExtendedSpendingKey`]: sapling::zip32::ExtendedSpendingKey
90    pub fn spending_key(
91        seed: &[u8],
92        coin_type: u32,
93        account: AccountId,
94    ) -> Option<ExtendedSpendingKey> {
95        if seed.len() < 32 {
96            panic!("ZIP 32 seeds MUST be at least 32 bytes");
97        }
98
99        ExtendedSpendingKey::from_path(
100            &ExtendedSpendingKey::master(seed)?,
101            &[
102                ChildIndex::hardened(32),
103                ChildIndex::hardened(coin_type),
104                account.into(),
105            ],
106        )
107    }
108}
109
110pub mod transparent;
111
112#[cfg(feature = "zcashd-compat")]
113pub mod zcashd;
114
115#[cfg(feature = "transparent-inputs")]
116fn to_transparent_child_index(j: DiversifierIndex) -> Option<NonHardenedChildIndex> {
117    let (low_4_bytes, rest) = j.as_bytes().split_at(4);
118    let transparent_j = u32::from_le_bytes(low_4_bytes.try_into().unwrap());
119    if rest.iter().any(|b| b != &0) {
120        None
121    } else {
122        NonHardenedChildIndex::from_index(transparent_j)
123    }
124}
125
126#[derive(Debug)]
127pub enum DerivationError {
128    /// Sapling key derivation produced an invalid spending key.
129    #[cfg(feature = "sapling")]
130    Sapling,
131    #[cfg(feature = "orchard")]
132    Orchard(orchard::zip32::Error),
133    #[cfg(feature = "transparent-inputs")]
134    Transparent(bip32::Error),
135    /// A [`UnifiedSpendingKey`] was constructed without a key for any protocol.
136    Empty,
137}
138
139impl Display for DerivationError {
140    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        match self {
142            #[cfg(feature = "sapling")]
143            DerivationError::Sapling => {
144                write!(_f, "Sapling error: derived an invalid spending key")
145            }
146            #[cfg(feature = "orchard")]
147            DerivationError::Orchard(e) => write!(_f, "Orchard error: {e}"),
148            #[cfg(feature = "transparent-inputs")]
149            DerivationError::Transparent(e) => write!(_f, "Transparent error: {e}"),
150            DerivationError::Empty => write!(_f, "No key was provided for any protocol"),
151        }
152    }
153}
154
155#[cfg(feature = "std")]
156impl std::error::Error for DerivationError {}
157
158/// A version identifier for the encoding of unified spending keys.
159///
160/// Each era corresponds to a range of block heights. During an era, the unified spending key
161/// parsed from an encoded form tagged with that era's identifier is expected to provide
162/// sufficient spending authority to spend any non-Sprout shielded note created in a transaction
163/// within the era's block range.
164#[cfg(feature = "unstable")]
165#[derive(Debug, PartialEq, Eq)]
166pub enum Era {
167    /// The Orchard era begins at Orchard activation, and will end if a new pool that requires a
168    /// change to unified spending keys is introduced.
169    Orchard,
170}
171
172/// A type for errors that can occur when decoding keys from their serialized representations.
173#[derive(Debug, PartialEq, Eq)]
174pub enum DecodingError {
175    #[cfg(feature = "unstable")]
176    ReadError(&'static str),
177    #[cfg(feature = "unstable")]
178    EraInvalid,
179    #[cfg(feature = "unstable")]
180    EraMismatch(Era),
181    #[cfg(feature = "unstable")]
182    TypecodeInvalid,
183    #[cfg(feature = "unstable")]
184    LengthInvalid,
185    #[cfg(feature = "unstable")]
186    LengthMismatch(Typecode, u32),
187    #[cfg(feature = "unstable")]
188    InsufficientData(Typecode),
189    /// The encoding holds two items with the given typecode.
190    #[cfg(feature = "unstable")]
191    DuplicateTypecode(Typecode),
192    /// The encoding holds no key for a protocol that the enabled features support.
193    #[cfg(feature = "unstable")]
194    Empty,
195    /// The key data could not be decoded from its string representation to a valid key.
196    KeyDataInvalid(Typecode),
197}
198
199impl core::fmt::Display for DecodingError {
200    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
201        match self {
202            #[cfg(feature = "unstable")]
203            DecodingError::ReadError(s) => write!(f, "Read error: {s}"),
204            #[cfg(feature = "unstable")]
205            DecodingError::EraInvalid => write!(f, "Invalid era"),
206            #[cfg(feature = "unstable")]
207            DecodingError::EraMismatch(e) => write!(f, "Era mismatch: actual {e:?}"),
208            #[cfg(feature = "unstable")]
209            DecodingError::TypecodeInvalid => write!(f, "Invalid typecode"),
210            #[cfg(feature = "unstable")]
211            DecodingError::LengthInvalid => write!(f, "Invalid length"),
212            #[cfg(feature = "unstable")]
213            DecodingError::LengthMismatch(t, l) => {
214                write!(f, "Length mismatch: received {l} bytes for typecode {t:?}")
215            }
216            #[cfg(feature = "unstable")]
217            DecodingError::InsufficientData(t) => {
218                write!(f, "Insufficient data for typecode {t:?}")
219            }
220            #[cfg(feature = "unstable")]
221            DecodingError::DuplicateTypecode(t) => write!(f, "Duplicate typecode {t:?}"),
222            #[cfg(feature = "unstable")]
223            DecodingError::Empty => write!(f, "No key for any supported protocol"),
224            DecodingError::KeyDataInvalid(t) => write!(f, "Invalid key data for key type {t:?}"),
225        }
226    }
227}
228
229#[cfg(feature = "std")]
230impl std::error::Error for DecodingError {}
231
232#[cfg(feature = "unstable")]
233impl Era {
234    /// Returns the unique identifier for the era.
235    fn id(&self) -> u32 {
236        // We use the consensus branch id of the network upgrade that introduced a
237        // new USK format as the identifier for the era.
238        match self {
239            Era::Orchard => u32::from(BranchId::Nu5),
240        }
241    }
242
243    fn try_from_id(id: u32) -> Option<Self> {
244        BranchId::try_from(id).ok().and_then(|b| match b {
245            BranchId::Nu5 => Some(Era::Orchard),
246            _ => None,
247        })
248    }
249}
250
251/// A set of spending keys for a single account, holding at most one key per protocol.
252///
253/// A key derived with [`Self::from_seed`] holds a key for every protocol that the enabled
254/// features support. A key built with [`Self::from_parts`] may hold any non-empty subset.
255///
256/// With the `zeroize` feature, the Sapling and Orchard spending keys are erased from
257/// memory when this key is dropped. The transparent spending key is not erased.
258#[derive(Clone)]
259pub struct UnifiedSpendingKey {
260    #[cfg(feature = "transparent-inputs")]
261    transparent: Option<crate::keys::transparent::AccountPrivKey>,
262    #[cfg(feature = "sapling")]
263    sapling: Option<sapling::ExtendedSpendingKey>,
264    #[cfg(feature = "orchard")]
265    orchard: Option<orchard::keys::SpendingKey>,
266}
267
268impl core::fmt::Debug for UnifiedSpendingKey {
269    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
270        let mut d = f.debug_struct("UnifiedSpendingKey");
271        #[cfg(feature = "transparent-inputs")]
272        d.field("transparent", &self.transparent.as_ref().map(|_| "..."));
273        #[cfg(feature = "sapling")]
274        d.field("sapling", &self.sapling.as_ref().map(|_| "..."));
275        #[cfg(feature = "orchard")]
276        d.field("orchard", &self.orchard.as_ref().map(|_| "..."));
277        d.finish()
278    }
279}
280
281impl UnifiedSpendingKey {
282    /// Derives the spending keys for the given ZIP 32 account from a seed.
283    ///
284    /// The result holds a key for every protocol that the enabled features support.
285    ///
286    /// # Panics
287    ///
288    /// Panics if `seed` is shorter than 32 bytes.
289    ///
290    /// # Errors
291    ///
292    /// Returns the [`DerivationError`] for the first protocol whose key derivation fails.
293    pub fn from_seed<P: consensus::Parameters>(
294        _params: &P,
295        seed: &[u8],
296        _account: AccountId,
297    ) -> Result<UnifiedSpendingKey, DerivationError> {
298        if seed.len() < 32 {
299            panic!("ZIP 32 seeds MUST be at least 32 bytes");
300        }
301
302        UnifiedSpendingKey::from_parts(
303            #[cfg(feature = "transparent-inputs")]
304            Some(
305                crate::keys::transparent::AccountPrivKey::from_seed(_params, seed, _account)
306                    .map_err(DerivationError::Transparent)?,
307            ),
308            #[cfg(feature = "sapling")]
309            Some(
310                sapling::spending_key(seed, _params.coin_type(), _account)
311                    .ok_or(DerivationError::Sapling)?,
312            ),
313            #[cfg(feature = "orchard")]
314            Some(
315                orchard::keys::SpendingKey::from_zip32_seed(seed, _params.coin_type(), _account)
316                    .map_err(DerivationError::Orchard)?,
317            ),
318        )
319    }
320
321    /// Constructs a spending key from the keys it holds for each protocol.
322    ///
323    /// A seed does not necessarily back up a key built this way. Wallets that store it
324    /// must also store, or otherwise back up, each of its parts.
325    ///
326    /// # Errors
327    ///
328    /// - [`DerivationError::Empty`] if every part is `None`.
329    /// - [`DerivationError::Transparent`] if transparent address derivation fails for the
330    ///   transparent part.
331    pub fn from_parts(
332        #[cfg(feature = "transparent-inputs")] transparent: Option<
333            crate::keys::transparent::AccountPrivKey,
334        >,
335        #[cfg(feature = "sapling")] sapling: Option<sapling::ExtendedSpendingKey>,
336        #[cfg(feature = "orchard")] orchard: Option<orchard::keys::SpendingKey>,
337    ) -> Result<UnifiedSpendingKey, DerivationError> {
338        let usk = UnifiedSpendingKey {
339            #[cfg(feature = "transparent-inputs")]
340            transparent,
341            #[cfg(feature = "sapling")]
342            sapling,
343            #[cfg(feature = "orchard")]
344            orchard,
345        };
346
347        if usk.is_empty() {
348            return Err(DerivationError::Empty);
349        }
350
351        // Verify that FVK and IVK derivation succeed; we don't want to construct a USK
352        // that can't derive transparent addresses.
353        #[cfg(feature = "transparent-inputs")]
354        if let Some(transparent) = usk.transparent.as_ref() {
355            let _ = transparent.to_account_pubkey().derive_external_ivk()?;
356        }
357
358        Ok(usk)
359    }
360
361    /// Returns `true` if this key holds no key for any protocol.
362    fn is_empty(&self) -> bool {
363        #[cfg(feature = "transparent-inputs")]
364        let has_transparent = self.transparent.is_some();
365        #[cfg(not(feature = "transparent-inputs"))]
366        let has_transparent = false;
367
368        #[cfg(feature = "sapling")]
369        let has_sapling = self.sapling.is_some();
370        #[cfg(not(feature = "sapling"))]
371        let has_sapling = false;
372
373        #[cfg(feature = "orchard")]
374        let has_orchard = self.orchard.is_some();
375        #[cfg(not(feature = "orchard"))]
376        let has_orchard = false;
377
378        !(has_transparent || has_sapling || has_orchard)
379    }
380
381    /// Returns the full viewing key for this key.
382    ///
383    /// The result holds a viewing key for exactly the protocols that this key holds a
384    /// spending key for.
385    pub fn to_unified_full_viewing_key(&self) -> UnifiedFullViewingKey {
386        UnifiedFullViewingKey {
387            #[cfg(feature = "transparent-inputs")]
388            transparent: self
389                .transparent
390                .as_ref()
391                .map(|t| TransparentFvk::P2pkh(t.to_account_pubkey())),
392            #[cfg(feature = "sapling")]
393            sapling: self
394                .sapling
395                .as_ref()
396                .map(|s| s.to_diversifiable_full_viewing_key()),
397            #[cfg(feature = "orchard")]
398            orchard: self.orchard.as_ref().map(|o| o.into()),
399            unknown: vec![],
400            expiry_height: None,
401            expiry_time: None,
402            unknown_metadata: vec![],
403        }
404    }
405
406    /// Returns the transparent component of this key, if it has one.
407    ///
408    /// For a key derived with [`Self::from_seed`], this is the key at the BIP 44 path
409    /// `m/44'/<coin_type>'/<account>'`.
410    #[cfg(feature = "transparent-inputs")]
411    pub fn transparent(&self) -> Option<&crate::keys::transparent::AccountPrivKey> {
412        self.transparent.as_ref()
413    }
414
415    /// Returns the Sapling extended spending key component of this key, if it has one.
416    #[cfg(feature = "sapling")]
417    pub fn sapling(&self) -> Option<&sapling::ExtendedSpendingKey> {
418        self.sapling.as_ref()
419    }
420
421    /// Returns the Orchard spending key component of this key, if it has one.
422    #[cfg(feature = "orchard")]
423    pub fn orchard(&self) -> Option<&orchard::keys::SpendingKey> {
424        self.orchard.as_ref()
425    }
426
427    /// Returns a binary encoding of this key suitable for decoding with [`Self::from_bytes`].
428    ///
429    /// The encoded form of a unified spending key is only intended for use
430    /// within wallets when required for storage and/or crossing FFI boundaries;
431    /// unified spending keys should not be exposed to users, and consequently
432    /// no string-based encoding is defined. This encoding does not include any
433    /// internal validation metadata (such as checksums) as keys decoded from
434    /// this form will necessarily be validated when the attempt is made to
435    /// spend a note that they have authority for.
436    ///
437    /// The encoding holds an item for each protocol that this key holds a key for.
438    #[cfg(feature = "unstable")]
439    pub fn to_bytes(&self, era: Era) -> SecretVec<u8> {
440        #[cfg(feature = "sapling")]
441        let sapling_key_bytes = self.sapling().map(|k| Zeroizing::new(k.to_bytes()));
442        #[cfg(feature = "transparent-inputs")]
443        let transparent_key_bytes = self.transparent().map(|k| Zeroizing::new(k.to_bytes()));
444
445        let items: Vec<(Typecode, &[u8])> = [
446            #[cfg(feature = "orchard")]
447            self.orchard()
448                .map(|k| (Typecode::ORCHARD, &k.to_bytes()[..])),
449            #[cfg(feature = "sapling")]
450            sapling_key_bytes
451                .as_ref()
452                .map(|k| (Typecode::SAPLING, &k[..])),
453            #[cfg(feature = "transparent-inputs")]
454            transparent_key_bytes
455                .as_ref()
456                .map(|k| (Typecode::P2PKH, &k[..])),
457        ]
458        .into_iter()
459        .flatten()
460        .collect();
461
462        // Reserve the full length up front, so that growing the buffer does not leave
463        // copies of the key material in freed memory.
464        let encoded_len =
465            items
466                .iter()
467                .fold(core::mem::size_of::<u32>(), |len, (typecode, key_bytes)| {
468                    len + CompactSize::serialized_size(usize::try_from(*typecode).unwrap())
469                        + CompactSize::serialized_size(key_bytes.len())
470                        + key_bytes.len()
471                });
472        let mut result = Vec::with_capacity(encoded_len);
473        result.write_u32::<LittleEndian>(era.id()).unwrap();
474        for (typecode, key_bytes) in items {
475            CompactSize::write(&mut result, usize::try_from(typecode).unwrap()).unwrap();
476            CompactSize::write(&mut result, key_bytes.len()).unwrap();
477            result.write_all(key_bytes).unwrap();
478        }
479
480        SecretVec::new(result)
481    }
482
483    /// Decodes a [`UnifiedSpendingKey`] value from its serialized representation.
484    ///
485    /// See [`Self::to_bytes`] for additional detail about the encoded form.
486    ///
487    /// # Errors
488    ///
489    /// - [`DecodingError::Empty`] if the encoding holds no key for a protocol that the
490    ///   enabled features support.
491    /// - [`DecodingError::DuplicateTypecode`] if the encoding holds two items with the
492    ///   same typecode.
493    /// - Any other [`DecodingError`] if the encoding is malformed or holds an invalid key.
494    #[cfg(feature = "unstable")]
495    pub fn from_bytes(era: Era, encoded: &[u8]) -> Result<Self, DecodingError> {
496        let mut source = corez::io::Cursor::new(encoded);
497        let decoded_era = source
498            .read_u32::<LittleEndian>()
499            .map_err(|_| DecodingError::ReadError("era"))
500            .and_then(|id| Era::try_from_id(id).ok_or(DecodingError::EraInvalid))?;
501
502        if decoded_era != era {
503            return Err(DecodingError::EraMismatch(decoded_era));
504        }
505
506        #[cfg(feature = "orchard")]
507        let mut orchard = None;
508        #[cfg(feature = "sapling")]
509        let mut sapling = None;
510        #[cfg(feature = "transparent-inputs")]
511        let mut transparent = None;
512        let mut seen_typecodes: Vec<Typecode> = vec![];
513        while usize::try_from(source.position()).is_ok_and(|pos| pos < encoded.len()) {
514            let tc = CompactSize::read_t::<_, u32>(&mut source)
515                .map_err(|_| DecodingError::ReadError("typecode"))
516                .and_then(|v| Typecode::try_from(v).map_err(|_| DecodingError::TypecodeInvalid))?;
517
518            if seen_typecodes.contains(&tc) {
519                return Err(DecodingError::DuplicateTypecode(tc));
520            }
521            seen_typecodes.push(tc);
522
523            let len = CompactSize::read_t::<_, u32>(&mut source)
524                .map_err(|_| DecodingError::ReadError("key length"))?;
525
526            match tc {
527                Typecode::ORCHARD => {
528                    if len != 32 {
529                        return Err(DecodingError::LengthMismatch(Typecode::ORCHARD, len));
530                    }
531
532                    let mut key = [0u8; 32];
533                    source
534                        .read_exact(&mut key)
535                        .map_err(|_| DecodingError::InsufficientData(Typecode::ORCHARD))?;
536
537                    #[cfg(feature = "orchard")]
538                    {
539                        orchard = Some(
540                            Option::<orchard::keys::SpendingKey>::from(
541                                orchard::keys::SpendingKey::from_bytes(key),
542                            )
543                            .ok_or(DecodingError::KeyDataInvalid(Typecode::ORCHARD))?,
544                        );
545                    }
546                }
547                Typecode::SAPLING => {
548                    if len != 169 {
549                        return Err(DecodingError::LengthMismatch(Typecode::SAPLING, len));
550                    }
551
552                    let mut key = [0u8; 169];
553                    source
554                        .read_exact(&mut key)
555                        .map_err(|_| DecodingError::InsufficientData(Typecode::SAPLING))?;
556
557                    #[cfg(feature = "sapling")]
558                    {
559                        sapling = Some(
560                            sapling::ExtendedSpendingKey::from_bytes(&key)
561                                .map_err(|_| DecodingError::KeyDataInvalid(Typecode::SAPLING))?,
562                        );
563                    }
564                }
565                Typecode::P2PKH => {
566                    if len != 74 {
567                        return Err(DecodingError::LengthMismatch(Typecode::P2PKH, len));
568                    }
569
570                    let mut key = [0u8; 74];
571                    source
572                        .read_exact(&mut key)
573                        .map_err(|_| DecodingError::InsufficientData(Typecode::P2PKH))?;
574
575                    #[cfg(feature = "transparent-inputs")]
576                    {
577                        transparent = Some(
578                            crate::keys::transparent::AccountPrivKey::from_bytes(&key)
579                                .ok_or(DecodingError::KeyDataInvalid(Typecode::P2PKH))?,
580                        );
581                    }
582                }
583                _ => {
584                    return Err(DecodingError::TypecodeInvalid);
585                }
586            }
587        }
588
589        UnifiedSpendingKey::from_parts(
590            #[cfg(feature = "transparent-inputs")]
591            transparent,
592            #[cfg(feature = "sapling")]
593            sapling,
594            #[cfg(feature = "orchard")]
595            orchard,
596        )
597        .map_err(|e| match e {
598            DerivationError::Empty => DecodingError::Empty,
599            _ => DecodingError::KeyDataInvalid(Typecode::P2PKH),
600        })
601    }
602
603    /// Returns the unified address corresponding to the smallest valid diversifier index,
604    /// along with that diversifier index.
605    ///
606    /// See [`UnifiedFullViewingKey::default_address`] for additional details.
607    #[cfg(any(test, feature = "test-dependencies"))]
608    pub fn default_address(
609        &self,
610        request: UnifiedAddressRequest,
611    ) -> (UnifiedAddress, DiversifierIndex) {
612        self.to_unified_full_viewing_key()
613            .default_address(request)
614            .unwrap()
615    }
616
617    /// Returns the default external transparent address using the transparent account pubkey.
618    ///
619    /// See [`ExternalIvk::default_address`] for more information.
620    ///
621    /// [`ExternalIvk::default_address`]: crate::keys::transparent::ExternalIvk::default_address
622    #[cfg(all(
623        feature = "transparent-inputs",
624        any(test, feature = "test-dependencies")
625    ))]
626    pub fn default_transparent_address(&self) -> (TransparentAddress, NonHardenedChildIndex) {
627        self.transparent()
628            .expect("the key has a transparent component")
629            .to_account_pubkey()
630            .derive_external_ivk()
631            .unwrap()
632            .default_address()
633    }
634}
635
636/// Errors that can occur in the generation of unified addresses.
637#[derive(Clone, Debug)]
638pub enum AddressGenerationError {
639    /// The requested diversifier index was outside the range of valid transparent
640    /// child address indices.
641    #[cfg(feature = "transparent-inputs")]
642    InvalidTransparentChildIndex(DiversifierIndex),
643    /// The requested key scope is not supported for address derivation.
644    #[cfg(feature = "transparent-inputs")]
645    UnsupportedTransparentKeyScope(TransparentKeyScope),
646    /// An error occurred in [`bip32`] derivation of a transparent address.
647    #[cfg(feature = "transparent-inputs")]
648    Bip32DerivationError(bip32::Error),
649    /// The diversifier index could not be mapped to a valid Sapling diversifier.
650    #[cfg(feature = "sapling")]
651    InvalidSaplingDiversifierIndex(DiversifierIndex),
652    /// The space of available diversifier indices has been exhausted.
653    DiversifierSpaceExhausted,
654    /// A requested address typecode was not recognized, so we are unable to generate the address
655    /// as requested.
656    ReceiverTypeNotSupported(Typecode),
657    /// A requested address typecode was recognized, but the unified key being used to generate the
658    /// address lacks an item of the requested type.
659    KeyNotAvailable(Typecode),
660    /// The address request permits no receiver that the unified key being used to generate the
661    /// address can provide.
662    ///
663    /// Omitting both shielded receiver types is permitted only for a key that has no shielded
664    /// item; see [`ReceiverRequirements::TRANSPARENT_ONLY`].
665    NoSatisfiableReceiver,
666}
667
668impl fmt::Display for AddressGenerationError {
669    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
670        match &self {
671            #[cfg(feature = "transparent-inputs")]
672            AddressGenerationError::InvalidTransparentChildIndex(i) => {
673                write!(
674                    f,
675                    "Child index {i:?} does not generate a valid transparent receiver"
676                )
677            }
678            #[cfg(feature = "transparent-inputs")]
679            AddressGenerationError::UnsupportedTransparentKeyScope(i) => {
680                write!(f, "Key scope {i:?} is not supported for key derivation")
681            }
682            #[cfg(feature = "transparent-inputs")]
683            AddressGenerationError::Bip32DerivationError(e) => {
684                write!(f, "{e}")
685            }
686            #[cfg(feature = "sapling")]
687            AddressGenerationError::InvalidSaplingDiversifierIndex(i) => {
688                write!(
689                    f,
690                    "Child index {i:?} does not generate a valid Sapling receiver"
691                )
692            }
693            AddressGenerationError::DiversifierSpaceExhausted => {
694                write!(
695                    f,
696                    "Exhausted the space of diversifier indices without finding an address."
697                )
698            }
699            AddressGenerationError::ReceiverTypeNotSupported(t) => {
700                write!(
701                    f,
702                    "Unified Address generation does not yet support receivers of type {t:?}."
703                )
704            }
705            AddressGenerationError::KeyNotAvailable(t) => {
706                write!(
707                    f,
708                    "The Unified Viewing Key does not contain a key for typecode {t:?}."
709                )
710            }
711            AddressGenerationError::NoSatisfiableReceiver => {
712                write!(
713                    f,
714                    "The address request permits no receiver that this Unified Viewing Key can provide."
715                )
716            }
717        }
718    }
719}
720
721#[cfg(feature = "std")]
722impl std::error::Error for AddressGenerationError {}
723
724#[cfg(feature = "transparent-inputs")]
725impl From<bip32::Error> for AddressGenerationError {
726    fn from(value: bip32::Error) -> Self {
727        AddressGenerationError::Bip32DerivationError(value)
728    }
729}
730
731/// An error type for failures in combining [`ReceiverRequirement`] values.
732#[derive(Clone, Copy, Debug, PartialEq, Eq)]
733pub enum ReceiverRequirementError {
734    /// The two requirements are incompatible: one requires inclusion and the other requires
735    /// omission.
736    Conflict,
737    /// A set of receiver requirements would not include any shielded receiver.
738    ///
739    /// See [`ReceiverRequirements::TRANSPARENT_ONLY`] for the one set of requirements that
740    /// permits no shielded receiver.
741    NoShieldedReceiver,
742}
743
744impl Display for ReceiverRequirementError {
745    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
746        match self {
747            ReceiverRequirementError::Conflict => {
748                write!(f, "Require and Omit receiver requirements are incompatible")
749            }
750            ReceiverRequirementError::NoShieldedReceiver => {
751                write!(
752                    f,
753                    "These receiver requirements must permit at least one shielded receiver"
754                )
755            }
756        }
757    }
758}
759
760/// An enumeration of the ways in which a receiver may be requested to be present in a generated
761/// [`UnifiedAddress`].
762#[derive(Clone, Copy, Debug, PartialEq, Eq)]
763pub enum ReceiverRequirement {
764    /// A receiver of the associated type is required to be present in the generated
765    /// `[UnifiedAddress`], and if it is not possible to generate a receiver of this type, the
766    /// address generation method should return an error. When calling [`Self::intersect`], this
767    /// variant will be preferred over [`ReceiverRequirement::Allow`].
768    Require,
769    /// The associated receiver should be included, if a corresponding item exists in the IVK from
770    /// which the address is being derived and derivation of the receiver succeeds at the given
771    /// diversifier index.
772    Allow,
773    /// No receiver of the associated type may be included in the generated [`UnifiedAddress`]
774    /// under any circumstances. When calling [`Self::intersect`], this variant will be preferred
775    /// over [`ReceiverRequirement::Allow`].
776    Omit,
777}
778
779impl ReceiverRequirement {
780    /// Return the intersection of two requirements that chooses the stronger requirement, if one
781    /// exists. [`ReceiverRequirement::Require`] and [`ReceiverRequirement::Omit`] are
782    /// incompatible; attempting an intersection between these will return an error.
783    pub fn intersect(self, other: Self) -> Result<Self, ReceiverRequirementError> {
784        match (self, other) {
785            (Require, Omit) | (Omit, Require) => Err(ReceiverRequirementError::Conflict),
786            (Require, Require) | (Require, Allow) | (Allow, Require) => Ok(Require),
787            (Allow, Allow) => Ok(Allow),
788            (Allow, Omit) | (Omit, Allow) | (Omit, Omit) => Ok(Omit),
789        }
790    }
791}
792
793/// Specification for how a unified address should be generated from a unified viewing key.
794#[derive(Clone, Copy, Debug)]
795pub enum UnifiedAddressRequest {
796    AllAvailableKeys,
797    Custom(ReceiverRequirements),
798}
799
800impl UnifiedAddressRequest {
801    /// Constructs a new unified address request that allows a receiver of each type.
802    pub const ALLOW_ALL: Self = Self::Custom(ReceiverRequirements::ALLOW_ALL);
803
804    /// Constructs a new unified address request that allows only shielded receivers.
805    pub const SHIELDED: Self = Self::Custom(ReceiverRequirements::SHIELDED);
806
807    /// Constructs a new unified address request that requires an Orchard receiver and no others.
808    pub const ORCHARD: Self = Self::Custom(ReceiverRequirements::ORCHARD);
809
810    /// Constructs a new unified address request that requires a transparent P2PKH receiver and
811    /// no others.
812    ///
813    /// See [`ReceiverRequirements::TRANSPARENT_ONLY`] for the constraints on the resulting
814    /// address.
815    pub const TRANSPARENT_ONLY: Self = Self::Custom(ReceiverRequirements::TRANSPARENT_ONLY);
816
817    pub fn custom(
818        orchard: ReceiverRequirement,
819        sapling: ReceiverRequirement,
820        p2pkh: ReceiverRequirement,
821    ) -> Result<Self, ReceiverRequirementError> {
822        ReceiverRequirements::new(orchard, sapling, p2pkh).map(UnifiedAddressRequest::Custom)
823    }
824
825    pub const fn unsafe_custom(
826        orchard: ReceiverRequirement,
827        sapling: ReceiverRequirement,
828        p2pkh: ReceiverRequirement,
829    ) -> Self {
830        UnifiedAddressRequest::Custom(ReceiverRequirements::unsafe_new(orchard, sapling, p2pkh))
831    }
832}
833
834/// Specification for how a unified address should be generated from a unified viewing key.
835#[derive(Clone, Copy, Debug)]
836pub struct ReceiverRequirements {
837    orchard: ReceiverRequirement,
838    sapling: ReceiverRequirement,
839    p2pkh: ReceiverRequirement,
840}
841
842impl ReceiverRequirements {
843    /// Construct a new unified address request from its constituent parts.
844    ///
845    /// Returns an error if the resulting unified address would not include at least one shielded
846    /// receiver. A unified address containing only a transparent receiver cannot be requested
847    /// this way; use [`Self::TRANSPARENT_ONLY`], which is applicable only to keys that have no
848    /// shielded item at all.
849    pub fn new(
850        orchard: ReceiverRequirement,
851        sapling: ReceiverRequirement,
852        p2pkh: ReceiverRequirement,
853    ) -> Result<Self, ReceiverRequirementError> {
854        if orchard == Omit && sapling == Omit {
855            Err(ReceiverRequirementError::NoShieldedReceiver)
856        } else {
857            Ok(Self {
858                orchard,
859                sapling,
860                p2pkh,
861            })
862        }
863    }
864
865    /// Constructs a new unified address request that allows a receiver of each type.
866    pub const ALLOW_ALL: ReceiverRequirements = { Self::unsafe_new(Allow, Allow, Allow) };
867
868    /// Constructs a new unified address request that allows only shielded receivers.
869    pub const SHIELDED: ReceiverRequirements = { Self::unsafe_new(Allow, Allow, Omit) };
870
871    /// Constructs a new unified address request that requires an Orchard receiver, and no others.
872    pub const ORCHARD: ReceiverRequirements = { Self::unsafe_new(Require, Omit, Omit) };
873
874    /// Constructs a new unified address request that requires a transparent P2PKH receiver, and
875    /// no others.
876    ///
877    /// An address satisfying these requirements has no shielded receiver, and so is
878    /// representable only as a [ZIP 316] Revision 2 transparent-including (`tu`) unified
879    /// address. Consequently this is the appropriate request only for a key that has no
880    /// shielded item; requesting it from a key that has one produces an address that
881    /// needlessly discards the recipient's shielded receiving capability. It is not reachable
882    /// via [`Self::new`] or [`Self::unsafe_new`] for that reason.
883    ///
884    /// [ZIP 316]: https://zips.z.cash/zip-0316
885    pub const TRANSPARENT_ONLY: ReceiverRequirements = Self {
886        orchard: Omit,
887        sapling: Omit,
888        p2pkh: Require,
889    };
890
891    /// Constructs a new unified address request that includes only the receivers that are allowed
892    /// both in itself and a given other request. Returns an error if requirements are incompatible
893    /// or if no shielded receiver type is allowed.
894    ///
895    /// Intersection preserves [`Omit`], so its result permits no shielded receiver only if at
896    /// least one of the operands already permitted none. In that case the result is no less
897    /// honest than the operand it came from and is returned; otherwise the shielded-receiver
898    /// requirement of [`Self::new`] applies.
899    ///
900    /// This operation is commutative and idempotent, but it is not associative. The rule above
901    /// inspects the operands and not only the meet, so an intermediate result that permits no
902    /// shielded receiver can be rejected under one bracketing and admitted under another.
903    ///
904    /// [`Omit`]: ReceiverRequirement::Omit
905    pub fn intersect(
906        &self,
907        other: &ReceiverRequirements,
908    ) -> Result<ReceiverRequirements, ReceiverRequirementError> {
909        let orchard = self.orchard.intersect(other.orchard)?;
910        let sapling = self.sapling.intersect(other.sapling)?;
911        let p2pkh = self.p2pkh.intersect(other.p2pkh)?;
912        match (orchard, sapling, p2pkh) {
913            (Omit, Omit, Require) if self.is_transparent_only() || other.is_transparent_only() => {
914                Ok(Self::TRANSPARENT_ONLY)
915            }
916            _ => Self::new(orchard, sapling, p2pkh),
917        }
918    }
919
920    /// Construct a new unified address request from its constituent parts.
921    ///
922    /// Panics: at least one of `orchard` or `sapling` must be allowed. Use
923    /// [`Self::TRANSPARENT_ONLY`] to describe a key that has no shielded item.
924    pub const fn unsafe_new(
925        orchard: ReceiverRequirement,
926        sapling: ReceiverRequirement,
927        p2pkh: ReceiverRequirement,
928    ) -> Self {
929        if matches!(orchard, Omit) && matches!(sapling, Omit) {
930            panic!("At least one shielded receiver must be allowed.")
931        }
932
933        Self {
934            orchard,
935            sapling,
936            p2pkh,
937        }
938    }
939
940    /// Returns whether these requirements permit no shielded receiver.
941    fn is_transparent_only(&self) -> bool {
942        self.orchard == Omit && self.sapling == Omit
943    }
944
945    /// Returns the [`ReceiverRequirement`] for inclusion of an Orchard receiver.
946    pub fn orchard(&self) -> ReceiverRequirement {
947        self.orchard
948    }
949
950    /// Returns the [`ReceiverRequirement`] for inclusion of a Sapling receiver.
951    pub fn sapling(&self) -> ReceiverRequirement {
952        self.sapling
953    }
954
955    /// Returns the [`ReceiverRequirement`] for inclusion of a P2PKH receiver.
956    pub fn p2pkh(&self) -> ReceiverRequirement {
957        self.p2pkh
958    }
959}
960
961#[cfg(feature = "transparent-inputs")]
962impl From<bip32::Error> for DerivationError {
963    fn from(e: bip32::Error) -> Self {
964        DerivationError::Transparent(e)
965    }
966}
967
968/// A key that provides the capability to recover outgoing transaction information from
969/// the block chain.
970#[derive(Clone, Copy)]
971pub struct OutgoingViewingKey([u8; 32]);
972
973impl core::fmt::Debug for OutgoingViewingKey {
974    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
975        f.debug_tuple("OutgoingViewingKey").field(&"...").finish()
976    }
977}
978
979impl From<[u8; 32]> for OutgoingViewingKey {
980    fn from(ovk: [u8; 32]) -> Self {
981        OutgoingViewingKey(ovk)
982    }
983}
984
985#[cfg(feature = "sapling")]
986impl From<OutgoingViewingKey> for ::sapling::keys::OutgoingViewingKey {
987    fn from(value: OutgoingViewingKey) -> Self {
988        ::sapling::keys::OutgoingViewingKey(value.0)
989    }
990}
991
992#[cfg(feature = "sapling")]
993impl From<::sapling::keys::OutgoingViewingKey> for OutgoingViewingKey {
994    fn from(value: ::sapling::keys::OutgoingViewingKey) -> Self {
995        OutgoingViewingKey(value.0)
996    }
997}
998
999#[cfg(feature = "orchard")]
1000impl From<OutgoingViewingKey> for ::orchard::keys::OutgoingViewingKey {
1001    fn from(value: OutgoingViewingKey) -> Self {
1002        ::orchard::keys::OutgoingViewingKey::from(value.0)
1003    }
1004}
1005
1006#[cfg(feature = "orchard")]
1007impl From<::orchard::keys::OutgoingViewingKey> for OutgoingViewingKey {
1008    fn from(value: ::orchard::keys::OutgoingViewingKey) -> Self {
1009        OutgoingViewingKey(*value.as_ref())
1010    }
1011}
1012
1013impl AsRef<[u8; 32]> for OutgoingViewingKey {
1014    fn as_ref(&self) -> &[u8; 32] {
1015        &self.0
1016    }
1017}
1018
1019/// A [ZIP 316](https://zips.z.cash/zip-0316) unified full viewing key.
1020#[derive(Clone)]
1021pub struct UnifiedFullViewingKey {
1022    #[cfg(feature = "transparent-inputs")]
1023    transparent: Option<TransparentFvk>,
1024    #[cfg(feature = "sapling")]
1025    sapling: Option<sapling::DiversifiableFullViewingKey>,
1026    #[cfg(feature = "orchard")]
1027    orchard: Option<orchard::keys::FullViewingKey>,
1028    unknown: Vec<(u32, Vec<u8>)>,
1029    expiry_height: Option<consensus::BlockHeight>,
1030    expiry_time: Option<u64>,
1031    unknown_metadata: Vec<(u32, Vec<u8>)>,
1032}
1033
1034/// The transparent component of a [`UnifiedFullViewingKey`].
1035///
1036/// ZIP 316 permits a unified viewing key to contain at most one transparent item, and
1037/// requires consumers to reject a key that carries both a P2PKH and a P2SH item.
1038#[cfg(feature = "transparent-inputs")]
1039#[derive(Clone, PartialEq, Eq)]
1040enum TransparentFvk {
1041    P2pkh(crate::keys::transparent::AccountPubKey),
1042    P2sh(P2shFullViewingKey),
1043}
1044
1045/// The transparent component of a [`UnifiedIncomingViewingKey`].
1046///
1047/// ZIP 316 permits a unified viewing key to contain at most one transparent item, and
1048/// requires consumers to reject a key that carries both a P2PKH and a P2SH item.
1049#[cfg(feature = "transparent-inputs")]
1050#[derive(Clone, PartialEq, Eq)]
1051enum TransparentIvk {
1052    P2pkh(crate::keys::transparent::ExternalIvk),
1053    P2sh(P2shIncomingViewingKey),
1054}
1055
1056impl core::fmt::Debug for UnifiedFullViewingKey {
1057    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1058        let mut d = f.debug_struct("UnifiedFullViewingKey");
1059        #[cfg(feature = "transparent-inputs")]
1060        d.field("p2pkh", &self.p2pkh().map(|_| "..."));
1061        #[cfg(feature = "transparent-inputs")]
1062        d.field("p2sh", &self.p2sh());
1063        #[cfg(feature = "sapling")]
1064        d.field("sapling", &self.sapling.as_ref().map(|_| "..."));
1065        #[cfg(feature = "orchard")]
1066        d.field("orchard", &self.orchard.as_ref().map(|_| "..."));
1067        d.field(
1068            "unknown_typecodes",
1069            &self
1070                .unknown
1071                .iter()
1072                .map(|(typecode, _)| *typecode)
1073                .collect::<Vec<_>>(),
1074        )
1075        .field("expiry_height", &self.expiry_height)
1076        .field("expiry_time", &self.expiry_time)
1077        .field(
1078            "unknown_metadata_typecodes",
1079            &self
1080                .unknown_metadata
1081                .iter()
1082                .map(|(typecode, _)| *typecode)
1083                .collect::<Vec<_>>(),
1084        )
1085        .finish()
1086    }
1087}
1088
1089impl UnifiedFullViewingKey {
1090    /// Construct a new unified full viewing key.
1091    ///
1092    /// This method is only available when the `test-dependencies` feature is enabled,
1093    /// as derivation from the USK or deserialization from the serialized form should
1094    /// be used instead.
1095    #[cfg(any(test, feature = "test-dependencies"))]
1096    pub fn new(
1097        #[cfg(feature = "transparent-inputs")] transparent: Option<
1098            crate::keys::transparent::AccountPubKey,
1099        >,
1100        #[cfg(feature = "sapling")] sapling: Option<sapling::DiversifiableFullViewingKey>,
1101        #[cfg(feature = "orchard")] orchard: Option<orchard::keys::FullViewingKey>,
1102        // TODO: Implement construction of UFVKs with metadata items.
1103    ) -> Result<UnifiedFullViewingKey, DerivationError> {
1104        Self::from_checked_parts(
1105            #[cfg(feature = "transparent-inputs")]
1106            transparent.map(TransparentFvk::P2pkh),
1107            #[cfg(feature = "sapling")]
1108            sapling,
1109            #[cfg(feature = "orchard")]
1110            orchard,
1111            vec![],
1112            None,
1113            None,
1114            vec![],
1115        )
1116    }
1117
1118    #[cfg(feature = "unstable-frost")]
1119    pub fn from_orchard_fvk(
1120        orchard: orchard::keys::FullViewingKey,
1121    ) -> Result<UnifiedFullViewingKey, DerivationError> {
1122        Self::from_checked_parts(
1123            #[cfg(feature = "transparent-inputs")]
1124            None,
1125            #[cfg(feature = "sapling")]
1126            None,
1127            #[cfg(feature = "orchard")]
1128            Some(orchard),
1129            vec![],
1130            None,
1131            None,
1132            vec![],
1133        )
1134    }
1135
1136    #[cfg(all(feature = "sapling", feature = "unstable"))]
1137    pub fn from_sapling_extended_full_viewing_key(
1138        sapling: ExtendedFullViewingKey,
1139    ) -> Result<UnifiedFullViewingKey, DerivationError> {
1140        Self::from_checked_parts(
1141            #[cfg(feature = "transparent-inputs")]
1142            None,
1143            #[cfg(feature = "sapling")]
1144            Some(sapling.to_diversifiable_full_viewing_key()),
1145            #[cfg(feature = "orchard")]
1146            None,
1147            vec![],
1148            None,
1149            None,
1150            vec![],
1151        )
1152    }
1153
1154    /// Constructs a unified full viewing key for a transparent-only account defined by a
1155    /// [ZIP 316] Revision 2 P2SH viewing key item.
1156    ///
1157    /// This is the one unified full viewing key that cannot be derived. Every other kind
1158    /// is reached through [`UnifiedSpendingKey::to_unified_full_viewing_key`], because a
1159    /// seed determines it; a P2SH account is instead defined by a set of cosigners'
1160    /// keys, so it has no spending key to derive from and must be assembled.
1161    ///
1162    /// The resulting key has no shielded components, so it encodes with the `tu` HRP and
1163    /// derives transparent-only unified addresses.
1164    ///
1165    /// [ZIP 316]: https://zips.z.cash/zip-0316
1166    #[cfg(feature = "transparent-inputs")]
1167    pub fn from_p2sh(p2sh: P2shFullViewingKey) -> Result<UnifiedFullViewingKey, DerivationError> {
1168        Self::from_checked_parts(
1169            Some(TransparentFvk::P2sh(p2sh)),
1170            #[cfg(feature = "sapling")]
1171            None,
1172            #[cfg(feature = "orchard")]
1173            None,
1174            vec![],
1175            None,
1176            None,
1177            vec![],
1178        )
1179    }
1180
1181    /// Construct a UFVK from its constituent parts, after verifying that UIVK derivation can
1182    /// succeed.
1183    #[allow(clippy::too_many_arguments)]
1184    fn from_checked_parts(
1185        #[cfg(feature = "transparent-inputs")] transparent: Option<TransparentFvk>,
1186        #[cfg(feature = "sapling")] sapling: Option<sapling::DiversifiableFullViewingKey>,
1187        #[cfg(feature = "orchard")] orchard: Option<orchard::keys::FullViewingKey>,
1188        unknown: Vec<(u32, Vec<u8>)>,
1189        expiry_height: Option<consensus::BlockHeight>,
1190        expiry_time: Option<u64>,
1191        unknown_metadata: Vec<(u32, Vec<u8>)>,
1192    ) -> Result<UnifiedFullViewingKey, DerivationError> {
1193        // Verify that the incoming viewing key form of the transparent component is
1194        // derivable; we don't want to construct a UFVK that can't derive transparent
1195        // addresses.
1196        #[cfg(feature = "transparent-inputs")]
1197        match transparent.as_ref() {
1198            Some(TransparentFvk::P2pkh(k)) => {
1199                let _ = k.derive_external_ivk()?;
1200            }
1201            Some(TransparentFvk::P2sh(p)) => {
1202                let _ = p.to_incoming_viewing_key()?;
1203            }
1204            None => {}
1205        }
1206
1207        Ok(UnifiedFullViewingKey {
1208            #[cfg(feature = "transparent-inputs")]
1209            transparent,
1210            #[cfg(feature = "sapling")]
1211            sapling,
1212            #[cfg(feature = "orchard")]
1213            orchard,
1214            unknown,
1215            expiry_height,
1216            expiry_time,
1217            unknown_metadata,
1218        })
1219    }
1220
1221    /// Parses a `UnifiedFullViewingKey` from its [ZIP 316] string encoding at any
1222    /// revision.
1223    ///
1224    /// # Errors
1225    ///
1226    /// - [`UnifiedDecodingError::Parse`] if the string is not a valid UFVK.
1227    /// - [`UnifiedDecodingError::NetworkMismatch`] if the key is for a network other than
1228    ///   that of `params`.
1229    /// - [`UnifiedDecodingError::InvalidItem`] if an item's data is not a valid key of its
1230    ///   type.
1231    ///
1232    /// [ZIP 316]: https://zips.z.cash/zip-0316
1233    pub fn decode<P: consensus::Parameters>(
1234        params: &P,
1235        encoding: &str,
1236    ) -> Result<Self, UnifiedDecodingError> {
1237        let (actual, _revision, ufvk) =
1238            unified::Ufvk::decode(encoding).map_err(UnifiedDecodingError::Parse)?;
1239        let expected = params.network_type();
1240        if actual != expected {
1241            return Err(UnifiedDecodingError::NetworkMismatch { expected, actual });
1242        }
1243
1244        Self::from_container(&ufvk).map_err(UnifiedDecodingError::InvalidItem)
1245    }
1246
1247    /// Constructs a `UnifiedFullViewingKey` from a parsed [ZIP 316] unified container.
1248    ///
1249    /// Returns [`DecodingError::KeyDataInvalid`] if an item's data is not a valid key of
1250    /// its type.
1251    ///
1252    /// [ZIP 316]: https://zips.z.cash/zip-0316
1253    pub fn parse(ufvk: &unified::Ufvk) -> Result<Self, DecodingError> {
1254        Self::from_container(ufvk).map_err(DecodingError::KeyDataInvalid)
1255    }
1256
1257    /// Constructs a `UnifiedFullViewingKey` from a parsed unified container.
1258    ///
1259    /// On error, returns the typecode of the first item whose data is not a valid key of
1260    /// its type.
1261    fn from_container(ufvk: &unified::Ufvk) -> Result<Self, Typecode> {
1262        #[cfg(feature = "orchard")]
1263        let mut orchard = None;
1264        #[cfg(feature = "sapling")]
1265        let mut sapling = None;
1266        #[cfg(feature = "transparent-inputs")]
1267        let mut transparent = None;
1268        let mut unknown = vec![];
1269        let mut expiry_height = None;
1270        let mut expiry_time = None;
1271        let mut unknown_metadata = vec![];
1272
1273        for item in ufvk.items_as_parsed() {
1274            match item {
1275                Uitem::Data(unified::Fvk::Orchard(data)) => {
1276                    #[cfg(feature = "orchard")]
1277                    {
1278                        orchard = Some(
1279                            orchard::keys::FullViewingKey::from_bytes(data)
1280                                .ok_or(Typecode::ORCHARD)?,
1281                        );
1282                    }
1283                    #[cfg(not(feature = "orchard"))]
1284                    unknown.push((u32::from(unified::Typecode::ORCHARD), data.to_vec()));
1285                }
1286                Uitem::Data(unified::Fvk::Sapling(data)) => {
1287                    #[cfg(feature = "sapling")]
1288                    {
1289                        sapling = Some(
1290                            sapling::DiversifiableFullViewingKey::from_bytes(data)
1291                                .ok_or(Typecode::SAPLING)?,
1292                        );
1293                    }
1294                    #[cfg(not(feature = "sapling"))]
1295                    unknown.push((u32::from(unified::Typecode::SAPLING), data.to_vec()));
1296                }
1297                Uitem::Data(unified::Fvk::P2pkh(data)) => {
1298                    #[cfg(feature = "transparent-inputs")]
1299                    {
1300                        transparent = Some(TransparentFvk::P2pkh(
1301                            crate::keys::transparent::AccountPubKey::deserialize(data)
1302                                .map_err(|_| Typecode::P2PKH)?,
1303                        ));
1304                    }
1305                    #[cfg(not(feature = "transparent-inputs"))]
1306                    unknown.push((u32::from(unified::Typecode::P2PKH), data.to_vec()));
1307                }
1308                Uitem::Data(unified::Fvk::P2sh(data)) => {
1309                    #[cfg(feature = "transparent-inputs")]
1310                    {
1311                        transparent = Some(TransparentFvk::P2sh(
1312                            P2shFullViewingKey::parse(data).map_err(|_| Typecode::P2SH)?,
1313                        ));
1314                    }
1315                    #[cfg(not(feature = "transparent-inputs"))]
1316                    unknown.push((u32::from(unified::Typecode::P2SH), data.to_vec()));
1317                }
1318                Uitem::Data(unified::Fvk::Unknown { typecode, data }) => {
1319                    unknown.push((*typecode, data.clone()));
1320                }
1321                Uitem::Metadata(MetadataItem::ExpiryHeight(h)) => {
1322                    expiry_height = Some(consensus::BlockHeight::from_u32(*h));
1323                }
1324                Uitem::Metadata(MetadataItem::ExpiryTime(t)) => {
1325                    expiry_time = Some(*t);
1326                }
1327                Uitem::Metadata(MetadataItem::Unknown { typecode, data }) => {
1328                    unknown_metadata.push((*typecode, data.clone()));
1329                }
1330            }
1331        }
1332
1333        // Only the derivation of the transparent item's incoming viewing key can fail.
1334        #[cfg(feature = "transparent-inputs")]
1335        let transparent_typecode = match transparent {
1336            Some(TransparentFvk::P2sh(_)) => Typecode::P2SH,
1337            _ => Typecode::P2PKH,
1338        };
1339        #[cfg(not(feature = "transparent-inputs"))]
1340        let transparent_typecode = Typecode::P2PKH;
1341
1342        Self::from_checked_parts(
1343            #[cfg(feature = "transparent-inputs")]
1344            transparent,
1345            #[cfg(feature = "sapling")]
1346            sapling,
1347            #[cfg(feature = "orchard")]
1348            orchard,
1349            unknown,
1350            expiry_height,
1351            expiry_time,
1352            unknown_metadata,
1353        )
1354        .map_err(|_| transparent_typecode)
1355    }
1356
1357    /// Returns the [ZIP 316] string encoding of this `UnifiedFullViewingKey` for the given
1358    /// network at the given revision.
1359    ///
1360    /// Returns [`UnifiedEncodingError::NotRepresentable`] if this key has no encoding at
1361    /// `revision`: [`Revision::R0`] cannot encode expiry metadata, a P2SH viewing key
1362    /// item, or a key whose only data items are transparent.
1363    ///
1364    /// [ZIP 316]: https://zips.z.cash/zip-0316
1365    pub fn encode_revision<P: consensus::Parameters>(
1366        &self,
1367        params: &P,
1368        revision: Revision,
1369    ) -> Result<String, UnifiedEncodingError> {
1370        self.to_ufvk(revision)
1371            .map(|ufvk| ufvk.encode(&params.network_type()))
1372    }
1373
1374    /// Returns the [ZIP 316] string encoding of this `UnifiedFullViewingKey` for the given
1375    /// network at the most widely supported revision that can represent it:
1376    /// [`Revision::R0`] if possible, and [`Revision::R2`] otherwise. Use
1377    /// [`encode_revision`](Self::encode_revision) to encode at a specific revision.
1378    ///
1379    /// Returns [`UnifiedEncodingError::NotRepresentable`] if this key has no encoding at
1380    /// either revision.
1381    ///
1382    /// [ZIP 316]: https://zips.z.cash/zip-0316
1383    pub fn encode<P: consensus::Parameters>(
1384        &self,
1385        params: &P,
1386    ) -> Result<String, UnifiedEncodingError> {
1387        self.encode_revision(params, Revision::R0)
1388            .or_else(|_| self.encode_revision(params, Revision::R2))
1389    }
1390
1391    /// Converts this key to a unified container at the given revision.
1392    fn to_ufvk(&self, revision: Revision) -> Result<unified::Ufvk, UnifiedEncodingError> {
1393        let data_items = core::iter::empty().chain(self.unknown.iter().map(|(typecode, data)| {
1394            unified::Fvk::Unknown {
1395                typecode: *typecode,
1396                data: data.clone(),
1397            }
1398        }));
1399        #[cfg(feature = "orchard")]
1400        let data_items = data_items.chain(
1401            self.orchard
1402                .as_ref()
1403                .map(|fvk| fvk.to_bytes())
1404                .map(unified::Fvk::Orchard),
1405        );
1406        #[cfg(feature = "sapling")]
1407        let data_items = data_items.chain(
1408            self.sapling
1409                .as_ref()
1410                .map(|dfvk| dfvk.to_bytes())
1411                .map(unified::Fvk::Sapling),
1412        );
1413        #[cfg(feature = "transparent-inputs")]
1414        let data_items = data_items.chain(self.transparent.as_ref().map(|t| match t {
1415            TransparentFvk::P2pkh(k) => {
1416                unified::Fvk::P2pkh(k.serialize().try_into().expect("key is 65 bytes"))
1417            }
1418            TransparentFvk::P2sh(p) => unified::Fvk::P2sh(p.to_bytes()),
1419        }));
1420
1421        let meta_items = core::iter::empty()
1422            .chain(self.unknown_metadata.iter().map(|(typecode, data)| {
1423                unified::MetadataItem::Unknown {
1424                    typecode: *typecode,
1425                    data: data.clone(),
1426                }
1427            }))
1428            .chain(
1429                self.expiry_height
1430                    .map(|h| unified::MetadataItem::ExpiryHeight(u32::from(h))),
1431            )
1432            .chain(self.expiry_time.map(unified::MetadataItem::ExpiryTime));
1433
1434        unified::Ufvk::try_from_items(
1435            revision,
1436            data_items
1437                .map(Uitem::Data)
1438                .chain(meta_items.map(Uitem::Metadata))
1439                .collect(),
1440        )
1441        .map_err(|cause| UnifiedEncodingError::NotRepresentable { revision, cause })
1442    }
1443
1444    /// Derives a Unified Incoming Viewing Key from this Unified Full Viewing Key.
1445    pub fn to_unified_incoming_viewing_key(&self) -> UnifiedIncomingViewingKey {
1446        UnifiedIncomingViewingKey {
1447            #[cfg(feature = "transparent-inputs")]
1448            transparent: self.transparent.as_ref().map(|t| match t {
1449                TransparentFvk::P2pkh(k) => TransparentIvk::P2pkh(
1450                    k.derive_external_ivk()
1451                        .expect("Transparent IVK derivation was checked at construction."),
1452                ),
1453                TransparentFvk::P2sh(p) => TransparentIvk::P2sh(
1454                    p.to_incoming_viewing_key()
1455                        .expect("P2SH IVK derivation was checked at construction."),
1456                ),
1457            }),
1458            #[cfg(feature = "sapling")]
1459            sapling: self.sapling.as_ref().map(|s| s.to_external_ivk()),
1460            #[cfg(feature = "orchard")]
1461            orchard: self.orchard.as_ref().map(|o| o.to_ivk(Scope::External)),
1462            expiry_height: self.expiry_height,
1463            expiry_time: self.expiry_time,
1464            // An item that this build cannot interpret has no derivable incoming viewing key
1465            // form, so it cannot be carried over. Record its typecode: the derived key is a
1466            // lossy description of the account, and callers that describe the account from it
1467            // must not present it as complete.
1468            unknown: Vec::new(),
1469            unconverted_typecodes: self.unknown.iter().map(|(typecode, _)| *typecode).collect(),
1470            unknown_metadata: vec![],
1471        }
1472    }
1473
1474    /// Returns the P2PKH component of the unified key at the
1475    /// BIP44 path `m/44'/<coin_type>'/<account>'`, if present.
1476    #[cfg(feature = "transparent-inputs")]
1477    #[deprecated(note = "Use `UnifiedFullViewingKey::p2pkh` instead.")]
1478    pub fn transparent(&self) -> Option<&crate::keys::transparent::AccountPubKey> {
1479        self.p2pkh()
1480    }
1481
1482    /// Returns the P2PKH component of the unified key at the
1483    /// BIP44 path `m/44'/<coin_type>'/<account>'`, if present.
1484    ///
1485    /// Returns `None` if the key has no transparent component, or carries a P2SH viewing
1486    /// key item instead; the two are mutually exclusive.
1487    #[cfg(feature = "transparent-inputs")]
1488    pub fn p2pkh(&self) -> Option<&crate::keys::transparent::AccountPubKey> {
1489        match self.transparent.as_ref() {
1490            Some(TransparentFvk::P2pkh(k)) => Some(k),
1491            Some(TransparentFvk::P2sh(_)) | None => None,
1492        }
1493    }
1494
1495    /// Returns the P2SH viewing key item of this unified key, if present.
1496    ///
1497    /// Returns `None` if the key has no transparent component, or carries a P2PKH
1498    /// viewing key instead; the two are mutually exclusive.
1499    #[cfg(feature = "transparent-inputs")]
1500    pub fn p2sh(&self) -> Option<&P2shFullViewingKey> {
1501        match self.transparent.as_ref() {
1502            Some(TransparentFvk::P2sh(p)) => Some(p),
1503            Some(TransparentFvk::P2pkh(_)) | None => None,
1504        }
1505    }
1506
1507    /// Returns the Sapling diversifiable full viewing key component of this unified key.
1508    #[cfg(feature = "sapling")]
1509    pub fn sapling(&self) -> Option<&sapling::DiversifiableFullViewingKey> {
1510        self.sapling.as_ref()
1511    }
1512
1513    /// Returns the Orchard full viewing key component of this unified key.
1514    #[cfg(feature = "orchard")]
1515    pub fn orchard(&self) -> Option<&orchard::keys::FullViewingKey> {
1516        self.orchard.as_ref()
1517    }
1518
1519    /// Returns whether this key has a Sapling component.
1520    pub fn has_sapling(&self) -> bool {
1521        #[cfg(feature = "sapling")]
1522        return self.sapling.is_some();
1523        #[cfg(not(feature = "sapling"))]
1524        return false;
1525    }
1526
1527    /// Returns whether this key has an Orchard component.
1528    pub fn has_orchard(&self) -> bool {
1529        #[cfg(feature = "orchard")]
1530        return self.orchard.is_some();
1531        #[cfg(not(feature = "orchard"))]
1532        return false;
1533    }
1534
1535    /// Returns the expiry height metadata for this key, if present.
1536    pub fn expiry_height(&self) -> Option<consensus::BlockHeight> {
1537        self.expiry_height
1538    }
1539
1540    /// Returns the expiry time metadata for this key, if present.
1541    pub fn expiry_time(&self) -> Option<u64> {
1542        self.expiry_time
1543    }
1544
1545    /// Returns `true` if this UFVK subsumes the given UIVK: every IVK item present in
1546    /// `other` has a matching item derivable from `self`. The UFVK may have additional
1547    /// items representing capabilities not present in the UIVK.
1548    pub fn subsumes_uivk(&self, other: &UnifiedIncomingViewingKey) -> bool {
1549        self.to_unified_incoming_viewing_key().subsumes(other)
1550    }
1551
1552    /// Returns `true` if this UFVK subsumes `other`: every FVK item in `other` has a
1553    /// matching item in `self`, including both incoming and outgoing viewing capability.
1554    ///
1555    /// For unknown items, exact equality of (typecode, data) is required.
1556    pub fn subsumes_ufvk(&self, other: &UnifiedFullViewingKey) -> bool {
1557        #[cfg(feature = "orchard")]
1558        match (&other.orchard, &self.orchard) {
1559            (Some(e), Some(n)) if e != n => {
1560                return false;
1561            }
1562            (Some(_), None) => return false,
1563            _ => {}
1564        }
1565
1566        #[cfg(feature = "sapling")]
1567        match (&other.sapling, &self.sapling) {
1568            (Some(e), Some(n)) if e != n => {
1569                return false;
1570            }
1571            (Some(_), None) => return false,
1572            _ => {}
1573        }
1574
1575        #[cfg(feature = "transparent-inputs")]
1576        match (&other.transparent, &self.transparent) {
1577            (Some(e), Some(n)) if e != n => {
1578                return false;
1579            }
1580            (Some(_), None) => return false,
1581            _ => {}
1582        }
1583
1584        // Every unknown item in `other` must have an identical entry in `self`.
1585        for item in &other.unknown {
1586            if !self.unknown.contains(item) {
1587                return false;
1588            }
1589        }
1590
1591        true
1592    }
1593
1594    /// Returns `true` if this UFVK and `other` carry the same viewing capability: each
1595    /// [subsumes](Self::subsumes_ufvk) the other. Metadata items are not compared.
1596    pub fn is_equivalent_to(&self, other: &UnifiedFullViewingKey) -> bool {
1597        self.subsumes_ufvk(other) && other.subsumes_ufvk(self)
1598    }
1599
1600    /// Attempts to derive the Unified Address for the given diversifier index and receiver types.
1601    ///
1602    /// Returns `None` if the specified index does not produce a valid diversifier.
1603    pub fn address(
1604        &self,
1605        j: DiversifierIndex,
1606        request: UnifiedAddressRequest,
1607    ) -> Result<UnifiedAddress, AddressGenerationError> {
1608        self.to_unified_incoming_viewing_key().address(j, request)
1609    }
1610
1611    /// Searches the diversifier space starting at diversifier index `j` for one which will produce
1612    /// a valid diversifier, and return the Unified Address constructed using that diversifier
1613    /// along with the index at which the valid diversifier was found.
1614    ///
1615    /// Returns an `Err(AddressGenerationError)` if no valid diversifier exists or if the features
1616    /// required to satisfy the unified address request are not properly enabled.
1617    pub fn find_address(
1618        &self,
1619        j: DiversifierIndex,
1620        request: UnifiedAddressRequest,
1621    ) -> Result<(UnifiedAddress, DiversifierIndex), AddressGenerationError> {
1622        self.to_unified_incoming_viewing_key()
1623            .find_address(j, request)
1624    }
1625
1626    /// Find the Unified Address corresponding to the smallest valid diversifier index, along with
1627    /// that index.
1628    ///
1629    /// Returns an `Err(AddressGenerationError)` if no valid diversifier exists or if the features
1630    /// required to satisfy the unified address request are not properly enabled.
1631    pub fn default_address(
1632        &self,
1633        request: UnifiedAddressRequest,
1634    ) -> Result<(UnifiedAddress, DiversifierIndex), AddressGenerationError> {
1635        self.find_address(DiversifierIndex::new(), request)
1636    }
1637
1638    /// Returns the default external transparent address using the transparent account pubkey.
1639    ///
1640    /// See [`ExternalIvk::default_address`] for more information.
1641    ///
1642    /// [`ExternalIvk::default_address`]: crate::keys::transparent::ExternalIvk::default_address
1643    #[cfg(all(
1644        feature = "transparent-inputs",
1645        any(test, feature = "test-dependencies")
1646    ))]
1647    pub fn default_transparent_address(
1648        &self,
1649    ) -> Option<(TransparentAddress, NonHardenedChildIndex)> {
1650        self.p2pkh().map(|k| {
1651            k.derive_external_ivk()
1652                .expect("ability to derive the external IVK was checked at construction")
1653                .default_address()
1654        })
1655    }
1656
1657    /// Selects an outgoing viewing key for a transaction's outputs based upon the type(s) of
1658    /// inputs spent in the transaction.
1659    ///
1660    /// This method selects the OVK of the highest-preference item in [ZIP 316] preference order
1661    /// from among the item types represented by the provided input types. It will return `None` in
1662    /// the case that this FVK does not contain any items corresponding to the provided input
1663    /// sources; this should ordinarily never occur because in order to spend an input, a spending
1664    /// key of the appropriate type must be available and that spending key should be represented
1665    /// among this UFVK's items.
1666    pub fn select_ovk(
1667        &self,
1668        scope: zip32::Scope,
1669        input_sources: &NonEmpty<PoolType>,
1670    ) -> Option<OutgoingViewingKey> {
1671        #[cfg(feature = "orchard")]
1672        if let Some(ovk) = input_sources
1673            .contains(&PoolType::ORCHARD)
1674            .then(|| {
1675                self.orchard()
1676                    .map(|k| OutgoingViewingKey::from(k.to_ovk(scope)))
1677            })
1678            .flatten()
1679        {
1680            return Some(ovk);
1681        };
1682
1683        #[cfg(feature = "sapling")]
1684        if let Some(ovk) = input_sources
1685            .contains(&PoolType::SAPLING)
1686            .then(|| {
1687                self.sapling()
1688                    .map(|k| OutgoingViewingKey::from(k.to_ovk(scope)))
1689            })
1690            .flatten()
1691        {
1692            return Some(ovk);
1693        }
1694
1695        #[cfg(feature = "transparent-inputs")]
1696        if let Some(ovk) = input_sources
1697            .contains(&PoolType::Transparent)
1698            .then(|| {
1699                self.p2pkh().map(|k| {
1700                    OutgoingViewingKey(match scope {
1701                        zip32::Scope::External => k.external_ovk().as_bytes(),
1702                        zip32::Scope::Internal => k.internal_ovk().as_bytes(),
1703                    })
1704                })
1705            })
1706            .flatten()
1707        {
1708            return Some(ovk);
1709        }
1710
1711        None
1712    }
1713}
1714
1715/// A [ZIP 316](https://zips.z.cash/zip-0316) unified incoming viewing key.
1716#[derive(Clone)]
1717pub struct UnifiedIncomingViewingKey {
1718    #[cfg(feature = "transparent-inputs")]
1719    transparent: Option<TransparentIvk>,
1720    #[cfg(feature = "sapling")]
1721    sapling: Option<::sapling::zip32::IncomingViewingKey>,
1722    #[cfg(feature = "orchard")]
1723    orchard: Option<orchard::keys::IncomingViewingKey>,
1724    unknown: Vec<(u32, Vec<u8>)>,
1725    /// The typecodes of the data items of the full viewing key that this key was derived from
1726    /// that could not be carried over, because this build cannot interpret them.
1727    ///
1728    /// These items are not part of this key's encoding, and take no part in equality or
1729    /// subsumption. They record only that the account has receiving capability that this key
1730    /// does not describe.
1731    unconverted_typecodes: Vec<u32>,
1732    expiry_height: Option<consensus::BlockHeight>,
1733    expiry_time: Option<u64>,
1734    unknown_metadata: Vec<(u32, Vec<u8>)>,
1735}
1736
1737impl core::fmt::Debug for UnifiedIncomingViewingKey {
1738    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1739        let mut d = f.debug_struct("UnifiedIncomingViewingKey");
1740        #[cfg(feature = "transparent-inputs")]
1741        d.field("p2pkh", &self.p2pkh().map(|_| "..."));
1742        #[cfg(feature = "transparent-inputs")]
1743        d.field("p2sh", &self.p2sh());
1744        #[cfg(feature = "sapling")]
1745        d.field("sapling", &self.sapling.as_ref().map(|_| "..."));
1746        #[cfg(feature = "orchard")]
1747        d.field("orchard", &self.orchard.as_ref().map(|_| "..."));
1748        d.field(
1749            "unknown_typecodes",
1750            &self
1751                .unknown
1752                .iter()
1753                .map(|(typecode, _)| *typecode)
1754                .collect::<Vec<_>>(),
1755        )
1756        .field("unconverted_typecodes", &self.unconverted_typecodes)
1757        .field("expiry_height", &self.expiry_height)
1758        .field("expiry_time", &self.expiry_time)
1759        .field(
1760            "unknown_metadata_typecodes",
1761            &self
1762                .unknown_metadata
1763                .iter()
1764                .map(|(typecode, _)| *typecode)
1765                .collect::<Vec<_>>(),
1766        )
1767        .finish()
1768    }
1769}
1770
1771impl PartialEq for UnifiedIncomingViewingKey {
1772    fn eq(&self, other: &Self) -> bool {
1773        self.subsumes(other) && other.subsumes(self)
1774    }
1775}
1776
1777impl Eq for UnifiedIncomingViewingKey {}
1778
1779impl UnifiedIncomingViewingKey {
1780    /// Construct a new unified incoming viewing key.
1781    ///
1782    /// This method is only available when the `test-dependencies` feature is enabled,
1783    /// as derivation from the UFVK or deserialization from the serialized form should
1784    /// be used instead.
1785    #[cfg(any(test, feature = "test-dependencies"))]
1786    pub fn new(
1787        #[cfg(feature = "transparent-inputs")] transparent: Option<
1788            crate::keys::transparent::ExternalIvk,
1789        >,
1790        #[cfg(feature = "sapling")] sapling: Option<::sapling::zip32::IncomingViewingKey>,
1791        #[cfg(feature = "orchard")] orchard: Option<orchard::keys::IncomingViewingKey>,
1792        unknown: Vec<(u32, Vec<u8>)>,
1793        expiry_height: Option<consensus::BlockHeight>,
1794        expiry_time: Option<u64>,
1795        unknown_metadata: Vec<(u32, Vec<u8>)>,
1796    ) -> UnifiedIncomingViewingKey {
1797        UnifiedIncomingViewingKey {
1798            #[cfg(feature = "transparent-inputs")]
1799            transparent: transparent.map(TransparentIvk::P2pkh),
1800            #[cfg(feature = "sapling")]
1801            sapling,
1802            #[cfg(feature = "orchard")]
1803            orchard,
1804            unknown,
1805            unconverted_typecodes: vec![],
1806            expiry_height,
1807            expiry_time,
1808            unknown_metadata,
1809        }
1810    }
1811
1812    /// Parses a `UnifiedIncomingViewingKey` from its [ZIP 316] string encoding at any
1813    /// revision.
1814    ///
1815    /// # Errors
1816    ///
1817    /// - [`UnifiedDecodingError::Parse`] if the string is not a valid UIVK.
1818    /// - [`UnifiedDecodingError::NetworkMismatch`] if the key is for a network other than
1819    ///   that of `params`.
1820    /// - [`UnifiedDecodingError::InvalidItem`] if an item's data is not a valid key of its
1821    ///   type.
1822    ///
1823    /// [ZIP 316]: https://zips.z.cash/zip-0316
1824    pub fn decode<P: consensus::Parameters>(
1825        params: &P,
1826        encoding: &str,
1827    ) -> Result<Self, UnifiedDecodingError> {
1828        let (actual, _revision, uivk) =
1829            unified::Uivk::decode(encoding).map_err(UnifiedDecodingError::Parse)?;
1830        let expected = params.network_type();
1831        if actual != expected {
1832            return Err(UnifiedDecodingError::NetworkMismatch { expected, actual });
1833        }
1834
1835        Self::from_container(&uivk).map_err(UnifiedDecodingError::InvalidItem)
1836    }
1837
1838    /// Constructs a `UnifiedIncomingViewingKey` from a parsed unified container.
1839    ///
1840    /// On error, returns the typecode of the first item whose data is not a valid key of
1841    /// its type.
1842    fn from_container(uivk: &unified::Uivk) -> Result<Self, Typecode> {
1843        #[cfg(feature = "orchard")]
1844        let mut orchard = None;
1845        #[cfg(feature = "sapling")]
1846        let mut sapling = None;
1847        #[cfg(feature = "transparent-inputs")]
1848        let mut transparent = None;
1849        let mut unknown = vec![];
1850        let mut expiry_height = None;
1851        let mut expiry_time = None;
1852        let mut unknown_metadata = vec![];
1853
1854        for item in uivk.items_as_parsed() {
1855            match item {
1856                Uitem::Data(unified::Ivk::Orchard(data)) => {
1857                    #[cfg(feature = "orchard")]
1858                    {
1859                        orchard = Some(
1860                            Option::from(orchard::keys::IncomingViewingKey::from_bytes(data))
1861                                .ok_or(Typecode::ORCHARD)?,
1862                        );
1863                    }
1864                    #[cfg(not(feature = "orchard"))]
1865                    unknown.push((u32::from(unified::Typecode::ORCHARD), data.to_vec()));
1866                }
1867                Uitem::Data(unified::Ivk::Sapling(data)) => {
1868                    #[cfg(feature = "sapling")]
1869                    {
1870                        sapling = Some(
1871                            Option::from(::sapling::zip32::IncomingViewingKey::from_bytes(data))
1872                                .ok_or(Typecode::SAPLING)?,
1873                        );
1874                    }
1875                    #[cfg(not(feature = "sapling"))]
1876                    unknown.push((u32::from(unified::Typecode::SAPLING), data.to_vec()));
1877                }
1878                Uitem::Data(unified::Ivk::P2pkh(data)) => {
1879                    #[cfg(feature = "transparent-inputs")]
1880                    {
1881                        transparent = Some(TransparentIvk::P2pkh(
1882                            crate::keys::transparent::ExternalIvk::deserialize(data)
1883                                .map_err(|_| Typecode::P2PKH)?,
1884                        ));
1885                    }
1886                    #[cfg(not(feature = "transparent-inputs"))]
1887                    unknown.push((u32::from(unified::Typecode::P2PKH), data.to_vec()));
1888                }
1889                Uitem::Data(unified::Ivk::P2sh(data)) => {
1890                    #[cfg(feature = "transparent-inputs")]
1891                    {
1892                        transparent = Some(TransparentIvk::P2sh(
1893                            P2shIncomingViewingKey::parse(data).map_err(|_| Typecode::P2SH)?,
1894                        ));
1895                    }
1896                    #[cfg(not(feature = "transparent-inputs"))]
1897                    unknown.push((u32::from(unified::Typecode::P2SH), data.to_vec()));
1898                }
1899                Uitem::Data(unified::Ivk::Unknown { typecode, data }) => {
1900                    unknown.push((*typecode, data.clone()));
1901                }
1902                Uitem::Metadata(MetadataItem::ExpiryHeight(h)) => {
1903                    expiry_height = Some(consensus::BlockHeight::from_u32(*h));
1904                }
1905                Uitem::Metadata(MetadataItem::ExpiryTime(t)) => {
1906                    expiry_time = Some(*t);
1907                }
1908                Uitem::Metadata(MetadataItem::Unknown { typecode, data }) => {
1909                    unknown_metadata.push((*typecode, data.clone()));
1910                }
1911            }
1912        }
1913
1914        Ok(Self {
1915            #[cfg(feature = "transparent-inputs")]
1916            transparent,
1917            #[cfg(feature = "sapling")]
1918            sapling,
1919            #[cfg(feature = "orchard")]
1920            orchard,
1921            unknown,
1922            // A parsed key keeps every item that it cannot interpret in `unknown`, and so
1923            // describes itself completely.
1924            unconverted_typecodes: vec![],
1925            expiry_height,
1926            expiry_time,
1927            unknown_metadata,
1928        })
1929    }
1930
1931    /// Returns the [ZIP 316] string encoding of this `UnifiedIncomingViewingKey` for the
1932    /// given network at the given revision.
1933    ///
1934    /// Returns [`UnifiedEncodingError::NotRepresentable`] if this key has no encoding at
1935    /// `revision`: [`Revision::R0`] cannot encode expiry metadata, a P2SH viewing key
1936    /// item, or a key whose only data items are transparent.
1937    ///
1938    /// [ZIP 316]: https://zips.z.cash/zip-0316
1939    pub fn encode_revision<P: consensus::Parameters>(
1940        &self,
1941        params: &P,
1942        revision: Revision,
1943    ) -> Result<String, UnifiedEncodingError> {
1944        self.render(revision)
1945            .map(|uivk| uivk.encode(&params.network_type()))
1946    }
1947
1948    /// Returns the [ZIP 316] string encoding of this `UnifiedIncomingViewingKey` for the
1949    /// given network at the most widely supported revision that can represent it:
1950    /// [`Revision::R0`] if possible, and [`Revision::R2`] otherwise. Use
1951    /// [`encode_revision`](Self::encode_revision) to encode at a specific revision.
1952    ///
1953    /// Returns [`UnifiedEncodingError::NotRepresentable`] if this key has no encoding at
1954    /// either revision.
1955    ///
1956    /// [ZIP 316]: https://zips.z.cash/zip-0316
1957    pub fn encode<P: consensus::Parameters>(
1958        &self,
1959        params: &P,
1960    ) -> Result<String, UnifiedEncodingError> {
1961        self.encode_revision(params, Revision::R0)
1962            .or_else(|_| self.encode_revision(params, Revision::R2))
1963    }
1964
1965    /// Converts this unified incoming viewing key to a unified container at the given
1966    /// revision.
1967    fn render(&self, revision: Revision) -> Result<unified::Uivk, UnifiedEncodingError> {
1968        let data_items = core::iter::empty().chain(self.unknown.iter().map(|(typecode, data)| {
1969            unified::Ivk::Unknown {
1970                typecode: *typecode,
1971                data: data.clone(),
1972            }
1973        }));
1974        #[cfg(feature = "orchard")]
1975        let data_items = data_items.chain(
1976            self.orchard
1977                .as_ref()
1978                .map(|ivk| ivk.to_bytes())
1979                .map(unified::Ivk::Orchard),
1980        );
1981        #[cfg(feature = "sapling")]
1982        let data_items = data_items.chain(
1983            self.sapling
1984                .as_ref()
1985                .map(|divk| divk.to_bytes())
1986                .map(unified::Ivk::Sapling),
1987        );
1988        #[cfg(feature = "transparent-inputs")]
1989        let data_items = data_items.chain(self.transparent.as_ref().map(|t| match t {
1990            TransparentIvk::P2pkh(k) => {
1991                unified::Ivk::P2pkh(k.serialize().try_into().expect("key is 65 bytes"))
1992            }
1993            TransparentIvk::P2sh(p) => unified::Ivk::P2sh(p.to_bytes()),
1994        }));
1995
1996        let meta_items = core::iter::empty()
1997            .chain(self.unknown_metadata.iter().map(|(typecode, data)| {
1998                unified::MetadataItem::Unknown {
1999                    typecode: *typecode,
2000                    data: data.clone(),
2001                }
2002            }))
2003            .chain(
2004                self.expiry_height
2005                    .map(|h| unified::MetadataItem::ExpiryHeight(u32::from(h))),
2006            )
2007            .chain(self.expiry_time.map(unified::MetadataItem::ExpiryTime));
2008
2009        unified::Uivk::try_from_items(
2010            revision,
2011            data_items
2012                .map(Uitem::Data)
2013                .chain(meta_items.map(Uitem::Metadata))
2014                .collect(),
2015        )
2016        .map_err(|cause| UnifiedEncodingError::NotRepresentable { revision, cause })
2017    }
2018
2019    /// Returns whether this uivk has a transparent key item.
2020    ///
2021    /// This method is available irrespective of whether the `transparent-inputs` feature flag is enabled.
2022    pub fn has_transparent(&self) -> bool {
2023        #[cfg(not(feature = "transparent-inputs"))]
2024        return false;
2025        #[cfg(feature = "transparent-inputs")]
2026        return self.transparent.is_some();
2027    }
2028
2029    /// Returns the transparent external IVK, if present.
2030    #[cfg(feature = "transparent-inputs")]
2031    #[deprecated(note = "Use `UnifiedIncomingViewingKey::p2pkh` instead.")]
2032    pub fn transparent(&self) -> Option<&crate::keys::transparent::ExternalIvk> {
2033        self.p2pkh()
2034    }
2035
2036    /// Returns the transparent external IVK, if present.
2037    ///
2038    /// Returns `None` if the key has no transparent component, or carries a P2SH viewing
2039    /// key item instead; the two are mutually exclusive.
2040    #[cfg(feature = "transparent-inputs")]
2041    pub fn p2pkh(&self) -> Option<&crate::keys::transparent::ExternalIvk> {
2042        match self.transparent.as_ref() {
2043            Some(TransparentIvk::P2pkh(k)) => Some(k),
2044            Some(TransparentIvk::P2sh(_)) | None => None,
2045        }
2046    }
2047
2048    /// Returns the P2SH viewing key item of this key, if present.
2049    ///
2050    /// Returns `None` if the key has no transparent component, or carries a P2PKH
2051    /// viewing key instead; the two are mutually exclusive.
2052    #[cfg(feature = "transparent-inputs")]
2053    pub fn p2sh(&self) -> Option<&P2shIncomingViewingKey> {
2054        match self.transparent.as_ref() {
2055            Some(TransparentIvk::P2sh(p)) => Some(p),
2056            Some(TransparentIvk::P2pkh(_)) | None => None,
2057        }
2058    }
2059
2060    /// Returns whether this uivk has a Sapling key item.
2061    ///
2062    /// This method is available irrespective of whether the `sapling` feature flag is enabled.
2063    pub fn has_sapling(&self) -> bool {
2064        #[cfg(not(feature = "sapling"))]
2065        return false;
2066        #[cfg(feature = "sapling")]
2067        return self.sapling.is_some();
2068    }
2069
2070    /// Returns the Sapling IVK, if present.
2071    #[cfg(feature = "sapling")]
2072    pub fn sapling(&self) -> &Option<::sapling::zip32::IncomingViewingKey> {
2073        &self.sapling
2074    }
2075
2076    /// Returns whether this uivk has an Orchard key item.
2077    ///
2078    /// This method is available irrespective of whether the `orchard` feature flag is enabled.
2079    pub fn has_orchard(&self) -> bool {
2080        #[cfg(not(feature = "orchard"))]
2081        return false;
2082        #[cfg(feature = "orchard")]
2083        return self.orchard.is_some();
2084    }
2085
2086    /// Returns the Orchard IVK, if present.
2087    #[cfg(feature = "orchard")]
2088    pub fn orchard(&self) -> &Option<orchard::keys::IncomingViewingKey> {
2089        &self.orchard
2090    }
2091
2092    /// Returns the expiry height metadata for this key, if present.
2093    pub fn expiry_height(&self) -> Option<consensus::BlockHeight> {
2094        self.expiry_height
2095    }
2096
2097    /// Returns the expiry time metadata for this key, if present.
2098    pub fn expiry_time(&self) -> Option<u64> {
2099        self.expiry_time
2100    }
2101
2102    /// Returns `true` if this UIVK subsumes `other`: every IVK item present in `other`
2103    /// has a matching item in `self`. This key may have additional items representing
2104    /// capabilities not present in `other`.
2105    ///
2106    /// For unknown items, exact equality of (typecode, data) is required. Future
2107    /// revisions may apply more specific semantics for known metadata typecodes.
2108    pub fn subsumes(&self, other: &UnifiedIncomingViewingKey) -> bool {
2109        #[cfg(feature = "orchard")]
2110        match (other.orchard(), &self.orchard) {
2111            (Some(e), Some(n)) if e != n => {
2112                return false;
2113            }
2114            (Some(_), None) => return false,
2115            _ => {}
2116        }
2117
2118        #[cfg(feature = "sapling")]
2119        match (other.sapling(), &self.sapling) {
2120            (Some(e), Some(n)) if e != n => {
2121                return false;
2122            }
2123            (Some(_), None) => return false,
2124            _ => {}
2125        }
2126
2127        #[cfg(feature = "transparent-inputs")]
2128        match (&other.transparent, &self.transparent) {
2129            (Some(e), Some(n)) if e != n => {
2130                return false;
2131            }
2132            (Some(_), None) => return false,
2133            _ => {}
2134        }
2135
2136        // Every unknown item in `other` must have an identical entry in `self`.
2137        for item in &other.unknown {
2138            if !self.unknown.contains(item) {
2139                return false;
2140            }
2141        }
2142
2143        true
2144    }
2145
2146    /// Attempts to derive the Unified Address for the given diversifier index and receiver types.
2147    ///
2148    /// Returns an error if the this key does not produce a valid receiver for a required receiver
2149    /// type at the given diversifier index.
2150    pub fn address(
2151        &self,
2152        _j: DiversifierIndex,
2153        request: UnifiedAddressRequest,
2154    ) -> Result<UnifiedAddress, AddressGenerationError> {
2155        let request = self
2156            .receiver_requirements(request)
2157            .map_err(|_| AddressGenerationError::NoSatisfiableReceiver)?;
2158
2159        // If we need to generate a transparent receiver, check that the user has not
2160        // specified an invalid transparent child index, from which we can never search to
2161        // find a valid index.
2162        #[cfg(feature = "transparent-inputs")]
2163        if request.p2pkh == ReceiverRequirement::Require
2164            && self.transparent.is_some()
2165            && to_transparent_child_index(_j).is_none()
2166        {
2167            return Err(AddressGenerationError::InvalidTransparentChildIndex(_j));
2168        }
2169
2170        #[cfg(feature = "orchard")]
2171        let mut orchard = None;
2172        if request.orchard != Omit {
2173            #[cfg(not(feature = "orchard"))]
2174            if request.orchard == Require {
2175                return Err(AddressGenerationError::ReceiverTypeNotSupported(
2176                    Typecode::ORCHARD,
2177                ));
2178            }
2179
2180            #[cfg(feature = "orchard")]
2181            if let Some(oivk) = &self.orchard {
2182                let orchard_j = orchard::keys::DiversifierIndex::from(*_j.as_bytes());
2183                orchard = Some(oivk.address_at(orchard_j))
2184            } else if request.orchard == Require {
2185                return Err(AddressGenerationError::KeyNotAvailable(Typecode::ORCHARD));
2186            }
2187        }
2188
2189        #[cfg(feature = "sapling")]
2190        let mut sapling = None;
2191        if request.sapling != Omit {
2192            #[cfg(not(feature = "sapling"))]
2193            if request.sapling == Require {
2194                return Err(AddressGenerationError::ReceiverTypeNotSupported(
2195                    Typecode::SAPLING,
2196                ));
2197            }
2198
2199            #[cfg(feature = "sapling")]
2200            if let Some(divk) = &self.sapling {
2201                // If a Sapling receiver type is requested, we must be able to construct an
2202                // address; if we're unable to do so, then no Unified Address exists at this
2203                // diversifier and we use `?` to early-return from this method.
2204                sapling = match (request.sapling, divk.address_at(_j)) {
2205                    (Require | Allow, Some(addr)) => Ok(Some(addr)),
2206                    (Require, None) => {
2207                        Err(AddressGenerationError::InvalidSaplingDiversifierIndex(_j))
2208                    }
2209                    _ => Ok(None),
2210                }?;
2211            } else if request.sapling == Require {
2212                return Err(AddressGenerationError::KeyNotAvailable(Typecode::SAPLING));
2213            }
2214        }
2215
2216        #[cfg(feature = "transparent-inputs")]
2217        let mut transparent = None;
2218        if request.p2pkh != Omit {
2219            #[cfg(not(feature = "transparent-inputs"))]
2220            if request.p2pkh == Require {
2221                return Err(AddressGenerationError::ReceiverTypeNotSupported(
2222                    Typecode::P2PKH,
2223                ));
2224            }
2225
2226            #[cfg(feature = "transparent-inputs")]
2227            if let Some(tivk) = self.transparent.as_ref() {
2228                // If a transparent receiver type is requested, we must be able to construct an
2229                // address; if we're unable to do so, then no Unified Address exists at this
2230                // diversifier.
2231                let j = to_transparent_child_index(_j);
2232                let derived = match tivk {
2233                    TransparentIvk::P2pkh(k) => j.and_then(|j| k.derive_address(j).ok()),
2234                    TransparentIvk::P2sh(p) => j.map(|j| p.derive_address(j).0),
2235                };
2236
2237                transparent = match (request.p2pkh, derived) {
2238                    (Require | Allow, Some(addr)) => Ok(Some(addr)),
2239                    (Require, None) => {
2240                        Err(AddressGenerationError::InvalidTransparentChildIndex(_j))
2241                    }
2242                    _ => Ok(None),
2243                }?;
2244            } else if request.p2pkh == Require {
2245                return Err(AddressGenerationError::KeyNotAvailable(Typecode::P2PKH));
2246            }
2247        }
2248        #[cfg(not(feature = "transparent-inputs"))]
2249        let transparent = None;
2250
2251        UnifiedAddress::from_receivers(
2252            #[cfg(feature = "orchard")]
2253            orchard,
2254            #[cfg(feature = "sapling")]
2255            sapling,
2256            transparent,
2257            self.expiry_height,
2258            self.expiry_time,
2259        )
2260        .ok_or(AddressGenerationError::NoSatisfiableReceiver)
2261    }
2262
2263    /// Searches the diversifier space starting at diversifier index `j` for one which will produce
2264    /// a valid address that conforms to the provided request, and returns that Unified Address
2265    /// along with the index at which the valid diversifier was found.
2266    ///
2267    /// If [`None`] is specified for the `request` parameter, a default request that [`Require`]s a
2268    /// receiver be present for each key item enabled by the feature flags in use will be used to
2269    /// search the diversifier space.
2270    ///
2271    /// Returns an `Err(AddressGenerationError)` if no valid diversifier exists or if the features
2272    /// required to satisfy the unified address request are not enabled.
2273    ///
2274    /// [`Require`]: ReceiverRequirement::Require
2275    #[allow(unused_mut)]
2276    pub fn find_address(
2277        &self,
2278        mut j: DiversifierIndex,
2279        request: UnifiedAddressRequest,
2280    ) -> Result<(UnifiedAddress, DiversifierIndex), AddressGenerationError> {
2281        // Only a Sapling receiver can reject a diversifier index, so only that configuration
2282        // has to search.
2283        #[cfg(feature = "sapling")]
2284        loop {
2285            match self.address(j, request) {
2286                Ok(ua) => return Ok((ua, j)),
2287                Err(AddressGenerationError::InvalidSaplingDiversifierIndex(_)) => {
2288                    if j.increment().is_err() {
2289                        return Err(AddressGenerationError::DiversifierSpaceExhausted);
2290                    }
2291                }
2292                Err(other) => return Err(other),
2293            }
2294        }
2295
2296        #[cfg(not(feature = "sapling"))]
2297        self.address(j, request).map(|ua| (ua, j))
2298    }
2299
2300    /// Find the Unified Address corresponding to the smallest valid diversifier index, along with
2301    /// that index.
2302    ///
2303    /// Returns an error if the this key does not produce a valid receiver for a required receiver
2304    /// type at any diversifier index.
2305    pub fn default_address(
2306        &self,
2307        request: UnifiedAddressRequest,
2308    ) -> Result<(UnifiedAddress, DiversifierIndex), AddressGenerationError> {
2309        self.find_address(DiversifierIndex::new(), request)
2310    }
2311
2312    /// Attempts to recover a diversifier index for each of the receivers of the given
2313    /// [`UnifiedAddress`].
2314    ///
2315    /// Returns the empty set if no shielded receiver of `ua` can be attributed to this key.
2316    /// Transparent receivers are not considered here, as recovering a diversifier index from a
2317    /// transparent receiver alone is not possible without additional context.
2318    pub fn decrypt_diversifiers(&self, ua: &UnifiedAddress) -> BTreeSet<DiversifierIndex> {
2319        #[cfg(not(any(feature = "sapling", feature = "orchard")))]
2320        let _ = ua;
2321
2322        #[cfg(not(feature = "sapling"))]
2323        let sapling_di: Option<DiversifierIndex> = None;
2324
2325        #[cfg(feature = "sapling")]
2326        let sapling_di = ua
2327            .sapling()
2328            .zip(self.sapling().as_ref())
2329            .and_then(|(receiver, ivk)| ivk.decrypt_diversifier(receiver));
2330
2331        #[cfg(not(feature = "orchard"))]
2332        let orchard_di: Option<DiversifierIndex> = None;
2333
2334        #[cfg(feature = "orchard")]
2335        let orchard_di = ua
2336            .orchard()
2337            .zip(self.orchard().as_ref())
2338            .and_then(|(receiver, ivk)| ivk.diversifier_index(receiver));
2339
2340        sapling_di.into_iter().chain(orchard_di).collect()
2341    }
2342
2343    /// Convenience method for choosing a set of receiver requirements based upon the given unified
2344    /// address request and the available items of this key.
2345    ///
2346    /// Returns an error if the provided request cannot be satisfied in address generation using
2347    /// this key.
2348    pub fn receiver_requirements(
2349        &self,
2350        request: UnifiedAddressRequest,
2351    ) -> Result<ReceiverRequirements, AddressGenerationError> {
2352        match request {
2353            UnifiedAddressRequest::AllAvailableKeys => self
2354                .to_receiver_requirements()
2355                .map_err(|_| AddressGenerationError::NoSatisfiableReceiver),
2356            UnifiedAddressRequest::Custom(req) => {
2357                if req.orchard() == Require && !self.has_orchard() {
2358                    return Err(AddressGenerationError::ReceiverTypeNotSupported(
2359                        Typecode::ORCHARD,
2360                    ));
2361                }
2362
2363                if req.sapling() == Require && !self.has_sapling() {
2364                    return Err(AddressGenerationError::ReceiverTypeNotSupported(
2365                        Typecode::SAPLING,
2366                    ));
2367                }
2368
2369                if req.p2pkh() == Require && !self.has_transparent() {
2370                    return Err(AddressGenerationError::ReceiverTypeNotSupported(
2371                        Typecode::P2PKH,
2372                    ));
2373                }
2374
2375                Ok(req)
2376            }
2377        }
2378    }
2379
2380    /// Returns whether this key has a data item that this build cannot interpret.
2381    ///
2382    /// An item of a pool whose feature is disabled and an item of a pool that postdates this
2383    /// crate are both uninterpretable, and either may be a shielded receiver.
2384    fn has_uninterpretable_data_item(&self) -> bool {
2385        !self.unknown.is_empty() || !self.unconverted_typecodes.is_empty()
2386    }
2387
2388    /// Constructs the [`ReceiverRequirements`] that requires a receiver for each data item of this UIVK.
2389    ///
2390    /// A key that has nothing but a transparent item describes a transparent-only account, and
2391    /// yields [`ReceiverRequirements::TRANSPARENT_ONLY`]; addresses generated from it are
2392    /// representable as [ZIP 316] Revision 2 transparent-including (`tu`) unified addresses.
2393    ///
2394    /// Returns an error if this key has no item for which a receiver can be derived, and also
2395    /// if the only receiver it can derive is transparent but the key has a data item that this
2396    /// build cannot interpret. A metadata item never prevents address generation.
2397    ///
2398    /// [ZIP 316]: https://zips.z.cash/zip-0316
2399    pub fn to_receiver_requirements(
2400        &self,
2401    ) -> Result<ReceiverRequirements, ReceiverRequirementError> {
2402        let orchard = if self.has_orchard() { Require } else { Omit };
2403        let sapling = if self.has_sapling() { Require } else { Omit };
2404        let p2pkh = if self.has_transparent() {
2405            Require
2406        } else {
2407            Omit
2408        };
2409
2410        match (orchard, sapling, p2pkh) {
2411            // Omitting the shielded receivers is the honest description of a key that has
2412            // nothing but a transparent item, so `ReceiverRequirements::new`'s
2413            // shielded-receiver requirement, which guards against callers discarding a key's
2414            // shielded capability, does not apply here.
2415            //
2416            // `TRANSPARENT_ONLY` silently omits receivers, so it is sound only for a key that
2417            // provably has nothing but transparent. A data item that this build cannot
2418            // interpret defeats that proof: the item may be a shielded receiver, and a
2419            // transparent-only address would discard the recipient's shielded receiving
2420            // capability. Fall through instead, and let the ordinary error surface.
2421            (Omit, Omit, Require) if !self.has_uninterpretable_data_item() => {
2422                Ok(ReceiverRequirements::TRANSPARENT_ONLY)
2423            }
2424            _ => ReceiverRequirements::new(orchard, sapling, p2pkh),
2425        }
2426    }
2427
2428    /// Returns the default external transparent address using the transparent account pubkey.
2429    ///
2430    /// See [`ExternalIvk::default_address`] for more information.
2431    ///
2432    /// [`ExternalIvk::default_address`]: crate::keys::transparent::ExternalIvk::default_address
2433    #[cfg(all(
2434        feature = "transparent-inputs",
2435        any(test, feature = "test-dependencies")
2436    ))]
2437    pub fn default_transparent_address(
2438        &self,
2439    ) -> Option<(TransparentAddress, NonHardenedChildIndex)> {
2440        self.p2pkh().map(|k| k.default_address())
2441    }
2442}
2443
2444#[cfg(any(test, feature = "test-dependencies"))]
2445pub mod testing {
2446    use proptest::prelude::*;
2447
2448    use super::UnifiedSpendingKey;
2449    use zcash_protocol::consensus::Network;
2450    use zip32::AccountId;
2451
2452    pub fn arb_unified_spending_key(params: Network) -> impl Strategy<Value = UnifiedSpendingKey> {
2453        prop::array::uniform32(prop::num::u8::ANY).prop_flat_map(move |seed| {
2454            prop::num::u32::ANY
2455                .prop_map(move |account| {
2456                    UnifiedSpendingKey::from_seed(
2457                        &params,
2458                        &seed,
2459                        AccountId::try_from(account & ((1 << 31) - 1)).unwrap(),
2460                    )
2461                })
2462                .prop_filter("seeds must generate valid USKs", |v| v.is_ok())
2463                .prop_map(|v| v.unwrap())
2464        })
2465    }
2466
2467    /// Generates a [`UnifiedSpendingKey`] that holds a random non-empty subset of the
2468    /// protocol keys that the enabled features support.
2469    pub fn arb_partial_unified_spending_key(
2470        params: Network,
2471    ) -> impl Strategy<Value = UnifiedSpendingKey> {
2472        (
2473            arb_unified_spending_key(params),
2474            prop::bool::ANY,
2475            prop::bool::ANY,
2476            prop::bool::ANY,
2477        )
2478            .prop_filter_map(
2479                "the key must hold at least one component",
2480                |(usk, _keep_transparent, _keep_sapling, _keep_orchard)| {
2481                    UnifiedSpendingKey::from_parts(
2482                        #[cfg(feature = "transparent-inputs")]
2483                        usk.transparent().filter(|_| _keep_transparent).cloned(),
2484                        #[cfg(feature = "sapling")]
2485                        usk.sapling().filter(|_| _keep_sapling).cloned(),
2486                        #[cfg(feature = "orchard")]
2487                        usk.orchard().filter(|_| _keep_orchard).cloned(),
2488                    )
2489                    .ok()
2490                },
2491            )
2492    }
2493}
2494
2495#[cfg(test)]
2496mod tests {
2497    use proptest::prelude::proptest;
2498    use secp256k1::{PublicKey, SecretKey};
2499    use zcash_encoding::CompactSize;
2500
2501    #[cfg(all(
2502        feature = "transparent-inputs",
2503        any(feature = "orchard", feature = "sapling")
2504    ))]
2505    use {
2506        super::ReceiverRequirement::*,
2507        crate::{address::Address, keys::UnifiedAddressRequest},
2508        zcash_address::test_vectors,
2509        zip32::DiversifierIndex,
2510    };
2511
2512    #[cfg(feature = "transparent-inputs")]
2513    use {
2514        crate::{
2515            encoding::AddressCodec,
2516            keys::transparent::{AccountPrivKey, IncomingViewingKey, NonHardenedChildIndex},
2517        },
2518        alloc::{string::ToString, vec::Vec},
2519        zcash_address::unified::Revision,
2520    };
2521
2522    use zcash_protocol::consensus::MAIN_NETWORK;
2523    use zip32::AccountId;
2524
2525    #[cfg(any(feature = "sapling", feature = "orchard"))]
2526    use super::{UnifiedFullViewingKey, UnifiedIncomingViewingKey};
2527
2528    #[cfg(all(
2529        feature = "orchard",
2530        feature = "sapling",
2531        feature = "transparent-inputs"
2532    ))]
2533    use {
2534        crate::{
2535            address::UnifiedAddress,
2536            encoding::{UnifiedDecodingError, UnifiedEncodingError},
2537        },
2538        assert_matches::assert_matches,
2539        zcash_address::unified::{self, Encoding},
2540        zcash_protocol::consensus::{NetworkType, TEST_NETWORK},
2541    };
2542
2543    #[cfg(feature = "orchard")]
2544    use zip32::Scope;
2545
2546    #[cfg(feature = "unstable")]
2547    use secrecy::ExposeSecret;
2548
2549    #[cfg(feature = "zeroize")]
2550    use zeroize::ZeroizeOnDrop;
2551
2552    #[cfg(feature = "sapling")]
2553    use super::sapling;
2554
2555    use super::{DerivationError, UnifiedSpendingKey};
2556
2557    #[cfg(feature = "unstable")]
2558    use {
2559        super::{DecodingError, Era, testing::arb_partial_unified_spending_key},
2560        zcash_address::unified::Typecode,
2561        zcash_protocol::consensus::BranchId,
2562    };
2563
2564    #[cfg(all(feature = "orchard", feature = "unstable"))]
2565    use subtle::ConstantTimeEq;
2566
2567    #[cfg(feature = "transparent-inputs")]
2568    fn seed() -> Vec<u8> {
2569        let seed_hex = "6ef5f84def6f4b9d38f466586a8380a38593bd47c8cda77f091856176da47f26b5bd1c8d097486e5635df5a66e820d28e1d73346f499801c86228d43f390304f";
2570        hex::decode(seed_hex).unwrap()
2571    }
2572
2573    #[test]
2574    #[should_panic]
2575    #[cfg(feature = "sapling")]
2576    fn spending_key_panics_on_short_seed() {
2577        let _ = sapling::spending_key(&[0; 31][..], 0, AccountId::ZERO);
2578    }
2579
2580    #[cfg(feature = "transparent-inputs")]
2581    #[test]
2582    fn pk_to_taddr() {
2583        let taddr = AccountPrivKey::from_seed(&MAIN_NETWORK, &seed(), AccountId::ZERO)
2584            .unwrap()
2585            .to_account_pubkey()
2586            .derive_external_ivk()
2587            .unwrap()
2588            .derive_address(NonHardenedChildIndex::ZERO)
2589            .unwrap()
2590            .encode(&MAIN_NETWORK);
2591        assert_eq!(taddr, "t1PKtYdJJHhc3Pxowmznkg7vdTwnhEsCvR4".to_string());
2592    }
2593
2594    #[test]
2595    #[cfg(all(
2596        feature = "orchard",
2597        feature = "sapling",
2598        feature = "transparent-inputs"
2599    ))]
2600    fn viewing_key_decode_reports_structured_errors() {
2601        use super::test_vectors::unified_viewing_keys_r2::TEST_VECTORS;
2602
2603        let tv = &TEST_VECTORS[0];
2604        let mismatch = Err(UnifiedDecodingError::NetworkMismatch {
2605            expected: NetworkType::Test,
2606            actual: NetworkType::Main,
2607        });
2608        assert_eq!(
2609            UnifiedFullViewingKey::decode(&TEST_NETWORK, tv.unified_fvk).map(|_| ()),
2610            mismatch
2611        );
2612        assert_eq!(
2613            UnifiedIncomingViewingKey::decode(&TEST_NETWORK, tv.unified_ivk).map(|_| ()),
2614            mismatch
2615        );
2616
2617        assert_matches!(
2618            UnifiedFullViewingKey::decode(&MAIN_NETWORK, "not a key"),
2619            Err(UnifiedDecodingError::Parse(_))
2620        );
2621        assert_matches!(
2622            UnifiedIncomingViewingKey::decode(&MAIN_NETWORK, "not a key"),
2623            Err(UnifiedDecodingError::Parse(_))
2624        );
2625    }
2626
2627    /// Re-encoding a key at another revision yields an equivalent key, and a key that lacks
2628    /// one of another key's items is not equivalent to it.
2629    #[test]
2630    #[cfg(all(
2631        feature = "orchard",
2632        feature = "sapling",
2633        feature = "transparent-inputs"
2634    ))]
2635    fn ufvk_equivalence_is_mutual_subsumption() {
2636        let usk = UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &[0; 32], AccountId::ZERO)
2637            .expect("the seed yields a valid spending key");
2638        let ufvk = usk.to_unified_full_viewing_key();
2639
2640        for revision in [Revision::R0, Revision::R2] {
2641            let reencoded = ufvk.encode_revision(&MAIN_NETWORK, revision).unwrap();
2642            let decoded = UnifiedFullViewingKey::decode(&MAIN_NETWORK, &reencoded).unwrap();
2643            assert!(decoded.is_equivalent_to(&ufvk));
2644            assert!(ufvk.is_equivalent_to(&decoded));
2645        }
2646
2647        let sapling_only = UnifiedFullViewingKey::new(None, ufvk.sapling().cloned(), None).unwrap();
2648        assert!(ufvk.subsumes_ufvk(&sapling_only));
2649        assert!(!ufvk.is_equivalent_to(&sapling_only));
2650        assert!(!sapling_only.is_equivalent_to(&ufvk));
2651    }
2652
2653    /// A viewing key has a Revision 0 encoding exactly when it has a shielded item and no
2654    /// item that Revision 0 does not define (expiry metadata or a P2SH viewing key item).
2655    /// That encoding decodes to the same key, and is the compatible encoding; otherwise
2656    /// the compatible encoding is the Revision 2 encoding.
2657    #[test]
2658    #[cfg(all(
2659        feature = "orchard",
2660        feature = "sapling",
2661        feature = "transparent-inputs"
2662    ))]
2663    fn viewing_keys_encode_at_r0_iff_representable() {
2664        use super::test_vectors::unified_viewing_keys_r2::TEST_VECTORS;
2665
2666        let mut representable = 0;
2667        let mut unrepresentable = 0;
2668        for tv in TEST_VECTORS {
2669            let r0_representable = tv.expiry_height.is_none()
2670                && tv.expiry_time.is_none()
2671                && tv.p2sh_fvk_bytes.is_none()
2672                && (tv.sapling_fvk_bytes.is_some() || tv.orchard_fvk_bytes.is_some());
2673
2674            let ufvk = UnifiedFullViewingKey::decode(&MAIN_NETWORK, tv.unified_fvk).unwrap();
2675            let uivk = UnifiedIncomingViewingKey::decode(&MAIN_NETWORK, tv.unified_ivk).unwrap();
2676            let ufvk_r0 = ufvk.encode_revision(&MAIN_NETWORK, Revision::R0);
2677            let uivk_r0 = uivk.encode_revision(&MAIN_NETWORK, Revision::R0);
2678            let ufvk_compatible = ufvk.encode(&MAIN_NETWORK).unwrap();
2679            let uivk_compatible = uivk.encode(&MAIN_NETWORK).unwrap();
2680
2681            if r0_representable {
2682                representable += 1;
2683
2684                let ufvk_r0 = ufvk_r0.unwrap();
2685                assert_eq!(ufvk_compatible, ufvk_r0);
2686                assert!(
2687                    ufvk_r0
2688                        .starts_with(zcash_address::constants::hrp_unified_fvk(NetworkType::Main))
2689                );
2690                assert_eq!(
2691                    UnifiedFullViewingKey::decode(&MAIN_NETWORK, &ufvk_r0)
2692                        .unwrap()
2693                        .encode_revision(&MAIN_NETWORK, Revision::R2)
2694                        .as_deref(),
2695                    Ok(tv.unified_fvk),
2696                );
2697
2698                let uivk_r0 = uivk_r0.unwrap();
2699                assert_eq!(uivk_compatible, uivk_r0);
2700                assert!(
2701                    uivk_r0
2702                        .starts_with(zcash_address::constants::hrp_unified_ivk(NetworkType::Main))
2703                );
2704                assert_eq!(
2705                    UnifiedIncomingViewingKey::decode(&MAIN_NETWORK, &uivk_r0)
2706                        .unwrap()
2707                        .encode_revision(&MAIN_NETWORK, Revision::R2)
2708                        .as_deref(),
2709                    Ok(tv.unified_ivk),
2710                );
2711            } else {
2712                unrepresentable += 1;
2713                assert_eq!(ufvk_compatible, tv.unified_fvk);
2714                assert_eq!(uivk_compatible, tv.unified_ivk);
2715                assert_matches!(
2716                    ufvk_r0,
2717                    Err(UnifiedEncodingError::NotRepresentable {
2718                        revision: Revision::R0,
2719                        ..
2720                    })
2721                );
2722                assert_matches!(
2723                    uivk_r0,
2724                    Err(UnifiedEncodingError::NotRepresentable {
2725                        revision: Revision::R0,
2726                        ..
2727                    })
2728                );
2729            }
2730        }
2731        assert!(representable > 0 && unrepresentable > 0);
2732    }
2733
2734    /// Tests UFVK encoding round-trip and verification against R2 test vectors from
2735    /// https://github.com/zcash/zcash-test-vectors/blob/667c92954acd7defc6e60e25b022fedf8831dfb3/test-vectors/rust/unified_viewing_keys_r2.rs
2736    #[test]
2737    #[cfg(all(
2738        feature = "orchard",
2739        feature = "sapling",
2740        feature = "transparent-inputs"
2741    ))]
2742    fn ufvk_round_trip() {
2743        use super::test_vectors::unified_viewing_keys_r2::TEST_VECTORS;
2744
2745        for tv in TEST_VECTORS {
2746            let ufvk =
2747                UnifiedFullViewingKey::decode(&MAIN_NETWORK, tv.unified_fvk).unwrap_or_else(|e| {
2748                    panic!("Failed to decode UFVK for account {}: {e}", tv.account)
2749                });
2750
2751            let reencoded = ufvk.encode_revision(&MAIN_NETWORK, Revision::R2);
2752            assert_eq!(
2753                reencoded.as_deref(),
2754                Ok(tv.unified_fvk),
2755                "UFVK round-trip failed for account {}",
2756                tv.account
2757            );
2758
2759            assert_eq!(
2760                ufvk.expiry_height(),
2761                tv.expiry_height
2762                    .map(zcash_protocol::consensus::BlockHeight::from_u32),
2763                "expiry height mismatch for account {}",
2764                tv.account
2765            );
2766            assert_eq!(
2767                ufvk.expiry_time(),
2768                tv.expiry_time,
2769                "expiry time mismatch for account {}",
2770                tv.account
2771            );
2772
2773            // Verify key data matches the test vector bytes.
2774            if let Some(ref expected) = tv.t_p2pkh_fvk_bytes {
2775                let actual = ufvk
2776                    .p2pkh()
2777                    .expect("transparent key present in test vector")
2778                    .serialize();
2779                assert_eq!(
2780                    &actual[..],
2781                    &expected[..],
2782                    "transparent FVK mismatch for account {}",
2783                    tv.account
2784                );
2785            }
2786
2787            if let Some(ref expected) = tv.sapling_fvk_bytes {
2788                let actual = ufvk
2789                    .sapling()
2790                    .expect("sapling key present in test vector")
2791                    .to_bytes();
2792                assert_eq!(
2793                    &actual[..],
2794                    &expected[..],
2795                    "sapling FVK mismatch for account {}",
2796                    tv.account
2797                );
2798            }
2799
2800            if let Some(ref expected) = tv.orchard_fvk_bytes {
2801                let actual = ufvk
2802                    .orchard()
2803                    .expect("orchard key present in test vector")
2804                    .to_bytes();
2805                assert_eq!(
2806                    &actual[..],
2807                    &expected[..],
2808                    "orchard FVK mismatch for account {}",
2809                    tv.account
2810                );
2811            }
2812
2813            assert_eq!(
2814                ufvk.p2sh().map(|p| p.to_bytes()).as_deref(),
2815                tv.p2sh_fvk_bytes,
2816                "P2SH FVK item mismatch for account {}",
2817                tv.account
2818            );
2819
2820            // The UIVK form of the P2SH item derived from the UFVK must match the
2821            // vector's UIVK item.
2822            let derived_uivk = ufvk.to_unified_incoming_viewing_key();
2823            assert_eq!(
2824                derived_uivk.p2sh().map(|p| p.to_bytes()).as_deref(),
2825                tv.p2sh_ivk_bytes,
2826                "derived P2SH IVK item mismatch for account {}",
2827                tv.account
2828            );
2829        }
2830    }
2831
2832    #[test]
2833    #[cfg(all(
2834        feature = "transparent-inputs",
2835        any(feature = "orchard", feature = "sapling")
2836    ))]
2837    fn ufvk_derivation() {
2838        for tv in test_vectors::UNIFIED {
2839            let usk = UnifiedSpendingKey::from_seed(
2840                &MAIN_NETWORK,
2841                &tv.root_seed,
2842                AccountId::try_from(tv.account).unwrap(),
2843            )
2844            .expect("seed produced a valid unified spending key");
2845
2846            let d_idx = DiversifierIndex::from(tv.diversifier_index);
2847            let ufvk = usk.to_unified_full_viewing_key();
2848
2849            // The test vectors contain some diversifier indices that do not generate
2850            // valid Sapling addresses, so skip those.
2851            #[cfg(feature = "sapling")]
2852            if ufvk.sapling().unwrap().address(d_idx).is_none() {
2853                continue;
2854            }
2855
2856            let ua = ufvk
2857                .address(
2858                    d_idx,
2859                    UnifiedAddressRequest::unsafe_custom(Omit, Require, Require),
2860                )
2861                .unwrap_or_else(|err| {
2862                    panic!(
2863                        "unified address generation failed for account {}: {:?}",
2864                        tv.account, err
2865                    )
2866                });
2867
2868            match Address::decode(&MAIN_NETWORK, tv.unified_addr) {
2869                Some(Address::Unified(tvua)) => {
2870                    // We always derive transparent and Sapling receivers, but not
2871                    // every value in the test vectors has these present.
2872                    if tvua.has_transparent() {
2873                        assert_eq!(tvua.transparent(), ua.transparent());
2874                    }
2875                    #[cfg(feature = "sapling")]
2876                    if tvua.has_sapling() {
2877                        assert_eq!(tvua.sapling(), ua.sapling());
2878                    }
2879                }
2880                _other => {
2881                    panic!(
2882                        "{} did not decode to a valid unified address",
2883                        tv.unified_addr
2884                    );
2885                }
2886            }
2887        }
2888    }
2889
2890    /// Tests UIVK encoding round-trip and verification against R2 test vectors from
2891    /// https://github.com/zcash/zcash-test-vectors/blob/667c92954acd7defc6e60e25b022fedf8831dfb3/test-vectors/rust/unified_viewing_keys_r2.rs
2892    #[test]
2893    #[cfg(all(
2894        feature = "orchard",
2895        feature = "sapling",
2896        feature = "transparent-inputs"
2897    ))]
2898    fn uivk_round_trip() {
2899        use super::test_vectors::unified_viewing_keys_r2::TEST_VECTORS;
2900        use zcash_protocol::consensus::NetworkType;
2901
2902        for tv in TEST_VECTORS {
2903            let decoded = UnifiedIncomingViewingKey::from_container(
2904                &unified::Uivk::decode(tv.unified_ivk).unwrap().2,
2905            )
2906            .unwrap_or_else(|e| panic!("Failed to decode UIVK for account {}: {e:?}", tv.account));
2907
2908            let reencoded = decoded
2909                .render(Revision::R2)
2910                .map(|uivk| uivk.encode(&NetworkType::Main));
2911            assert_eq!(
2912                reencoded.as_deref(),
2913                Ok(tv.unified_ivk),
2914                "UIVK round-trip failed for account {}",
2915                tv.account
2916            );
2917
2918            // ZIP 316 requires the source UFVK's expiry metadata to be retained
2919            // unmodified in the derived UIVK.
2920            assert_eq!(
2921                decoded.expiry_height(),
2922                tv.expiry_height
2923                    .map(zcash_protocol::consensus::BlockHeight::from_u32),
2924                "expiry height mismatch for account {}",
2925                tv.account
2926            );
2927            assert_eq!(
2928                decoded.expiry_time(),
2929                tv.expiry_time,
2930                "expiry time mismatch for account {}",
2931                tv.account
2932            );
2933
2934            // The Unified Address derived from the decoded UIVK must match the vector,
2935            // including the P2SH receiver obtained by evaluating a P2SH viewing key
2936            // item's wallet policy.
2937            let ua = decoded
2938                .address(
2939                    DiversifierIndex::from(tv.diversifier_index),
2940                    UnifiedAddressRequest::AllAvailableKeys,
2941                )
2942                .unwrap_or_else(|e| {
2943                    panic!("UA derivation failed for account {}: {e:?}", tv.account)
2944                });
2945            assert_eq!(
2946                ua.encode_revision(&MAIN_NETWORK, Revision::R2).as_deref(),
2947                Ok(tv.derived_ua),
2948                "derived UA mismatch for account {}",
2949                tv.account
2950            );
2951
2952            // Verify key data matches the test vector bytes.
2953            if let Some(ref expected) = tv.t_p2pkh_ivk_bytes {
2954                let actual = decoded
2955                    .p2pkh()
2956                    .expect("transparent key present in test vector")
2957                    .serialize();
2958                assert_eq!(
2959                    &actual[..],
2960                    &expected[..],
2961                    "transparent IVK mismatch for account {}",
2962                    tv.account
2963                );
2964            }
2965
2966            if let Some(ref expected) = tv.sapling_ivk_bytes {
2967                let actual = decoded
2968                    .sapling
2969                    .as_ref()
2970                    .expect("sapling key present in test vector")
2971                    .to_bytes();
2972                assert_eq!(
2973                    &actual[..],
2974                    &expected[..],
2975                    "sapling IVK mismatch for account {}",
2976                    tv.account
2977                );
2978            }
2979
2980            if let Some(ref expected) = tv.orchard_ivk_bytes {
2981                let actual = decoded
2982                    .orchard
2983                    .as_ref()
2984                    .expect("orchard key present in test vector")
2985                    .to_bytes();
2986                assert_eq!(
2987                    &actual[..],
2988                    &expected[..],
2989                    "orchard IVK mismatch for account {}",
2990                    tv.account
2991                );
2992            }
2993
2994            assert_eq!(
2995                decoded.p2sh().map(|p| p.to_bytes()).as_deref(),
2996                tv.p2sh_ivk_bytes,
2997                "P2SH IVK item mismatch for account {}",
2998                tv.account
2999            );
3000        }
3001    }
3002
3003    #[test]
3004    #[cfg(all(
3005        feature = "transparent-inputs",
3006        any(feature = "orchard", feature = "sapling")
3007    ))]
3008    fn uivk_derivation() {
3009        for tv in test_vectors::UNIFIED {
3010            let usk = UnifiedSpendingKey::from_seed(
3011                &MAIN_NETWORK,
3012                &tv.root_seed,
3013                AccountId::try_from(tv.account).unwrap(),
3014            )
3015            .expect("seed produced a valid unified spending key");
3016
3017            let d_idx = DiversifierIndex::from(tv.diversifier_index);
3018            let uivk = usk
3019                .to_unified_full_viewing_key()
3020                .to_unified_incoming_viewing_key();
3021
3022            // The test vectors contain some diversifier indices that do not generate
3023            // valid Sapling addresses, so skip those.
3024            #[cfg(feature = "sapling")]
3025            if uivk.sapling().as_ref().unwrap().address_at(d_idx).is_none() {
3026                continue;
3027            }
3028
3029            let ua = uivk
3030                .address(
3031                    d_idx,
3032                    UnifiedAddressRequest::unsafe_custom(Omit, Require, Require),
3033                )
3034                .unwrap_or_else(|err| {
3035                    panic!(
3036                        "unified address generation failed for account {}: {:?}",
3037                        tv.account, err
3038                    )
3039                });
3040
3041            match Address::decode(&MAIN_NETWORK, tv.unified_addr) {
3042                Some(Address::Unified(tvua)) => {
3043                    // We always derive transparent and Sapling receivers, but not
3044                    // every value in the test vectors has these present.
3045                    if tvua.has_transparent() {
3046                        assert_eq!(tvua.transparent(), ua.transparent());
3047                    }
3048                    #[cfg(feature = "sapling")]
3049                    if tvua.has_sapling() {
3050                        assert_eq!(tvua.sapling(), ua.sapling());
3051                    }
3052                }
3053                _other => {
3054                    panic!(
3055                        "{} did not decode to a valid unified address",
3056                        tv.unified_addr
3057                    );
3058                }
3059            }
3060        }
3061    }
3062
3063    proptest! {
3064        #[test]
3065        #[cfg(feature = "unstable")]
3066        fn prop_usk_roundtrip(usk in arb_partial_unified_spending_key(zcash_protocol::consensus::Network::MainNetwork)) {
3067            let encoded = usk.to_bytes(Era::Orchard);
3068            let encoded = encoded.expose_secret();
3069
3070            #[allow(clippy::let_and_return)]
3071            let encoded_len = {
3072                let len = 4;
3073
3074                #[cfg(feature = "orchard")]
3075                let len = len + usk.orchard().map_or(0, |_| 2 + 32);
3076
3077                #[cfg(feature = "sapling")]
3078                let len = len + usk.sapling().map_or(0, |_| 2 + 169);
3079
3080                // Transparent part is an `xprv` transparent extended key deserialized
3081                // into bytes from Base58, minus the 4 prefix bytes.
3082                #[cfg(feature = "transparent-inputs")]
3083                let len = len + usk.transparent().map_or(0, |_| 2 + 74);
3084
3085                #[allow(clippy::let_and_return)]
3086                len
3087            };
3088            assert_eq!(encoded.len(), encoded_len);
3089
3090            let decoded = UnifiedSpendingKey::from_bytes(Era::Orchard, encoded);
3091            let decoded = decoded.unwrap_or_else(|e| panic!("Error decoding USK: {:?}", e));
3092
3093            #[cfg(feature = "orchard")]
3094            match (decoded.orchard(), usk.orchard()) {
3095                (Some(d), Some(u)) => assert!(bool::from(d.ct_eq(u))),
3096                (None, None) => {}
3097                _ => panic!("Orchard component presence changed in round trip"),
3098            }
3099
3100            #[cfg(feature = "sapling")]
3101            assert_eq!(decoded.sapling(), usk.sapling());
3102
3103            #[cfg(feature = "transparent-inputs")]
3104            assert_eq!(
3105                decoded.transparent().map(|k| k.to_bytes()),
3106                usk.transparent().map(|k| k.to_bytes())
3107            );
3108
3109            // The viewing key holds exactly the protocols that the spending key holds.
3110            let ufvk = usk.to_unified_full_viewing_key();
3111            #[cfg(feature = "orchard")]
3112            assert_eq!(ufvk.orchard().is_some(), usk.orchard().is_some());
3113            #[cfg(feature = "sapling")]
3114            assert_eq!(ufvk.sapling().is_some(), usk.sapling().is_some());
3115            #[cfg(feature = "transparent-inputs")]
3116            assert_eq!(ufvk.p2pkh().is_some(), usk.transparent().is_some());
3117        }
3118    }
3119
3120    #[test]
3121    fn usk_from_parts_rejects_empty() {
3122        assert!(matches!(
3123            UnifiedSpendingKey::from_parts(
3124                #[cfg(feature = "transparent-inputs")]
3125                None,
3126                #[cfg(feature = "sapling")]
3127                None,
3128                #[cfg(feature = "orchard")]
3129                None,
3130            ),
3131            Err(DerivationError::Empty)
3132        ));
3133    }
3134
3135    #[test]
3136    #[cfg(feature = "unstable")]
3137    fn usk_from_bytes_rejects_empty_encoding() {
3138        let encoded = u32::from(BranchId::Nu5).to_le_bytes();
3139        assert_eq!(
3140            UnifiedSpendingKey::from_bytes(Era::Orchard, &encoded).err(),
3141            Some(DecodingError::Empty)
3142        );
3143    }
3144
3145    #[test]
3146    #[cfg(all(feature = "unstable", feature = "sapling"))]
3147    fn usk_from_bytes_rejects_duplicate_typecode() {
3148        let usk = UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &[0; 32], AccountId::ZERO).unwrap();
3149        let sapling_key_bytes = usk.sapling().unwrap().to_bytes();
3150
3151        let mut encoded = u32::from(BranchId::Nu5).to_le_bytes().to_vec();
3152        for _ in 0..2 {
3153            CompactSize::write(&mut encoded, usize::try_from(Typecode::SAPLING).unwrap()).unwrap();
3154            CompactSize::write(&mut encoded, sapling_key_bytes.len()).unwrap();
3155            encoded.extend_from_slice(&sapling_key_bytes);
3156        }
3157
3158        assert_eq!(
3159            UnifiedSpendingKey::from_bytes(Era::Orchard, &encoded).err(),
3160            Some(DecodingError::DuplicateTypecode(Typecode::SAPLING))
3161        );
3162    }
3163
3164    #[test]
3165    #[cfg(all(
3166        feature = "sapling",
3167        feature = "orchard",
3168        feature = "transparent-inputs"
3169    ))]
3170    fn uivk_decrypt_diversifier_matches_own_ua_and_rejects_foreign() {
3171        let ufvk_a = UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &[1u8; 32], AccountId::ZERO)
3172            .unwrap()
3173            .to_unified_full_viewing_key();
3174        let ufvk_b = UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &[2u8; 32], AccountId::ZERO)
3175            .unwrap()
3176            .to_unified_full_viewing_key();
3177
3178        let (ua_a, mut di_a) = ufvk_a
3179            .default_address(UnifiedAddressRequest::AllAvailableKeys)
3180            .unwrap();
3181
3182        // The UIVK for A recovers the diversifier index used to derive A's own UA.
3183        let uivk_a = ufvk_a.to_unified_incoming_viewing_key();
3184        let ua_a_dis = uivk_a.decrypt_diversifiers(&ua_a);
3185        assert_eq!(ua_a_dis.len(), 1);
3186        assert_eq!(ua_a_dis.first(), Some(di_a).as_ref());
3187
3188        // The UIVK for B, which did not derive A's UA, returns None.
3189        let uivk_b = ufvk_b.to_unified_incoming_viewing_key();
3190        assert_eq!(uivk_b.decrypt_diversifiers(&ua_a).len(), 0);
3191
3192        // A frankenstein UA combining A's Sapling receiver with B's Orchard receiver is
3193        // attributed to A (matched via Sapling, tried first).
3194        let (ua_b, di_b) = ufvk_b
3195            .default_address(UnifiedAddressRequest::AllAvailableKeys)
3196            .unwrap();
3197        let franken = UnifiedAddress::from_receivers(
3198            Some(*ua_b.orchard().unwrap()),
3199            Some(*ua_a.sapling().unwrap()),
3200            None,
3201            None,
3202            None,
3203        )
3204        .unwrap();
3205
3206        let franken_dis_a = uivk_a.decrypt_diversifiers(&franken);
3207        assert_eq!(franken_dis_a.len(), 1);
3208        assert_eq!(franken_dis_a.first(), Some(di_a).as_ref());
3209
3210        let franken_dis_b = uivk_b.decrypt_diversifiers(&franken);
3211        assert_eq!(franken_dis_b.len(), 1);
3212        assert_eq!(franken_dis_b.first(), Some(di_b).as_ref());
3213
3214        di_a.increment()
3215            .expect("diversifier space is not exhausted");
3216        let (next_ua_a, _) = ufvk_a
3217            .find_address(di_a, UnifiedAddressRequest::AllAvailableKeys)
3218            .unwrap();
3219        let mixed_ua = UnifiedAddress::from_receivers(
3220            Some(*ua_a.orchard().unwrap()),
3221            Some(*next_ua_a.sapling().unwrap()),
3222            None,
3223            None,
3224            None,
3225        )
3226        .unwrap();
3227        let mixed_dis_a = uivk_a.decrypt_diversifiers(&mixed_ua);
3228        assert_eq!(mixed_dis_a.len(), 2);
3229    }
3230
3231    /// A key with no shielded item describes a transparent-only account, and generates
3232    /// transparent-only ZIP 316 Revision 2 (`tu`) Unified Addresses.
3233    #[test]
3234    #[cfg(feature = "transparent-inputs")]
3235    fn transparent_only_key_generates_tu_address() {
3236        use super::{
3237            ReceiverRequirement::{Omit, Require},
3238            UnifiedAddressRequest,
3239        };
3240        use crate::address::UnifiedAddress;
3241
3242        let account_pubkey = AccountPrivKey::from_seed(&MAIN_NETWORK, &seed(), AccountId::ZERO)
3243            .unwrap()
3244            .to_account_pubkey();
3245        let ufvk = super::UnifiedFullViewingKey::new(
3246            Some(account_pubkey),
3247            #[cfg(feature = "sapling")]
3248            None,
3249            #[cfg(feature = "orchard")]
3250            None,
3251        )
3252        .unwrap();
3253        let uivk = ufvk.to_unified_incoming_viewing_key();
3254
3255        let requirements = uivk
3256            .to_receiver_requirements()
3257            .expect("a transparent item is a receiver requirement");
3258        assert_eq!(requirements.orchard(), Omit);
3259        assert_eq!(requirements.sapling(), Omit);
3260        assert_eq!(requirements.p2pkh(), Require);
3261
3262        let (ufvk_addr, _) = ufvk
3263            .default_address(UnifiedAddressRequest::AllAvailableKeys)
3264            .expect("a transparent-only key has a default address");
3265        let (uivk_addr, _) = uivk
3266            .default_address(UnifiedAddressRequest::AllAvailableKeys)
3267            .expect("a transparent-only key has a default address");
3268        assert_eq!(ufvk_addr, uivk_addr);
3269
3270        assert!(ufvk_addr.has_transparent());
3271        assert!(!ufvk_addr.has_sapling());
3272        assert!(!ufvk_addr.has_orchard());
3273        assert_eq!(
3274            ufvk_addr.transparent(),
3275            ufvk.default_transparent_address()
3276                .map(|(addr, _)| addr)
3277                .as_ref()
3278        );
3279
3280        // The address is encoded using the Revision 2 transparent-including HRP, and
3281        // round-trips through that encoding.
3282        let encoded = ufvk_addr
3283            .encode_revision(&MAIN_NETWORK, Revision::R2)
3284            .expect("every address has a Revision 2 encoding");
3285        assert!(
3286            encoded.starts_with(zcash_address::constants::hrp_unified_address_r2_ti(
3287                zcash_protocol::consensus::NetworkType::Main
3288            )),
3289            "{encoded} is not a transparent-including Revision 2 Unified Address",
3290        );
3291        assert_eq!(
3292            UnifiedAddress::decode(&MAIN_NETWORK, &encoded).as_ref(),
3293            Ok(&ufvk_addr)
3294        );
3295    }
3296
3297    /// A key that has a transparent item and a data item that this build cannot interpret is
3298    /// not transparent-only: the uninterpretable item may be a shielded receiver, so no
3299    /// address can be generated for all of the key's items.
3300    #[test]
3301    #[cfg(feature = "transparent-inputs")]
3302    fn key_with_uninterpretable_data_item_is_not_transparent_only() {
3303        use super::{
3304            AddressGenerationError,
3305            ReceiverRequirement::{Omit, Require},
3306            ReceiverRequirementError, UnifiedAddressRequest,
3307        };
3308        use zcash_protocol::consensus::BlockHeight;
3309
3310        // A data typecode that this crate does not know. Metadata typecodes start at 0xC0, so
3311        // this is a data item: a pool that postdates this crate.
3312        const FUTURE_POOL_TYPECODE: u32 = 0x04;
3313
3314        let account_privkey =
3315            AccountPrivKey::from_seed(&MAIN_NETWORK, &seed(), AccountId::ZERO).unwrap();
3316        let account_pubkey = account_privkey.to_account_pubkey();
3317        let transparent_ivk = account_pubkey.derive_external_ivk().unwrap();
3318
3319        // The incoming viewing key form, which keeps an uninterpretable item in `unknown`.
3320        let uivk = super::UnifiedIncomingViewingKey::new(
3321            Some(transparent_ivk.clone()),
3322            #[cfg(feature = "sapling")]
3323            None,
3324            #[cfg(feature = "orchard")]
3325            None,
3326            vec![(FUTURE_POOL_TYPECODE, vec![0u8; 32])],
3327            None,
3328            None,
3329            vec![],
3330        );
3331
3332        assert_eq!(
3333            uivk.to_receiver_requirements().err(),
3334            Some(ReceiverRequirementError::NoShieldedReceiver)
3335        );
3336        assert!(matches!(
3337            uivk.default_address(UnifiedAddressRequest::AllAvailableKeys),
3338            Err(AddressGenerationError::NoSatisfiableReceiver)
3339        ));
3340
3341        // The full viewing key form. Deriving its incoming viewing key cannot carry the
3342        // uninterpretable item over, so the derived key must record that it is incomplete;
3343        // otherwise every consumer that describes an account through that derivation, as
3344        // wallet backends do, sees a transparent-only key.
3345        let ufvk = super::UnifiedFullViewingKey::from_checked_parts(
3346            Some(super::TransparentFvk::P2pkh(account_pubkey)),
3347            #[cfg(feature = "sapling")]
3348            None,
3349            #[cfg(feature = "orchard")]
3350            None,
3351            vec![(FUTURE_POOL_TYPECODE, vec![0u8; 32])],
3352            None,
3353            None,
3354            vec![],
3355        )
3356        .unwrap();
3357
3358        assert_eq!(
3359            ufvk.to_unified_incoming_viewing_key()
3360                .to_receiver_requirements()
3361                .err(),
3362            Some(ReceiverRequirementError::NoShieldedReceiver)
3363        );
3364        assert!(matches!(
3365            ufvk.default_address(UnifiedAddressRequest::AllAvailableKeys),
3366            Err(AddressGenerationError::NoSatisfiableReceiver)
3367        ));
3368
3369        // Metadata items are not receivers, so they never prevent address generation.
3370        let with_metadata = super::UnifiedIncomingViewingKey::new(
3371            Some(transparent_ivk),
3372            #[cfg(feature = "sapling")]
3373            None,
3374            #[cfg(feature = "orchard")]
3375            None,
3376            vec![],
3377            Some(BlockHeight::from_u32(1_000_000)),
3378            Some(1730506496),
3379            vec![(0xC5, vec![0u8; 4])],
3380        );
3381
3382        let requirements = with_metadata
3383            .to_receiver_requirements()
3384            .expect("metadata items do not prevent address generation");
3385        assert_eq!(requirements.orchard(), Omit);
3386        assert_eq!(requirements.sapling(), Omit);
3387        assert_eq!(requirements.p2pkh(), Require);
3388    }
3389
3390    /// Decoding a genuine Orchard-and-transparent UFVK in a build that cannot interpret Orchard
3391    /// keeps the Orchard item, and so must not describe the key as transparent-only.
3392    #[test]
3393    #[cfg(all(
3394        feature = "sapling",
3395        feature = "transparent-inputs",
3396        not(feature = "orchard")
3397    ))]
3398    fn orchard_and_transparent_ufvk_is_not_transparent_only_without_orchard() {
3399        use super::test_vectors::unified_viewing_keys_r2::TEST_VECTORS;
3400        use super::{AddressGenerationError, UnifiedAddressRequest};
3401
3402        let mut checked = 0;
3403        for tv in TEST_VECTORS {
3404            if tv.orchard_fvk_bytes.is_none()
3405                || tv.sapling_fvk_bytes.is_some()
3406                || tv.t_p2pkh_fvk_bytes.is_none()
3407            {
3408                continue;
3409            }
3410            checked += 1;
3411
3412            let ufvk =
3413                UnifiedFullViewingKey::decode(&MAIN_NETWORK, tv.unified_fvk).unwrap_or_else(|e| {
3414                    panic!("Failed to decode UFVK for account {}: {e}", tv.account)
3415                });
3416
3417            // The Orchard item is still part of the key: it re-encodes byte-identically.
3418            assert_eq!(
3419                ufvk.encode_revision(&MAIN_NETWORK, Revision::R2).as_deref(),
3420                Ok(tv.unified_fvk),
3421                "UFVK round-trip failed for account {}",
3422                tv.account
3423            );
3424
3425            assert!(
3426                matches!(
3427                    ufvk.default_address(UnifiedAddressRequest::AllAvailableKeys),
3428                    Err(AddressGenerationError::NoSatisfiableReceiver)
3429                ),
3430                "account {} produced an address that discards its Orchard receiver",
3431                tv.account
3432            );
3433        }
3434
3435        assert!(
3436            checked > 0,
3437            "no test vector has an Orchard item, a transparent item, and no Sapling item"
3438        );
3439    }
3440
3441    /// Requirements that permit no shielded receiver cannot arise from constructing a request
3442    /// or from intersecting two requests; [`ReceiverRequirements::TRANSPARENT_ONLY`] is the
3443    /// only way to name them.
3444    #[test]
3445    #[cfg(all(feature = "transparent-inputs", feature = "sapling"))]
3446    fn shielded_less_requirements_unreachable_by_construction_or_intersection() {
3447        use super::{
3448            ReceiverRequirement::{Allow, Omit, Require},
3449            ReceiverRequirementError, ReceiverRequirements, UnifiedAddressRequest,
3450        };
3451
3452        let account_pubkey = AccountPrivKey::from_seed(&MAIN_NETWORK, &seed(), AccountId::ZERO)
3453            .unwrap()
3454            .to_account_pubkey();
3455        let ufvk = super::UnifiedFullViewingKey::new(
3456            Some(account_pubkey),
3457            Some(
3458                sapling::spending_key(&seed(), 1, AccountId::ZERO)
3459                    .expect("the derivation path yields a valid key")
3460                    .to_diversifiable_full_viewing_key(),
3461            ),
3462            #[cfg(feature = "orchard")]
3463            None,
3464        )
3465        .unwrap();
3466        let uivk = ufvk.to_unified_incoming_viewing_key();
3467
3468        // The requirements derived from the key require its Sapling receiver.
3469        let requirements = uivk.to_receiver_requirements().unwrap();
3470        assert_eq!(requirements.sapling(), Require);
3471
3472        // A shielded-less request cannot be constructed through the ordinary request path.
3473        assert_eq!(
3474            UnifiedAddressRequest::custom(Omit, Omit, Require).err(),
3475            Some(ReceiverRequirementError::NoShieldedReceiver)
3476        );
3477        assert_eq!(
3478            ReceiverRequirements::new(Omit, Omit, Require).err(),
3479            Some(ReceiverRequirementError::NoShieldedReceiver)
3480        );
3481
3482        // Nor can it be reached by intersection with the key's own requirements.
3483        assert_eq!(
3484            requirements
3485                .intersect(&ReceiverRequirements::TRANSPARENT_ONLY)
3486                .err(),
3487            Some(ReceiverRequirementError::Conflict)
3488        );
3489
3490        // Intersection does not introduce a shielded-less requirement from two operands that
3491        // each permit a shielded receiver ...
3492        assert_eq!(
3493            ReceiverRequirements::unsafe_new(Omit, Allow, Allow)
3494                .intersect(&ReceiverRequirements::unsafe_new(Allow, Omit, Allow))
3495                .err(),
3496            Some(ReceiverRequirementError::NoShieldedReceiver)
3497        );
3498
3499        // ... but preserves it when an operand is already transparent-only.
3500        let intersected = ReceiverRequirements::TRANSPARENT_ONLY
3501            .intersect(&ReceiverRequirements::ALLOW_ALL)
3502            .expect("a transparent-only operand keeps the intersection transparent-only");
3503        assert_eq!(intersected.orchard(), Omit);
3504        assert_eq!(intersected.sapling(), Omit);
3505        assert_eq!(intersected.p2pkh(), Require);
3506
3507        // The address generated for all of the key's available items retains the Sapling
3508        // receiver.
3509        let (addr, _) = ufvk
3510            .default_address(UnifiedAddressRequest::AllAvailableKeys)
3511            .unwrap();
3512        assert!(addr.has_sapling());
3513        assert!(addr.has_transparent());
3514
3515        // `TRANSPARENT_ONLY` is a deliberate escape hatch: requesting it against a key that
3516        // has a shielded item is documented misuse, not a rejected request.
3517        let (addr, _) = ufvk
3518            .default_address(UnifiedAddressRequest::TRANSPARENT_ONLY)
3519            .unwrap();
3520        assert!(!addr.has_sapling());
3521        assert!(addr.has_transparent());
3522    }
3523
3524    /// ZIP 316 permits at most one transparent item in a unified viewing key, so a key
3525    /// carrying a P2SH item has no P2PKH component, and vice versa.
3526    #[test]
3527    #[cfg(feature = "transparent-inputs")]
3528    fn p2sh_and_p2pkh_components_are_mutually_exclusive() {
3529        use super::test_vectors::unified_viewing_keys_r2::TEST_VECTORS;
3530
3531        let with_p2sh = TEST_VECTORS
3532            .iter()
3533            .find(|tv| tv.p2sh_fvk_bytes.is_some())
3534            .expect("a test vector carries a P2SH viewing key item");
3535        let ufvk =
3536            super::UnifiedFullViewingKey::decode(&MAIN_NETWORK, with_p2sh.unified_fvk).unwrap();
3537        assert!(ufvk.p2sh().is_some());
3538        assert!(ufvk.p2pkh().is_none());
3539
3540        let uivk = ufvk.to_unified_incoming_viewing_key();
3541        assert!(uivk.p2sh().is_some());
3542        assert!(uivk.p2pkh().is_none());
3543        assert!(uivk.has_transparent());
3544
3545        let with_p2pkh = TEST_VECTORS
3546            .iter()
3547            .find(|tv| tv.t_p2pkh_fvk_bytes.is_some())
3548            .expect("a test vector carries a P2PKH viewing key");
3549        let ufvk =
3550            super::UnifiedFullViewingKey::decode(&MAIN_NETWORK, with_p2pkh.unified_fvk).unwrap();
3551        assert!(ufvk.p2pkh().is_some());
3552        assert!(ufvk.p2sh().is_none());
3553    }
3554
3555    /// A P2SH account has no seed to derive a unified key from, so the constructor is the
3556    /// only way to reach one. What it builds has to survive the encoding, or an account
3557    /// registered from a cosigner set is not the account read back from the wallet.
3558    #[test]
3559    #[cfg(feature = "transparent-inputs")]
3560    fn ufvk_from_p2sh_round_trips_and_is_transparent_only() {
3561        use super::{UnifiedAddressRequest, UnifiedFullViewingKey};
3562        use crate::keys::transparent::zip48::{P2shFullViewingKey, P2shKey};
3563        use core::num::NonZeroU8;
3564        use secp256k1::{PublicKey, SecretKey};
3565
3566        let key_info = [1u8, 2, 3]
3567            .iter()
3568            .map(|i| {
3569                let sk = SecretKey::from_secret_bytes([*i; 32]).expect("valid secret key");
3570                P2shKey::new([*i; 32], PublicKey::from_secret_key(&sk))
3571            })
3572            .collect::<Vec<_>>();
3573        let item = P2shFullViewingKey::new(NonZeroU8::new(2).unwrap(), key_info)
3574            .expect("valid cosigner set");
3575
3576        let ufvk = UnifiedFullViewingKey::from_p2sh(item.clone()).expect("constructible");
3577
3578        assert_eq!(ufvk.p2sh(), Some(&item));
3579        assert_eq!(ufvk.p2pkh(), None);
3580
3581        let encoded = ufvk.encode(&MAIN_NETWORK).expect("encodes");
3582        let decoded = UnifiedFullViewingKey::decode(&MAIN_NETWORK, &encoded).expect("decodes");
3583        assert_eq!(decoded.p2sh(), Some(&item));
3584
3585        // A key with no shielded items yields a transparent-only unified address, which
3586        // is what makes the account portable between wallets at all.
3587        let (address, _) = ufvk
3588            .default_address(UnifiedAddressRequest::ALLOW_ALL)
3589            .expect("derives an address");
3590        assert!(address.has_transparent());
3591        assert!(
3592            address.encode(&MAIN_NETWORK).starts_with("tu"),
3593            "expected a transparent-only UA, got {}",
3594            address.encode(&MAIN_NETWORK),
3595        );
3596    }
3597
3598    #[test]
3599    fn p2sh_item_is_unconverted_without_transparent_inputs() {
3600        use zcash_address::unified::{Encoding, Fvk, Revision, Ufvk, Uitem};
3601
3602        /// The shortest ZIP 48 P2SH FVK item.
3603        ///
3604        /// The shortest possible P2SH FVK item would be `sh(pk(@0/**))`), but
3605        /// `P2shFullViewingKey::parse` only supports ZIP 48.
3606        const TEMPLATE: &str = "sh(sortedmulti(1,@0/**))";
3607
3608        let secret_key = SecretKey::from_secret_bytes([1; 32]).unwrap();
3609        let public_key = PublicKey::from_secret_key(&secret_key);
3610
3611        let mut payload = vec![];
3612        CompactSize::write(&mut payload, TEMPLATE.len()).unwrap();
3613        payload.extend_from_slice(TEMPLATE.as_bytes());
3614        CompactSize::write(&mut payload, 1).unwrap();
3615        // A BIP 32 chain code is 32 bytes.
3616        payload.extend_from_slice(&[0; 32]);
3617        payload.extend_from_slice(&public_key.serialize());
3618
3619        let ufvk =
3620            Ufvk::try_from_items(Revision::R2, vec![Uitem::Data(Fvk::P2sh(payload.clone()))])
3621                .unwrap();
3622
3623        let parsed = super::UnifiedFullViewingKey::parse(&ufvk).unwrap();
3624
3625        #[cfg(feature = "transparent-inputs")]
3626        assert_eq!(parsed.p2sh().unwrap().to_bytes(), payload);
3627
3628        // Without the `transparent-inputs` feature a P2SH viewing key item cannot be
3629        // interpreted, so it is retained as an unknown item and recorded as unconverted in
3630        // the derived incoming viewing key. Otherwise that derived key describes the account
3631        // as having no transparent receiving capability at all.
3632        #[cfg(not(feature = "transparent-inputs"))]
3633        {
3634            // The typecode ZIP 316 assigns to a P2SH viewing key item.
3635            const P2SH_TYPECODE: u32 = 0x01;
3636
3637            assert_eq!(parsed.unknown, vec![(P2SH_TYPECODE, payload)]);
3638            assert_eq!(
3639                parsed
3640                    .to_unified_incoming_viewing_key()
3641                    .unconverted_typecodes,
3642                vec![P2SH_TYPECODE]
3643            );
3644        }
3645    }
3646
3647    #[cfg(feature = "unstable")]
3648    #[test]
3649    fn usk_debug_redaction() {
3650        let seed = [0u8; 64];
3651        let usk = UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed, AccountId::ZERO).unwrap();
3652        assert!(format!("{usk:?}").contains("\"...\""));
3653    }
3654
3655    #[test]
3656    #[cfg(any(feature = "orchard", feature = "sapling"))]
3657    fn ufvk_debug_redaction() {
3658        #[cfg(feature = "orchard")]
3659        let orchard = {
3660            let sk =
3661                orchard::keys::SpendingKey::from_zip32_seed(&[0; 32], 0, AccountId::ZERO).unwrap();
3662            Some(orchard::keys::FullViewingKey::from(&sk))
3663        };
3664
3665        #[cfg(feature = "sapling")]
3666        let sapling = {
3667            let extsk = sapling::spending_key(&[0; 32], 0, AccountId::ZERO)
3668                .expect("the derivation path yields a valid key");
3669            Some(extsk.to_diversifiable_full_viewing_key())
3670        };
3671
3672        #[cfg(feature = "transparent-inputs")]
3673        let transparent = {
3674            let privkey =
3675                AccountPrivKey::from_seed(&MAIN_NETWORK, &[0; 32], AccountId::ZERO).unwrap();
3676            Some(privkey.to_account_pubkey())
3677        };
3678
3679        let ufvk = UnifiedFullViewingKey::new(
3680            #[cfg(feature = "transparent-inputs")]
3681            transparent,
3682            #[cfg(feature = "sapling")]
3683            sapling,
3684            #[cfg(feature = "orchard")]
3685            orchard,
3686        )
3687        .unwrap();
3688
3689        let debug_str = format!("{ufvk:?}");
3690        #[cfg(feature = "transparent-inputs")]
3691        assert!(debug_str.contains("p2pkh: Some(\"...\")"));
3692        #[cfg(feature = "sapling")]
3693        assert!(debug_str.contains("sapling: Some(\"...\")"));
3694        #[cfg(feature = "orchard")]
3695        assert!(debug_str.contains("orchard: Some(\"...\")"));
3696    }
3697
3698    #[test]
3699    #[cfg(any(feature = "orchard", feature = "sapling"))]
3700    fn uivk_debug_redaction() {
3701        #[cfg(feature = "orchard")]
3702        let orchard = {
3703            let sk =
3704                orchard::keys::SpendingKey::from_zip32_seed(&[0; 32], 0, AccountId::ZERO).unwrap();
3705            Some(orchard::keys::FullViewingKey::from(&sk).to_ivk(Scope::External))
3706        };
3707
3708        #[cfg(feature = "sapling")]
3709        let sapling = {
3710            let extsk = sapling::spending_key(&[0; 32], 0, AccountId::ZERO)
3711                .expect("the derivation path yields a valid key");
3712            Some(extsk.to_diversifiable_full_viewing_key().to_external_ivk())
3713        };
3714
3715        #[cfg(feature = "transparent-inputs")]
3716        let transparent = {
3717            let privkey =
3718                AccountPrivKey::from_seed(&MAIN_NETWORK, &[0; 32], AccountId::ZERO).unwrap();
3719            Some(privkey.to_account_pubkey().derive_external_ivk().unwrap())
3720        };
3721
3722        let uivk = UnifiedIncomingViewingKey::new(
3723            #[cfg(feature = "transparent-inputs")]
3724            transparent,
3725            #[cfg(feature = "sapling")]
3726            sapling,
3727            #[cfg(feature = "orchard")]
3728            orchard,
3729            vec![],
3730            None,
3731            None,
3732            vec![],
3733        );
3734
3735        let debug_str = format!("{uivk:?}");
3736        #[cfg(feature = "sapling")]
3737        assert!(debug_str.contains("sapling: Some(\"...\")"));
3738        #[cfg(feature = "orchard")]
3739        assert!(debug_str.contains("orchard: Some(\"...\")"));
3740    }
3741
3742    #[test]
3743    fn ovk_debug_redaction() {
3744        assert_eq!(
3745            format!("{:?}", super::OutgoingViewingKey::from([0u8; 32])),
3746            "OutgoingViewingKey(\"...\")"
3747        );
3748    }
3749
3750    #[cfg(any(feature = "sapling", feature = "orchard"))]
3751    #[test]
3752    fn subsumes_ufvk_same_key() {
3753        let seed = vec![0u8; 32];
3754        let usk =
3755            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed, AccountId::ZERO).unwrap();
3756        let ufvk = usk.to_unified_full_viewing_key();
3757
3758        // A UFVK subsumes itself.
3759        assert!(ufvk.subsumes_ufvk(&ufvk));
3760    }
3761
3762    #[cfg(any(feature = "sapling", feature = "orchard"))]
3763    #[test]
3764    fn subsumes_uivk_from_same_ufvk() {
3765        let seed = vec![0u8; 32];
3766        let usk =
3767            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed, AccountId::ZERO).unwrap();
3768        let ufvk = usk.to_unified_full_viewing_key();
3769        let uivk = ufvk.to_unified_incoming_viewing_key();
3770
3771        // A UFVK subsumes the UIVK derived from it.
3772        assert!(ufvk.subsumes_uivk(&uivk));
3773    }
3774
3775    #[cfg(all(feature = "sapling", feature = "orchard"))]
3776    #[test]
3777    fn subsumes_ufvk_subset() {
3778        let seed = vec![0u8; 32];
3779        let usk =
3780            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed, AccountId::ZERO).unwrap();
3781        let ufvk = usk.to_unified_full_viewing_key();
3782
3783        // A UFVK with all components subsumes one with fewer components.
3784        let subset_ufvk = UnifiedFullViewingKey::new(
3785            #[cfg(feature = "transparent-inputs")]
3786            None,
3787            ufvk.sapling().cloned(),
3788            None, // no Orchard
3789        )
3790        .unwrap();
3791        assert!(ufvk.subsumes_ufvk(&subset_ufvk));
3792        // The subset does not subsume the full key.
3793        assert!(!subset_ufvk.subsumes_ufvk(&ufvk));
3794    }
3795
3796    #[cfg(any(feature = "sapling", feature = "orchard"))]
3797    #[test]
3798    fn subsumes_ufvk_different_keys() {
3799        let seed0 = vec![0u8; 32];
3800        let seed1 = vec![1u8; 32];
3801        let usk0 =
3802            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed0, AccountId::ZERO).unwrap();
3803        let usk1 =
3804            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed1, AccountId::ZERO).unwrap();
3805        let ufvk0 = usk0.to_unified_full_viewing_key();
3806        let ufvk1 = usk1.to_unified_full_viewing_key();
3807
3808        // UFVKs from different seeds do not subsume each other.
3809        assert!(!ufvk0.subsumes_ufvk(&ufvk1));
3810        assert!(!ufvk1.subsumes_ufvk(&ufvk0));
3811    }
3812
3813    /// Fails to compile unless the shielded spending keys held by a
3814    /// `UnifiedSpendingKey` erase themselves on drop.
3815    #[cfg(feature = "zeroize")]
3816    #[test]
3817    fn shielded_spending_keys_zeroize_on_drop() {
3818        fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
3819        #[cfg(feature = "sapling")]
3820        assert_zeroize_on_drop::<::sapling::zip32::ExtendedSpendingKey>();
3821        #[cfg(feature = "orchard")]
3822        assert_zeroize_on_drop::<::orchard::keys::SpendingKey>();
3823    }
3824}