1use 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#[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 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 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 pub fn to_account_pubkey(&self) -> AccountPubKey {
93 AccountPubKey {
94 origin: self.origin.clone(),
95 key: self.key.public_key(),
96 }
97 }
98
99 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#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct AccountPubKey {
123 origin: KeyOrigin,
124 key: ExtendedPublicKey<PublicKey>,
125}
126
127impl AccountPubKey {
128 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 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 fn coin_type_and_account(&self) -> (u32, AccountId) {
165 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 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 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
217pub struct FullViewingKey {
224 threshold: NonZeroU8,
225 key_info: NonEmpty<AccountPubKey>,
226}
227
228impl FullViewingKey {
229 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 {
247 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 Ok(Self {
263 threshold,
264 key_info,
265 })
266 }
267 }
268
269 fn coin_type_and_account(&self) -> (u32, AccountId) {
271 self.key_info.first().coin_type_and_account()
274 }
275
276 pub fn wallet_descriptor_template(&self) -> String {
280 self.standard_descriptor(|i, _| format!("@{i}/**"))
281 }
282
283 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 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 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 Ok(None)
322 }
323
324 pub fn derive_address(
327 &self,
328 scope: zip32::Scope,
329 address_index: NonHardenedChildIndex,
330 ) -> (TransparentAddress, script::Redeem) {
331 let keys = self
333 .key_info
334 .iter()
335 .map(|pubkey| {
336 pubkey.key_expression_for_address(
337 Prefix::XPUB,
339 scope,
340 address_index,
341 )
342 })
343 .collect::<Vec<_>>();
344
345 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 let addr = TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid");
354
355 (addr, redeem_script)
356 }
357}
358
359const P2SH_KEY_ENCODING_LEN: usize = 65;
362
363const FVK_MULTIPATH: &str = "/**";
366
367const IVK_MULTIPATH: &str = "/*";
370
371const MAX_KEYS: usize = 15;
374
375#[derive(Clone, Debug, PartialEq, Eq)]
382pub struct P2shKey {
383 chain_code: [u8; 32],
384 public_key: PublicKey,
385}
386
387impl P2shKey {
388 pub fn new(chain_code: [u8; 32], public_key: PublicKey) -> Self {
390 Self {
391 chain_code,
392 public_key,
393 }
394 }
395
396 pub fn chain_code(&self) -> &[u8; 32] {
398 &self.chain_code
399 }
400
401 pub fn public_key(&self) -> &PublicKey {
403 &self.public_key
404 }
405
406 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 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 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 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 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 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
470fn 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
481fn 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
496fn 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 if template != render_template(threshold, key_info.len(), multipath) {
543 return Err(P2shViewingKeyError::UnsupportedTemplate);
544 }
545
546 Ok((threshold, key_info))
547}
548
549fn parse_threshold(template: &str) -> Option<NonZeroU8> {
551 template
552 .strip_prefix("sh(sortedmulti(")?
553 .split(',')
554 .next()?
555 .parse()
556 .ok()
557}
558
559fn 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#[derive(Clone, Debug, PartialEq, Eq)]
586pub struct P2shFullViewingKey {
587 threshold: NonZeroU8,
588 key_info: NonEmpty<P2shKey>,
589}
590
591impl P2shFullViewingKey {
592 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 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 pub fn threshold(&self) -> NonZeroU8 {
619 self.threshold
620 }
621
622 pub fn key_info(&self) -> &NonEmpty<P2shKey> {
624 &self.key_info
625 }
626
627 pub fn wallet_descriptor_template(&self) -> String {
631 render_template(self.threshold, self.key_info.len(), FVK_MULTIPATH)
632 }
633
634 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 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 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#[derive(Clone, Debug, PartialEq, Eq)]
672pub struct P2shIncomingViewingKey {
673 threshold: NonZeroU8,
674 key_info: NonEmpty<P2shKey>,
675}
676
677impl P2shIncomingViewingKey {
678 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 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 pub fn threshold(&self) -> NonZeroU8 {
705 self.threshold
706 }
707
708 pub fn key_info(&self) -> &NonEmpty<P2shKey> {
710 &self.key_info
711 }
712
713 pub fn wallet_descriptor_template(&self) -> String {
717 render_template(self.threshold, self.key_info.len(), IVK_MULTIPATH)
718 }
719
720 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 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 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 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#[derive(Clone, Debug, PartialEq, Eq)]
760pub enum P2shViewingKeyError {
761 NoPubKeys,
763 TooManyPubKeys,
765 InvalidThreshold,
767 Malformed,
769 UnsupportedTemplate,
771 InvalidKey(bip32::Error),
773}
774
775#[derive(Clone, Debug)]
777pub enum FullViewingKeyError {
778 NoPubKeys,
780 TooManyPubKeys,
782 InvalidThreshold,
784 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 const B58_ADDRESS_PREFIX_LEN: usize = 2;
806
807 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(¶ms, 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(¶ms),
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 ¶ms,
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, ¶ms).as_ref(),
919 Some(key),
920 );
921 assert_eq!(&key.key_info_expression(¶ms), 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}