Skip to main content

zcash_keys/keys/
transparent.rs

1//! Transparent key components: BIP 44 account keys with their incoming and outgoing
2//! viewing keys, derivation-path index types, functions that read BIP 44 and ZIP 48
3//! derivation paths from PCZT metadata, and zcashd-compatible encodings of standalone
4//! transparent spending keys.
5
6use core::fmt;
7
8use ::transparent::pczt::Bip32Derivation;
9use bip32::ChildNumber;
10use subtle::{Choice, ConstantTimeEq};
11use zip32::DiversifierIndex;
12
13#[cfg(feature = "transparent-inputs")]
14use {
15    ::transparent::address::TransparentAddress,
16    alloc::{string::ToString, vec::Vec},
17    bip32::{ExtendedKey, ExtendedKeyAttrs, ExtendedPrivateKey, ExtendedPublicKey, Prefix},
18    zcash_protocol::consensus::{self, NetworkConstants},
19    zcash_spec::PrfExpand,
20    zip32::AccountId,
21};
22
23#[cfg(feature = "transparent-key-encoding")]
24use {
25    bip32::{PrivateKey, PrivateKeyBytes},
26    core::array::TryFromSliceError,
27    secp256k1::SecretKey,
28    secrecy::{ExposeSecret, SecretString, SecretVec, Zeroize, zeroize::ZeroizeOnDrop},
29    zcash_protocol::consensus::NetworkType,
30};
31
32#[cfg(any(feature = "transparent-inputs", feature = "transparent-key-encoding"))]
33use secp256k1::PublicKey;
34
35#[cfg(feature = "transparent-inputs")]
36pub mod gap_limits;
37
38#[cfg(feature = "transparent-inputs")]
39pub mod zip48;
40
41/// An error indicating that a DER-encoded secret key could not be decoded.
42#[cfg(feature = "transparent-key-encoding")]
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct DerDecodeError;
45
46#[cfg(feature = "transparent-key-encoding")]
47impl core::fmt::Display for DerDecodeError {
48    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
49        write!(f, "Invalid DER encoding for transparent secret key")
50    }
51}
52
53/// Errors that can occur in the parsing of Bitcoin-style base58-encoded secret key material
54#[cfg(feature = "transparent-key-encoding")]
55#[derive(Debug)]
56pub enum ParseError {
57    /// The data being decoded had an incorrect length, an incorrect prefix, or has the correct
58    /// length for a compressed encoding but has its final byte not equal to `1`.
59    InvalidEncoding,
60    /// Errors that occur in base58 decoding.
61    Base58(bs58::decode::Error),
62    /// Errors that occur when a decoded binary value does not correspond to a valid secp256k1 secret key.
63    Bip32(bip32::Error),
64}
65
66#[cfg(feature = "transparent-key-encoding")]
67impl core::fmt::Debug for Key {
68    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
69        f.debug_struct("Key")
70            .field("secret", &"...")
71            .field("compressed", &self.compressed)
72            .finish()
73    }
74}
75
76#[cfg(feature = "transparent-key-encoding")]
77impl From<bs58::decode::Error> for ParseError {
78    fn from(value: bs58::decode::Error) -> Self {
79        ParseError::Base58(value)
80    }
81}
82
83#[cfg(feature = "transparent-key-encoding")]
84impl From<TryFromSliceError> for ParseError {
85    fn from(_: TryFromSliceError) -> Self {
86        ParseError::InvalidEncoding
87    }
88}
89
90#[cfg(feature = "transparent-key-encoding")]
91impl From<bip32::Error> for ParseError {
92    fn from(value: bip32::Error) -> Self {
93        ParseError::Bip32(value)
94    }
95}
96
97/// A secp256k1 secret key, along with a flag indicating whether a compressed encoding should be
98/// used when performing DER serialization.
99#[cfg(feature = "transparent-key-encoding")]
100pub struct Key {
101    secret: SecretKey,
102    compressed: bool,
103}
104
105#[cfg(feature = "transparent-key-encoding")]
106impl Key {
107    /// Constructs a new key value from a secret key and a flag indicating whether
108    /// the compressed encoding should be used when performing DER serialization.
109    pub fn new(secret: SecretKey, compressed: bool) -> Self {
110        Self { secret, compressed }
111    }
112
113    /// Decodes a base58-encoded secret key.
114    ///
115    /// This corresponds to <https://github.com/zcash/zcash/blob/1f1f7a385adc048154e7f25a3a0de76f3658ca09/src/key_io.cpp#L282>
116    pub fn decode_base58(network: NetworkType, encoded: &SecretString) -> Result<Self, ParseError> {
117        let decoded = SecretVec::new(
118            bs58::decode(encoded.expose_secret())
119                .with_check(None)
120                .into_vec()?,
121        );
122        let prefix = crate::constants::b58_secret_key_prefix(network);
123        let decoded_len = decoded.expose_secret().len();
124        let compressed =
125            decoded_len == (33 + prefix.len()) && decoded.expose_secret().last() == Some(&1);
126        if (decoded_len == 32 + prefix.len() || compressed)
127            && decoded.expose_secret()[0..prefix.len()] == prefix
128        {
129            let key_end = decoded_len - if compressed { 1 } else { 0 };
130            let bytes = PrivateKeyBytes::try_from(&decoded.expose_secret()[prefix.len()..key_end])?;
131            Ok(Self {
132                secret: SecretKey::from_bytes(&bytes)?,
133                compressed,
134            })
135        } else {
136            Err(ParseError::InvalidEncoding)
137        }
138    }
139
140    /// Encodes a base58-encoded secret key.
141    ///
142    /// This corresponds to <https://github.com/zcash/zcash/blob/1f1f7a385adc048154e7f25a3a0de76f3658ca09/src/key_io.cpp#L298>
143    pub fn encode_base58(&self, network: NetworkType) -> SecretString {
144        let input = SecretVec::new(
145            crate::constants::b58_secret_key_prefix(network)
146                .iter()
147                .chain(self.secret.to_secret_bytes().iter())
148                .chain(self.compressed.then_some(&1))
149                .copied()
150                .collect(),
151        );
152
153        SecretString::new(
154            bs58::encode(input.expose_secret())
155                .with_check()
156                .into_string(),
157        )
158    }
159
160    /// Returns the wrapped secp256k1 secret key.
161    pub fn secret(&self) -> &SecretKey {
162        &self.secret
163    }
164
165    /// Returns the value of the compressed flag.
166    pub fn compressed(&self) -> bool {
167        self.compressed
168    }
169
170    /// Derives the secp256k1 public key corresponding to the secret key.
171    pub fn pubkey(&self) -> PublicKey {
172        self.secret.public_key()
173    }
174
175    /// Generates the "openssh-inspired" DER encoding of the secret key used by zcashd.
176    pub fn der_encode(&self) -> SecretVec<u8> {
177        // Ported from https://github.com/zcash/zcash/blob/1f1f7a385adc048154e7f25a3a0de76f3658ca09/src/key.cpp#L93
178        // The original c++ code is retained as comments.
179
180        //    secp256k1_pubkey pubkey;
181        //    size_t pubkeylen = 0;
182        //    if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
183        //        *seckeylen = 0;
184        //        return 0;
185        //    }
186        let keypair = self.secret().keypair();
187
188        if self.compressed {
189            let begin = [0x30, 0x81, 0xD3, 0x02, 0x01, 0x01, 0x04, 0x20];
190            let middle = [
191                0xA0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2C, 0x06, 0x07, 0x2A,
192                0x86, 0x48, 0xCE, 0x3D, 0x01, 0x01, 0x02, 0x21, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
193                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
194                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F, 0x30,
195                0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, 0x21, 0x02, 0x79, 0xBE, 0x66, 0x7E,
196                0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07, 0x02, 0x9B,
197                0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98,
198                0x02, 0x21, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
199                0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF,
200                0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xA1, 0x24, 0x03, 0x22,
201                0x00,
202            ];
203            //        unsigned char *ptr = seckey;
204            //        memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
205            //        memcpy(ptr, key32, 32); ptr += 32;
206            //        memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
207            //        pubkeylen = CPubKey::COMPRESSED_PUBLIC_KEY_SIZE;
208            //        secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
209            //        ptr += pubkeylen;
210            //        *seckeylen = ptr - seckey;
211            //        assert(*seckeylen == CKey::COMPRESSED_PRIVATE_KEY_SIZE);
212            SecretVec::new(
213                begin
214                    .iter()
215                    .chain(keypair.to_secret_bytes().iter())
216                    .chain(middle.iter())
217                    .chain(keypair.public_key().serialize().iter())
218                    .copied()
219                    .collect(),
220            )
221        } else {
222            let begin = [0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20];
223            let middle = [
224                0xA0, 0x81, 0xA5, 0x30, 0x81, 0xA2, 0x02, 0x01, 0x01, 0x30, 0x2C, 0x06, 0x07, 0x2A,
225                0x86, 0x48, 0xCE, 0x3D, 0x01, 0x01, 0x02, 0x21, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
226                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
227                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F, 0x30,
228                0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, 0x41, 0x04, 0x79, 0xBE, 0x66, 0x7E,
229                0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07, 0x02, 0x9B,
230                0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98,
231                0x48, 0x3A, 0xDA, 0x77, 0x26, 0xA3, 0xC4, 0x65, 0x5D, 0xA4, 0xFB, 0xFC, 0x0E, 0x11,
232                0x08, 0xA8, 0xFD, 0x17, 0xB4, 0x48, 0xA6, 0x85, 0x54, 0x19, 0x9C, 0x47, 0xD0, 0x8F,
233                0xFB, 0x10, 0xD4, 0xB8, 0x02, 0x21, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
234                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF,
235                0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01,
236                0xA1, 0x44, 0x03, 0x42, 0x00,
237            ];
238            //        unsigned char *ptr = seckey;
239            //        memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
240            //        memcpy(ptr, key32, 32); ptr += 32;
241            //        memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
242            //        pubkeylen = CPubKey::PUBLIC_KEY_SIZE;
243            //        secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
244            //        ptr += pubkeylen;
245            //        *seckeylen = ptr - seckey;
246            //        assert(*seckeylen == CKey::PRIVATE_KEY_SIZE);
247            SecretVec::new(
248                begin
249                    .iter()
250                    .chain(keypair.to_secret_bytes().iter())
251                    .chain(middle.iter())
252                    .chain(keypair.public_key().serialize_uncompressed().iter())
253                    .copied()
254                    .collect(),
255            )
256        }
257    }
258
259    // Decodes a secret key from the "openssl-inspired" DER encoding used by zcashd.
260    pub fn der_decode(encoded: &SecretVec<u8>, compressed: bool) -> Result<Self, DerDecodeError> {
261        // Ported from https://github.com/zcash/zcash/blob/1f1f7a385adc048154e7f25a3a0de76f3658ca09/src/key.cpp#L36
262        // The original c++ code is retained as comments.
263
264        let seckey = encoded.expose_secret();
265
266        //    /* sequence header */
267        //    if (end - seckey < 1 || *seckey != 0x30u) {
268        //        return 0;
269        //    }
270        //    seckey++;
271        let seckey = match seckey.split_first() {
272            Some((&0x30, rest)) => Ok(rest),
273            _ => Err(DerDecodeError),
274        }?;
275
276        //    /* sequence length constructor */
277        //    if (end - seckey < 1 || !(*seckey & 0x80u)) {
278        //        return 0;
279        //    }
280        //    size_t lenb = *seckey & ~0x80u; seckey++;
281        //    if (lenb < 1 || lenb > 2) {
282        //        return 0;
283        //    }
284        //    if (end - seckey < lenb) {
285        //        return 0;
286        //    }
287        let (lenb, seckey) = match seckey.split_first() {
288            Some((lenb, seckey)) if lenb & 0x80 != 0 => Ok((usize::from(lenb & !0x80), seckey)),
289            _ => Err(DerDecodeError),
290        }?;
291        if !(1..=2).contains(&lenb) {
292            return Err(DerDecodeError);
293        }
294        if seckey.len() < lenb {
295            return Err(DerDecodeError);
296        }
297
298        //    /* sequence length */
299        //    size_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u);
300        //    seckey += lenb;
301        //    if (end - seckey < len) {
302        //        return 0;
303        //    }
304        let len_low_bits = usize::from(seckey[lenb - 1]);
305        let len_high_bits = if lenb > 1 {
306            usize::from(seckey[lenb - 2]) << 8
307        } else {
308            0
309        };
310        let len = len_low_bits | len_high_bits;
311        let seckey = &seckey[lenb..];
312        if seckey.len() < len {
313            return Err(DerDecodeError);
314        }
315
316        //    /* sequence element 0: version number (=1) */
317        //    if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) {
318        //        return 0;
319        //    }
320        //    seckey += 3;
321        let seckey = match seckey.split_at(3) {
322            (&[0x02, 0x01, 0x01], rest) => Ok(rest),
323            _ => Err(DerDecodeError),
324        }?;
325
326        //    /* sequence element 1: octet string, up to 32 bytes */
327        //    if (end - seckey < 2 || seckey[0] != 0x04u) {
328        //        return 0;
329        //    }
330        //    size_t oslen = seckey[1];
331        //    seckey += 2;
332        //    if (oslen > 32 || end - seckey < oslen) {
333        //        return 0;
334        //    }
335        //    memcpy(out32 + (32 - oslen), seckey, oslen);
336        //    if (!secp256k1_ec_seckey_verify(ctx, out32)) {
337        //        memset(out32, 0, 32);
338        //        return 0;
339        //    }
340        //    return 1;
341        //}
342        if seckey.len() < 2 || seckey[0] != 0x04 {
343            return Err(DerDecodeError);
344        }
345        let oslen = usize::from(seckey[1]);
346        let seckey = &seckey[2..];
347        if oslen > 32 || seckey.len() < oslen {
348            return Err(DerDecodeError);
349        }
350        let mut secret_buf = [0u8; 32];
351        secret_buf[(32 - oslen)..].copy_from_slice(&seckey[..oslen]);
352        let secret_key = SecretKey::from_bytes(&secret_buf);
353        secret_buf.zeroize();
354
355        secret_key
356            .map(|secret| Self { secret, compressed })
357            .map_err(|_| DerDecodeError)
358    }
359}
360
361#[cfg(feature = "transparent-key-encoding")]
362impl Zeroize for Key {
363    fn zeroize(&mut self) {
364        self.secret.non_secure_erase();
365    }
366}
367
368#[cfg(feature = "transparent-key-encoding")]
369impl ZeroizeOnDrop for Key {}
370
371/// The scope of a transparent key.
372///
373/// This type can represent [`zip32`] internal and external scopes, as well as custom scopes that
374/// may be used in non-hardened derivation at the `change` level of the BIP 44 key path.
375#[derive(Clone, Copy, PartialEq, Eq, Hash)]
376pub struct TransparentKeyScope(u32);
377
378impl TransparentKeyScope {
379    /// Returns an arbitrary custom `TransparentKeyScope`.
380    ///
381    /// This should be used with care: funds associated with keys derived under a custom
382    /// scope may not be recoverable if the wallet seed is restored in another wallet. It
383    /// is usually preferable to use standardized key scopes.
384    pub const fn custom(i: u32) -> Option<Self> {
385        if i < (1 << 31) {
386            Some(TransparentKeyScope(i))
387        } else {
388            None
389        }
390    }
391
392    /// The scope used to derive keys for external transparent addresses,
393    /// intended to be used to send funds to this wallet.
394    pub const EXTERNAL: Self = TransparentKeyScope(0);
395
396    /// The scope used to derive keys for internal wallet operations, e.g.
397    /// change or UTXO management.
398    pub const INTERNAL: Self = TransparentKeyScope(1);
399
400    /// The scope used to derive keys for ephemeral transparent addresses.
401    pub const EPHEMERAL: Self = TransparentKeyScope(2);
402}
403
404impl fmt::Debug for TransparentKeyScope {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        match *self {
407            Self::EXTERNAL => f.write_str("TransparentKeyScope::EXTERNAL"),
408            Self::INTERNAL => f.write_str("TransparentKeyScope::INTERNAL"),
409            Self::EPHEMERAL => f.write_str("TransparentKeyScope::EPHEMERAL"),
410            TransparentKeyScope(other) => f.write_str(&format!("TransparentKeyScope({other})")),
411        }
412    }
413}
414
415impl From<zip32::Scope> for TransparentKeyScope {
416    fn from(value: zip32::Scope) -> Self {
417        match value {
418            zip32::Scope::External => TransparentKeyScope::EXTERNAL,
419            zip32::Scope::Internal => TransparentKeyScope::INTERNAL,
420        }
421    }
422}
423
424impl From<TransparentKeyScope> for ChildNumber {
425    fn from(value: TransparentKeyScope) -> Self {
426        ChildNumber::new(value.0, false).expect("TransparentKeyScope is correct by construction")
427    }
428}
429
430/// A child index for a derived transparent address.
431///
432/// Only NON-hardened derivation is supported.
433#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
434pub struct NonHardenedChildIndex(u32);
435
436impl core::fmt::Debug for NonHardenedChildIndex {
437    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438        f.write_str(&format!("NonHardenedChildIndex({})", self.0))
439    }
440}
441
442impl ConstantTimeEq for NonHardenedChildIndex {
443    fn ct_eq(&self, other: &Self) -> Choice {
444        self.0.ct_eq(&other.0)
445    }
446}
447
448impl NonHardenedChildIndex {
449    /// The minimum valid non-hardened child index.
450    pub const ZERO: NonHardenedChildIndex = NonHardenedChildIndex(0);
451
452    /// The maximum valid non-hardened child index.
453    pub const MAX: NonHardenedChildIndex = NonHardenedChildIndex((1 << 31) - 1);
454
455    /// Parses the given ZIP 32 child index.
456    ///
457    /// Returns `None` if the hardened bit is set.
458    pub const fn from_index(i: u32) -> Option<Self> {
459        if i <= Self::MAX.0 {
460            Some(NonHardenedChildIndex(i))
461        } else {
462            None
463        }
464    }
465
466    /// Constructs a [`NonHardenedChildIndex`] from a ZIP 32 child index.
467    ///
468    /// Panics: if the hardened bit is set.
469    pub const fn const_from_index(i: u32) -> Self {
470        assert!(i <= Self::MAX.0);
471        NonHardenedChildIndex(i)
472    }
473
474    /// Returns the index as a 32-bit integer.
475    pub const fn index(&self) -> u32 {
476        self.0
477    }
478
479    /// Returns the successor to this index.
480    pub const fn next(&self) -> Option<Self> {
481        // overflow cannot happen because self.0 is 31 bits, and the next index is at most 32 bits
482        // which in that case would lead from_index to return None.
483        Self::from_index(self.0 + 1)
484    }
485
486    /// Subtracts the given delta from this index.
487    pub const fn saturating_sub(&self, delta: u32) -> Self {
488        NonHardenedChildIndex(self.0.saturating_sub(delta))
489    }
490
491    /// Adds the given delta to this index, returning a maximum possible value of
492    /// [`NonHardenedChildIndex::MAX`].
493    pub const fn saturating_add(&self, delta: u32) -> Self {
494        let idx = self.0.saturating_add(delta);
495        if idx > Self::MAX.0 {
496            Self::MAX
497        } else {
498            NonHardenedChildIndex(idx)
499        }
500    }
501}
502
503impl TryFrom<ChildNumber> for NonHardenedChildIndex {
504    type Error = ();
505
506    fn try_from(value: ChildNumber) -> Result<Self, Self::Error> {
507        if value.is_hardened() {
508            Err(())
509        } else {
510            NonHardenedChildIndex::from_index(value.index()).ok_or(())
511        }
512    }
513}
514
515impl From<NonHardenedChildIndex> for ChildNumber {
516    fn from(value: NonHardenedChildIndex) -> Self {
517        Self::new(value.index(), false).expect("NonHardenedChildIndex is correct by construction")
518    }
519}
520
521impl TryFrom<DiversifierIndex> for NonHardenedChildIndex {
522    type Error = ();
523
524    fn try_from(value: DiversifierIndex) -> Result<Self, Self::Error> {
525        let idx = u32::try_from(value).map_err(|_| ())?;
526        NonHardenedChildIndex::from_index(idx).ok_or(())
527    }
528}
529
530impl From<NonHardenedChildIndex> for DiversifierIndex {
531    fn from(value: NonHardenedChildIndex) -> Self {
532        DiversifierIndex::from(value.0)
533    }
534}
535
536/// An end-exclusive iterator over a range of non-hardened child indexes.
537pub struct NonHardenedChildIter {
538    next: Option<NonHardenedChildIndex>,
539    end: NonHardenedChildIndex,
540}
541
542impl Iterator for NonHardenedChildIter {
543    type Item = NonHardenedChildIndex;
544
545    fn next(&mut self) -> Option<Self::Item> {
546        let cur = self.next;
547        self.next = self
548            .next
549            .and_then(|i| i.next())
550            .filter(|succ| succ < &self.end);
551        cur
552    }
553}
554
555/// An end-exclusive range of non-hardened child indexes.
556pub struct NonHardenedChildRange(core::ops::Range<NonHardenedChildIndex>);
557
558impl From<core::ops::Range<NonHardenedChildIndex>> for NonHardenedChildRange {
559    fn from(value: core::ops::Range<NonHardenedChildIndex>) -> Self {
560        Self(value)
561    }
562}
563
564impl IntoIterator for NonHardenedChildRange {
565    type Item = NonHardenedChildIndex;
566    type IntoIter = NonHardenedChildIter;
567
568    fn into_iter(self) -> Self::IntoIter {
569        NonHardenedChildIter {
570            next: (self.0.start < self.0.end).then_some(self.0.start),
571            end: self.0.end,
572        }
573    }
574}
575
576/// The hardened BIP 43 purpose index of a BIP 44 derivation path.
577const BIP_44_PURPOSE: ChildNumber = ChildNumber(44 | ChildNumber::HARDENED_FLAG);
578
579/// The hardened BIP 43 purpose index of a ZIP 48 derivation path.
580const ZIP_48_PURPOSE: ChildNumber = ChildNumber(48 | ChildNumber::HARDENED_FLAG);
581
582/// The hardened ZIP 48 script type index for P2SH.
583const ZIP_48_P2SH_SCRIPT_TYPE: ChildNumber = ChildNumber(133000 | ChildNumber::HARDENED_FLAG);
584
585/// Extracts the BIP 44 account index, scope, and address index from a PCZT derivation
586/// path.
587///
588/// `expected_coin_type` is the hardened coin type index of the network.
589///
590/// Returns `None` if the seed fingerprints don't match, or if this is not a BIP 44
591/// derivation path for `expected_coin_type`.
592pub fn extract_bip_44_fields(
593    derivation: &Bip32Derivation,
594    seed_fp: &zip32::fingerprint::SeedFingerprint,
595    expected_coin_type: ChildNumber,
596) -> Option<(zip32::AccountId, TransparentKeyScope, NonHardenedChildIndex)> {
597    if *derivation.seed_fingerprint() == seed_fp.to_bytes() {
598        match &derivation.derivation_path()[..] {
599            [purpose, coin_type, account_index, scope, address_index]
600                if purpose == &BIP_44_PURPOSE
601                    && coin_type.is_hardened()
602                    && coin_type == &expected_coin_type
603                    && account_index.is_hardened()
604                    && !scope.is_hardened()
605                    && !address_index.is_hardened() =>
606            {
607                let account_index = zip32::AccountId::try_from(account_index.index())
608                    .expect("account_index is hardened");
609
610                let scope =
611                    TransparentKeyScope::custom(scope.index()).expect("scope is not hardened");
612
613                let address_index = NonHardenedChildIndex::from_index(address_index.index())
614                    .expect("address_index is not hardened");
615
616                Some((account_index, scope, address_index))
617            }
618            _ => None,
619        }
620    } else {
621        None
622    }
623}
624
625/// Extracts the ZIP 48 account index, scope, and address index from a PCZT derivation
626/// path.
627///
628/// `expected_coin_type` is the hardened coin type index of the network.
629///
630/// Returns `None` if the seed fingerprints don't match, if this is not a ZIP 48
631/// derivation path for `expected_coin_type`, or if its scope is neither external (0)
632/// nor internal (1).
633pub fn extract_zip_48_fields(
634    derivation: &Bip32Derivation,
635    seed_fp: &zip32::fingerprint::SeedFingerprint,
636    expected_coin_type: ChildNumber,
637) -> Option<(zip32::AccountId, zip32::Scope, NonHardenedChildIndex)> {
638    if *derivation.seed_fingerprint() == seed_fp.to_bytes() {
639        match &derivation.derivation_path()[..] {
640            [
641                purpose,
642                coin_type,
643                account_index,
644                script_type,
645                scope,
646                address_index,
647            ] if purpose == &ZIP_48_PURPOSE
648                && coin_type.is_hardened()
649                && coin_type == &expected_coin_type
650                && account_index.is_hardened()
651                && script_type == &ZIP_48_P2SH_SCRIPT_TYPE
652                && !scope.is_hardened()
653                && !address_index.is_hardened() =>
654            {
655                let account_index = zip32::AccountId::try_from(account_index.index())
656                    .expect("account_index is hardened");
657
658                let scope = match scope.index() {
659                    0 => Some(zip32::Scope::External),
660                    1 => Some(zip32::Scope::Internal),
661                    _ => None,
662                };
663
664                let address_index = NonHardenedChildIndex::from_index(address_index.index())
665                    .expect("address_index is not hardened");
666
667                scope.map(|scope| (account_index, scope, address_index))
668            }
669            _ => None,
670        }
671    } else {
672        None
673    }
674}
675
676/// A [BIP44] private key at the account path level `m/44'/<coin_type>'/<account>'`.
677///
678/// [BIP44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
679#[derive(Clone)]
680#[cfg(feature = "transparent-inputs")]
681pub struct AccountPrivKey(ExtendedPrivateKey<secp256k1::SecretKey>);
682
683#[cfg(feature = "transparent-inputs")]
684impl core::fmt::Debug for AccountPrivKey {
685    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
686        f.debug_tuple("AccountPrivKey").field(&"...").finish()
687    }
688}
689
690#[cfg(feature = "transparent-inputs")]
691impl AccountPrivKey {
692    /// Performs derivation of the extended private key for the BIP44 path:
693    /// `m/44'/<coin_type>'/<account>'`.
694    ///
695    /// This produces the root of the derivation tree for transparent
696    /// viewing keys and addresses for the provided account.
697    pub fn from_seed<P: consensus::Parameters>(
698        params: &P,
699        seed: &[u8],
700        account: AccountId,
701    ) -> Result<AccountPrivKey, bip32::Error> {
702        ExtendedPrivateKey::new(seed)?
703            .derive_child(BIP_44_PURPOSE)?
704            .derive_child(ChildNumber::new(params.coin_type(), true)?)?
705            .derive_child(ChildNumber::new(account.into(), true)?)
706            .map(AccountPrivKey)
707    }
708
709    pub fn from_extended_privkey(extprivkey: ExtendedPrivateKey<secp256k1::SecretKey>) -> Self {
710        AccountPrivKey(extprivkey)
711    }
712
713    pub fn to_account_pubkey(&self) -> AccountPubKey {
714        AccountPubKey(ExtendedPublicKey::from(&self.0))
715    }
716
717    /// Derives the BIP44 private spending key for the child path
718    /// `m/44'/<coin_type>'/<account>'/<scope>/<address_index>`.
719    pub fn derive_secret_key(
720        &self,
721        scope: TransparentKeyScope,
722        address_index: NonHardenedChildIndex,
723    ) -> Result<secp256k1::SecretKey, bip32::Error> {
724        self.0
725            .derive_child(scope.into())?
726            .derive_child(address_index.into())
727            .map(|k| *k.private_key())
728    }
729
730    /// Derives the BIP44 private spending key for the external (incoming payment) child path
731    /// `m/44'/<coin_type>'/<account>'/0/<address_index>`.
732    pub fn derive_external_secret_key(
733        &self,
734        address_index: NonHardenedChildIndex,
735    ) -> Result<secp256k1::SecretKey, bip32::Error> {
736        self.derive_secret_key(zip32::Scope::External.into(), address_index)
737    }
738
739    /// Derives the BIP44 private spending key for the internal (change) child path
740    /// `m/44'/<coin_type>'/<account>'/1/<address_index>`.
741    pub fn derive_internal_secret_key(
742        &self,
743        address_index: NonHardenedChildIndex,
744    ) -> Result<secp256k1::SecretKey, bip32::Error> {
745        self.derive_secret_key(zip32::Scope::Internal.into(), address_index)
746    }
747
748    /// Returns the `AccountPrivKey` serialized using the encoding for a
749    /// [BIP 32](https://en.bitcoin.it/wiki/BIP_0032) ExtendedPrivateKey, excluding the
750    /// 4 prefix bytes.
751    pub fn to_bytes(&self) -> Vec<u8> {
752        // Convert to `xprv` encoding.
753        let xprv_encoded = self.0.to_extended_key(Prefix::XPRV).to_string();
754
755        // Now decode it and return the bytes we want.
756        bs58::decode(xprv_encoded)
757            .with_check(None)
758            .into_vec()
759            .expect("correct")
760            .split_off(Prefix::LENGTH)
761    }
762
763    /// Decodes the `AccountPrivKey` from the encoding specified for a
764    /// [BIP 32](https://en.bitcoin.it/wiki/BIP_0032) ExtendedPrivateKey, excluding the
765    /// 4 prefix bytes.
766    pub fn from_bytes(b: &[u8]) -> Option<Self> {
767        // Convert to `xprv` encoding.
768        let mut bytes = Prefix::XPRV.to_bytes().to_vec();
769        bytes.extend_from_slice(b);
770        let xprv_encoded = bs58::encode(bytes).with_check().into_string();
771
772        // Now we can parse it.
773        xprv_encoded
774            .parse::<ExtendedKey>()
775            .ok()
776            .and_then(|k| ExtendedPrivateKey::try_from(k).ok())
777            .map(AccountPrivKey::from_extended_privkey)
778    }
779}
780
781/// A [BIP44] public key at the account path level `m/44'/<coin_type>'/<account>'`.
782///
783/// This provides the necessary derivation capability for the transparent component of a unified
784/// full viewing key.
785///
786/// [BIP44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
787#[cfg(feature = "transparent-inputs")]
788#[derive(Clone)]
789pub struct AccountPubKey(ExtendedPublicKey<PublicKey>);
790
791/// Compares only the chain code and public key, ignoring BIP 32 derivation
792/// metadata (depth, parent fingerprint, child number) which are not preserved
793/// by the UFVK encoding.
794#[cfg(feature = "transparent-inputs")]
795impl PartialEq for AccountPubKey {
796    fn eq(&self, other: &Self) -> bool {
797        self.0.attrs().chain_code == other.0.attrs().chain_code
798            && self.0.public_key() == other.0.public_key()
799    }
800}
801
802#[cfg(feature = "transparent-inputs")]
803impl Eq for AccountPubKey {}
804
805#[cfg(feature = "transparent-inputs")]
806impl core::fmt::Debug for AccountPubKey {
807    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
808        f.debug_tuple("AccountPubKey").field(&"...").finish()
809    }
810}
811
812#[cfg(feature = "transparent-inputs")]
813impl AccountPubKey {
814    /// Derives the BIP44 public key at the external "change level" path
815    /// `m/44'/<coin_type>'/<account>'/0`.
816    pub fn derive_external_ivk(&self) -> Result<ExternalIvk, bip32::Error> {
817        self.0
818            .derive_child(ChildNumber::new(0, false)?)
819            .map(ExternalIvk)
820    }
821
822    /// Derives the BIP44 public key at the internal "change level" path
823    /// `m/44'/<coin_type>'/<account>'/1`.
824    pub fn derive_internal_ivk(&self) -> Result<InternalIvk, bip32::Error> {
825        self.0
826            .derive_child(ChildNumber::new(1, false)?)
827            .map(InternalIvk)
828    }
829
830    /// Derives the public key at the "ephemeral" path
831    /// `m/44'/<coin_type>'/<account>'/2`.
832    pub fn derive_ephemeral_ivk(&self) -> Result<EphemeralIvk, bip32::Error> {
833        self.0
834            .derive_child(ChildNumber::new(2, false)?)
835            .map(EphemeralIvk)
836    }
837
838    /// Derives the BIP44 public key at the "address level" path corresponding to the given scope
839    /// and address index.
840    pub fn derive_address_pubkey(
841        &self,
842        scope: TransparentKeyScope,
843        address_index: NonHardenedChildIndex,
844    ) -> Result<secp256k1::PublicKey, bip32::Error> {
845        Ok(*self
846            .0
847            .derive_child(scope.into())?
848            .derive_child(address_index.into())?
849            .public_key())
850    }
851
852    /// Derives the public key corresponding to the given full BIP 32 path.
853    ///
854    /// This enforces that the path has a prefix that could have been used to derive this
855    /// `AccountPubKey`.
856    pub fn derive_pubkey_at_bip32_path<P: consensus::Parameters>(
857        &self,
858        params: &P,
859        expected_account_index: AccountId,
860        path: &[ChildNumber],
861    ) -> Result<secp256k1::PublicKey, bip32::Error> {
862        if path.len() < 3 {
863            Err(bip32::Error::ChildNumber)
864        } else {
865            match path.split_at(3) {
866                ([purpose, coin_type, account_index], sub_path)
867                    if purpose.is_hardened()
868                        && purpose.index() == 44
869                        && coin_type.is_hardened()
870                        && coin_type.index() == params.network_type().coin_type()
871                        && account_index.is_hardened()
872                        && account_index.index() == expected_account_index.into() =>
873                {
874                    sub_path
875                        .iter()
876                        .try_fold(self.0.clone(), |acc, child_index| {
877                            acc.derive_child(*child_index)
878                        })
879                        .map(|k| *k.public_key())
880                }
881                _ => Err(bip32::Error::ChildNumber),
882            }
883        }
884    }
885
886    /// Derives the internal ovk and external ovk corresponding to this
887    /// transparent fvk. As specified in [ZIP 316][transparent-ovk].
888    ///
889    /// A wallet uses these both to encrypt the outgoing ciphertexts of a transaction that spends
890    /// transparent funds, and to recover the outgoing ciphertexts of such a transaction.
891    ///
892    /// [transparent-ovk]: https://zips.z.cash/zip-0316#deriving-internal-keys
893    pub fn ovks_for_shielding(&self) -> ShieldingOvks {
894        let i_ovk = PrfExpand::TRANSPARENT_ZIP316_OVK
895            .with(&self.0.attrs().chain_code, &self.0.public_key().serialize());
896        let ovk_external = ExternalOvk(i_ovk[..32].try_into().unwrap());
897        let ovk_internal = InternalOvk(i_ovk[32..].try_into().unwrap());
898
899        ShieldingOvks::new(ovk_internal, ovk_external)
900    }
901
902    /// Derives the internal ovk corresponding to this transparent fvk.
903    pub fn internal_ovk(&self) -> InternalOvk {
904        self.ovks_for_shielding().internal
905    }
906
907    /// Derives the external ovk corresponding to this transparent fvk.
908    pub fn external_ovk(&self) -> ExternalOvk {
909        self.ovks_for_shielding().external
910    }
911
912    pub fn serialize(&self) -> Vec<u8> {
913        let mut buf = self.0.attrs().chain_code.to_vec();
914        buf.extend_from_slice(&self.0.public_key().serialize());
915        buf
916    }
917
918    pub fn deserialize(data: &[u8; 65]) -> Result<Self, bip32::Error> {
919        let chain_code = data[..32].try_into().expect("correct length");
920        let public_key = PublicKey::from_slice(&data[32..])?;
921        Ok(AccountPubKey(ExtendedPublicKey::new(
922            public_key,
923            ExtendedKeyAttrs {
924                depth: 3,
925                // We do not expose the inner `ExtendedPublicKey`, so we can use dummy
926                // values for the fields that are not encoded in an `AccountPubKey`.
927                parent_fingerprint: [0xff, 0xff, 0xff, 0xff],
928                child_number: ChildNumber::new(0, true).expect("correct"),
929                chain_code,
930            },
931        )))
932    }
933}
934
935#[cfg(feature = "transparent-inputs")]
936pub(crate) mod private {
937    use super::TransparentKeyScope;
938    use bip32::ExtendedPublicKey;
939    use secp256k1::PublicKey;
940    pub trait SealedChangeLevelKey {
941        const SCOPE: TransparentKeyScope;
942        fn extended_pubkey(&self) -> &ExtendedPublicKey<PublicKey>;
943        fn from_extended_pubkey(key: ExtendedPublicKey<PublicKey>) -> Self;
944    }
945}
946
947/// Trait representing a transparent "incoming viewing key".
948///
949/// Unlike the Sapling and Orchard shielded protocols (which have viewing keys built into
950/// their key trees and bound to specific spending keys), the transparent protocol has no
951/// "viewing key" concept. Transparent viewing keys are instead emulated by making two
952/// observations:
953///
954/// - [BIP32] hierarchical derivation is structured as a tree.
955/// - The [BIP44] key paths use non-hardened derivation below the account level.
956///
957/// A transparent viewing key for an account is thus defined as the root of a specific
958/// non-hardened subtree underneath the account's path.
959///
960/// [BIP32]: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
961/// [BIP44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
962#[cfg(feature = "transparent-inputs")]
963pub trait IncomingViewingKey: private::SealedChangeLevelKey + core::marker::Sized {
964    /// Derives a transparent address at the provided child index.
965    #[allow(deprecated)]
966    fn derive_address(
967        &self,
968        address_index: NonHardenedChildIndex,
969    ) -> Result<TransparentAddress, bip32::Error> {
970        Ok(TransparentAddress::from_pubkey(
971            &self.derive_pubkey(address_index)?,
972        ))
973    }
974
975    /// Derives the public key at the provided child index.
976    ///
977    /// This is the key material [`derive_address`](Self::derive_address) hashes, which a
978    /// caller needs directly when the address is determined by a script over several keys
979    /// rather than by a single key hash.
980    fn derive_pubkey(
981        &self,
982        address_index: NonHardenedChildIndex,
983    ) -> Result<PublicKey, bip32::Error> {
984        Ok(*self
985            .extended_pubkey()
986            .derive_child(address_index.into())?
987            .public_key())
988    }
989
990    /// Searches the space of child indexes for an index that will
991    /// generate a valid transparent address, and returns the resulting
992    /// address and the index at which it was generated.
993    fn default_address(&self) -> (TransparentAddress, NonHardenedChildIndex) {
994        let mut address_index = NonHardenedChildIndex::ZERO;
995        loop {
996            match self.derive_address(address_index) {
997                Ok(addr) => {
998                    return (addr, address_index);
999                }
1000                Err(_) => {
1001                    address_index = address_index.next().unwrap_or_else(|| {
1002                        panic!("Exhausted child index space attempting to find a default address.");
1003                    });
1004                }
1005            }
1006        }
1007    }
1008
1009    fn serialize(&self) -> Vec<u8> {
1010        let extpubkey = self.extended_pubkey();
1011        let mut buf = extpubkey.attrs().chain_code.to_vec();
1012        buf.extend_from_slice(&extpubkey.public_key().serialize());
1013        buf
1014    }
1015
1016    fn deserialize(data: &[u8; 65]) -> Result<Self, bip32::Error> {
1017        let chain_code = data[..32].try_into().expect("correct length");
1018        let public_key = PublicKey::from_slice(&data[32..])?;
1019        Ok(Self::from_extended_pubkey(ExtendedPublicKey::new(
1020            public_key,
1021            ExtendedKeyAttrs {
1022                depth: 4,
1023                // We do not expose the inner `ExtendedPublicKey`, so we can use a dummy
1024                // value for the `parent_fingerprint` that is not encoded in an
1025                // `IncomingViewingKey`.
1026                parent_fingerprint: [0xff, 0xff, 0xff, 0xff],
1027                child_number: Self::SCOPE.into(),
1028                chain_code,
1029            },
1030        )))
1031    }
1032}
1033
1034/// An incoming viewing key at the [BIP44] "external" path
1035/// `m/44'/<coin_type>'/<account>'/0`.
1036///
1037/// This allows derivation of child addresses that may be provided to external parties.
1038///
1039/// [BIP44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
1040#[cfg(feature = "transparent-inputs")]
1041#[derive(Clone, PartialEq, Eq)]
1042pub struct ExternalIvk(ExtendedPublicKey<PublicKey>);
1043
1044#[cfg(feature = "transparent-inputs")]
1045impl core::fmt::Debug for ExternalIvk {
1046    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1047        f.debug_tuple("ExternalIvk").field(&"...").finish()
1048    }
1049}
1050
1051#[cfg(feature = "transparent-inputs")]
1052impl private::SealedChangeLevelKey for ExternalIvk {
1053    const SCOPE: TransparentKeyScope = TransparentKeyScope(0);
1054
1055    fn extended_pubkey(&self) -> &ExtendedPublicKey<PublicKey> {
1056        &self.0
1057    }
1058
1059    fn from_extended_pubkey(key: ExtendedPublicKey<PublicKey>) -> Self {
1060        ExternalIvk(key)
1061    }
1062}
1063
1064#[cfg(feature = "transparent-inputs")]
1065impl IncomingViewingKey for ExternalIvk {}
1066
1067/// An incoming viewing key at the [BIP44] "internal" path
1068/// `m/44'/<coin_type>'/<account>'/1`.
1069///
1070/// This allows derivation of change addresses for use within the wallet, but which should
1071/// not be shared with external parties.
1072///
1073/// [BIP44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
1074#[cfg(feature = "transparent-inputs")]
1075#[derive(Clone)]
1076pub struct InternalIvk(ExtendedPublicKey<PublicKey>);
1077
1078#[cfg(feature = "transparent-inputs")]
1079impl core::fmt::Debug for InternalIvk {
1080    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1081        f.debug_tuple("InternalIvk").field(&"...").finish()
1082    }
1083}
1084
1085#[cfg(feature = "transparent-inputs")]
1086impl private::SealedChangeLevelKey for InternalIvk {
1087    const SCOPE: TransparentKeyScope = TransparentKeyScope(1);
1088
1089    fn extended_pubkey(&self) -> &ExtendedPublicKey<PublicKey> {
1090        &self.0
1091    }
1092
1093    fn from_extended_pubkey(key: ExtendedPublicKey<PublicKey>) -> Self {
1094        InternalIvk(key)
1095    }
1096}
1097
1098#[cfg(feature = "transparent-inputs")]
1099impl IncomingViewingKey for InternalIvk {}
1100
1101/// An incoming viewing key at the "ephemeral" path
1102/// `m/44'/<coin_type>'/<account>'/2`.
1103///
1104/// This allows derivation of ephemeral addresses for use within the wallet.
1105#[cfg(feature = "transparent-inputs")]
1106#[derive(Clone)]
1107pub struct EphemeralIvk(ExtendedPublicKey<PublicKey>);
1108
1109#[cfg(feature = "transparent-inputs")]
1110impl core::fmt::Debug for EphemeralIvk {
1111    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1112        f.debug_tuple("EphemeralIvk").field(&"...").finish()
1113    }
1114}
1115
1116#[cfg(feature = "transparent-inputs")]
1117impl EphemeralIvk {
1118    /// Derives a transparent address at the provided child index.
1119    pub fn derive_ephemeral_address(
1120        &self,
1121        address_index: NonHardenedChildIndex,
1122    ) -> Result<TransparentAddress, bip32::Error> {
1123        let child_key = self.0.derive_child(address_index.into())?;
1124        #[allow(deprecated)]
1125        Ok(TransparentAddress::from_pubkey(child_key.public_key()))
1126    }
1127}
1128
1129/// Internal outgoing viewing key used for autoshielding.
1130pub struct InternalOvk([u8; 32]);
1131
1132impl core::fmt::Debug for InternalOvk {
1133    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1134        f.debug_tuple("InternalOvk").field(&"...").finish()
1135    }
1136}
1137
1138impl InternalOvk {
1139    pub fn as_bytes(&self) -> [u8; 32] {
1140        self.0
1141    }
1142}
1143
1144/// External outgoing viewing key used by `zcashd` for transparent-to-shielded spends to
1145/// external receivers.
1146pub struct ExternalOvk([u8; 32]);
1147
1148impl core::fmt::Debug for ExternalOvk {
1149    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1150        f.debug_tuple("ExternalOvk").field(&"...").finish()
1151    }
1152}
1153
1154impl ExternalOvk {
1155    pub fn as_bytes(&self) -> [u8; 32] {
1156        self.0
1157    }
1158}
1159
1160/// The pair of outgoing viewing keys derived from a transparent full viewing key, as specified in
1161/// [ZIP 316][transparent-ovk].
1162///
1163/// The two keys are distinct types, but a consumer reaches [`InternalOvk::as_bytes`] or
1164/// [`ExternalOvk::as_bytes`] almost immediately, and past that point the scope of a key is carried
1165/// only by the position it was read from. [`Self::internal`] and [`Self::external`] name the scope
1166/// at that boundary, so that binding a key to the wrong scope is a visible mistake rather than a
1167/// transposition.
1168///
1169/// [transparent-ovk]: https://zips.z.cash/zip-0316#deriving-internal-keys
1170#[derive(Debug)]
1171pub struct ShieldingOvks {
1172    internal: InternalOvk,
1173    external: ExternalOvk,
1174}
1175
1176impl ShieldingOvks {
1177    /// Constructs the pair from its two scopes.
1178    pub fn new(internal: InternalOvk, external: ExternalOvk) -> Self {
1179        Self { internal, external }
1180    }
1181
1182    /// Returns the outgoing viewing key for the internal scope, which a wallet uses for the
1183    /// outputs it sends to itself.
1184    pub fn internal(&self) -> &InternalOvk {
1185        &self.internal
1186    }
1187
1188    /// Returns the outgoing viewing key for the external scope, which a wallet uses for the
1189    /// outputs it sends to other recipients.
1190    pub fn external(&self) -> &ExternalOvk {
1191        &self.external
1192    }
1193}
1194
1195#[cfg(all(
1196    feature = "transparent-key-encoding",
1197    any(test, feature = "test-dependencies")
1198))]
1199pub mod test_vectors;
1200
1201#[cfg(all(test, feature = "transparent-inputs"))]
1202mod derivation_test_vectors;
1203
1204#[cfg(all(test, feature = "transparent-key-encoding"))]
1205mod tests {
1206    use rand::{Rng, RngExt, SeedableRng as _};
1207    use rand_chacha::ChaChaRng;
1208    use secp256k1::SecretKey;
1209    use secrecy::SecretString;
1210    use zcash_protocol::consensus::NetworkType;
1211    use zcash_script::script::Evaluable;
1212
1213    use super::{
1214        Key,
1215        test_vectors::{INVALID, VALID, VectorKind},
1216    };
1217    use crate::address::Address;
1218
1219    /// Generates a uniformly random secp256k1 secret key.
1220    fn random_secret_key(rng: &mut impl Rng) -> SecretKey {
1221        loop {
1222            let mut bytes = [0u8; 32];
1223            rng.fill_bytes(&mut bytes);
1224            if let Ok(secret) = SecretKey::from_secret_bytes(bytes) {
1225                return secret;
1226            }
1227        }
1228    }
1229
1230    #[test]
1231    #[cfg(feature = "transparent-key-encoding")]
1232    fn der_encoding_roundtrip() {
1233        let mut rng = ChaChaRng::from_seed([0u8; 32]);
1234        for _ in 0..100 {
1235            let secret = random_secret_key(&mut rng);
1236            let compressed = rng.random_bool(0.5);
1237            let key = Key { secret, compressed };
1238
1239            let encoded = key.der_encode();
1240            let decoded = Key::der_decode(&encoded, compressed).unwrap();
1241
1242            assert_eq!(key.secret(), decoded.secret());
1243        }
1244    }
1245
1246    /// Checks that parsed keys match test payload.
1247    #[test]
1248    fn base58_keys_valid_parse() {
1249        for v in VALID {
1250            match v.kind {
1251                VectorKind::Privkey { is_compressed } => {
1252                    // Must be valid private key
1253                    let secret = &SecretString::new(v.base58_encoding.into());
1254                    let privkey = Key::decode_base58(v.network, secret).unwrap();
1255                    assert_eq!(privkey.compressed, is_compressed);
1256                    assert_eq!(
1257                        hex::encode(privkey.secret.to_secret_bytes()),
1258                        v.raw_bytes_hex
1259                    );
1260
1261                    // Private key must be invalid public key
1262                    assert_eq!(
1263                        zcash_address::ZcashAddress::try_from_encoded(v.base58_encoding),
1264                        Err(zcash_address::ParseError::NotZcash),
1265                    );
1266                }
1267                VectorKind::Pubkey => {
1268                    // Must be valid public key
1269                    let destination =
1270                        match zcash_address::ZcashAddress::try_from_encoded(v.base58_encoding)
1271                            .unwrap()
1272                            .convert_if_network::<Address>(v.network)
1273                            .unwrap()
1274                        {
1275                            Address::Transparent(addr) => addr,
1276                            _ => panic!("{} is not a transparent address", v.base58_encoding),
1277                        };
1278                    let script = destination.script();
1279                    assert_eq!(hex::encode(script.to_bytes()), v.raw_bytes_hex);
1280
1281                    // Public key must be invalid private key
1282                    assert!(
1283                        Key::decode_base58(v.network, &SecretString::new(v.base58_encoding.into()))
1284                            .is_err()
1285                    );
1286                }
1287            }
1288        }
1289    }
1290
1291    /// Checks that Base58 key parsing code is robust against a variety of corrupted data.
1292    #[test]
1293    fn base58_keys_invalid() {
1294        for &encoded in INVALID {
1295            assert!(
1296                Key::decode_base58(NetworkType::Main, &SecretString::new(encoded.into())).is_err()
1297            );
1298            assert_eq!(
1299                zcash_address::ZcashAddress::try_from_encoded(encoded),
1300                Err(zcash_address::ParseError::NotZcash),
1301            );
1302        }
1303    }
1304
1305    #[test]
1306    #[cfg(feature = "transparent-key-encoding")]
1307    fn key_debug_redaction() {
1308        let mut rng = ChaChaRng::from_seed([0u8; 32]);
1309        let secret = random_secret_key(&mut rng);
1310        let key = Key {
1311            secret,
1312            compressed: true,
1313        };
1314        let debug_str = format!("{key:?}");
1315        assert!(debug_str.contains("secret: \"...\""));
1316        assert!(debug_str.contains("compressed: true"));
1317    }
1318}
1319
1320#[cfg(test)]
1321mod derivation_path_tests {
1322    use bip32::ChildNumber;
1323    use zcash_protocol::consensus::{MAIN_NETWORK, NetworkConstants};
1324    use zip32::{AccountId, fingerprint::SeedFingerprint};
1325
1326    use ::transparent::pczt::Bip32Derivation;
1327
1328    use super::{
1329        BIP_44_PURPOSE, NonHardenedChildIndex, TransparentKeyScope, ZIP_48_P2SH_SCRIPT_TYPE,
1330        ZIP_48_PURPOSE, extract_bip_44_fields, extract_zip_48_fields,
1331    };
1332
1333    const HARDENED: u32 = ChildNumber::HARDENED_FLAG;
1334
1335    /// The account index used by every path below.
1336    const ACCOUNT: u32 = 3;
1337
1338    /// The address index used by every path below.
1339    const ADDRESS_INDEX: u32 = 5;
1340
1341    fn seed_fingerprint() -> SeedFingerprint {
1342        SeedFingerprint::from_seed(&[0u8; 32]).unwrap()
1343    }
1344
1345    fn coin_type() -> ChildNumber {
1346        ChildNumber(MAIN_NETWORK.coin_type() | HARDENED)
1347    }
1348
1349    fn derivation(path: &[u32]) -> Bip32Derivation {
1350        Bip32Derivation::parse(seed_fingerprint().to_bytes(), path.to_vec()).unwrap()
1351    }
1352
1353    fn bip_44_path() -> [u32; 5] {
1354        [
1355            BIP_44_PURPOSE.0,
1356            MAIN_NETWORK.coin_type() | HARDENED,
1357            ACCOUNT | HARDENED,
1358            TransparentKeyScope::INTERNAL.0,
1359            ADDRESS_INDEX,
1360        ]
1361    }
1362
1363    fn zip_48_path() -> [u32; 6] {
1364        [
1365            ZIP_48_PURPOSE.0,
1366            MAIN_NETWORK.coin_type() | HARDENED,
1367            ACCOUNT | HARDENED,
1368            ZIP_48_P2SH_SCRIPT_TYPE.0,
1369            TransparentKeyScope::EXTERNAL.0,
1370            ADDRESS_INDEX,
1371        ]
1372    }
1373
1374    #[test]
1375    fn extract_bip_44_fields_reads_a_bip_44_path() {
1376        assert_eq!(
1377            extract_bip_44_fields(
1378                &derivation(&bip_44_path()),
1379                &seed_fingerprint(),
1380                coin_type()
1381            ),
1382            Some((
1383                AccountId::try_from(ACCOUNT).unwrap(),
1384                TransparentKeyScope::INTERNAL,
1385                NonHardenedChildIndex::from_index(ADDRESS_INDEX).unwrap(),
1386            ))
1387        );
1388    }
1389
1390    #[test]
1391    fn extract_bip_44_fields_rejects_other_paths() {
1392        // A ZIP 48 path is not a BIP 44 path.
1393        assert_eq!(
1394            extract_bip_44_fields(
1395                &derivation(&zip_48_path()),
1396                &seed_fingerprint(),
1397                coin_type()
1398            ),
1399            None
1400        );
1401        // A different seed.
1402        let other_seed = SeedFingerprint::from_seed(&[1u8; 32]).unwrap();
1403        assert_eq!(
1404            extract_bip_44_fields(&derivation(&bip_44_path()), &other_seed, coin_type()),
1405            None
1406        );
1407    }
1408
1409    #[test]
1410    fn extract_zip_48_fields_reads_a_zip_48_path() {
1411        assert_eq!(
1412            extract_zip_48_fields(
1413                &derivation(&zip_48_path()),
1414                &seed_fingerprint(),
1415                coin_type()
1416            ),
1417            Some((
1418                AccountId::try_from(ACCOUNT).unwrap(),
1419                zip32::Scope::External,
1420                NonHardenedChildIndex::from_index(ADDRESS_INDEX).unwrap(),
1421            ))
1422        );
1423    }
1424
1425    #[test]
1426    fn extract_zip_48_fields_rejects_other_paths() {
1427        assert_eq!(
1428            extract_zip_48_fields(
1429                &derivation(&bip_44_path()),
1430                &seed_fingerprint(),
1431                coin_type()
1432            ),
1433            None
1434        );
1435    }
1436}
1437
1438#[cfg(test)]
1439mod derivation_tests {
1440    use alloc::vec::Vec;
1441    use core::ops::Range;
1442
1443    use bip32::ChildNumber;
1444    use subtle::ConstantTimeEq;
1445
1446    use super::{NonHardenedChildIndex, NonHardenedChildRange};
1447
1448    #[cfg(feature = "transparent-inputs")]
1449    use {
1450        super::{
1451            AccountPrivKey, AccountPubKey, IncomingViewingKey, TransparentKeyScope,
1452            derivation_test_vectors as test_vectors,
1453        },
1454        ::transparent::address::TransparentAddress,
1455        zcash_protocol::consensus::{MAIN_NETWORK, NetworkConstants},
1456    };
1457
1458    #[test]
1459    #[cfg(feature = "transparent-inputs")]
1460    fn address_derivation() {
1461        let seed = [
1462            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
1463            24, 25, 26, 27, 28, 29, 30, 31,
1464        ];
1465
1466        for account_index in 0..5 {
1467            let account_index = zip32::AccountId::try_from(account_index).unwrap();
1468            let account_sk =
1469                AccountPrivKey::from_seed(&MAIN_NETWORK, &seed, account_index).unwrap();
1470            let account_pubkey = account_sk.to_account_pubkey();
1471
1472            let external_ivk = account_pubkey.derive_external_ivk().unwrap();
1473            let (address, address_index) = external_ivk.default_address();
1474
1475            let address_pubkey = account_pubkey
1476                .derive_address_pubkey(TransparentKeyScope::EXTERNAL, address_index)
1477                .unwrap();
1478            assert_eq!(TransparentAddress::from_pubkey(&address_pubkey), address);
1479
1480            let expected_path = [
1481                ChildNumber::new(44, true).unwrap(),
1482                ChildNumber::new(MAIN_NETWORK.coin_type(), true).unwrap(),
1483                ChildNumber::new(account_index.into(), true).unwrap(),
1484                TransparentKeyScope::EXTERNAL.into(),
1485                address_index.into(),
1486            ];
1487
1488            // For short paths, we get an error.
1489            for i in 0..3 {
1490                assert_eq!(
1491                    account_pubkey.derive_pubkey_at_bip32_path(
1492                        &MAIN_NETWORK,
1493                        account_index,
1494                        &expected_path[..i]
1495                    ),
1496                    Err(bip32::Error::ChildNumber),
1497                );
1498            }
1499
1500            // The truncated-by-one path gives the external IVK.
1501            assert_eq!(
1502                account_pubkey.derive_pubkey_at_bip32_path(
1503                    &MAIN_NETWORK,
1504                    account_index,
1505                    &expected_path[..4],
1506                ),
1507                Ok(*external_ivk.0.public_key()),
1508            );
1509
1510            // The full path gives the correct pubkey.
1511            assert_eq!(
1512                account_pubkey.derive_pubkey_at_bip32_path(
1513                    &MAIN_NETWORK,
1514                    account_index,
1515                    &expected_path,
1516                ),
1517                Ok(address_pubkey),
1518            );
1519        }
1520    }
1521
1522    #[test]
1523    #[cfg(feature = "transparent-inputs")]
1524    fn bip_32_test_vectors() {
1525        let seed = [
1526            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
1527            24, 25, 26, 27, 28, 29, 30, 31,
1528        ];
1529
1530        for tv in test_vectors::bip_32() {
1531            let account_sk = AccountPrivKey::from_seed(
1532                &MAIN_NETWORK,
1533                &seed,
1534                zip32::AccountId::try_from(tv.account).unwrap(),
1535            )
1536            .unwrap();
1537            let account_pubkey = account_sk.to_account_pubkey();
1538
1539            let mut key_bytes = [0u8; 65];
1540            key_bytes[..32].copy_from_slice(&tv.c);
1541            key_bytes[32..].copy_from_slice(&tv.pk);
1542            assert_eq!(account_pubkey.serialize(), key_bytes);
1543
1544            let shielding_ovks = account_pubkey.ovks_for_shielding();
1545            assert_eq!(shielding_ovks.internal().as_bytes(), tv.internal_ovk);
1546            assert_eq!(shielding_ovks.external().as_bytes(), tv.external_ovk);
1547
1548            // The test vectors are broken here: they should be deriving an address at the
1549            // address level, but instead use the account pubkey as an address.
1550            let address = TransparentAddress::PublicKeyHash(tv.address);
1551
1552            #[cfg(feature = "transparent-inputs")]
1553            assert_eq!(
1554                TransparentAddress::from_pubkey(account_pubkey.0.public_key()),
1555                address
1556            );
1557        }
1558    }
1559
1560    #[test]
1561    #[cfg(feature = "transparent-inputs")]
1562    fn check_ovk_test_vectors() {
1563        for tv in test_vectors::transparent_ovk() {
1564            let mut key_bytes = [0u8; 65];
1565            key_bytes[..32].copy_from_slice(&tv.c);
1566            key_bytes[32..].copy_from_slice(&tv.pk);
1567            let account_key = AccountPubKey::deserialize(&key_bytes).unwrap();
1568
1569            let shielding_ovks = account_key.ovks_for_shielding();
1570
1571            assert_eq!(tv.internal_ovk, shielding_ovks.internal().as_bytes());
1572            assert_eq!(tv.external_ovk, shielding_ovks.external().as_bytes());
1573        }
1574    }
1575
1576    #[test]
1577    fn nonhardened_indexes_accepted() {
1578        assert_eq!(0, NonHardenedChildIndex::from_index(0).unwrap().index());
1579        assert_eq!(
1580            0x7fffffff,
1581            NonHardenedChildIndex::from_index(0x7fffffff)
1582                .unwrap()
1583                .index()
1584        );
1585    }
1586
1587    #[test]
1588    fn hardened_indexes_rejected() {
1589        assert!(NonHardenedChildIndex::from_index(0x80000000).is_none());
1590        assert!(NonHardenedChildIndex::from_index(0xffffffff).is_none());
1591    }
1592
1593    #[test]
1594    fn nonhardened_index_next() {
1595        assert_eq!(1, NonHardenedChildIndex::ZERO.next().unwrap().index());
1596        assert!(
1597            NonHardenedChildIndex::from_index(0x7fffffff)
1598                .unwrap()
1599                .next()
1600                .is_none()
1601        );
1602    }
1603
1604    #[test]
1605    fn nonhardened_child_range() {
1606        let collect = |range: Range<NonHardenedChildIndex>| {
1607            NonHardenedChildRange::from(range)
1608                .into_iter()
1609                .collect::<Vec<_>>()
1610        };
1611        let zero = NonHardenedChildIndex::ZERO;
1612        let one = zero.next().unwrap();
1613        let two = one.next().unwrap();
1614
1615        assert_eq!(collect(zero..two), [zero, one]);
1616        assert_eq!(collect(one..one), []);
1617        assert_eq!(collect(two..one), []);
1618    }
1619
1620    #[test]
1621    fn nonhardened_index_ct_eq() {
1622        assert!(check(
1623            NonHardenedChildIndex::ZERO,
1624            NonHardenedChildIndex::ZERO
1625        ));
1626        assert!(!check(
1627            NonHardenedChildIndex::ZERO,
1628            NonHardenedChildIndex::ZERO.next().unwrap()
1629        ));
1630
1631        fn check<T: ConstantTimeEq>(v1: T, v2: T) -> bool {
1632            v1.ct_eq(&v2).into()
1633        }
1634    }
1635
1636    #[test]
1637    fn nonhardened_index_tryfrom_keyindex() {
1638        let nh: NonHardenedChildIndex = ChildNumber::new(0, false).unwrap().try_into().unwrap();
1639        assert_eq!(nh.index(), 0);
1640
1641        assert!(NonHardenedChildIndex::try_from(ChildNumber::new(0, true).unwrap()).is_err());
1642    }
1643
1644    #[test]
1645    #[cfg(feature = "transparent-inputs")]
1646    fn account_priv_key_debug_redaction() {
1647        let sk =
1648            AccountPrivKey::from_seed(&MAIN_NETWORK, &[0u8; 64], zip32::AccountId::ZERO).unwrap();
1649        assert_eq!(format!("{sk:?}"), "AccountPrivKey(\"...\")");
1650    }
1651
1652    #[test]
1653    #[cfg(feature = "transparent-inputs")]
1654    fn viewing_key_debug_redaction() {
1655        let seed = [0u8; 32];
1656        let account_sk =
1657            AccountPrivKey::from_seed(&MAIN_NETWORK, &seed, zip32::AccountId::ZERO).unwrap();
1658        let account_pubkey = account_sk.to_account_pubkey();
1659        assert_eq!(format!("{account_pubkey:?}"), "AccountPubKey(\"...\")");
1660
1661        let external_ivk = account_pubkey.derive_external_ivk().unwrap();
1662        assert_eq!(format!("{external_ivk:?}"), "ExternalIvk(\"...\")");
1663
1664        let internal_ivk = account_pubkey.derive_internal_ivk().unwrap();
1665        assert_eq!(format!("{internal_ivk:?}"), "InternalIvk(\"...\")");
1666
1667        let ephemeral_ivk = account_pubkey.derive_ephemeral_ivk().unwrap();
1668        assert_eq!(format!("{ephemeral_ivk:?}"), "EphemeralIvk(\"...\")");
1669
1670        let shielding_ovks = account_pubkey.ovks_for_shielding();
1671        assert_eq!(
1672            format!("{shielding_ovks:?}"),
1673            "ShieldingOvks { internal: InternalOvk(\"...\"), external: ExternalOvk(\"...\") }"
1674        );
1675    }
1676}