Skip to main content

zcash_keys/keys/transparent/
zip48.rs

1//! Keys for [ZIP 48] transparent multisig accounts.
2//!
3//! [ZIP 48]: https://zips.z.cash/zip-0048
4
5use alloc::collections::BTreeSet;
6use alloc::string::{String, ToString};
7use alloc::vec::Vec;
8use core::num::NonZeroU8;
9
10use ::transparent::address::TransparentAddress;
11use bip32::{ChildNumber, ExtendedKeyAttrs, ExtendedPrivateKey, ExtendedPublicKey, Prefix};
12use nonempty::NonEmpty;
13use secp256k1::{PublicKey, SecretKey};
14use zcash_encoding::CompactSize;
15use zcash_protocol::consensus::{self, NetworkConstants};
16use zcash_script::{
17    descriptor::{self, KeyExpression, KeyOrigin, sh, sortedmulti},
18    script,
19};
20use zip32::AccountId;
21
22use super::{NonHardenedChildIndex, TransparentKeyScope, ZIP_48_P2SH_SCRIPT_TYPE, ZIP_48_PURPOSE};
23
24fn pub_prefix<P: consensus::Parameters>(params: &P) -> Prefix {
25    match params.network_type() {
26        consensus::NetworkType::Main => Prefix::XPUB,
27        consensus::NetworkType::Test => Prefix::TPUB,
28        consensus::NetworkType::Regtest => Prefix::TPUB,
29    }
30}
31
32/// A [ZIP 48] private key at the P2SH level `m/48'/<coin_type>'/<account>'/133000'`.
33///
34/// [ZIP 48]: https://zips.z.cash/zip-0048
35#[derive(Clone)]
36pub struct AccountPrivKey {
37    origin: KeyOrigin,
38    key: ExtendedPrivateKey<SecretKey>,
39}
40
41impl core::fmt::Debug for AccountPrivKey {
42    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
43        f.debug_struct("AccountPrivKey")
44            .field("origin", &self.origin)
45            .field("key", &"...")
46            .finish()
47    }
48}
49
50impl AccountPrivKey {
51    /// Performs derivation of the extended private key for the ZIP 48 path:
52    /// `m/48'/<coin_type>'/<account>'/133000'`.
53    pub fn from_seed<P: consensus::Parameters>(
54        params: &P,
55        seed: &[u8],
56        account: AccountId,
57    ) -> Result<AccountPrivKey, bip32::Error> {
58        Self::from_seed_with_coin_type(seed, params.coin_type(), account)
59    }
60
61    /// Internal helper constructor that doesn't depend on [`consensus::Parameters`].
62    fn from_seed_with_coin_type(
63        seed: &[u8],
64        coin_type: u32,
65        account: AccountId,
66    ) -> Result<AccountPrivKey, bip32::Error> {
67        let root = ExtendedPrivateKey::new(seed)?;
68        let fingerprint = root.public_key().fingerprint();
69        let derivation = vec![
70            ZIP_48_PURPOSE,
71            ChildNumber::new(coin_type, true)?,
72            ChildNumber::new(account.into(), true)?,
73            ZIP_48_P2SH_SCRIPT_TYPE,
74        ];
75
76        let key = derivation
77            .iter()
78            .try_fold(root, |key, child_number| key.derive_child(*child_number))?;
79
80        Ok(AccountPrivKey {
81            origin: KeyOrigin::from_parts(fingerprint, derivation),
82            key,
83        })
84    }
85
86    /// Returns the public key corresponding to this private key.
87    ///
88    /// This is the public key that will be added to the key information vector for the
89    /// corresponding [BIP 388] wallet policy.
90    ///
91    /// [BIP 388]: https://github.com/bitcoin/bips/blob/master/bip-0388.mediawiki
92    pub fn to_account_pubkey(&self) -> AccountPubKey {
93        AccountPubKey {
94            origin: self.origin.clone(),
95            key: self.key.public_key(),
96        }
97    }
98
99    /// Derives the signing key for this account's scoped address at the given index.
100    pub fn derive_signing_key(
101        &self,
102        scope: zip32::Scope,
103        address_index: NonHardenedChildIndex,
104    ) -> SecretKey {
105        *self
106            .key
107            .derive_child(TransparentKeyScope::from(scope).into())
108            .expect("chance of failure is around 2^-127")
109            .derive_child(address_index.into())
110            .expect("chance of failure is around 2^-127")
111            .private_key()
112    }
113}
114
115/// A [ZIP 48] public key at the P2SH level `m/48'/<coin_type>'/<account>'/133000'`.
116///
117/// This provides the necessary derivation capability for a participant in a P2SH multisig
118/// account.
119///
120/// [ZIP 48]: https://zips.z.cash/zip-0048
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct AccountPubKey {
123    origin: KeyOrigin,
124    key: ExtendedPublicKey<PublicKey>,
125}
126
127impl AccountPubKey {
128    /// Attempts to parse a [BIP 388 `KEY_INFO` expression] as a ZIP 48 public key.
129    ///
130    /// Returns `None` if:
131    /// - the string is not a valid `KEY_INFO` expresson.
132    /// - the expression has no [`KeyOrigin`].
133    /// - the key origin does not match ZIP 48.
134    /// - the key is for the wrong network.
135    ///
136    /// [BIP 388 `KEY_INFO` expression]: https://github.com/bitcoin/bips/blob/master/bip-0388.mediawiki#key-information-vector
137    pub fn parse_key_info_expression<P: consensus::Parameters>(
138        s: &str,
139        params: &P,
140    ) -> Option<Self> {
141        match s.parse::<KeyExpression>().ok()?.into_parts() {
142            (Some(origin), descriptor::Key::Xpub { prefix, key, child })
143                if prefix == pub_prefix(params) && child.is_empty() =>
144            {
145                // Verify that this `KEY_INFO` expression is for ZIP 48.
146                match origin.derivation() {
147                    [purpose, coin_type, account, script_type]
148                        if purpose == &ZIP_48_PURPOSE
149                            && coin_type.index() == params.coin_type()
150                            && coin_type.is_hardened()
151                            && account.is_hardened()
152                            && script_type == &ZIP_48_P2SH_SCRIPT_TYPE =>
153                    {
154                        Some(Self { origin, key })
155                    }
156                    _ => None,
157                }
158            }
159            _ => None,
160        }
161    }
162
163    /// Returns the ZIP 48 coin type and account ID for this public key.
164    fn coin_type_and_account(&self) -> (u32, AccountId) {
165        // By construction, the derivation is always a ZIP 48 path.
166        let derivation = self.origin.derivation();
167        (
168            derivation
169                .get(1)
170                .expect("valid ZIP 48 derivation path")
171                .index(),
172            AccountId::try_from(
173                derivation
174                    .get(2)
175                    .expect("valid ZIP 48 derivation path")
176                    .index(),
177            )
178            .expect("valid"),
179        )
180    }
181
182    /// Encodes this public key as a [BIP 388 `KEY_INFO` expression].
183    ///
184    /// [BIP 388 `KEY_INFO` expression]: https://github.com/bitcoin/bips/blob/master/bip-0388.mediawiki#key-information-vector
185    pub fn key_info_expression<P: consensus::Parameters>(&self, params: &P) -> String {
186        self.key_expression_inner(pub_prefix(params), vec![])
187            .to_string()
188    }
189
190    /// Produces a [`KeyExpression`] from this public key corresponding to a specific
191    /// address.
192    pub fn key_expression_for_address(
193        &self,
194        prefix: Prefix,
195        scope: zip32::Scope,
196        address_index: NonHardenedChildIndex,
197    ) -> KeyExpression {
198        self.key_expression_inner(
199            prefix,
200            vec![
201                TransparentKeyScope::from(scope).into(),
202                address_index.into(),
203            ],
204        )
205    }
206
207    fn key_expression_inner(
208        &self,
209        prefix: Prefix,
210        child: Vec<bip32::ChildNumber>,
211    ) -> KeyExpression {
212        KeyExpression::from_xpub(Some(self.origin.clone()), prefix, self.key.clone(), child)
213            .expect("correct by construction")
214    }
215}
216
217/// A [ZIP 48] P2SH multisig full viewing key.
218///
219/// This provides the necessary derivation capability to view all funds controlled by a
220/// P2SH multisig account.
221///
222/// [ZIP 48]: https://zips.z.cash/zip-0048
223pub struct FullViewingKey {
224    threshold: NonZeroU8,
225    key_info: NonEmpty<AccountPubKey>,
226}
227
228impl FullViewingKey {
229    /// Constructs a full viewing key for a standard ZIP 48 account.
230    ///
231    /// This uses the standard wallet descriptor template. For example:
232    /// - `threshold == 2`
233    /// - `key_info.len() == 3`
234    /// - Wallet descriptor template: `"sh(sortedmulti(2,@0/**,@1/**,@2/**))"`
235    pub fn standard(
236        threshold: NonZeroU8,
237        key_info: Vec<AccountPubKey>,
238    ) -> Result<Self, FullViewingKeyError> {
239        let key_info = NonEmpty::from_vec(key_info).ok_or(FullViewingKeyError::NoPubKeys)?;
240        if key_info.len() > 15 {
241            Err(FullViewingKeyError::TooManyPubKeys)
242        } else if usize::from(threshold.get()) > key_info.len() {
243            Err(FullViewingKeyError::InvalidThreshold)
244        } else {
245            // Verify `key_info` in a scope so we can borrow from it.
246            {
247                // To be compatible with ZIP 48, all keys must have the same derivation
248                // information. We check this by collecting into a set, and then checking
249                // it contains one entry. We don't need to verify the derivation's
250                // structure because `AccountPubKey` enforces it by construction.
251                let derivations = key_info
252                    .iter()
253                    .map(|key| key.origin.derivation())
254                    .collect::<BTreeSet<_>>();
255                if derivations.len() != 1 {
256                    return Err(FullViewingKeyError::IncompatiblePubKeys);
257                }
258            }
259
260            // TODO: Decide whether `key_info` should be sorted (or checked to be sorted)
261            // to ensure a canonical multipath descriptor.
262            Ok(Self {
263                threshold,
264                key_info,
265            })
266        }
267    }
268
269    /// Returns the ZIP 48 coin type and account ID for this full viewing key.
270    fn coin_type_and_account(&self) -> (u32, AccountId) {
271        // By construction of `Self`, all keys in `key_info` have the same derivation
272        // information, so we only need to look at the first.
273        self.key_info.first().coin_type_and_account()
274    }
275
276    /// Returns the [BIP 388 wallet descriptor template] for this full viewing key.
277    ///
278    /// [BIP 388 wallet descriptor template]: https://github.com/bitcoin/bips/blob/master/bip-0388.mediawiki#wallet-descriptor-template
279    pub fn wallet_descriptor_template(&self) -> String {
280        self.standard_descriptor(|i, _| format!("@{i}/**"))
281    }
282
283    /// Returns the [BIP 389] multipath descriptor for this full viewing key.
284    ///
285    /// [BIP 389]: https://github.com/bitcoin/bips/blob/master/bip-0389.mediawiki
286    pub fn multipath_descriptor<P: consensus::Parameters>(&self, params: &P) -> String {
287        self.standard_descriptor(|_, key| format!("{}/<0;1>/*", key.key_info_expression(params)))
288    }
289
290    /// Because the only constructor for `FullViewingKey` forces a specific wallet
291    /// descriptor template, we can fix it here.
292    fn standard_descriptor(&self, key_encoder: impl Fn(usize, &AccountPubKey) -> String) -> String {
293        let mut t = format!("sh(sortedmulti({}", self.threshold);
294        for (i, key) in self.key_info.iter().enumerate() {
295            t.push(',');
296            t.push_str(&key_encoder(i, key));
297        }
298        t.push_str("))");
299        t
300    }
301
302    /// Derives the [`AccountPrivKey`] from the given seed that matches this full viewing
303    /// key.
304    ///
305    /// Returns `Ok(None)` if the given seed does not match any of the public keys.
306    pub fn derive_matching_account_priv_key(
307        &self,
308        seed: &[u8],
309    ) -> Result<Option<AccountPrivKey>, bip32::Error> {
310        let (coin_type, account) = self.coin_type_and_account();
311        let candiate_privkey = AccountPrivKey::from_seed_with_coin_type(seed, coin_type, account)?;
312        let candiate_pubkey = candiate_privkey.to_account_pubkey();
313
314        for key in &self.key_info {
315            if key == &candiate_pubkey {
316                return Ok(Some(candiate_privkey));
317            }
318        }
319
320        // Nothing matched.
321        Ok(None)
322    }
323
324    /// Derives the scoped P2SH address for this account at the given index, along with
325    /// the corresponding redeem script.
326    pub fn derive_address(
327        &self,
328        scope: zip32::Scope,
329        address_index: NonHardenedChildIndex,
330    ) -> (TransparentAddress, script::Redeem) {
331        // Produce the key expressions corresponding to the desired address.
332        let keys = self
333            .key_info
334            .iter()
335            .map(|pubkey| {
336                pubkey.key_expression_for_address(
337                    // Prefix doesn't matter, we aren't serializing the key expressions.
338                    Prefix::XPUB,
339                    scope,
340                    address_index,
341                )
342            })
343            .collect::<Vec<_>>();
344
345        // Derive the P2SH script for the desired address. Because the only constructor
346        // for `FullViewingKey` forces a specific wallet descriptor template, we can
347        // fix it here.
348        let redeem_script = sortedmulti(self.threshold.get(), &keys)
349            .expect("child numbers are non-hardened, chance of failure is around 2^-127");
350        let script_pubkey = sh(&redeem_script);
351
352        // Extract the address from the script.
353        let addr = TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid");
354
355        (addr, redeem_script)
356    }
357}
358
359/// The encoded length of one [`P2shKey`]: a 32-byte BIP 32 chain code followed by a
360/// 33-byte SEC1 compressed public key.
361const P2SH_KEY_ENCODING_LEN: usize = 65;
362
363/// The multipath notation a key placeholder carries in a full viewing key item, which
364/// derives both external and internal addresses.
365const FVK_MULTIPATH: &str = "/**";
366
367/// The multipath notation a key placeholder carries in an incoming viewing key item,
368/// which derives external addresses only.
369const IVK_MULTIPATH: &str = "/*";
370
371/// The largest number of keys the standard descriptor template can carry, bounded by the
372/// small integer opcodes the resulting script uses.
373const MAX_KEYS: usize = 15;
374
375/// A key of the key information vector of a [ZIP 316] Revision 2 P2SH viewing key item.
376///
377/// The item encoding carries a BIP 32 chain code and compressed public key, and no key
378/// origin information, so an entry does not identify its own derivation path.
379///
380/// [ZIP 316]: https://zips.z.cash/zip-0316
381#[derive(Clone, Debug, PartialEq, Eq)]
382pub struct P2shKey {
383    chain_code: [u8; 32],
384    public_key: PublicKey,
385}
386
387impl P2shKey {
388    /// Constructs a key information vector entry from its parts.
389    pub fn new(chain_code: [u8; 32], public_key: PublicKey) -> Self {
390        Self {
391            chain_code,
392            public_key,
393        }
394    }
395
396    /// Returns the BIP 32 chain code of this entry.
397    pub fn chain_code(&self) -> &[u8; 32] {
398        &self.chain_code
399    }
400
401    /// Returns the public key of this entry.
402    pub fn public_key(&self) -> &PublicKey {
403        &self.public_key
404    }
405
406    /// Parses a key information vector entry.
407    ///
408    /// Returns an error if the entry does not encode a valid compressed public key.
409    pub fn from_bytes(data: &[u8; P2SH_KEY_ENCODING_LEN]) -> Result<Self, bip32::Error> {
410        Ok(Self {
411            chain_code: data[..32].try_into().expect("correct length"),
412            public_key: PublicKey::from_slice(&data[32..])?,
413        })
414    }
415
416    /// Returns the encoding of this entry.
417    pub fn to_bytes(&self) -> [u8; P2SH_KEY_ENCODING_LEN] {
418        let mut data = [0; P2SH_KEY_ENCODING_LEN];
419        data[..32].copy_from_slice(&self.chain_code);
420        data[32..].copy_from_slice(&self.public_key.serialize());
421        data
422    }
423
424    fn extended_pubkey(&self) -> ExtendedPublicKey<PublicKey> {
425        ExtendedPublicKey::new(
426            self.public_key,
427            ExtendedKeyAttrs {
428                depth: 3,
429                // The entry encoding carries neither of these, and this key is never
430                // serialized as an extended key, so dummy values suffice.
431                parent_fingerprint: [0xff, 0xff, 0xff, 0xff],
432                child_number: ChildNumber::new(0, true).expect("valid"),
433                chain_code: self.chain_code,
434            },
435        )
436    }
437
438    /// Derives the non-hardened child of this key at the given index.
439    pub fn derive_child(&self, index: NonHardenedChildIndex) -> Result<Self, bip32::Error> {
440        let child = self.extended_pubkey().derive_child(index.into())?;
441        Ok(Self {
442            chain_code: child.attrs().chain_code,
443            public_key: *child.public_key(),
444        })
445    }
446
447    fn key_expression(&self, child: Vec<ChildNumber>) -> KeyExpression {
448        // Neither the prefix nor the absent origin is serialized: the expression exists
449        // only to evaluate the descriptor to a script.
450        KeyExpression::from_xpub(None, Prefix::XPUB, self.extended_pubkey(), child)
451            .expect("correct by construction")
452    }
453}
454
455impl Ord for P2shKey {
456    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
457        // ZIP 316 requires the key information vector of an item to be ordered
458        // lexicographically by chain code and then public key, which is the order of the
459        // entry encoding.
460        self.to_bytes().cmp(&other.to_bytes())
461    }
462}
463
464impl PartialOrd for P2shKey {
465    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
466        Some(self.cmp(other))
467    }
468}
469
470/// Renders the standard ZIP 48 descriptor template for the given shape.
471fn render_template(threshold: NonZeroU8, n_keys: usize, multipath: &str) -> String {
472    let mut t = format!("sh(sortedmulti({threshold}");
473    for i in 0..n_keys {
474        t.push(',');
475        t.push_str(&format!("@{i}{multipath}"));
476    }
477    t.push_str("))");
478    t
479}
480
481/// Checks the invariants shared by both viewing key item forms.
482fn check_shape(
483    threshold: NonZeroU8,
484    key_info: Vec<P2shKey>,
485) -> Result<(NonZeroU8, NonEmpty<P2shKey>), P2shViewingKeyError> {
486    let key_info = NonEmpty::from_vec(key_info).ok_or(P2shViewingKeyError::NoPubKeys)?;
487    if key_info.len() > MAX_KEYS {
488        Err(P2shViewingKeyError::TooManyPubKeys)
489    } else if usize::from(threshold.get()) > key_info.len() {
490        Err(P2shViewingKeyError::InvalidThreshold)
491    } else {
492        Ok((threshold, key_info))
493    }
494}
495
496/// Parses a P2SH viewing key item, requiring the standard template for `multipath`.
497fn parse_item(
498    bytes: &[u8],
499    multipath: &str,
500) -> Result<(NonZeroU8, NonEmpty<P2shKey>), P2shViewingKeyError> {
501    let mut cursor = corez::io::Cursor::new(bytes);
502    let template_len = CompactSize::read(&mut cursor)
503        .ok()
504        .and_then(|n| usize::try_from(n).ok())
505        .ok_or(P2shViewingKeyError::Malformed)?;
506    let template_start = usize::try_from(cursor.position()).expect("cursor fits in usize");
507    let template_end = template_start
508        .checked_add(template_len)
509        .filter(|end| *end <= bytes.len())
510        .ok_or(P2shViewingKeyError::Malformed)?;
511    let template = core::str::from_utf8(&bytes[template_start..template_end])
512        .map_err(|_| P2shViewingKeyError::Malformed)?;
513    cursor.set_position(template_end as u64);
514
515    let n_keys = CompactSize::read(&mut cursor)
516        .ok()
517        .and_then(|n| usize::try_from(n).ok())
518        .ok_or(P2shViewingKeyError::Malformed)?;
519    let keys_start = usize::try_from(cursor.position()).expect("cursor fits in usize");
520    if n_keys
521        .checked_mul(P2SH_KEY_ENCODING_LEN)
522        .and_then(|len| keys_start.checked_add(len))
523        != Some(bytes.len())
524    {
525        return Err(P2shViewingKeyError::Malformed);
526    }
527
528    let mut key_info = Vec::with_capacity(n_keys);
529    for i in 0..n_keys {
530        let entry: [u8; P2SH_KEY_ENCODING_LEN] = bytes
531            [keys_start + i * P2SH_KEY_ENCODING_LEN..keys_start + (i + 1) * P2SH_KEY_ENCODING_LEN]
532            .try_into()
533            .expect("length checked above");
534        key_info.push(P2shKey::from_bytes(&entry).map_err(P2shViewingKeyError::InvalidKey)?);
535    }
536
537    let threshold = parse_threshold(template).ok_or(P2shViewingKeyError::UnsupportedTemplate)?;
538    let (threshold, key_info) = check_shape(threshold, key_info)?;
539
540    // The template is rendered canonically on encoding, so only a template that is
541    // already canonical can round-trip unchanged.
542    if template != render_template(threshold, key_info.len(), multipath) {
543        return Err(P2shViewingKeyError::UnsupportedTemplate);
544    }
545
546    Ok((threshold, key_info))
547}
548
549/// Extracts the multisig threshold from a standard descriptor template.
550fn parse_threshold(template: &str) -> Option<NonZeroU8> {
551    template
552        .strip_prefix("sh(sortedmulti(")?
553        .split(',')
554        .next()?
555        .parse()
556        .ok()
557}
558
559/// Writes the canonical encoding of a P2SH viewing key item.
560fn write_item<W: corez::io::Write>(
561    threshold: NonZeroU8,
562    key_info: &NonEmpty<P2shKey>,
563    multipath: &str,
564    mut writer: W,
565) -> corez::io::Result<()> {
566    let template = render_template(threshold, key_info.len(), multipath);
567    CompactSize::write(&mut writer, template.len())?;
568    writer.write_all(template.as_bytes())?;
569    CompactSize::write(&mut writer, key_info.len())?;
570    for key in key_info.iter() {
571        writer.write_all(&key.to_bytes())?;
572    }
573    Ok(())
574}
575
576/// A [ZIP 316] Revision 2 P2SH viewing key item, in full viewing key form.
577///
578/// The item encodes a [BIP 388] wallet policy: a descriptor template together with the
579/// key information vector its `@N` placeholders refer to. Only the standard ZIP 48
580/// template is representable, so the descriptor of a value of this type is always one
581/// this crate can evaluate.
582///
583/// [ZIP 316]: https://zips.z.cash/zip-0316
584/// [BIP 388]: https://github.com/bitcoin/bips/blob/master/bip-0388.mediawiki
585#[derive(Clone, Debug, PartialEq, Eq)]
586pub struct P2shFullViewingKey {
587    threshold: NonZeroU8,
588    key_info: NonEmpty<P2shKey>,
589}
590
591impl P2shFullViewingKey {
592    /// Constructs a P2SH viewing key item for a standard ZIP 48 account.
593    ///
594    /// Returns an error if no keys are given, if more than 15 are given, or if
595    /// `threshold` exceeds the number of keys.
596    pub fn new(threshold: NonZeroU8, key_info: Vec<P2shKey>) -> Result<Self, P2shViewingKeyError> {
597        let (threshold, key_info) = check_shape(threshold, key_info)?;
598        Ok(Self {
599            threshold,
600            key_info,
601        })
602    }
603
604    /// Parses the canonical encoding of a P2SH viewing key item.
605    ///
606    /// Returns an error if the encoding is malformed, if a key information vector entry
607    /// is not a valid public key, or if the descriptor template is not the standard ZIP 48
608    /// template for a full viewing key.
609    pub fn parse(bytes: &[u8]) -> Result<Self, P2shViewingKeyError> {
610        let (threshold, key_info) = parse_item(bytes, FVK_MULTIPATH)?;
611        Ok(Self {
612            threshold,
613            key_info,
614        })
615    }
616
617    /// Returns the multisig threshold of this item's descriptor.
618    pub fn threshold(&self) -> NonZeroU8 {
619        self.threshold
620    }
621
622    /// Returns this item's key information vector.
623    pub fn key_info(&self) -> &NonEmpty<P2shKey> {
624        &self.key_info
625    }
626
627    /// Returns the [BIP 388 wallet descriptor template] of this item.
628    ///
629    /// [BIP 388 wallet descriptor template]: https://github.com/bitcoin/bips/blob/master/bip-0388.mediawiki#wallet-descriptor-template
630    pub fn wallet_descriptor_template(&self) -> String {
631        render_template(self.threshold, self.key_info.len(), FVK_MULTIPATH)
632    }
633
634    /// Writes the canonical encoding of this item.
635    pub fn write<W: corez::io::Write>(&self, writer: W) -> corez::io::Result<()> {
636        write_item(self.threshold, &self.key_info, FVK_MULTIPATH, writer)
637    }
638
639    /// Returns the canonical encoding of this item.
640    pub fn to_bytes(&self) -> Vec<u8> {
641        let mut result = vec![];
642        self.write(&mut result)
643            .expect("writing to a Vec cannot fail");
644        result
645    }
646
647    /// Derives the incoming viewing key form of this item.
648    ///
649    /// Each key is advanced to its external (index 0) non-hardened child, and the keys are
650    /// re-sorted into the lexicographic order ZIP 316 requires of the encoding.
651    pub fn to_incoming_viewing_key(&self) -> Result<P2shIncomingViewingKey, bip32::Error> {
652        let mut key_info = self
653            .key_info
654            .iter()
655            .map(|key| key.derive_child(NonHardenedChildIndex::ZERO))
656            .collect::<Result<Vec<_>, _>>()?;
657        key_info.sort_unstable();
658        Ok(P2shIncomingViewingKey {
659            threshold: self.threshold,
660            key_info: NonEmpty::from_vec(key_info).expect("derived from a non-empty vector"),
661        })
662    }
663}
664
665/// A [ZIP 316] Revision 2 P2SH viewing key item, in incoming viewing key form.
666///
667/// This derives the P2SH receivers of an account without the ability to derive its
668/// internal (change) addresses.
669///
670/// [ZIP 316]: https://zips.z.cash/zip-0316
671#[derive(Clone, Debug, PartialEq, Eq)]
672pub struct P2shIncomingViewingKey {
673    threshold: NonZeroU8,
674    key_info: NonEmpty<P2shKey>,
675}
676
677impl P2shIncomingViewingKey {
678    /// Constructs a P2SH incoming viewing key item for a standard ZIP 48 account.
679    ///
680    /// Returns an error if no keys are given, if more than 15 are given, or if
681    /// `threshold` exceeds the number of keys.
682    pub fn new(threshold: NonZeroU8, key_info: Vec<P2shKey>) -> Result<Self, P2shViewingKeyError> {
683        let (threshold, key_info) = check_shape(threshold, key_info)?;
684        Ok(Self {
685            threshold,
686            key_info,
687        })
688    }
689
690    /// Parses the canonical encoding of a P2SH viewing key item.
691    ///
692    /// Returns an error if the encoding is malformed, if a key information vector entry
693    /// is not a valid public key, or if the descriptor template is not the standard ZIP 48
694    /// template for an incoming viewing key.
695    pub fn parse(bytes: &[u8]) -> Result<Self, P2shViewingKeyError> {
696        let (threshold, key_info) = parse_item(bytes, IVK_MULTIPATH)?;
697        Ok(Self {
698            threshold,
699            key_info,
700        })
701    }
702
703    /// Returns the multisig threshold of this item's descriptor.
704    pub fn threshold(&self) -> NonZeroU8 {
705        self.threshold
706    }
707
708    /// Returns this item's key information vector.
709    pub fn key_info(&self) -> &NonEmpty<P2shKey> {
710        &self.key_info
711    }
712
713    /// Returns the [BIP 388 wallet descriptor template] of this item.
714    ///
715    /// [BIP 388 wallet descriptor template]: https://github.com/bitcoin/bips/blob/master/bip-0388.mediawiki#wallet-descriptor-template
716    pub fn wallet_descriptor_template(&self) -> String {
717        render_template(self.threshold, self.key_info.len(), IVK_MULTIPATH)
718    }
719
720    /// Writes the canonical encoding of this item.
721    pub fn write<W: corez::io::Write>(&self, writer: W) -> corez::io::Result<()> {
722        write_item(self.threshold, &self.key_info, IVK_MULTIPATH, writer)
723    }
724
725    /// Returns the canonical encoding of this item.
726    pub fn to_bytes(&self) -> Vec<u8> {
727        let mut result = vec![];
728        self.write(&mut result)
729            .expect("writing to a Vec cannot fail");
730        result
731    }
732
733    /// Derives the P2SH address at the given address index, with the redeem script that
734    /// spends from it.
735    pub fn derive_address(
736        &self,
737        address_index: NonHardenedChildIndex,
738    ) -> (TransparentAddress, script::Redeem) {
739        let keys = self
740            .key_info
741            .iter()
742            .map(|key| key.key_expression(vec![address_index.into()]))
743            .collect::<Vec<_>>();
744
745        // The only constructors for this type force the standard descriptor template, so
746        // it can be fixed here.
747        let redeem_script = sortedmulti(self.threshold.get(), &keys)
748            .expect("child numbers are non-hardened, chance of failure is around 2^-127");
749        let script_pubkey = sh(&redeem_script);
750
751        (
752            TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid"),
753            redeem_script,
754        )
755    }
756}
757
758/// Errors that can occur while constructing or parsing a P2SH viewing key item.
759#[derive(Clone, Debug, PartialEq, Eq)]
760pub enum P2shViewingKeyError {
761    /// No keys were provided.
762    NoPubKeys,
763    /// The standard descriptor template can carry at most 15 keys.
764    TooManyPubKeys,
765    /// The provided threshold was larger than the number of keys.
766    InvalidThreshold,
767    /// The item encoding was malformed.
768    Malformed,
769    /// The descriptor template is not the standard ZIP 48 template for this item's form.
770    UnsupportedTemplate,
771    /// A key information vector entry was not a valid public key.
772    InvalidKey(bip32::Error),
773}
774
775/// Errors that can occur while constructing a [`FullViewingKey`].
776#[derive(Clone, Debug)]
777pub enum FullViewingKeyError {
778    /// No pubkeys were provided.
779    NoPubKeys,
780    /// The script for a standard [`FullViewingKey`] can contain at most 15 pubkeys.
781    TooManyPubKeys,
782    /// The provided threshold was larger than the number of pubkeys.
783    InvalidThreshold,
784    /// The pubkeys were not all derived following ZIP 48.
785    IncompatiblePubKeys,
786}
787
788#[cfg(test)]
789mod test_vectors;
790
791#[cfg(test)]
792mod tests {
793    use alloc::vec::Vec;
794    use core::num::NonZeroU8;
795
796    use ::transparent::address::TransparentAddress;
797    use bip32::Prefix;
798    use zcash_protocol::consensus::{MainNetwork, Network};
799    use zip32::AccountId;
800
801    use super::{AccountPrivKey, AccountPubKey, FullViewingKey, test_vectors::TEST_VECTORS};
802    use crate::keys::transparent::NonHardenedChildIndex;
803
804    /// The length of the version prefix of a Base58Check-encoded transparent address.
805    const B58_ADDRESS_PREFIX_LEN: usize = 2;
806
807    /// Returns the P2SH address that a Base58Check-encoded test vector names.
808    ///
809    /// The string encoding of a transparent address belongs to `zcash_address`, which
810    /// tests the version prefixes. This helper checks only the script hash.
811    fn p2sh_address_from_vector(encoded: &str) -> TransparentAddress {
812        let decoded = bs58::decode(encoded)
813            .with_check(None)
814            .into_vec()
815            .expect("test vector is valid Base58Check");
816        TransparentAddress::ScriptHash(
817            decoded[B58_ADDRESS_PREFIX_LEN..]
818                .try_into()
819                .expect("test vector has a 20-byte payload"),
820        )
821    }
822
823    #[test]
824    fn zip_48_example() {
825        let params = MainNetwork;
826        let seeds = [[1; 32], [2; 32], [3; 32]];
827
828        let key_info = seeds
829            .iter()
830            .map(|seed| {
831                AccountPrivKey::from_seed(&params, seed, AccountId::ZERO)
832                    .unwrap()
833                    .to_account_pubkey()
834            })
835            .collect();
836
837        let fvk = FullViewingKey::standard(NonZeroU8::new(2).unwrap(), key_info).unwrap();
838
839        assert_eq!(
840            fvk.wallet_descriptor_template(),
841            "sh(sortedmulti(2,@0/**,@1/**,@2/**))",
842        );
843        assert_eq!(
844            fvk.multipath_descriptor(&params),
845            "sh(sortedmulti(2,[4ba43603/48'/133'/0'/133000']xpub6E96VHgq8MKkYGuNLDjxLxH3LH93NGJX5xSufVjnh7zM8bKehGr3iekJLyc8WJiMemYWuXLPKwygt3j9nfJCapPkYRfCc5YFvzb3aMLsQdV/<0;1>/*,[8dfc9b34/48'/133'/0'/133000']xpub6EuQaJQHwbf2mbyHoYcyjcj9ByB8EeKp4zSKTT9EdxfaQJDgou3SR3oYtP7AYoHQtEUsnsjgdZD8n7c7G4Pv4iXMt98sCvdWNXs1bvhEu29/<0;1>/*,[56c4fac3/48'/133'/0'/133000']xpub6EVJBC6rV3qaNwfK3ChbjpEHnqhymSLmvqB1rKu7sRPH7szS9f4jDAiPyAF7PbnRH512uHhT4te6EJppbCWURtDKbiygGWphd5ej21oNqAx/<0;1>/*))",
846        );
847        for (i, addr) in [
848            (0, "t3gDnw36YBC6SSmccqJYCsq6xtzGXamGxKd"),
849            (1, "t3Tb7JHhVdVJ3vQPpji6pAHbFazTgVHhJZC"),
850            (2, "t3gXpirdnRUdsXaeeMjMpTcXVFigQst5ekR"),
851        ] {
852            assert_eq!(
853                fvk.derive_address(
854                    zip32::Scope::External,
855                    NonHardenedChildIndex::const_from_index(i)
856                )
857                .0,
858                p2sh_address_from_vector(addr),
859            );
860        }
861    }
862
863    #[test]
864    #[allow(deprecated)]
865    fn test_vectors() {
866        let seeds = (0..16)
867            .map(|i| {
868                [
869                    i, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48,
870                    0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48, 0x48,
871                    0x48, 0x48, 0x48, 0x48, 0x48, 0x48,
872                ]
873            })
874            .collect::<Vec<_>>();
875
876        for tv in TEST_VECTORS {
877            let (params, xprv_prefix, xpub_prefix) = match tv.network {
878                "mainnet" => (Network::MainNetwork, Prefix::XPRV, Prefix::XPUB),
879                "testnet" => (Network::TestNetwork, Prefix::TPRV, Prefix::TPUB),
880                _ => unreachable!(),
881            };
882
883            let privkeys = (0..tv.key_information_vector.len())
884                .zip(&seeds)
885                .map(|(_, seed)| {
886                    AccountPrivKey::from_seed(
887                        &params,
888                        seed,
889                        zip32::AccountId::try_from(tv.account).unwrap(),
890                    )
891                    .unwrap()
892                })
893                .collect::<Vec<_>>();
894
895            for (actual, expected) in privkeys.iter().zip(tv.xprv_keys) {
896                assert_eq!(actual.key.to_string(xprv_prefix).as_str(), *expected);
897            }
898
899            let key_info = privkeys
900                .iter()
901                .map(|privkey| privkey.to_account_pubkey())
902                .collect::<Vec<_>>();
903
904            for (actual, expected) in key_info.iter().zip(tv.xpub_keys) {
905                assert_eq!(actual.key.to_string(xpub_prefix).as_str(), *expected);
906            }
907
908            let fvk =
909                FullViewingKey::standard(NonZeroU8::new(tv.required).unwrap(), key_info).unwrap();
910
911            assert_eq!(
912                fvk.wallet_descriptor_template(),
913                tv.wallet_descriptor_template,
914            );
915
916            for (key, expected) in fvk.key_info.iter().zip(tv.key_information_vector) {
917                assert_eq!(
918                    AccountPubKey::parse_key_info_expression(expected, &params).as_ref(),
919                    Some(key),
920                );
921                assert_eq!(&key.key_info_expression(&params), expected);
922            }
923
924            for (i, seed) in seeds.iter().enumerate() {
925                if i < tv.key_information_vector.len() {
926                    assert!(matches!(
927                        fvk.derive_matching_account_priv_key(seed),
928                        Ok(Some(_)),
929                    ));
930                } else {
931                    assert!(matches!(
932                        fvk.derive_matching_account_priv_key(seed),
933                        Ok(None),
934                    ));
935                }
936            }
937
938            for (i, address) in tv.external_addresses {
939                assert_eq!(
940                    fvk.derive_address(
941                        zip32::Scope::External,
942                        NonHardenedChildIndex::const_from_index(*i)
943                    )
944                    .0,
945                    p2sh_address_from_vector(address),
946                )
947            }
948
949            for (i, address) in tv.change_addresses {
950                assert_eq!(
951                    fvk.derive_address(
952                        zip32::Scope::Internal,
953                        NonHardenedChildIndex::const_from_index(*i)
954                    )
955                    .0,
956                    p2sh_address_from_vector(address),
957                )
958            }
959        }
960    }
961}